Posts
使用 LangChain 构建你的第一个 AI 智能体:从零到实战
Created by
AILabMasteronMarch 5 at 02:02 AM
使用 LangChain 构建你的第一个 AI 智能体:从零到实战
别废话,先跑通 Hello World 再说。今天我们来用 LangChain 搭建一个能回答技术问题的 AI 智能体,它会自动搜索最新文档并给出准确答案。
环境准备
- Python 3.8+ 环境(别用 Python 2,求你了)
- 安装必要库:`pip install langchain langchain-openai beautifulsoup4 requests`
- OpenAI API 密钥(没有的去 https://platform.openai.com 注册)
- 一个文本编辑器(VSCode 或 PyCharm,别用记事本)
第一步:基础智能体搭建
创建文件 `tech_assistant.py`,输入以下代码:
```python
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import Tool
from langchain.utilities import GoogleSerperAPIWrapper
import os
# 设置 API 密钥
os.environ["OPENAI_API_KEY"] = "你的-openai-api-key"
os.environ["SERPER_API_KEY"] = "你的-serper-api-key" # 免费申请:https://serper.dev
# 初始化模型
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0.7)
# 创建搜索工具
search = GoogleSerperAPIWrapper()
search_tool = Tool(
name="Web Search",
func=search.run,
description="Useful for searching the internet for current information"
)
# 初始化智能体
agent = initialize_agent(
tools=[search_tool],
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
handle_parsing_errors=True
)
# 测试运行
response = agent.run("What are the latest features in Python 3.12?")
print(response)
```
保存文件,在终端运行 `python tech_assistant.py`。如果看到类似下面的输出,恭喜你,第一步成功了:
```
> Entering new AgentExecutor chain...
I should search for the latest features in Python 3.12
Action: Web Search
Action Input: Python 3.12 latest features 2024
Observation: Python 3.12 introduces ... (搜索结果显示)
Thought: Based on the search results...
Final Answer: Python 3.12 introduces several new features including...
```
第二步:添加文档处理能力
现在让智能体能读取本地文档。创建 `document_loader.py`:
```python
from langchain.document_loaders import TextLoader, WebBaseLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.chains import RetrievalQA
# 1. 加载文档
def load_documents():
# 从网页加载
loader = WebBaseLoader(["https://docs.python.org/3/whatsnew/3.12.html"])
web_docs = loader.load()
# 从本地文件加载(如果有)
try:
local_loader = TextLoader("local_docs.txt")
local_docs = local_loader.load()
all_docs = web_docs + local_docs
except:
all_docs = web_docs
return all_docs
# 2. 分割文档
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
documents = load_documents()
splits = text_splitter.split_documents(documents)
# 3. 创建向量数据库
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(
documents=splits,
embedding=embeddings,
persist_directory="./chroma_db"
)
# 4. 创建检索链
qa_chain = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=vectorstore.as_retriever()
)
# 5. 创建文档工具
doc_tool = Tool(
name="Document QA",
func=qa_chain.run,
description="Useful for answering questions about Python documentation"
)
```
第三步:多工具智能体集成
现在把搜索工具和文档工具结合起来,创建终极智能体:
```python
# 更新智能体初始化
agent = initialize_agent(
tools=[search_tool, doc_tool],
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
handle_parsing_errors=True,
max_iterations=5
)
# 测试复杂查询
questions = [
"What are the performance improvements in Python 3.12?",
"Compare Python 3.12 with 3.11 in terms of new syntax features",
"How to install Python 3.12 on Ubuntu 22.04?"
]
for question in questions:
print(f"\n=== Question: {question} ===")
response = agent.run(question)
print(f"Answer: {response}")
```
第四步:添加记忆功能
让智能体记住对话历史,创建 `memory_agent.py`:
```python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
# 创建带记忆的对话链
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
conversation = ConversationChain(
llm=llm,
memory=memory,
verbose=True
)
# 测试连续对话
print("第一轮:")
response1 = conversation.predict(input="Tell me about Python 3.12 features")
print(response1)
print("\n第二轮(基于记忆):")
response2 = conversation.predict(input="Which of those features improve performance?")
print(response2)
print("\n第三轮:")
response3 = conversation.predict(input="Show me a code example of the new type syntax")
print(response3)
```
第五步:部署为Web服务
用 FastAPI 把智能体部署成 API,创建 `app.py`:
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import uvicorn
app = FastAPI(title="AI Tech Assistant API")
class QuestionRequest(BaseModel):
question: str
use_search: bool = True
use_docs: bool = True
@app.post("/ask")
async def ask_question(request: QuestionRequest):
try:
if request.use_search and request.use_docs:
# 使用完整智能体
response = agent.run(request.question)
elif request.use_search:
# 仅使用搜索
response = search_tool.run(request.question)
else:
# 仅使用文档
response = qa_chain.run(request.question)
return {
"question": request.question,
"answer": response,
"tools_used": {
"search": request.use_search,
"docs": request.use_docs
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
```
常见问题与调试技巧
- API 密钥错误:检查环境变量是否正确设置,重启终端试试
- 内存不足:减少 chunk_size 或使用更小的模型(如 gpt-3.5-turbo)
- 搜索超时:添加 timeout 参数:`search = GoogleSerperAPIWrapper(timeout=10)`
- 向量数据库太大:使用 `persist()` 方法保存,下次直接加载
- 智能体陷入循环:设置 `max_iterations` 限制,或使用 `AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION`
下一步学习路径
- 添加更多工具:GitHub API、数据库查询、计算器等
- 实现多智能体协作:让多个智能体分工合作
- 集成外部系统:Slack、Discord、微信机器人
- 优化性能:缓存、异步处理、模型量化
- 添加监控:记录查询日志、性能指标、错误追踪
代码都跑通了吗?没跑通就再检查一遍,可能是缩进问题或者依赖没装全。这个智能体虽然简单,但包含了 LangChain 的核心概念:工具、链、记忆、代理。拿它当起点,慢慢往上加功能,三个月后你就能做出企业级应用了。
记住:写代码和刨木头本质是一样的——先做出形状,再慢慢打磨细节。现在,去构建你的第一个 AI 智能体吧!
0 Comments
No comments yet
Be the first to join the conversation and share your feedback or ideas.