2025-08-31 00:34:26 +08:00
|
|
|
from pathlib import Path
|
|
|
|
|
|
2025-10-25 20:01:23 +08:00
|
|
|
from langchain.agents import create_agent
|
|
|
|
|
from langchain.agents.middleware import ModelRequest, ModelResponse, dynamic_prompt, wrap_model_call
|
2025-08-31 00:34:26 +08:00
|
|
|
|
|
|
|
|
from src.agents.common.base import BaseAgent
|
|
|
|
|
from src.agents.common.models import load_chat_model
|
|
|
|
|
from src.agents.common.tools import get_buildin_tools
|
2025-09-01 22:37:03 +08:00
|
|
|
from src.utils import logger
|
2025-08-31 00:34:26 +08:00
|
|
|
|
2025-09-01 22:37:03 +08:00
|
|
|
|
2025-10-25 20:01:23 +08:00
|
|
|
@dynamic_prompt
|
|
|
|
|
def context_aware_prompt(request: ModelRequest) -> str:
|
|
|
|
|
runtime = request.runtime
|
|
|
|
|
return runtime.context.system_prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@wrap_model_call
|
|
|
|
|
async def context_based_model(request: ModelRequest, handler) -> ModelResponse:
|
|
|
|
|
# 从 runtime context 读取配置
|
|
|
|
|
model_spec = request.runtime.context.model
|
|
|
|
|
model = load_chat_model(model_spec)
|
|
|
|
|
|
|
|
|
|
request = request.override(model=model)
|
|
|
|
|
return await handler(request)
|
2025-03-29 19:13:56 +08:00
|
|
|
|
2025-09-01 22:37:03 +08:00
|
|
|
|
2025-03-29 19:13:56 +08:00
|
|
|
class ReActAgent(BaseAgent):
|
2025-10-25 20:01:23 +08:00
|
|
|
name = "智能体 Demo"
|
2025-03-29 19:13:56 +08:00
|
|
|
description = "A react agent that can answer questions and help with tasks."
|
|
|
|
|
|
2025-08-31 00:34:26 +08:00
|
|
|
def __init__(self, **kwargs):
|
|
|
|
|
super().__init__(**kwargs)
|
|
|
|
|
|
2025-10-25 20:01:23 +08:00
|
|
|
def get_tools(self):
|
|
|
|
|
return get_buildin_tools()
|
|
|
|
|
|
2025-05-20 22:21:51 +08:00
|
|
|
async def get_graph(self, **kwargs):
|
2025-08-31 00:34:26 +08:00
|
|
|
if self.graph:
|
|
|
|
|
return self.graph
|
|
|
|
|
|
2025-10-12 23:45:17 +08:00
|
|
|
# 创建 ReActAgent
|
2025-10-25 20:01:23 +08:00
|
|
|
graph = create_agent(
|
2025-10-25 22:49:20 +08:00
|
|
|
model=load_chat_model("siliconflow/Qwen/Qwen3-235B-A22B-Instruct-2507"), # 实际会被覆盖
|
2025-10-25 20:01:23 +08:00
|
|
|
tools=self.get_tools(),
|
|
|
|
|
middleware=[context_aware_prompt, context_based_model],
|
|
|
|
|
checkpointer=await self._get_checkpointer(),
|
|
|
|
|
)
|
|
|
|
|
|
2025-08-31 00:34:26 +08:00
|
|
|
self.graph = graph
|
2025-07-26 03:36:54 +08:00
|
|
|
return graph
|