2025-08-31 00:34:26 +08:00
|
|
|
from pathlib import Path
|
|
|
|
|
|
2025-09-01 22:37:03 +08:00
|
|
|
from langchain_core.messages import AnyMessage, SystemMessage
|
2025-08-31 00:34:26 +08:00
|
|
|
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver, aiosqlite
|
|
|
|
|
from langgraph.prebuilt import create_react_agent
|
|
|
|
|
from langgraph.runtime import get_runtime
|
|
|
|
|
|
|
|
|
|
from src import config as sys_config
|
|
|
|
|
from src.agents.common.base import BaseAgent
|
2025-09-01 22:37:03 +08:00
|
|
|
from src.agents.common.context import BaseContext
|
2025-08-31 00:34:26 +08:00
|
|
|
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
|
|
|
|
|
|
|
|
model = load_chat_model("siliconflow/Qwen/Qwen3-235B-A22B-Instruct-2507")
|
|
|
|
|
|
2025-09-01 22:37:03 +08:00
|
|
|
|
2025-08-31 00:34:26 +08:00
|
|
|
def prompt(state) -> list[AnyMessage]:
|
|
|
|
|
runtime = get_runtime(BaseContext)
|
|
|
|
|
system_msg = SystemMessage(content=runtime.context.system_prompt)
|
|
|
|
|
return [system_msg] + state["messages"]
|
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-08-31 00:34:26 +08:00
|
|
|
name = "ReAct (all tools)"
|
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)
|
|
|
|
|
self.graph = None
|
|
|
|
|
self.workdir = Path(sys_config.save_dir) / "agents" / self.module_name
|
|
|
|
|
self.workdir.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
available_tools = get_buildin_tools()
|
|
|
|
|
|
|
|
|
|
sqlite_checkpointer = AsyncSqliteSaver(await aiosqlite.connect(self.workdir / "react_history.db"))
|
2025-09-01 22:37:03 +08:00
|
|
|
graph = create_react_agent(model, tools=available_tools, checkpointer=sqlite_checkpointer, prompt=prompt)
|
2025-08-31 00:34:26 +08:00
|
|
|
self.graph = graph
|
|
|
|
|
logger.info("ReActAgent使用SQLite checkpointer构建成功")
|
2025-07-26 03:36:54 +08:00
|
|
|
return graph
|