模拟帝国驿站是什么 模拟帝国驿站游戏玩法与特色介绍
2026-07-11 3393829
2026-07-11 0
普通 AI:你问 → 它答,一问一答。

Agent:你给任务 → 它自己决定用什么工具 → 执行 → 看结果 → 不满意再调 → 直到完成任务。
普通AI:"1+1等于几" → "2"Agent: "帮我算 (15*8+200)/4" → 调计算器 → 拿结果 → "等于80"
Agent 的代码结构简单到离谱——你 Week 1 就写过:
# Week 1 的聊天机器人while True:user_input = input("你: ")reply = api.call(user_input)print(f"AI: {reply}")# Week 4 的 Agentwhile not done:response = api.call(messages, tools=[计算器, 读文件, Python沙箱...])if response wants to use tool:result = run_tool(response.tool_name, response.args)messages.append(result) # 把工具结果告诉 AIelse:print(response.content) # AI 给出最终答案done = True
多出来的只是"判断要不要调工具"这一步。
import jsonfrom openai import OpenAItools = [{"type": "function","function": {"name": "calculator","description": "计算数学表达式","parameters": {"type": "object","properties": {"expression": {"type": "string"}},"required": ["expression"]}}}]def run_agent(client, task, max_iterations=8):messages = [{"role": "system", "content": "你是一个Agent,可以用工具完成任务。"},{"role": "user", "content": task}]for i in range(max_iterations):response = client.chat.completions.create(model="deepseek-chat",messages=messages,tools=tools,# ← 关键:告诉 AI 有哪些工具stream=False)msg = response.choices[0].messageif msg.tool_calls:# AI 决定调工具messages.append(msg)for tc in msg.tool_calls:args = json.loads(tc.function.arguments)result = eval(args["expression"])# 执行工具messages.append({"role": "tool","tool_call_id": tc.id,"content": str(result)})continue # 回到循环开头,让 AI 看结果return msg.content # AI 直接回答了return "达到最大循环次数"
这就是 Agent 的全部秘密——没有黑魔法,没有复杂框架。
| 工具 | 能干什么 |
|---|---|
| calculator | 安全计算数学表达式 |
| read_file | 读本地文件 |
| write_file | 写入文件 |
| list_files | 列目录 |
| python_repl | 安全执行 Python(沙箱隔离) |
| get_current_time | 查时间 |
| search_docs | 在文档中语义搜索(接入了 RAG) |
Agent 真正厉害的不是单次工具调用,而是一次任务多次决策:
用户:"先看看项目目录有什么文件,读最大的那个,然后总结"→ Agent: list_files → 发现 plan.md 最大→ Agent: read_file("plan.md") → 获取内容→ Agent: 输出总结(全程自己决策,没问我"要读哪个文件")
stream=TrueGitHub:github.com/Speed-Fanta…
完整代码在 week04/ + week06/(Agent 升级版,加了文档检索)。
下一篇:Python 新手如何用 AI 辅助两个月做出 6 个项目