0%

LangChain 框架入门:构建 AI 应用的最佳实践

LangChain 框架入门:构建 AI 应用的最佳实践

写在前面:LangChain 是构建 AI 应用的主流框架。这篇文章详解 LangChain 核心概念和实战用法。


一、核心概念

1.1 Components(组件)

1
2
3
4
5
6
7
8
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate

# 模型
llm = ChatOpenAI(model="gpt-3.5-turbo")

# Prompt 模板
prompt = ChatPromptTemplate.from_template("你好,{name}")

1.2 Chains(链)

1
2
3
4
from langchain.chains import LLMChain

chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(name="John")

二、实战案例

2.1 文档问答

1
2
3
4
5
6
7
8
9
10
11
12
13
from langchain.document_loaders import TextLoader
from langchain.vectorstores import FAISS

# 加载文档
loader = TextLoader("doc.txt")
docs = loader.load()

# 创建向量存储
vectorstore = FAISS.from_documents(docs, embeddings)

# 问答链
qa = VectorDBQA.from_chain_type(llm, retriever=vectorstore.as_retriever())
result = qa.run("文档讲了什么?")

2.2 Agent 工具调用

1
2
3
4
5
6
7
8
from langchain.agents import initialize_agent, Tool

tools = [
Tool(name="Search", func=search, description="搜索工具"),
]

agent = initialize_agent(tools, llm, agent="zero-shot-react-description")
result = agent.run("查下北京天气")

三、最佳实践

实践 说明
组件复用 避免重复创建
Prompt 优化 清晰描述任务
错误处理 添加重试机制
日志记录 便于调试

作者:John
创建时间:2026-03-06
文档版本:v1.0