langchain中常用的api
1,ChatOpenAI
2,PromptTemplate
3,ConversationBufferMemory
4,ConversationSummaryMemory
5,LLMChain
6,SimpleSequentialChain
一、ChatOpenAI
from langchain_openai import ChatOpenAI
# 初始化 ChatOpenAI 模型
chat_model = ChatOpenAI(
openai_api_key=openai_api_key
model_name="gpt-3.5-turbo",
temperature=0.2, # 随机性 值越大越随机
openai_api_base=openai_base_url
)
二、PromptTemplate
提示词模板 API,用于标准化、可复用化构建提示词,避免手动拼接字符串带来的冗余和错误。
from langchain.prompts import PromptTemplate
"""创建一个对话链"""
template = """
你是一个有用的助手。请根据以下对话历史和最新消息进行回复。
对话历史:
{history}
最新消息: {input}
请保持对话的连贯性,并根据上下文提供合适的回复。
助手回复:"""
prompt = PromptTemplate(
input_variables=["history", "input"],
template=template
)
更多提示词模板编写查看 langchain之模板提示词
三、ConversationBufferMemory (完整缓冲记忆)
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(memory_key="chat_history", input_key="input", output_key="output")
四、ConversationSummaryMemory(对话摘要记忆)
from langchain.memory import ConversationSummaryMemory
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
# 1. 初始化摘要记忆(自动摘要对话历史)
memory = ConversationSummaryMemory(
llm=chat_model, # 需要传入模型用于生成摘要
return_messages=True
)
# 2. 初始化对话链
prompt = ChatPromptTemplate.from_messages([
("system", "你是一名友好的技术助手,根据对话历史回答用户问题"),
MessagesPlaceholder(variable_name="history"), # 插入对话历史占位符
("human", "{input}")
])
conversation_chain = ConversationChain(
llm=chat_model,
memory=memory,
prompt=prompt,
verbose=True
)
# 3. 多轮长对话
print("\n=== ConversationSummaryMemory 多轮对话 ===")
conversation_chain.invoke({"input": "LangChain 的 PromptTemplate 可以标准化提示词,支持多变量填充"})
conversation_chain.invoke({"input": "DocumentLoader 可以加载 PDF、TXT 等多种格式的文档"})
result = conversation_chain.invoke({"input": "请总结一下我们刚才讨论的 LangChain 功能"})
print("总结回答:", result["response"])
五、LLMChain
def create_memory_chain():
"""创建带记忆功能的对话链"""
template = """
你是一个有用的AI助手。请根据对话历史和用户的新问题进行回复。
{chat_history}
问题: {input}
回答:"""
prompt = PromptTemplate(
input_variables=["chat_history", "input"],
template=template
)
# 使用通义千问API兼容模式
llm = ChatOpenAI(
openai_api_key=settings.dashscope_api_key,
model=settings.dashscope_model, # 直接指定model参数
temperature=0.7,
openai_api_base=settings.dashscope_base_url
)
memory = ConversationBufferMemory(memory_key="chat_history", input_key="input", output_key="output")
chain = LLMChain(
llm=llm,
prompt=prompt,
memory=memory,
output_key="output"
)
return chain
# 在其他地方调用
# 创建带记忆的对话链
memory_chain = create_memory_chain()
# 执行对话 - 不需要手动传递历史,链内部会自动管理
result = memory_chain.invoke({
"input": request.message
})
return {
"input": request.message,
"response": result.get("output", result),
"session_id": request.session_id,
"status": "success"
}
六、SimpleSequentialChain:带顺序链的调用
from langchain.chains import LLMChain, SimpleSequentialChain
# 链 1:生成文章标题
prompt1 = ChatPromptTemplate.from_messages([
("system", "你是一名技术博主,语言简洁专业"),
("human", "为 {topic} 生成一个吸引人的文章标题")
])
chain1 = prompt1 | chat_model
# 链 2:根据标题生成文章摘要
prompt2 = ChatPromptTemplate.from_messages([
("system", "你是一名技术博主,摘要不超过 200 字"),
("human", "根据标题:{title},生成一篇技术文章的摘要")
])
chain2 = prompt2 | chat_model
# 3. 初始化简单顺序链(链 1 输出 → 链 2 输入,自动映射变量)
# 注意:SimpleSequentialChain 要求前一个链的输出键为 "output",后一个链的输入键为 "input"
# 管道符语法下可通过 `with_config` 配置变量,此处用传统方式更易理解
from langchain.chains import SimpleSequentialChain
from langchain.chains import LLMChain
# 传统 LLMChain 定义(兼容顺序链)
chain1_legacy = LLMChain(
llm=chat_model,
prompt=PromptTemplate.from_template("为 {topic} 生成一个吸引人的技术文章标题"),
output_key="title"
)
chain2_legacy = LLMChain(
llm=chat_model,
prompt=PromptTemplate.from_template("根据标题:{title},生成一篇技术文章的摘要(200 字以内)"),
input_key="title",
output_key="abstract"
)
# 初始化顺序链
sequential_chain = SimpleSequentialChain(
chains=[chain1_legacy, chain2_legacy],
verbose=True # 开启详细日志,查看链的执行流程
)
# 4. 运行顺序链
result = sequential_chain.invoke(topic="LangChain 常用 API 实战")
print("\n=== SimpleSequentialChain 输出结果 ===")
print("最终摘要:", result)