增加智能体
This commit is contained in:
1 parent
39def1c20b
commit
37bd8c6591
10 files changed
+600
-90
No files matched your search
@@ -1,4 +1,5 @@
|
||||
from .clarification_tool import ask_clarification_tool
|
||||
from .fast_chat_tool import fast_chat_tool, fast_llm_answer
|
||||
from .present_file_tool import present_file_tool
|
||||
from .scheduled_task_tool import scheduled_task_tool
|
||||
from .setup_agent_tool import setup_agent
|
||||
@@ -12,4 +13,6 @@ __all__ = [
|
||||
"scheduled_task_tool",
|
||||
"view_image_tool",
|
||||
"task_tool",
|
||||
"fast_chat_tool",
|
||||
"fast_llm_answer",
|
||||
]
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
"""Fast chat tool - call new_chat API for fast Q&A mode."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Annotated, Any
|
||||
|
||||
from langchain.tools import InjectedToolCallId, ToolRuntime, tool
|
||||
from langchain_core.messages import HumanMessage
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
from langgraph.typing import ContextT
|
||||
|
||||
from deerflow.agents.thread_state import ThreadState
|
||||
from deerflow.config.app_config import get_app_config
|
||||
from deerflow.models import create_chat_model
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _get_runtime_value(runtime: ToolRuntime[ContextT, ThreadState], key: str, default: Any = None) -> Any:
|
||||
"""Get value from runtime context or config."""
|
||||
if runtime.context and isinstance(runtime.context, dict):
|
||||
value = runtime.context.get(key)
|
||||
if value is not None:
|
||||
return value
|
||||
|
||||
runtime_config = getattr(runtime, "config", None) or {}
|
||||
configurable = runtime_config.get("configurable", {})
|
||||
if isinstance(configurable, dict):
|
||||
value = configurable.get(key)
|
||||
if value is not None:
|
||||
return value
|
||||
|
||||
return default
|
||||
|
||||
|
||||
@tool("fast_chat", parse_docstring=True, return_direct=True)
|
||||
async def fast_chat_tool(
|
||||
runtime: ToolRuntime[ContextT, ThreadState],
|
||||
prompt: str,
|
||||
tool_call_id: Annotated[str, InjectedToolCallId],
|
||||
search_space_id: int | None = None,
|
||||
mentioned_document_ids: list[int] | None = None,
|
||||
pic_query: list[dict[str, Any]] | None = None,
|
||||
model_name: str | None = None,
|
||||
) -> str:
|
||||
"""Fast chat tool - 快速问答模式调用后端聊天接口.
|
||||
|
||||
用于 fast 子 Agent 直接调用后端 new_chat 接口进行快速问答.
|
||||
|
||||
Args:
|
||||
runtime: 运行时上下文,自动注入.
|
||||
prompt: 用户问题内容.
|
||||
tool_call_id: 工具调用 ID,自动注入.
|
||||
search_space_id: 搜索空间 ID (可选,从 context.subagent_search_space_id 获取).
|
||||
mentioned_document_ids: 引用的文档 ID 列表 (可选).
|
||||
pic_query: 图片查询列表 (可选).
|
||||
model_name: 使用的模型名称 (默认使用 context.subagent_model_name 或 OpenAI3).
|
||||
|
||||
Returns:
|
||||
API 响应结果的 JSON 字符串.
|
||||
"""
|
||||
import asyncio
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
# 从 context 读取参数,支持外部传入或运行时获取
|
||||
thread_id = _get_runtime_value(runtime, "thread_id")
|
||||
if thread_id is None:
|
||||
return json.dumps({"error": "thread_id not found in context", "passed": False})
|
||||
|
||||
# 参数优先级:显式传入 > context 注入
|
||||
effective_search_space_id = search_space_id if search_space_id is not None else _get_runtime_value(runtime, "subagent_search_space_id")
|
||||
effective_model_name = model_name or _get_runtime_value(runtime, "subagent_model_name", "OpenAI3")
|
||||
effective_mentioned_ids = mentioned_document_ids or _get_runtime_value(runtime, "subagent_mentioned_document_ids") or []
|
||||
effective_pic_query = pic_query or _get_runtime_value(runtime, "subagent_pic_query") or []
|
||||
|
||||
app_config = get_app_config()
|
||||
backend_url = getattr(app_config, "backend_url", "http://localhost:8001")
|
||||
|
||||
messages = [{"role": "user", "content": prompt}]
|
||||
|
||||
req_body = {
|
||||
"chat_id": thread_id,
|
||||
"user_query": prompt,
|
||||
"search_space_id": effective_search_space_id,
|
||||
"messages": messages,
|
||||
"mentioned_document_ids": effective_mentioned_ids,
|
||||
"pic_query": effective_pic_query,
|
||||
"model_name": effective_model_name,
|
||||
}
|
||||
|
||||
req_url = f"{backend_url}/api/v1/new_chat"
|
||||
|
||||
def _make_request():
|
||||
data = json.dumps(req_body).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
req_url,
|
||||
data=data,
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=30) as response:
|
||||
return response.read().decode("utf-8")
|
||||
|
||||
result = await asyncio.to_thread(_make_request)
|
||||
return result
|
||||
|
||||
except urllib.error.HTTPError as exc:
|
||||
logger.warning(f"Fast chat API HTTP error: {exc.code} {exc.reason}")
|
||||
return json.dumps({"error": f"HTTP {exc.code}: {exc.reason}", "passed": False})
|
||||
except Exception as exc:
|
||||
logger.warning(f"Fast chat API failed: {exc}")
|
||||
return json.dumps({"error": str(exc), "passed": False})
|
||||
|
||||
|
||||
@tool("fast_llm_answer", parse_docstring=True, return_direct=True)
|
||||
def fast_llm_answer(prompt: str) -> str:
|
||||
"""Fast LLM answer tool - 使用 LLM 直接回答简单问题.
|
||||
|
||||
当 fast 模式不需要调用外部 API 时,直接使用 LLM 回答简单事实查询.
|
||||
|
||||
Args:
|
||||
prompt: 用户问题.
|
||||
|
||||
Returns:
|
||||
LLM 回答内容.
|
||||
"""
|
||||
try:
|
||||
app_config = get_app_config()
|
||||
model_name = app_config.models[0].name if app_config.models else None
|
||||
model = create_chat_model(name=model_name, thinking_enabled=False, app_config=app_config)
|
||||
|
||||
response = model.invoke([HumanMessage(content=prompt)], config=RunnableConfig())
|
||||
content = response.content if hasattr(response, "content") else str(response)
|
||||
return content
|
||||
|
||||
except Exception as exc:
|
||||
logger.warning(f"Fast LLM answer failed: {exc}")
|
||||
return f"抱歉,处理您的问题时出现错误: {str(exc)}"
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
"""Router quality check tool — validates sub-agent output completeness."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
from langchain_core.messages import HumanMessage
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
from langchain_core.tools import tool
|
||||
|
||||
from deerflow.config.app_config import get_app_config
|
||||
from deerflow.models import create_chat_model
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
QUALITY_CHECK_PROMPT = """你是一个质检员。上游子 Agent 已根据问题执行完毕。
|
||||
请判断以下结果是否完整覆盖了用户问题的所有子问题。
|
||||
|
||||
用户原始问题:{original_question}
|
||||
|
||||
子 Agent 执行结果:
|
||||
{agent_output}
|
||||
|
||||
请只返回 JSON 格式:
|
||||
{{
|
||||
"passed": true/false,
|
||||
"reason": "判断理由(10字内)",
|
||||
"missing_parts": ["缺失的子问题1", "缺失的子问题2"] // 如果 passed=false
|
||||
}}"""
|
||||
|
||||
|
||||
@tool("router_quality_check", parse_docstring=True, return_direct=True)
|
||||
def router_quality_check(original_question: str, agent_output: str) -> str:
|
||||
"""质检工具 — 判断子 Agent 输出是否完整覆盖用户问题。
|
||||
|
||||
路由器在子 Agent 执行完毕后调用此工具进行完整性质检。
|
||||
质检通过则流式输出到前端,不通过则重新匹配模式并再次执行。
|
||||
|
||||
Args:
|
||||
original_question: 用户原始问题。
|
||||
agent_output: 子 Agent 的执行结果。
|
||||
|
||||
Returns:
|
||||
JSON 格式的质检结果:{{"passed": bool, "reason": str, "missing_parts": list[str]}}
|
||||
"""
|
||||
try:
|
||||
app_config = get_app_config()
|
||||
model_name = app_config.models[0].name if app_config.models else None
|
||||
model = create_chat_model(name=model_name, thinking_enabled=False, app_config=app_config)
|
||||
|
||||
prompt = QUALITY_CHECK_PROMPT.format(
|
||||
original_question=original_question,
|
||||
agent_output=agent_output,
|
||||
)
|
||||
|
||||
response = model.invoke([HumanMessage(content=prompt)], config=RunnableConfig())
|
||||
content = response.content if hasattr(response, "content") else str(response)
|
||||
|
||||
# Try to parse JSON from the response
|
||||
# The model might wrap it in ```json or just return raw JSON
|
||||
json_str = content.strip()
|
||||
if json_str.startswith("```json"):
|
||||
json_str = json_str[7:]
|
||||
if json_str.startswith("```"):
|
||||
json_str = json_str[3:]
|
||||
if json_str.endswith("```"):
|
||||
json_str = json_str[:-3]
|
||||
json_str = json_str.strip()
|
||||
|
||||
result = json.loads(json_str)
|
||||
return json.dumps(result, ensure_ascii=False)
|
||||
|
||||
except Exception as exc:
|
||||
logger.warning(f"Router quality check failed: {exc}")
|
||||
# Fallback: pass with unknown reason on error
|
||||
return json.dumps({"passed": True, "reason": "质检异常默认通过", "missing_parts": []})
|
||||
@@ -6,7 +6,7 @@ from deerflow.config import get_app_config
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.reflection import resolve_variable
|
||||
from deerflow.sandbox.security import is_host_bash_allowed
|
||||
from deerflow.tools.builtins import ask_clarification_tool, present_file_tool, scheduled_task_tool, task_tool, view_image_tool
|
||||
from deerflow.tools.builtins import ask_clarification_tool, fast_chat_tool, fast_llm_answer, present_file_tool, scheduled_task_tool, task_tool, view_image_tool
|
||||
from deerflow.tools.builtins.tool_search import reset_deferred_registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -14,6 +14,8 @@ logger = logging.getLogger(__name__)
|
||||
BUILTIN_TOOLS = [
|
||||
present_file_tool,
|
||||
ask_clarification_tool,
|
||||
fast_chat_tool,
|
||||
fast_llm_answer,
|
||||
]
|
||||
|
||||
SUBAGENT_TOOLS = [
|
||||
|
||||
Reference in new issue
Block a user