Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 96 additions & 119 deletions app/core/agent_loop.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
"""ReAct Agent 主循环。

Thought → Action → Observation 循环是 Agent 的心脏。
这个文件是你的第三个实现目标,也是三个文件中最复杂的一个。
"""

from __future__ import annotations

import json
import time
from dataclasses import dataclass, field
from uuid import UUID, uuid4
from dataclasses import dataclass

from app.core.agent_config import AgentConfig
from app.core.event_bus import EventBus, get_event_bus
from app.core.event_types import EventType, StopReason
from app.core.llm_client import LLMClient, LLMError
from app.core.tool_registry import ToolRegistry, ToolExecutionError, ToolNotFoundError

DEFAULT_SYSTEM_PROMPT = (
"You are a helpful AI assistant with access to tools. "
"Use tools when you need to look up information or perform calculations. "
"After using tools, synthesize the results into a clear answer. "
"If a tool returns an error, try a different approach or explain the issue to the user."
)

# ─── 数据结构 ───────────────────────────────────────────


@dataclass
Expand All @@ -33,20 +34,31 @@ class LoopState:
def _build_tool_call_message(tool_calls: list[dict], content: str | None) -> dict:
openai_tool_calls = []
for tc in tool_calls:
openai_tool_calls.append({
"id": tc["id"],
"type": "function",
"function": {
"name": tc["name"],
"arguments": json.dumps(tc["arguments"], ensure_ascii=False),
},
})
msg: dict = {"role": "assistant", "content": content, "tool_calls": openai_tool_calls}
return msg

openai_tool_calls.append(
{
"id":tc["id"],
"type":"function",
"function":{
"name":tc["name"],
"arguments":json.dumps(tc["arguments"],ensure_ascii=False)
}
}
)
result_dict_cm = {
"role":"assistant",
"content":content,
"tool_calls":openai_tool_calls
}
return result_dict_cm

def _build_tool_result_message(tool_call_id: str, result_str: str) -> dict:
return {"role": "tool", "tool_call_id": tool_call_id, "content": result_str}
result_dict_rs = {
"role":"tool",
"tool_call_id":tool_call_id,
"content":result_str
}
return result_dict_rs
# ─── 主函数:你要实现的 ────────────────────────────────────


async def run_agent_loop(
Expand All @@ -58,114 +70,79 @@ async def run_agent_loop(
node_id: str = "",
event_bus: EventBus | None = None,
) -> LoopState:
event_bus = event_bus or get_event_bus()
tools_schema = await tools.get_all_as_openai_schema()
if event_bus is None:
event_bus = get_event_bus()
schema = await tools.get_all_as_openai_schema()
state = LoopState(
session_id=session_id,
node_id=node_id,
messages=list(messages),
session_id = session_id,
node_id = node_id,
messages = list(messages)
)

for iteration in range(1, config.max_iterations + 1):
for iteration in range(1,config.max_iterations + 1):
state.iteration = iteration

try:
response = await llm.chat(state.messages, tools_schema)
except LLMError as e:
state.error = str(e)
response = await llm.chat(state.messages,schema)
if response.thinking:
await event_bus.emit(node_id,session_id,EventType.THINKING,{"content":response.thinking,"iteration":iteration})
if response.content:
await event_bus.emit(node_id,session_id,EventType.TEXT,{"content":response.content,"iteration":iteration,"is_final":not bool(response.tool_calls)})
if not response.tool_calls:
state.final_answer = response.content
state.should_stop = True
state.messages.append({"role":"assistant","content":response.content})
break
else:
assistant = _build_tool_call_message(response.tool_calls,response.content)
state.messages.append(assistant)
for tc in response.tool_calls:
tool_call_id = tc["id"]
tool_name = tc["name"]
arguments = tc["arguments"]
await event_bus.emit(node_id,session_id,EventType.TOOL_CALL,{
"tool_call_id":tool_call_id,
"tool_name":tool_name,
"arguments":arguments,
"iteration":iteration,
})
start_time = time.monotonic()
try:
result = await tools.execute(tool_name,arguments)
result_str = json.dumps(result,ensure_ascii=False)
duration_ms = int((time.monotonic() - start_time) * 1000)
await event_bus.emit(node_id,session_id,EventType.TOOL_RESULT,{
"tool_call_id":tool_call_id,
"tool_name":tool_name,
"result":result,
"duration_ms":duration_ms,
"is_error":False,
})
except (ToolExecutionError,ToolNotFoundError) as e:
result_str = json.dumps({"error":str(e)})
duration_ms = int((time.monotonic() - start_time) * 1000)
await event_bus.emit(node_id,session_id,EventType.TOOL_RESULT,{
"tool_call_id":tool_call_id,
"tool_name":tool_name,
"result":{"error":str(e)},
"duration_ms":duration_ms,
"is_error":True,
})
state.messages.append(_build_tool_result_message(tool_call_id,result_str))
except LLMError as exc:
state.error = str(exc)
state.should_stop = True
await event_bus.emit(node_id, session_id, EventType.ERROR, {
"message": str(e),
"iteration": iteration,
})
break

if response.thinking:
await event_bus.emit(node_id, session_id, EventType.THINKING, {
"content": response.thinking,
"iteration": iteration,
})

if response.content:
await event_bus.emit(node_id, session_id, EventType.TEXT, {
"content": response.content,
"iteration": iteration,
"is_final": not bool(response.tool_calls),
})

if not response.tool_calls:
state.final_answer = response.content
state.should_stop = True
state.messages.append({"role": "assistant", "content": response.content})
await event_bus.emit(node_id, session_id, EventType.STATUS, {
"status": "completed",
"message": "Agent finished",
"stop_reason": StopReason.FINISH.value,
"iterations": iteration,
})
break

assistant_msg = _build_tool_call_message(response.tool_calls, response.content)
state.messages.append(assistant_msg)

for tc in response.tool_calls:
tool_call_id = tc["id"]
tool_name = tc["name"]
arguments = tc["arguments"]

await event_bus.emit(node_id, session_id, EventType.TOOL_CALL, {
"tool_call_id": tool_call_id,
"tool_name": tool_name,
"arguments": arguments,
"iteration": iteration,
})

start_time = time.monotonic()
try:
result = await tools.execute(tool_name, arguments)
duration_ms = int((time.monotonic() - start_time) * 1000)
await event_bus.emit(node_id, session_id, EventType.TOOL_RESULT, {
"tool_call_id": tool_call_id,
"tool_name": tool_name,
"result": result,
"duration_ms": duration_ms,
"is_error": False,
})
result_str = json.dumps(result, ensure_ascii=False)
except (ToolExecutionError, ToolNotFoundError) as e:
duration_ms = int((time.monotonic() - start_time) * 1000)
result_str = json.dumps({"error": str(e)})
await event_bus.emit(node_id, session_id, EventType.TOOL_RESULT, {
"tool_call_id": tool_call_id,
"tool_name": tool_name,
"result": {"error": str(e)},
"duration_ms": duration_ms,
"is_error": True,
})

state.messages.append(_build_tool_result_message(tool_call_id, result_str))

else:
state.should_stop = True
await event_bus.emit(node_id, session_id, EventType.STATUS, {
"status": "completed",
"message": f"Reached max iterations ({config.max_iterations})",
"stop_reason": StopReason.MAX_ITERATIONS.value,
"iterations": iteration,
})

state.messages.append({
"role": "user",
"content": "Maximum steps reached. Summarize what you found so far and give your best answer.",
state.should_stop = True
await event_bus.emit(node_id,session_id,EventType.STATUS,{
"status":"completed",
"message":f"Reached max iterations({config.max_iterations})",
"stop_reason":StopReason.MAX_ITERATIONS.value,
"iterations":config.max_iterations
})
state.messages.append({"role":"user","content":"Maximum steps reached. Summarize what you found so far and give your best answer."})
try:
fallback = await llm.chat(state.messages)
state.final_answer = fallback.content
await event_bus.emit(node_id, session_id, EventType.TEXT, {
"content": fallback.content,
"is_final": True,
})
except LLMError:
except LLMError as exc:
state.final_answer = "Agent reached iteration limit but could not produce a summary."

return state
return state
59 changes: 32 additions & 27 deletions app/core/event_bus.py
Original file line number Diff line number Diff line change
@@ -1,69 +1,74 @@
"""事件总线。

Agent 循环过程中每发生一件事就通过 EventBus 推送出去,
订阅者(如 SSE 连接)收到事件后推给前端。
"""

from __future__ import annotations

import asyncio
import json
from datetime import datetime, timezone
from typing import Any
from uuid import UUID

from app.core.event_types import EventType


class EventBus:
def __init__(self):
self._subscribers: dict[str, list[asyncio.Queue]] = {}
self._pending_events: list[dict] = []

def subscribe(self, session_id: str, queue: asyncio.Queue):
def subscribe(self, session_id: str, queue: asyncio.Queue) -> None:
if not hasattr(self,"_subscribers"):
self._subscribers = {}
if session_id not in self._subscribers:
self._subscribers[session_id] = []
self._subscribers[session_id].append(queue)

def unsubscribe(self, session_id: str, queue: asyncio.Queue):
def unsubscribe(self, session_id: str, queue: asyncio.Queue) -> None:
if not hasattr(self, "_subscribers"):
return
if session_id in self._subscribers:
subs = self._subscribers[session_id]
if queue in subs:
subs.remove(queue)
if queue in self._subscribers[session_id]:
self._subscribers[session_id].remove(queue)

async def emit(
self,
node_id: str,
session_id: str,
event_type: EventType,
payload: dict[str, Any],
):
) -> None:
event_data = {
"node_id": str(node_id),
"session_id": str(session_id),
"type": event_type.value,
**payload,
"timestamp": datetime.now(timezone.utc).isoformat(),
"type": event_type.value, # EventType 是 str enum, .value 拿字符串
**payload, # payload 的键值展开到事件顶层的其余字段
"timestamp": datetime.now(timezone.utc).isoformat()
}

self._pending_events.append({
"session_id": session_id,
"node_id": node_id,
"event_type": event_type.value,
"payload": payload,
})

for queue in self._subscribers.get(session_id, []):
if not hasattr(self,"_pending_events"):
self._pending_events = []
self._pending_events.append(event_data)
if not hasattr(self,"_subscribers"):
return
for queue in self._subscribers.get(session_id,[]):
try:
queue.put_nowait(event_data)
except asyncio.QueueFull:
pass

def flush_events(self) -> list[dict]:
events = self._pending_events.copy()
self._pending_events.clear()
return events
if not hasattr(self,"_pending_events"):
return []
result = self._pending_events
self._pending_events = []
return result

# ─── 全局单例(已给,直接用)─────────────────────────────

_global_event_bus: EventBus | None = None


def get_event_bus() -> EventBus:
"""获取全局唯一的 EventBus 实例。"""
global _global_event_bus
if _global_event_bus is None:
_global_event_bus = EventBus()
return _global_event_bus
return _global_event_bus
2 changes: 1 addition & 1 deletion tests/manual_smoke_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ async def test_agent_loop_with_tool():
print(f" Answer: {state.final_answer[:200]}...")

events = event_bus.flush_events()
event_types = [e["event_type"] for e in events]
event_types = [e["type"] for e in events]
print(f" Event types: {event_types}")
assert state.final_answer is not None
assert "tool_call" in event_types, f"Expected tool_call event, got {event_types}"
Expand Down
Loading
Loading