关于 langchain
langchain 是用于构建 LLM 应用的框架,面向开发者,提供可组合链与 LangGraph Agent 图,并涵盖 RAG、结构化输出和追踪等模式。
主要功能
- 01通过 LCEL 组合链
- 02使用 LangGraph 构建 Agent 图
- 03构建 RAG 流水线
- 04生成结构化输出
- 05管理对话历史并流式输出
- 06使用 LangSmith 追踪运行
适用场景
- 01组合提示词与 LLM 调用
- 02构建基于向量存储的检索流程
- 03定义带工具的 Agent 工作流
- 04追踪链的调用过程
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ hoodini/ ai-agents-skills --skill langchain安装后在 Claude Code 中输入/langchain确认已加载。
详细介绍
LangChain 与 LangGraph
通过可组合的链和 Agent 图,构建复杂的大模型应用。
快速入门
pip install langchain langchain-openai langchain-anthropic langgraph
from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
# Simple chain
llm = ChatAnthropic(model="claude-3-sonnet-20240229")
prompt = ChatPromptTemplate.from_template("Explain {topic} in simple terms.")
chain = prompt | llm
response = chain.invoke({"topic": "quantum computing"})
LCEL(LangChain 表达式语言)
使用管道运算符组合链:
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
# Chain with parsing
chain = (
{"topic": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
result = chain.invoke("machine learning")
RAG 管道
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import Chroma
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
# Create vector store
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(documents, embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
# RAG prompt
prompt = ChatPromptTemplate.from_template("""
Answer based on the following context:
{context}
Question: {question}
""")
# RAG chain
rag_chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
answer = rag_chain.invoke("What is the refund policy?")
LangGraph Agent
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode
from langchain_core.tools import tool
from typing import TypedDict, Annotated
import operator
# Define state
class AgentState(TypedDict):
messages: Annotated[list, operator.add]
# Define tools
@tool
def search(query: str) -> str:
"""Search the web."""
return f"Results for: {query}"
@tool
def calculator(expression: str) -> str:
"""Calculate mathematical expression."""
return str(eval(expression))
tools = [search, calculator]
# Create graph
graph = StateGraph(AgentState)
# Add nodes
graph.add_node("agent", call_model)
graph.add_node("tools", ToolNode(tools))
# Add edges
graph.set_entry_point("agent")
graph.add_conditional_edges(
"agent",
should_continue,
{"continue": "tools", "end": END}
)
graph.add_edge("tools", "agent")
# Compile
app = graph.compile()
# Run
result = app.invoke({"messages": [HumanMessage(content="What is 25 * 4?")]})
结构化输出
from langchain_core.pydantic_v1 import BaseModel, Field
class Person(BaseModel):
name: str = Field(description="Person's name")
age: int = Field(description="Person's age")
occupation: str = Field(description="Person's job")
# Structured LLM
structured_llm = llm.with_structured_output(Person)
result = structured_llm.invoke("John is a 30 year old engineer")
# Person(name='John', age=30, occupation='engineer')
记忆
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
# Message history
store = {}
def get_session_history(session_id: str):
if session_id not in store:
store[session_id] = ChatMessageHistory()
return store[session_id]
# Chain with memory
with_memory = RunnableWithMessageHistory(
chain,
get_session_history,
input_messages_key="input",
history_messages_key="history"
)
# Use with session
response = with_memory.invoke(
{"input": "My name is Alice"},
config={"configurable": {"session_id": "user123"}}
)
流式传输
# Stream tokens
async for chunk in chain.astream({"topic": "AI"}):
print(chunk.content, end="", flush=True)
# Stream events (for debugging)
async for event in chain.astream_events({"topic": "AI"}, version="v1"):
print(event)
LangSmith 跟踪
import os
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_API_KEY"] = "your-api-key"
os.environ["LANGCHAIN_PROJECT"] = "my-project"
# All chains are now traced automatically
chain.invoke({"topic": "AI"})
资源
- LangChain 文档:https://python.langchain.com/docs/introduction/
- LangGraph 文档:https://langchain-ai.github.io/langgraph/
- LangSmith:https://smith.langchain.com/
- LangChain Hub:https://smith.langchain.com/hub
- LangChain 模板:https://github.com/langchain-ai/langchain/tree/master/templates
评论
支持 Markdown