LangChain入门:10分钟搭建RAG Pipeline

📘 AI教程 💬 🔥 Trending 发布者: leakey
LangChain入门:10分钟搭建RAG Pipeline

🩺 摘要

LangChain的名气很大,但每次看教程都被各种概念搞晕——Chain、Agent、Tool、Memory、Retriever……到底怎么用?能不能先跑起来再说?

📝 详情

先跑起来

pip install langchain langchain-openai
from langchain_openai import ChatOpenAI
from langchain.schema import HumanMessage

llm = ChatOpenAI(model="gpt-4o")
response = llm.invoke([HumanMessage(content="用一句话解释LangChain")])
print(response.content)

好了,你已经用LangChain调了一次AI。就是这么简单。

Chain:把多个步骤串起来

from langchain import LLMChain
from langchain.prompts import PromptTemplate

prompt = PromptTemplate(
    input_variables=["topic"],
    template="用{topic}的风格写一句话。"
)

chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run("鲁迅"))

Chain就是把prompt和模型组合成一个可调用的单元。

加记忆:让AI记住对话

from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory)

print(conversation.predict(input="我叫张三"))
print(conversation.predict(input="我叫什么名字?"))  # 它还记住

加检索:让AI读取你自己的文档

from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains import RetrievalQA

# 加载文档
text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=50)
texts = text_splitter.split_text(open("我的文档.txt").read())

# 向量化存储
docsearch = Chroma.from_texts(texts, OpenAIEmbeddings())

# RAG问答
qa = RetrievalQA.from_chain_type(llm=llm, retriever=docsearch.as_retriever())
print(qa.invoke("文档里说了什么?"))

这就是一个完整的RAG应用。不到20行代码。

加工具:让AI调用API

from langchain.agents import Tool, initialize_agent
from langchain.tools import tool

@tool
def calculate(expression: str) -> str:
    """计算数学表达式"""
    return str(eval(expression))

tools = [Tool(name="计算器", func=calculate, description="数学计算")]

agent = initialize_agent(tools, llm, agent="zero-shot-react-description")
print(agent.run("12345乘以67890等于多少?"))

学LangChain的正确顺序

  1. 先调LLM(LLMChain)— 5分钟
  2. 再加记忆(Memory)— 5分钟
  3. 再加检索(Retriever)— 10分钟
  4. 最后加工具(Agent)— 10分钟

不要一上来就看所有概念。从最简单的开始,用到什么学什么。

一句话

LangChain就是AI开发的「胶水」——把模型、数据、工具粘在一起。

相关文章