Repository navigation
Expand file tree
/
Copy pathlangchain_agent.py
More file actions
73 lines (61 loc) · 2.51 KB
/
Copy pathlangchain_agent.py
File metadata and controls
73 lines (61 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import os
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from langchain.tools import tool
from langgraph.checkpoint.memory import MemorySaver # ← 加记忆
# ===== 第一步:定义工具 =====
@tool
def get_weather(city: str) -> str:
"""查询指定城市的天气情况"""
data = {"北京": "晴, 25°C", "上海": "小雨, 22°C", "广州": "多云, 30°C"}
return data.get(city, f"{city}天气未收录")
@tool
def get_order(order_id: str) -> str:
"""查询订单的状态信息"""
orders = {"A001": "iPhone 16, 已发货", "B002": "机械键盘, 打包中"}
return orders.get(order_id, f"订单{order_id}未找到")
tools = [get_weather, get_order]
# ===== 第二步:初始化模型 =====
llm = ChatOpenAI(
model="deepseek-chat",
api_key=os.environ.get("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com",
temperature=0
)
# ===== 第三步:拼装 Agent + 记忆 =====
memory = MemorySaver() # ← 保存对话状态的组件
agent_executor = create_agent(
model=llm,
tools=tools,
system_prompt="你是一个全能助手,可以查天气、查订单。",
checkpointer=memory # ← 传入记忆,否则每次 invoke 都是新对话
)
# ===== 运行 =====
config = {"configurable": {"thread_id": "user-001"}} # ← 线程 ID,同一 ID 共享记忆
print("=== LangChain Agent 有记忆+思维链版(输入 quit 退出)===")
while True:
user_input = input("\n你: ")
if user_input.lower() == "quit":
break
try:
# stream 替代 invoke:每步实时返回,而不是等全部跑完
for event in agent_executor.stream(
{"messages": [("user", user_input)]},
config=config,
stream_mode="values" # 返回每一步的完整状态
):
msg = event["messages"][-1]
# 判断这一步在做什么
msg_type = getattr(msg, "type", "")
if msg_type == "ai":
# 模型的消息:可能是 tool_calls(决定调工具),也可能是 final answer
tool_calls = getattr(msg, "tool_calls", []) or []
if tool_calls:
for tc in tool_calls:
print(f" ⚡ Action: {tc['name']}({tc['args']})")
elif msg.content:
print(f" 💬 Answer: {msg.content}")
elif msg_type == "tool":
print(f" 👁️ Observation: {msg.content}")
except Exception as e:
print(f"执行出错: {e}")