ForcePilot/src/agents/chatbot/graph.py

87 lines
3.1 KiB
Python
Raw Normal View History

2025-03-24 23:00:14 +08:00
import asyncio
import uuid
from typing import Any
from datetime import datetime
2025-03-24 19:07:51 +08:00
from langchain_core.runnables import RunnableConfig
2025-03-24 23:00:14 +08:00
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.checkpoint.memory import MemorySaver
2025-03-29 17:33:09 +08:00
from langchain_community.tools.tavily_search import TavilySearchResults
2025-03-24 19:07:51 +08:00
from src.agents.registry import State, BaseAgent
2025-03-29 17:33:09 +08:00
from src.agents.utils import load_chat_model
2025-03-25 16:28:23 +08:00
from src.agents.chatbot.configuration import ChatbotConfiguration, multiply
2025-03-24 19:07:51 +08:00
class ChatbotAgent(BaseAgent):
2025-03-25 05:40:07 +08:00
name = "chatbot"
description = "A chatbot that can answer questions and help with tasks."
2025-03-24 23:00:14 +08:00
_graph_cache = None
2025-03-29 17:33:09 +08:00
config_schema = ChatbotConfiguration.to_dict()
2025-03-24 23:00:14 +08:00
2025-03-28 11:40:46 +08:00
def __init__(self, **kwargs):
super().__init__(**kwargs)
2025-03-25 05:40:07 +08:00
2025-03-28 11:40:46 +08:00
def _get_tools(self, config_schema: RunnableConfig):
2025-03-25 05:40:07 +08:00
"""根据配置获取工具"""
2025-03-29 17:33:09 +08:00
tools = [multiply, TavilySearchResults(max_results=10)]
2025-03-25 05:40:07 +08:00
return tools
2025-03-29 17:33:09 +08:00
def llm_call(self, state: State, config: RunnableConfig = None) -> dict[str, Any]:
"""调用 llm 模型"""
config_schema = config or {}
conf = ChatbotConfiguration.from_runnable_config(config_schema)
model = load_chat_model(conf.model)
model_with_tools = model.bind_tools(self._get_tools(config_schema))
2025-03-25 05:40:07 +08:00
2025-03-29 17:33:09 +08:00
res = model_with_tools.invoke(
[{"role": "system", "content": conf.system_prompt}, *state["messages"]]
)
2025-03-24 23:00:14 +08:00
return {"messages": [res]}
2025-03-28 11:40:46 +08:00
def get_graph(self, config_schema: RunnableConfig = None):
2025-03-24 23:00:14 +08:00
"""构建图"""
2025-03-29 17:33:09 +08:00
workflow = StateGraph(State, config_schema=ChatbotConfiguration)
2025-03-25 05:40:07 +08:00
workflow.add_node("chatbot", self.llm_call)
2025-03-28 11:40:46 +08:00
workflow.add_node("tools", ToolNode(tools=self._get_tools(config_schema)))
2025-03-25 05:40:07 +08:00
workflow.add_edge(START, "chatbot")
workflow.add_conditional_edges(
"chatbot",
tools_condition,
)
workflow.add_edge("tools", "chatbot")
workflow.add_edge("chatbot", END)
graph = workflow.compile(checkpointer=MemorySaver())
return graph
2025-03-24 23:00:14 +08:00
2025-03-28 11:40:46 +08:00
def stream_values(self, messages: list[str], config_schema: RunnableConfig = None):
graph = self.get_graph(config_schema)
for event in graph.stream({"messages": messages}, stream_mode="values", config=config_schema):
2025-03-24 23:00:14 +08:00
yield event["messages"]
2025-03-29 17:33:09 +08:00
def stream_messages(self, messages: list[str], config_schema: RunnableConfig = None):
graph = self.get_graph(config_schema)
conf = ChatbotConfiguration.from_runnable_config(config_schema)
for msg, metadata in graph.stream({"messages": messages}, stream_mode="messages", config=config_schema):
2025-03-24 23:00:14 +08:00
msg_type = msg.type
2025-03-29 17:33:09 +08:00
return_keys =conf.return_keys
2025-03-24 23:00:14 +08:00
if not return_keys or msg_type in return_keys:
yield msg, metadata
def main():
agent = ChatbotAgent(ChatbotConfiguration())
2025-03-24 19:07:51 +08:00
2025-03-24 23:00:14 +08:00
thread_id = str(uuid.uuid4())
config = {"configurable": {"thread_id": thread_id}}
2025-03-24 19:07:51 +08:00
2025-03-25 05:40:07 +08:00
from src.agents.utils import agent_cli
2025-03-24 23:00:14 +08:00
agent_cli(agent, config)
2025-03-24 19:07:51 +08:00
2025-03-24 23:00:14 +08:00
if __name__ == "__main__":
main()
# asyncio.run(main())