AI Agent 简介
AI Agent(智能体)是"会做事"的 AI:不仅会聊天,还能调用工具、做规划、执行任务、处理结果。你给它一个目标,它自己拆解步骤并完成。
普通对话 AI 像顾问(只给建议),Agent 像员工(动手干活)。比如:"帮我把这周订单整理成报表发到邮箱"——Agent 会查数据、生成报表、发邮件。
核心组成
- 大模型大脑:理解和决策
- 工具 Tools:查数据库、调 API、读写文件
- 记忆 Memory:记住上下文和历史
- 规划 Planning:拆解任务、决定步骤
- 执行循环:思考 → 行动 → 观察 → 再思考
代码示例
# Agent 工作循环(简化伪代码)
def agent_loop(task):
memory = [{"role": "user", "content": task}]
for step in range(10): # 最多 10 步
# 1. 思考:让模型决定下一步
reply = llm(memory)
memory.append(reply)
# 2. 如果是工具调用
if reply.tool_call:
result = run_tool(reply.tool_name, reply.args)
memory.append({"role": "tool", "content": result})
continue
# 3. 如果给出最终答案
if reply.final:
return reply.answer
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
print("hello") | 输出到控制台 |
name = "张三" | 变量赋值(无需声明类型) |
if x > 0: ... | 条件判断(注意冒号和缩进) |
for i in range(10): ... | 循环(缩进是语法的一部分) |
while x < 10: ... | 条件循环 |
def fn(a, b): return a + b | 定义函数 |
class Person: ... | 定义类 |
list = [1, 2, 3] | 列表(可改) |
tuple = (1, 2) | 元组(不可改) |
dict = {"key": "value"} | 字典(键值对) |
set = {1, 2, 3} | 集合(去重) |
len(obj) | 取长度 |
str(x) / int(x) / float(x) | 类型转换 |
s.split(",") | 字符串按分隔符拆分 |
" ".join(list) | 列表拼接成字符串 |
import os | 导入模块 |
from math import sqrt | 从模块导入指定函数 |
try: ... except Exception as e: ... | 异常捕获 |
with open("a.txt", "r") as f: ... | 文件读取(自动关闭) |
f"你好 {name}" | f-string 格式化 |
lambda x: x * 2 | 匿名函数 |
list(map(fn, arr)) | 函数式处理列表 |
range(start, stop, step) | 生成数字序列 |
if __name__ == "__main__": | 主入口判断 |
pip install 包名 | 安装第三方包(命令行) |