diff --git a/backend/app/modules/ai/chat/service.py b/backend/app/modules/ai/chat/service.py
index a5f542c3f..8e67948af 100644
--- a/backend/app/modules/ai/chat/service.py
+++ b/backend/app/modules/ai/chat/service.py
@@ -8,7 +8,13 @@
from typing import Any
import httpx
+from agno.run.team import ModelRequestStartedEvent as TeamModelRequestStartedEvent
+from agno.run.team import RunContentCompletedEvent as TeamRunContentCompletedEvent
+from agno.run.team import RunContentEvent as TeamRunContentEvent
+from agno.run.team import RunCancelledEvent as TeamRunCancelledEvent
+from agno.run.team import RunErrorEvent as TeamRunErrorEvent
from agno.run.team import TeamRunOutput
+from agno.run.team import ToolCallStartedEvent as TeamToolCallStartedEvent
from agno.session.team import TeamSession
from redis.asyncio import Redis
@@ -187,20 +193,36 @@ async def chat_query(
logger.info("开始流式生成: session_id={} message={!r}", session_id, message[:80])
chunk_count = 0
try:
- stream = agent.arun(input=message, stream=True)
+ stream = agent.arun(input=message, stream=True, stream_events=True)
if hasattr(stream, "__aiter__"):
- async for chunk in stream: # type: ignore[union-attr]
+ pending_text: list[str] = []
+ async for chunk in stream:
if stop_event is not None and stop_event.is_set():
- logger.info("用户主动停止生成: session_id={}", session_id)
return
- if chunk and getattr(chunk, "content", None):
- chunk_count += 1
- yield str(chunk.content)
+ if isinstance(chunk, TeamRunCancelledEvent):
+ raise asyncio.CancelledError
+ if isinstance(chunk, TeamRunErrorEvent):
+ raise RuntimeError("AI 运行失败")
+ if getattr(chunk, "parent_run_id", None):
+ continue
+ if isinstance(chunk, (TeamModelRequestStartedEvent, TeamToolCallStartedEvent)):
+ pending_text.clear()
+ elif isinstance(chunk, TeamRunContentEvent) and chunk.content:
+ # 调用工具前也可能先生成正文,等 Team 确认正文结束再发送。
+ pending_text.append(str(chunk.content))
+ elif isinstance(chunk, TeamRunContentCompletedEvent):
+ for text in pending_text:
+ if stop_event is not None and stop_event.is_set():
+ return
+ chunk_count += 1
+ yield text
+ pending_text.clear()
else:
- # 兼容非流式直接返回结果的场景
- result: Any = stream
- if result and getattr(result, "content", None):
- yield str(result.content)
+ if isinstance(stream, TeamRunOutput) and stream.status == "CANCELLED":
+ raise asyncio.CancelledError
+ if isinstance(stream, TeamRunOutput) and stream.status != "ERROR" and stream.content:
+ chunk_count += 1
+ yield str(stream.content)
except asyncio.CancelledError:
logger.info("生成任务被取消: session_id={}", session_id)
raise
diff --git a/backend/app/utils/ai_factory.py b/backend/app/utils/ai_factory.py
index 34b93857d..4bdced85f 100644
--- a/backend/app/utils/ai_factory.py
+++ b/backend/app/utils/ai_factory.py
@@ -1,8 +1,10 @@
+from inspect import getdoc
from typing import Any
from agno.agent import Agent
from agno.models.openai.like import OpenAILike
from agno.team import Team
+from agno.utils.team import get_member_id
from app.config.setting import settings
@@ -28,7 +30,7 @@ def create_agent(
model_config: dict[str, Any] | None = None,
tools: list[Any] | None = None,
) -> Team:
- """创建带 Agent 的 Team 实例。
+ """创建 Team,仅在提供工具时加入成员 Agent。
参数:
- user_id (str): 用户标识。
@@ -55,32 +57,49 @@ def create_agent(
if isinstance(model_config.get("temperature"), (int, float)):
temperature = float(model_config["temperature"])
- # 创建 Agent
- fastapiadmin_agent = Agent(
- id=user_id,
- name="fastapiadmin_agent",
- role="You are a helpful AI assistant",
- description=self.AGENT_DESCRIPTION,
- tools=list(tools or []),
+ model = OpenAILike(
+ id=model_id,
+ api_key=api_key,
+ base_url=base_url,
+ temperature=temperature,
+ timeout=self.REQUEST_TIMEOUT,
)
+ members: list[Agent | Team] = []
+ instructions = list(self.AGENT_INSTRUCTIONS)
+ if tools:
+ fastapiadmin_agent = Agent(
+ model=model,
+ id=user_id,
+ name="fastapiadmin_agent",
+ role="You are a helpful AI assistant",
+ description=self.AGENT_DESCRIPTION,
+ tools=list(tools),
+ )
+ members.append(fastapiadmin_agent)
+ tool_descriptions = []
+ for tool in tools:
+ name = getattr(tool, "__name__", None)
+ description = getdoc(tool)
+ if name and description:
+ tool_descriptions.append(f"{name}:{description}")
+ if tool_descriptions:
+ # 使用 Agno 委派时匹配的 ID,它可能与用户名或成员名称不同。
+ member_id = get_member_id(fastapiadmin_agent)
+ instructions.append(f"委派工具的 member_id 参数使用成员实际 ID {member_id}。")
+ instructions.append(f"成员 {member_id} 可使用的只读工具:\n" + "\n".join(tool_descriptions))
# 创建 Team
fastapiadmin_team = Team(
id=team_id,
user_id=user_id,
session_id=session_id,
- model=OpenAILike(
- id=model_id,
- api_key=api_key,
- base_url=base_url,
- temperature=temperature,
- timeout=self.REQUEST_TIMEOUT,
- ),
- members=[fastapiadmin_agent],
- instructions=self.AGENT_INSTRUCTIONS,
+ model=model,
+ members=members,
+ instructions=instructions,
expected_output=self.AGENT_EXPECTED_OUTPUT,
add_datetime_to_context=True,
add_history_to_context=True,
+ add_member_tools_to_context=bool(tools),
markdown=True,
num_history_runs=self.NUM_HISTORY_RUNS,
input_schema=None,
diff --git a/backend/tests/test_ai_chat_helpers.py b/backend/tests/test_ai_chat_helpers.py
index ef560054d..da824f892 100644
--- a/backend/tests/test_ai_chat_helpers.py
+++ b/backend/tests/test_ai_chat_helpers.py
@@ -5,6 +5,9 @@
from types import SimpleNamespace
import pytest
+from agno.run.team import RunContentCompletedEvent as TeamRunContentCompletedEvent
+from agno.run.team import RunContentEvent as TeamRunContentEvent
+from agno.run.team import TeamRunOutput
from app.core.exceptions import CustomException
from app.modules.ai.chat.service import AiModelConfigService, ChatService
@@ -182,9 +185,10 @@ def svc(stream):
assert await _collect(svc(None).chat_query(ChatQuerySchema(message=" "))) == ["请输入消息内容"]
async def chunks():
for c in ("a","b"):
- yield SimpleNamespace(content=c)
+ yield TeamRunContentEvent(content=c)
+ yield TeamRunContentCompletedEvent()
assert await _collect(svc(chunks()).chat_query(ChatQuerySchema(message="hi"))) == ["a","b"]
- assert await _collect(svc(SimpleNamespace(content="z")).chat_query(ChatQuerySchema(message="hi"))) == ["z"]
+ assert await _collect(svc(TeamRunOutput(content="z")).chat_query(ChatQuerySchema(message="hi"))) == ["z"]
async def bad():
raise RuntimeError()
yield
diff --git a/backend/tests/test_ai_readonly_tools.py b/backend/tests/test_ai_readonly_tools.py
index f47f0c52b..896b3e4bd 100644
--- a/backend/tests/test_ai_readonly_tools.py
+++ b/backend/tests/test_ai_readonly_tools.py
@@ -7,13 +7,20 @@
"""
import inspect
+import json
from types import SimpleNamespace
from typing import Any
+import httpx
import pytest
+from agno.models.openai.like import OpenAILike
+from openai import AsyncOpenAI
+from starlette.websockets import WebSocket
from app.core.exceptions import CustomException
from app.modules.ai import tools as ai_tools_pkg
+from app.modules.ai.chat import controller as chat_controller
+from app.modules.ai.chat import service as chat_service_module
from app.modules.ai.chat.service import ChatService
from app.modules.ai.tools import registry as registry_module
from app.modules.ai.tools.registry import build_readonly_tools
@@ -177,6 +184,122 @@ def test_chat_service_tools_switch_off_keeps_behavior() -> None:
assert all(callable(item) for item in enabled)
+@pytest.mark.parametrize("use_tools", [True, False])
+async def test_chat_delegation_uses_tool_context_only_when_enabled(
+ monkeypatch: pytest.MonkeyPatch, use_tools: bool,
+) -> None:
+ contexts = []
+ model_tools = []
+ monitor_calls = 0
+
+ async def fake_monitor() -> SimpleNamespace:
+ nonlocal monitor_calls
+ monitor_calls += 1
+ return SimpleNamespace(
+ cpu=SimpleNamespace(model_dump=lambda: {"cpu_num": 8}),
+ mem=SimpleNamespace(model_dump=lambda: {"usage": 62.5}),
+ disks=[SimpleNamespace(model_dump=lambda: {"dir_name": "/", "usage": 68.0})],
+ )
+
+ def model_response(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content)
+ messages = body["messages"]
+ tools = {tool["function"]["name"] for tool in body.get("tools", [])}
+ model_tools.append(tools)
+ results = [message["content"] for message in messages if message["role"] == "tool"]
+ delta: dict[str, Any] = {"role": "assistant"}
+ extra_text = []
+ tool = None
+ if not use_tools:
+ contexts.append(messages[0]["content"])
+ delta["content"] = "当前对话未启用监控工具"
+ elif "delegate_task_to_member" in tools and not results:
+ contexts.append(messages[0]["content"])
+ delta["content"] = "Team 将任务委派给成员"
+ tool = ("delegate_task_to_member", {"member_id": "verify-user", "task": "调用 server_status"})
+ elif "server_status" in tools and not results:
+ delta["content"] = "Agent 正在查询"
+ tool = ("server_status", {})
+ elif "server_status" in tools:
+ assert "62.5" in results[-1] and "68.0" in results[-1]
+ delta["content"] = "Agent 已取得监控数据 62.5%"
+ else:
+ assert "62.5" in results[-1]
+ delta["content"] = "内存 62.5%"
+ extra_text = [",磁盘 68%"]
+
+ if tool:
+ name, arguments = tool
+ delta["tool_calls"] = [{
+ "index": 0, "id": f"call_{name}", "type": "function",
+ "function": {"name": name, "arguments": json.dumps(arguments)},
+ }]
+ chunk = {"id": "fixture", "object": "chat.completion.chunk", "created": 1, "model": "fixture"}
+ events = [
+ {**chunk, "choices": [{"index": 0, "delta": delta, "finish_reason": None}]},
+ *[
+ {**chunk, "choices": [{"index": 0, "delta": {"content": text}, "finish_reason": None}]}
+ for text in extra_text
+ ],
+ {**chunk, "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls" if tool else "stop"}]},
+ ]
+ data = "".join(f"data: {json.dumps(event)}\n\n" for event in events)
+ return httpx.Response(200, headers={"Content-Type": "text/event-stream"}, text=data + "data: [DONE]\n\n")
+
+ monkeypatch.setattr(registry_module.ServerService, "get_server_monitor_info", fake_monitor)
+ monkeypatch.setattr(chat_service_module, "ChatSessionCRUD", lambda auth: SimpleNamespace(db=None))
+ config = {"base_url": "https://model.invalid/v1", "api_key": "fixture", "model_id": "fixture"}
+ auth = SimpleNamespace(user=SimpleNamespace(id=1, username="verify_user", is_superuser=True))
+
+ async def authenticate(websocket: WebSocket) -> tuple[SimpleNamespace, None]:
+ return auth, None
+
+ async def get_model_config(redis: Any, user_id: int) -> dict[str, str]:
+ return config
+
+ monkeypatch.setattr(chat_controller, "websocket_authenticate", authenticate)
+ monkeypatch.setattr(chat_controller, "get_user_model_config", get_model_config)
+ query = {"message": "现在服务器的内存和磁盘使用率是多少?", "session_id": "fixture", "use_tools": use_tools}
+ incoming = iter([
+ {"type": "websocket.connect"},
+ {"type": "websocket.receive", "text": json.dumps(query)},
+ {"type": "websocket.disconnect", "code": 1000},
+ ])
+ frames = []
+
+ async def receive() -> dict[str, Any]:
+ return next(incoming)
+
+ async def send(message: dict[str, Any]) -> None:
+ if message["type"] == "websocket.send":
+ frames.append(message["text"])
+
+ websocket = WebSocket(
+ {"type": "websocket", "app": SimpleNamespace(state=SimpleNamespace(redis=None)), "client": None},
+ receive=receive,
+ send=send,
+ )
+ async with httpx.AsyncClient(transport=httpx.MockTransport(model_response)) as http:
+ client = AsyncOpenAI(base_url=config["base_url"], api_key=config["api_key"], http_client=http)
+ monkeypatch.setattr(OpenAILike, "get_async_client", lambda self: client)
+ await chat_controller.websocket_chat_controller(websocket)
+
+ assert len(contexts) == 1
+ if use_tools:
+ assert 'member id="verify-user"' in contexts[0]
+ assert "member_id" in contexts[0] and "verify-user" in contexts[0]
+ assert "server_status" in contexts[0] and "查询服务器资源状态" in contexts[0]
+ assert "redis_keys" in contexts[0] and "只返回键名" in contexts[0]
+ assert monitor_calls == 1
+ assert frames == ["内存 62.5%", ",磁盘 68%", "[DONE]"]
+ else:
+ assert model_tools == [{"get_chat_history"}]
+ assert "server_status" not in contexts[0] and "redis_keys" not in contexts[0]
+ assert "member_id" not in contexts[0]
+ assert monitor_calls == 0
+ assert frames == ["当前对话未启用监控工具", "[DONE]"]
+
+
def test_ai_tools_router_exposes_tools_listing() -> None:
from app.modules.ai.chat.controller import ChatRouter
diff --git a/backend/tests/test_security_utils_coverage.py b/backend/tests/test_security_utils_coverage.py
index 9a3e54a6a..a9d0f842a 100644
--- a/backend/tests/test_security_utils_coverage.py
+++ b/backend/tests/test_security_utils_coverage.py
@@ -54,7 +54,8 @@ def __init__(self, **kwargs):
monkeypatch.setattr(ai_factory, "OpenAILike", FakeModel)
factory = ai_factory.AgnoFactory()
factory.create_agent("u1", "t1", "s1")
- assert captured["agent"]["id"] == "u1"
+ assert "agent" not in captured
+ assert captured["team"]["members"] == []
assert captured["team"]["id"] == "t1"
assert captured["model"]["temperature"] == factory.AGENT_TEMPERATURE
@@ -66,5 +67,13 @@ def __init__(self, **kwargs):
model_config={"base_url": "http://x", "api_key": "k", "model_id": "m", "temperature": 0.2},
tools=[lambda: None],
)
- assert captured["model"] == {"id": "m", "api_key": "k", "base_url": "http://x", "temperature": 0.2, "timeout": factory.REQUEST_TIMEOUT}
+ assert captured["model"] == {
+ "id": "m",
+ "api_key": "k",
+ "base_url": "http://x",
+ "temperature": 0.2,
+ "timeout": factory.REQUEST_TIMEOUT,
+ }
+ assert captured["agent"]["id"] == "u2"
+ assert captured["agent"]["model"] is captured["team"]["model"]
assert len(captured["agent"]["tools"]) == 1
diff --git a/frontend/web/src/views/module_ai/chat/components/FaChatInput.vue b/frontend/web/src/views/module_ai/chat/components/FaChatInput.vue
index 900644c65..0e03e5485 100644
--- a/frontend/web/src/views/module_ai/chat/components/FaChatInput.vue
+++ b/frontend/web/src/views/module_ai/chat/components/FaChatInput.vue
@@ -76,6 +76,13 @@
+