前置准备
在开始之前,请确保已安装:
- Python 3.9+
openai库(或langchain-openai)- 有效的 OpenAI API Key
pip install openai
第一步:定义工具
Agent 通过工具与外部世界交互。我们先定义两个简单工具:计算器和当前时间查询。
from datetime import datetime
def get_current_time() -> str:
"""获取当前日期和时间。当用户询问现在几点、今天日期时使用。"""
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def calculator(expression: str) -> str:
"""计算数学表达式。输入如 '2+3*4' 的字符串,返回计算结果。"""
try:
result = eval(expression)
return str(result)
except Exception as e:
return f"计算错误: {e}"
第二步:工具 Schema 与调用逻辑
为让 LLM 理解何时调用工具,需要定义符合 OpenAI Function Calling 格式的 schema:
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "获取当前系统日期和时间",
"parameters": {"type": "object", "properties": {}}
}
},
{
"type": "function",
"function": {
"name": "calculator",
"description": "计算数学表达式,如 2+3*4",
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "数学表达式"}
},
"required": ["expression"]
}
}
}
]
def run_tool(name: str, args: dict) -> str:
if name == "get_current_time":
return get_current_time()
if name == "calculator":
return calculator(args.get("expression", ""))
return "未知工具"
第三步:Agent 主循环
Agent 的核心循环:调用 LLM → 若返回工具调用则执行 → 将结果回传给 LLM → 重复直至得到最终回复。
from openai import OpenAI
client = OpenAI()
messages = [
{"role": "system", "content": "你是助手,能查询时间并做数学计算。请根据用户需求调用相应工具。"},
{"role": "user", "content": "现在几点?再帮我算一下 (10+20)*3"}
]
while True:
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
msg = response.choices[0].message
if msg.tool_calls:
for tc in msg.tool_calls:
result = run_tool(tc.function.name, json.loads(tc.function.arguments))
messages.append({"role": "tool", "tool_call_id": tc.id, "content": result})
messages.append({"role": "assistant", "content": None, "tool_calls": msg.tool_calls})
else:
print(msg.content)
break
第四步:运行与测试
运行脚本,输入「现在几点?再帮我算 (10+20)*3」,Agent 会依次调用 get_current_time 和 calculator,并汇总结果回复。
小结
通过定义工具、编写 schema 和实现主循环,你已经完成了一个最简 Agent。在此基础上,可以继续增加更多工具、引入记忆(Memory)或改用 LangChain 等框架以简化开发。