Repository navigation
Expand file tree
/
Copy pathagent_framework.py
More file actions
150 lines (133 loc) · 4.91 KB
/
Copy pathagent_framework.py
File metadata and controls
150 lines (133 loc) · 4.91 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# agent_framework.py —— 可复用 Agent 框架
import os, json
from openai import OpenAI
# ================================================================
# 工具函数(业务代码,和框架无关)
# ================================================================
def get_weather(city):
data = {
"北京": "晴, 25°C", "上海": "小雨, 22°C", "广州": "多云, 30°C"
}
return data.get(city, f"{city}天气未收录")
def get_order(order_id):
orders = {"A001": "iPhone 16, 已发货", "B002": "机械键盘, 打包中"}
return orders.get(order_id, f"订单{order_id}未找到")
def calculate(expression):
try:
return f"{expression} = {eval(expression)}"
except:
return "计算失败"
# ================================================================
# Agent 类
# ================================================================
class Agent:
def __init__(self, name, system_prompt, tool_map, tools_config):
self.name = name
self.system_prompt = system_prompt
self.tool_map = tool_map
self.tools_config = tools_config
self.messages = []
self.client = OpenAI(
api_key=os.environ.get("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com"
)
self.max_rounds = 5
def reset(self):
"""重置对话历史"""
self.messages = [{"role": "system", "content": self.system_prompt}]
def _think_and_act(self):
"""ReAct 内层循环:思考 → 行动 → 观察 → 再思考"""
round_num = 0
while round_num < self.max_rounds:
round_num += 1
response = self.client.chat.completions.create(
model="deepseek-chat",
messages=self.messages,
tools=self.tools_config,
temperature=0
)
msg = response.choices[0].message
if msg.tool_calls:
self.messages.append(msg)
for tool_call in msg.tool_calls:
func_name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
result = self.tool_map[func_name](**args)
print(f" 🧠 Thought → ⚡ {func_name}({args})")
print(f" 👁️ Observation: {result}")
self.messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result
})
else:
self.messages.append({"role": "assistant", "content": msg.content})
return msg.content
return "⚠️ 达到最大推理轮数,请简化问题后重试。"
def run(self):
"""启动对话循环"""
self.reset()
print(f"=== {self.name}(输入 quit 退出)===")
while True:
user_input = input("\n👤 你: ")
if user_input.lower() == "quit":
print("👋 再见!")
break
self.messages.append({"role": "user", "content": user_input})
answer = self._think_and_act()
print(f"🤖 {self.name}: {answer}")
# ================================================================
# 使用示例
# ================================================================
if __name__ == "__main__":
# 几行代码创建一个 Agent
tool_map = {
"get_weather": get_weather,
"get_order": get_order,
"calculate": calculate
}
tools_config = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询城市天气",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "get_order",
"description": "查询订单状态",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"]
}
}
},
{
"type": "function",
"function": {
"name": "calculate",
"description": "数学计算",
"parameters": {
"type": "object",
"properties": {"expression": {"type": "string"}},
"required": ["expression"]
}
}
}
]
assistant = Agent(
name="小智",
system_prompt="你是一个全能助手,语气友善简洁。可以查天气、查订单、算数学。",
tool_map=tool_map,
tools_config=tools_config
)
assistant.run()