Spaces:
Sleeping
Sleeping
File size: 22,659 Bytes
74e7808 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 | # -*- coding: utf-8 -*-
"""
Tests for AgentExecutor with mocked LLM adapter.
Covers:
- ReAct loop: tool-calling β result feedback β final answer
- Dashboard JSON parsing (markdown blocks, raw JSON, json_repair)
- Max step limit
- Tool execution error handling
- _serialize_tool_result for various types
- _build_user_message formatting
"""
import json
import time
import unittest
import sys
import os
from dataclasses import dataclass
from unittest.mock import MagicMock
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
# Keep this test runnable when optional LLM runtime deps are not installed.
try:
import litellm # noqa: F401
except ModuleNotFoundError:
sys.modules["litellm"] = MagicMock()
from src.agent.executor import AgentExecutor, AgentResult
from src.agent.llm_adapter import LLMResponse, ToolCall
from src.agent.runner import parse_dashboard_json, run_agent_loop, serialize_tool_result
from src.agent.tools.registry import ToolRegistry, ToolDefinition, ToolParameter
# ============================================================
# Helpers
# ============================================================
def _make_registry_with_echo():
"""Create a registry with a simple echo tool."""
registry = ToolRegistry()
tool = ToolDefinition(
name="echo",
description="Echoes back the input",
parameters=[
ToolParameter(name="message", type="string", description="Message to echo"),
],
handler=lambda message: {"echo": message},
)
registry.register(tool)
return registry
def _make_mock_adapter():
"""Create a MagicMock LLMToolAdapter."""
adapter = MagicMock()
return adapter
SAMPLE_DASHBOARD = {
"stock_name": "θ΄΅ε·θ
ε°",
"sentiment_score": 75,
"trend_prediction": "ηε€",
"operation_advice": "ζζ",
"decision_type": "hold",
"confidence_level": "δΈ",
"dashboard": {
"core_conclusion": {
"one_sentence": "θ
ε°θΏζιθ‘θ΅°εΌΊ",
"signal_type": "π‘ζζθ§ζ",
},
},
"analysis_summary": "Overall bullish trend",
"key_points": "Strong revenue growth",
"risk_warning": "High valuation",
"buy_reason": "Sector leader",
"trend_analysis": "Upward trend",
"technical_analysis": "MACD golden cross",
}
# ============================================================
# AgentExecutor Tests
# ============================================================
class TestAgentExecutor(unittest.TestCase):
"""Test the ReAct loop logic."""
def test_simple_text_response(self):
"""Agent returns text immediately (no tool calls) with JSON dashboard."""
registry = _make_registry_with_echo()
adapter = _make_mock_adapter()
# LLM returns a text response with the dashboard JSON
adapter.call_with_tools.return_value = LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD, ensure_ascii=False),
tool_calls=[],
usage={"total_tokens": 100},
provider="openai",
)
executor = AgentExecutor(registry, adapter, max_steps=5)
result = executor.run("Analyze 600519")
self.assertTrue(result.success)
self.assertIsNotNone(result.dashboard)
self.assertEqual(result.dashboard["sentiment_score"], 75)
self.assertEqual(result.total_steps, 1)
self.assertEqual(result.provider, "openai")
self.assertEqual(len(result.tool_calls_log), 0)
def test_tool_call_then_text(self):
"""Agent calls a tool, gets result, then returns final answer."""
registry = _make_registry_with_echo()
adapter = _make_mock_adapter()
# Step 1: LLM requests tool call
step1_response = LLMResponse(
content="Let me check the data.",
tool_calls=[
ToolCall(id="call_1", name="echo", arguments={"message": "hello"}),
],
usage={"total_tokens": 50},
provider="gemini",
)
# Step 2: LLM returns final text
step2_response = LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD, ensure_ascii=False),
tool_calls=[],
usage={"total_tokens": 80},
provider="gemini",
)
adapter.call_with_tools.side_effect = [step1_response, step2_response]
executor = AgentExecutor(registry, adapter, max_steps=5)
result = executor.run("Analyze 600519")
self.assertTrue(result.success)
self.assertEqual(result.total_steps, 2)
self.assertEqual(result.total_tokens, 130)
self.assertEqual(len(result.tool_calls_log), 1)
self.assertEqual(result.tool_calls_log[0]["tool"], "echo")
self.assertTrue(result.tool_calls_log[0]["success"])
def test_multiple_tool_calls_in_one_step(self):
"""Agent requests multiple tool calls in a single response."""
registry = _make_registry_with_echo()
adapter = _make_mock_adapter()
step1 = LLMResponse(
content="Gathering data.",
tool_calls=[
ToolCall(id="c1", name="echo", arguments={"message": "a"}),
ToolCall(id="c2", name="echo", arguments={"message": "b"}),
],
usage={"total_tokens": 40},
provider="openai",
)
step2 = LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD),
tool_calls=[],
usage={"total_tokens": 60},
provider="openai",
)
adapter.call_with_tools.side_effect = [step1, step2]
executor = AgentExecutor(registry, adapter, max_steps=5)
result = executor.run("Analyze 600519")
self.assertTrue(result.success)
self.assertEqual(len(result.tool_calls_log), 2)
def test_max_steps_exceeded(self):
"""Agent keeps calling tools until max_steps is hit."""
registry = _make_registry_with_echo()
adapter = _make_mock_adapter()
# Always return tool calls, never final text
tool_response = LLMResponse(
content="Still working.",
tool_calls=[
ToolCall(id="c1", name="echo", arguments={"message": "loop"}),
],
usage={"total_tokens": 20},
provider="openai",
)
adapter.call_with_tools.return_value = tool_response
executor = AgentExecutor(registry, adapter, max_steps=3)
result = executor.run("Analyze loop")
self.assertFalse(result.success)
self.assertIn("max steps", result.error.lower())
self.assertEqual(result.total_steps, 3)
def test_tool_execution_error(self):
"""Tool raises exception β should be logged and error sent to LLM."""
def _always_fail():
raise RuntimeError("db down")
registry = ToolRegistry()
tool = ToolDefinition(
name="failing_tool",
description="Always fails",
parameters=[],
handler=_always_fail,
)
registry.register(tool)
adapter = _make_mock_adapter()
step1 = LLMResponse(
content="",
tool_calls=[
ToolCall(id="f1", name="failing_tool", arguments={}),
],
usage={"total_tokens": 30},
provider="openai",
)
step2 = LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD),
tool_calls=[],
usage={"total_tokens": 50},
provider="openai",
)
adapter.call_with_tools.side_effect = [step1, step2]
executor = AgentExecutor(registry, adapter, max_steps=5)
result = executor.run("Test error handling")
# Should still succeed overall (agent handles tool errors gracefully)
self.assertTrue(result.success)
# The failing tool call should be logged as failure
self.assertEqual(len(result.tool_calls_log), 1)
self.assertFalse(result.tool_calls_log[0]["success"])
def test_unknown_tool_called(self):
"""LLM requests a tool not in the registry β should handle gracefully."""
registry = _make_registry_with_echo()
adapter = _make_mock_adapter()
step1 = LLMResponse(
content="",
tool_calls=[
ToolCall(id="u1", name="nonexistent_tool", arguments={}),
],
usage={"total_tokens": 20},
provider="openai",
)
step2 = LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD),
tool_calls=[],
usage={"total_tokens": 50},
provider="openai",
)
adapter.call_with_tools.side_effect = [step1, step2]
executor = AgentExecutor(registry, adapter, max_steps=5)
result = executor.run("Test unknown tool")
self.assertTrue(result.success)
self.assertEqual(len(result.tool_calls_log), 1)
self.assertFalse(result.tool_calls_log[0]["success"])
self.assertFalse(result.tool_calls_log[0]["cached"])
def test_non_retriable_tool_failure_is_cached_across_hk_variants(self):
"""Equivalent HK code variants should not re-execute a non-retriable failing tool."""
calls = []
def _quote(stock_code):
calls.append(stock_code)
return {
"error": f"No realtime quote available for {stock_code}",
"retriable": False,
"note": "Skip retry",
}
registry = ToolRegistry()
registry.register(
ToolDefinition(
name="get_realtime_quote",
description="Get realtime quote",
parameters=[
ToolParameter(name="stock_code", type="string", description="Stock code"),
],
handler=_quote,
)
)
adapter = _make_mock_adapter()
adapter.call_with_tools.side_effect = [
LLMResponse(
content="",
tool_calls=[
ToolCall(id="q1", name="get_realtime_quote", arguments={"stock_code": "hk01810"}),
],
usage={"total_tokens": 10},
provider="openai",
),
LLMResponse(
content="",
tool_calls=[
ToolCall(id="q2", name="get_realtime_quote", arguments={"stock_code": "1810.HK"}),
],
usage={"total_tokens": 10},
provider="openai",
),
LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD, ensure_ascii=False),
tool_calls=[],
usage={"total_tokens": 10},
provider="openai",
),
]
executor = AgentExecutor(registry, adapter, max_steps=5)
result = executor.run("Analyze HK01810")
self.assertTrue(result.success)
self.assertEqual(calls, ["hk01810"])
self.assertEqual(len(result.tool_calls_log), 2)
self.assertFalse(result.tool_calls_log[0]["cached"])
self.assertTrue(result.tool_calls_log[1]["cached"])
def test_model_trace_deduplicates_and_keeps_order(self):
"""Model trace should keep call order and de-duplicate repeated models."""
registry = _make_registry_with_echo()
adapter = _make_mock_adapter()
step1 = LLMResponse(
content="first tool call",
tool_calls=[ToolCall(id="m1", name="echo", arguments={"message": "a"})],
usage={"total_tokens": 10},
provider="gemini",
model="gemini/gemini-2.0-flash",
)
step2 = LLMResponse(
content="second tool call",
tool_calls=[ToolCall(id="m2", name="echo", arguments={"message": "b"})],
usage={"total_tokens": 10},
provider="gemini",
model="gemini/gemini-2.0-flash",
)
step3 = LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD, ensure_ascii=False),
tool_calls=[],
usage={"total_tokens": 10},
provider="openai",
model="openai/gpt-4o-mini",
)
adapter.call_with_tools.side_effect = [step1, step2, step3]
executor = AgentExecutor(registry, adapter, max_steps=5)
result = executor.run("Analyze 600519")
self.assertTrue(result.success)
self.assertEqual(result.model, "gemini/gemini-2.0-flash, openai/gpt-4o-mini")
def test_model_trace_skips_error_provider(self):
"""Error provider placeholder should not appear in model trace."""
registry = _make_registry_with_echo()
adapter = _make_mock_adapter()
adapter.call_with_tools.return_value = LLMResponse(
content="llm failed",
tool_calls=[],
usage={"total_tokens": 3},
provider="error",
model="",
)
executor = AgentExecutor(registry, adapter, max_steps=2)
result = executor.run("Analyze 600519")
self.assertFalse(result.success)
self.assertEqual(result.model, "")
def test_timeout_budget_aborts_single_agent_loop(self):
"""Single-agent executor should stop once the configured timeout budget is exhausted."""
registry = _make_registry_with_echo()
adapter = _make_mock_adapter()
def _slow_llm(*_args, **_kwargs):
time.sleep(0.03)
return LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD, ensure_ascii=False),
tool_calls=[],
usage={"total_tokens": 10},
provider="openai",
)
adapter.call_with_tools.side_effect = _slow_llm
executor = AgentExecutor(registry, adapter, max_steps=2, timeout_seconds=0.01)
result = executor.run("Analyze 600519")
self.assertFalse(result.success)
self.assertIn("timed out", (result.error or "").lower())
def test_parallel_tool_timeout_marks_only_pending_calls(self):
"""Parallel tool batches should emit timeout errors for unfinished tools."""
registry = ToolRegistry()
def _maybe_slow_echo(message):
if message == "slow":
time.sleep(0.05)
return {"echo": message}
registry.register(
ToolDefinition(
name="echo",
description="Echoes back the input",
parameters=[
ToolParameter(name="message", type="string", description="Message to echo"),
],
handler=_maybe_slow_echo,
)
)
adapter = _make_mock_adapter()
adapter.call_with_tools.side_effect = [
LLMResponse(
content="Gathering data.",
tool_calls=[
ToolCall(id="fast", name="echo", arguments={"message": "fast"}),
ToolCall(id="slow", name="echo", arguments={"message": "slow"}),
],
usage={"total_tokens": 10},
provider="openai",
),
LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD, ensure_ascii=False),
tool_calls=[],
usage={"total_tokens": 10},
provider="openai",
),
]
result = run_agent_loop(
messages=[
{"role": "system", "content": "system"},
{"role": "user", "content": "Analyze"},
],
tool_registry=registry,
llm_adapter=adapter,
max_steps=3,
tool_call_timeout_seconds=0.01,
)
self.assertTrue(result.success)
self.assertEqual(len(result.tool_calls_log), 2)
timeout_logs = [log for log in result.tool_calls_log if log.get("timeout")]
self.assertEqual(len(timeout_logs), 1)
self.assertEqual(timeout_logs[0]["arguments"]["message"], "slow")
def test_single_tool_timeout_marks_tool_failed(self):
"""Single tool calls should also respect the configured tool timeout."""
registry = ToolRegistry()
def _slow_echo(message):
time.sleep(0.05)
return {"echo": message}
registry.register(
ToolDefinition(
name="echo",
description="Echoes back the input",
parameters=[
ToolParameter(name="message", type="string", description="Message to echo"),
],
handler=_slow_echo,
)
)
adapter = _make_mock_adapter()
adapter.call_with_tools.side_effect = [
LLMResponse(
content="Gathering data.",
tool_calls=[ToolCall(id="slow", name="echo", arguments={"message": "slow"})],
usage={"total_tokens": 10},
provider="openai",
),
LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD, ensure_ascii=False),
tool_calls=[],
usage={"total_tokens": 10},
provider="openai",
),
]
result = run_agent_loop(
messages=[
{"role": "system", "content": "system"},
{"role": "user", "content": "Analyze"},
],
tool_registry=registry,
llm_adapter=adapter,
max_steps=3,
tool_call_timeout_seconds=0.01,
)
self.assertTrue(result.success)
self.assertEqual(len(result.tool_calls_log), 1)
self.assertTrue(result.tool_calls_log[0].get("timeout"))
self.assertEqual(result.tool_calls_log[0]["arguments"]["message"], "slow")
def test_llm_call_receives_remaining_timeout_budget(self):
"""LLM tool calls should receive the remaining wall-clock budget."""
registry = _make_registry_with_echo()
adapter = _make_mock_adapter()
captured = {}
def _capture_timeout(*_args, **kwargs):
captured["timeout"] = kwargs.get("timeout")
return LLMResponse(
content=json.dumps(SAMPLE_DASHBOARD, ensure_ascii=False),
tool_calls=[],
usage={"total_tokens": 10},
provider="openai",
)
adapter.call_with_tools.side_effect = _capture_timeout
executor = AgentExecutor(registry, adapter, max_steps=2, timeout_seconds=0.2)
result = executor.run("Analyze 600519")
self.assertTrue(result.success)
self.assertIsNotNone(captured.get("timeout"))
self.assertGreater(captured["timeout"], 0.0)
self.assertLessEqual(captured["timeout"], 0.2)
# ============================================================
# Dashboard parsing
# ============================================================
class TestDashboardParsing(unittest.TestCase):
"""Test parse_dashboard_json with various input formats."""
def test_parse_markdown_json_block(self):
content = f"Here is my analysis:\n```json\n{json.dumps(SAMPLE_DASHBOARD)}\n```\nDone."
result = parse_dashboard_json(content)
self.assertIsNotNone(result)
self.assertEqual(result["sentiment_score"], 75)
def test_parse_raw_json(self):
content = json.dumps(SAMPLE_DASHBOARD)
result = parse_dashboard_json(content)
self.assertIsNotNone(result)
def test_parse_json_in_text(self):
content = f"Let me present: {json.dumps(SAMPLE_DASHBOARD)} β that's all."
result = parse_dashboard_json(content)
self.assertIsNotNone(result)
def test_parse_empty_content(self):
self.assertIsNone(parse_dashboard_json(""))
self.assertIsNone(parse_dashboard_json(None))
def test_parse_no_json(self):
self.assertIsNone(parse_dashboard_json("This is just plain text with no JSON"))
# ============================================================
# Serialization
# ============================================================
class TestSerializeToolResult(unittest.TestCase):
"""Test serialize_tool_result for various types."""
def test_serialize_none(self):
result = serialize_tool_result(None)
self.assertEqual(json.loads(result), {"result": None})
def test_serialize_string(self):
result = serialize_tool_result("hello")
self.assertEqual(result, "hello")
def test_serialize_dict(self):
d = {"key": "value", "num": 42}
result = serialize_tool_result(d)
self.assertEqual(json.loads(result), d)
def test_serialize_list(self):
lst = [1, 2, 3]
result = serialize_tool_result(lst)
self.assertEqual(json.loads(result), lst)
def test_serialize_dataclass(self):
@dataclass
class Sample:
name: str = "test"
value: int = 42
result = serialize_tool_result(Sample())
parsed = json.loads(result)
self.assertEqual(parsed["name"], "test")
self.assertEqual(parsed["value"], 42)
# ============================================================
# User message builder
# ============================================================
class TestBuildUserMessage(unittest.TestCase):
"""Test _build_user_message formatting."""
def setUp(self):
self.executor = AgentExecutor(
ToolRegistry(), _make_mock_adapter(), max_steps=1
)
def test_basic_message(self):
msg = self.executor._build_user_message("Analyze 600519")
self.assertIn("Analyze 600519", msg)
self.assertIn("ε³ηδ»ͺ葨η", msg)
def test_message_with_context(self):
msg = self.executor._build_user_message(
"Analyze",
context={"stock_code": "600519", "report_type": "daily"},
)
self.assertIn("θ‘η₯¨δ»£η : 600519", msg)
self.assertIn("ζ₯εη±»ε: daily", msg)
# ============================================================
# AgentResult dataclass
# ============================================================
class TestAgentResult(unittest.TestCase):
"""Test AgentResult defaults."""
def test_defaults(self):
r = AgentResult()
self.assertFalse(r.success)
self.assertEqual(r.content, "")
self.assertIsNone(r.dashboard)
self.assertEqual(r.tool_calls_log, [])
self.assertEqual(r.total_steps, 0)
self.assertEqual(r.total_tokens, 0)
self.assertIsNone(r.error)
if __name__ == '__main__':
unittest.main()
|