github star gitee star atomgit star PyPI Downloads AI编程 AI交流群

大家好,这里是程序员晚枫,正在all in AI编程实战

第21讲:AI Agent开发——让AI自主完成任务

什么是AI Agent?

AI Agent = AI + 工具 + 记忆

  • AI是大脑
  • 工具是手脚(搜索、代码、文件操作)
  • 记忆是经验

1、安装Agent框架

1
pip install langchain langchain-community openai

2、给AI装上工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from langchain.agents import initialize_agent, Tool
from langchain.tools import WikipediaQueryRun
from langchain.utilities import WikipediaAPIWrapper
from openai import OpenAI

client = OpenAI(api_key="你的Key", base_url="https://api.deepseek.com")

# 定义工具
tools = [
Tool(
name="搜索",
func=wikipedia.run,
description="当你需要搜索信息时使用"
),
Tool(
name="计算器",
func=lambda x: str(eval(x)),
description="用于数学计算"
)
]

3、构建Agent

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from langchain.agents import initialize_agent
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(
model="deepseek-chat",
openai_api_base="https://api.deepseek.com",
openai_api_key="你的Key"
)

agent = initialize_agent(
tools=tools,
llm=llm,
agent="zero-shot-react-description",
verbose=True
)

# 让Agent自主完成任务
result = agent.run("帮我搜索Python之父是谁,然后计算他2025年的年龄")
print(result)

4、给Agent添加记忆

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(memory_key="chat_history")

agent = initialize_agent(
tools=tools,
llm=llm,
agent="conversational-react-description",
memory=memory,
verbose=True
)

# 多次对话,Agent记住上下文
agent.run("我叫小明")
agent.run("我叫什么名字?") # 能记住:小明

5、实战:个人助理Agent

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
import os
import office

def read_file_tool(query):
"""读取文件工具"""
files = os.listdir(".")
return "\n".join(files)

def write_note_tool(content):
"""写笔记工具"""
with open("笔记.md", "a", encoding="utf-8") as f:
f.write(f"\n{content}")
return "笔记已保存"

tools = [
Tool(name="读文件", func=read_file_tool, description="列出当前目录文件"),
Tool(name="写笔记", func=write_note_tool, description="保存笔记内容")
]

agent = initialize_agent(tools, llm, agent="zero-shot-react-description")

while True:
user_input = input("你:")
if user_input == "退出":
break
result = agent.run(user_input)
print(f"助理:{result}")

6、Agent的执行流程

1
2
3
用户提问 → Agent思考 → 选择工具 → 执行工具 → 获得结果 → 继续思考 → 完成任务
↑ ↓
←←←←←←←←←←←←←←←←←←←← 结果反馈 ←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←

下讲预告

学会了Agent开发,下一讲我们学 AI工作流自动化——把多个AI能力串起来。

敬请期待!


程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

前3讲可以试听,试听链接:https://www.bilibili.com/cheese/play/ss982042944