Commit 3a0716c1 by sunqi02 Committed by 胡悦

feat: 添加描述字段到 AgentConfig,更新相关逻辑以支持新字段

1 parent 23044088
......@@ -120,6 +120,12 @@ async def chat(
if allowed_agent_codes is not None and MOUTH_AGENT_CODE not in allowed_agent_codes:
if MOUTH_AGENT_CODE in agent_hub.agents:
allowed_agent_codes.append(MOUTH_AGENT_CODE)
# 发言人使用主Agent的bot_id发送消息
if MOUTH_AGENT_CODE not in bot_id_mapping:
steward_key = agent_hub._find_steward_key()
steward_bot_id = bot_id_mapping.get(steward_key)
if steward_bot_id:
bot_id_mapping[MOUTH_AGENT_CODE] = steward_bot_id
# 4. 追加消息到 buffer(在 BackgroundTask 之外,确保锁外追加)
from app.service.session_buffer import SessionBuffer
......
......@@ -54,7 +54,8 @@ class ConfigLoader:
result[key] = AgentConfig(
name=row.name,
code=str(row.id),
prompt=row.description or "",
prompt=row.prompt or row.description or "",
description=row.description or "",
skills=skills,
is_steward=row.is_steward,
)
......
......@@ -13,6 +13,7 @@ class AgentConfig(BaseModel):
name: str
code: str
prompt: str
description: str = "" # 子Agent职责简述,供主Agent调度时了解子Agent能力边界
is_steward: bool = False
skills: List[str] = []
......
......@@ -11,13 +11,14 @@
| `message_gate.py` | `MessageGate` | **消息门控层** — 激活识别(chat/pass) |
封装流程:
1. `evaluate()` 获取 session 锁,等待非 text 消息的补充窗口(默认 6s)
2. 检查 running task(已有则跳过,防重复处理)
1. `evaluate()` 锁外检查 `_running_tasks`(有在途任务则走 busy 分支,不排队)
2. 获取 session 锁(`_get_lock` 按 session 串行化),等待非 text 消息的补充窗口(默认 6s)
3. `_classify_and_rewrite()` 调 LLM 做二元激活识别(chat vs pass),无历史上下文,只看当前消息
4. 根据 intent 分支:
- `chat` → `_handle_chat()` 只追加用户消息到 conversation_history,不触发 AgentHub,不发 IM("已读不回")
- `pass` → `_handle_actionable()` 提取 query/file_url,调用 `AgentHub.process_message()`
5. `_get_lock(session_id)` 按 session 串行化,防止并发竞争
5. 在途任务忙碌:`busy` → `_handle_busy()` 保存用户消息到 history,发固定告知回复(`BUSY_REPLY`),不排队
6. `_running_tasks[session_id] = asyncio.current_task()` 标记在途,`finally` 清理
| 文件 | 类 | 职责 |
|------|----|------|
......@@ -138,9 +139,14 @@ BackgroundTasks.add_task() ← 异步后台处理,HTTP 立即返回 200
▼
MessageGate.evaluate() ← app/service/message_gate.py
│
├── 检查 _running_tasks(锁外,有在途任务则立即返回)
│ └── busy → _handle_busy()
│ 保存用户消息到 history → save_to_db()
│ 发固定告知回复(BUSY_REPLY)→ IM 发送
│ 不排队,不触发 AgentHub
│
├── 获取 session 锁(按 session_id 串行化)
├── 等待非 text 消息补充窗口(默认 6s)
├── 检查 running task(已有则跳过)
├── _classify_and_rewrite() → LLM 二元激活识别(chat/pass)
│
├── intent=chat → _handle_chat()
......
......@@ -4,6 +4,7 @@ from functools import partial
from pathlib import Path
from typing import Dict, List, Optional, Any
from app.config.loader import ConfigLoader
from app.config.settings import AgentConfig
from app.service.active_session_service import ActiveSessionService
from agentscope.tool import Toolkit
from app.hooks.post_reply import PostReplyHook
......@@ -23,21 +24,6 @@ logger = logging.getLogger(__name__)
# sub_agent 专用低 temperature:调用子 Agent 处理确定性任务时使用更稳定的输出
SUB_AGENT_TEMPERATURE = 0.2
DISPATCH_GUIDE = """
## 调度规则
1. 分析用户意图,判断是否在你的能力范围内(追问、澄清、简单对话等),可以直接回复
2. 复杂任务拆解为子任务步骤,按顺序调用子Agent(通过 call_sub_agent 工具),每次一个
3. 所有子Agent 执行完毕后,必须调用"发言人"Agent(调用码: -1)总结回复
4. 不要再调用同一个子Agent重复处理同一任务
"""
THINKING_GUIDE = """
## 思考风格
- reasoning 阶段的思考文字 ≤20 字
- 行动时直接输出 tool_call,不要附加解释
- 需要详细推理时在 tool result 里总结
"""
async def _im_post_reasoning_hook(
......@@ -129,6 +115,18 @@ class AgentHub:
raise AgentHubError("preloaded_agents is required — load from DB via ConfigLoader.load_agents_from_db()")
self.agents: Dict[str, Any] = preloaded_agents
# 发言人(口)Agent:框架级固定构件,不依赖数据库
self.agents["-1"] = AgentConfig(
name="发言人",
code="-1",
prompt=(
"你是发言人,负责将各子Agent的处理结果汇总为自然流畅、用户友好的回复。"
"不要重复执行子Agent的任务,只做总结和润色。"
),
description="汇总子Agent处理结果,生成统一回复",
is_steward=False,
)
self.main_model_config = config_loader.load_models()["main"]
self.post_reply_hook = PostReplyHook(im_service=im_service)
......@@ -319,7 +317,10 @@ class AgentHub:
When allowed_agent_codes is set, only agents in that list are advertised.
"""
steward = self._find_steward_agent()
prompt = steward.prompt # 完整文本,直接使用
prompt = steward.prompt # 角色定义
if steward.description:
prompt += "\n\n" + steward.description # 调度规则
# Collect duties from sub-agents, filtered by position if applicable
sub_lines = []
......@@ -328,12 +329,13 @@ class AgentHub:
continue
if allowed_agent_codes is not None and code not in allowed_agent_codes:
continue
sub_lines.append(f"- {agent.name}(调用码: {code}): {agent.name}相关任务")
duty = agent.description or f"{agent.name}相关任务"
sub_lines.append(f"- {agent.name}(调用码: {code}): {duty}")
if sub_lines:
prompt += "\n\n## 可调用的子Agent\n" + "\n".join(sub_lines)
return prompt + self.soul_guide + DISPATCH_GUIDE + THINKING_GUIDE
return prompt + self.soul_guide
def _build_sub_agent_prompt(self, agent_code: str) -> str:
"""Build prompt for a sub-agent when handling a routed query."""
......@@ -341,7 +343,7 @@ class AgentHub:
if not agent:
raise AgentHubError(f"Agent {agent_code} 配置未找到")
return agent.prompt + self.soul_guide + THINKING_GUIDE # sub 加回复风格+思考约束
return agent.prompt + self.soul_guide
def _dict_to_msg(self, m: dict) -> Msg:
"""SessionStore dict → AgentScope Msg。只处理 user/assistant 文本消息。"""
......
......@@ -23,12 +23,14 @@ def _make_test_agents():
name="管家 Agent",
code="11",
prompt="你是智能助手,负责协调各个岗位Agent协作回答用户问题。",
description="协调调度各子Agent,分析用户意图并分发任务",
is_steward=True,
),
MEETING_KEY: AgentConfig(
name="会议Agent",
code="17",
prompt="你是会议纪要助手,职责包括处理会议纪要相关的任务。",
description="会议录音转写、会议纪要生成与导出",
skills=["meeting_minutes"],
is_steward=False,
),
......@@ -804,27 +806,28 @@ async def test_call_sub_agent_uses_sub_model():
assert captured_model is not hub.model
# ── Tests for THINKING_GUIDE injection ──
# ── Tests for prompt assembly (hardcoded guides removed, now in DB prompt) ──
def test_main_prompt_includes_thinking_guide():
"""_build_main_prompt 输出应包含 THINKING_GUIDE。"""
def test_main_prompt_no_hardcoded_guides():
"""_build_main_prompt 不应包含硬编码的 DISPATCH_GUIDE 和 THINKING_GUIDE。"""
hub = _make_test_hub()
prompt = hub._build_main_prompt()
assert "思考" in prompt
assert "20" in prompt
# main 独有:DISPATCH_GUIDE 应在
assert "调度规则" in prompt
assert "调度规则" not in prompt
assert "思考风格" not in prompt
# 但不影响 steward.prompt 和 soul_guide 的正常拼接
assert "你是智能助手" in prompt
assert "说人话" in prompt
def test_sub_agent_prompt_includes_thinking_guide_only():
"""_build_sub_agent_prompt 应只拼 THINKING_GUIDE,不含 DISPATCH_GUIDE。"""
def test_sub_agent_prompt_no_hardcoded_guides():
"""_build_sub_agent_prompt 不应包含硬编码的 DISPATCH_GUIDE 和 THINKING_GUIDE。"""
hub = _make_test_hub()
prompt = hub._build_sub_agent_prompt(MEETING_KEY)
assert "思考" in prompt
assert "20" in prompt
# sub 不应有 DISPATCH_GUIDE
assert "调度规则" not in prompt
assert "思考风格" not in prompt
assert "你是会议纪要助手" in prompt
assert "说人话" in prompt
# ── Tests for soul_guide injection ──
......
......@@ -10,14 +10,16 @@ class TestLoadAgentsFromDb:
def _seed_agents(self, db_session):
steward = Agent(
name="管家 AGENT", code="agent_steward_001",
description="你是智能助手,负责协调各个岗位Agent协作回答用户问题。",
prompt="你是智能助手,负责协调各个岗位Agent协作回答用户问题。",
description="协调调度各子Agent,分析用户意图并分发任务",
is_steward=True, is_deleted=False,
)
db_session.add(steward)
db_session.flush()
sub = Agent(
name="会议Agent", code="agent_meeting_001",
description="你是会议纪要助手,负责处理会议纪要相关的任务。",
prompt="你是会议纪要助手,负责处理会议纪要相关的任务。",
description="会议录音转写、会议纪要生成与导出",
is_steward=False, is_deleted=False,
)
db_session.add(sub)
......@@ -65,10 +67,13 @@ class TestLoadAgentsFromDb:
steward = result["agent_steward_001"]
assert steward.name == "管家 AGENT"
assert steward.prompt == "你是智能助手,负责协调各个岗位Agent协作回答用户问题。"
assert steward.description == "协调调度各子Agent,分析用户意图并分发任务"
assert steward.is_steward is True
assert steward.skills == []
sub = result["agent_meeting_001"]
assert sub.name == "会议Agent"
assert sub.prompt == "你是会议纪要助手,负责处理会议纪要相关的任务。"
assert sub.description == "会议录音转写、会议纪要生成与导出"
assert sub.is_steward is False
assert sub.skills == ["meeting_minutes"]
self._clean_agents(db_session)
......
......@@ -10,7 +10,9 @@ def _make_test_agents():
return {
"steward_key": AgentConfig(
name="管家 Agent", code="11",
prompt="你是智能助手", is_steward=True,
prompt="你是智能助手",
description="协调调度各子Agent",
is_steward=True,
),
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!