langchain示例
from langchain.output_parsers import PydanticOutputParser # 关键修正1:导入PydanticOutputParser
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel # 关键修正2:导入BaseModel
# 定义Pydantic数据模型 ✅
class Joke(BaseModel):
setup: str
punchline: str
# 初始化解析器 ✅
output_parser = PydanticOutputParser(pydantic_object=Joke)
# 构建提示模板 ✅
prompt = PromptTemplate(
template="生成一个笑话。\n{format_instructions}\n问题: {question}", # 修正3:使用单花括号
input_variables=["question"],
partial_variables={
"format_instructions": output_parser.get_format_instructions() # 关键修正4:正确引用解析器
}
)
# 初始化模型 ✅
API_KEY = "sk-24b51c6eec4393a044e826" # 请替换为有效API密钥
model = ChatOpenAI(
model_name="deepseek-chat",
api_key=API_KEY,
base_url="https://api.deepseek.com/v1" # 修正5:更新API端点
)
# 构建调用链 ✅
chain = prompt | model | output_parser
# 执行调用 ✅
response = chain.invoke({"question": "为什么程序员喜欢黑暗?"}) # 修正6:使用单花括号
# 输出结果 ✅
print("开头:", response.setup)
print("笑点:", response.punchline)
这段代码展示了 LangChain 如何与 Pydantic 结合,实现对模型输出的结构化解析,这在需要特定格式输出的应用场景中非常有用。
一、代码解释
from langchain.output_parsers import PydanticOutputParser
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
导入必要的模块:PydanticOutputParser 用于解析结构化输出,PromptTemplate 用于构建提示词,ChatOpenAI 用于连接大模型,BaseModel 是 Pydantic 的基础模型类。
# 定义Pydantic数据模型
class Joke(BaseModel):
setup: str
punchline: str
创建一个 Pydantic 模型 Joke,定义了笑话的结构:包含 setup(笑话开头)和 punchline(笑话笑点)两个字符串字段。
# 初始化解析器
output_parser = PydanticOutputParser(pydantic_object=Joke)
创建 PydanticOutputParser 实例,指定要使用 Joke 模型来解析输出。
# 构建提示模板
prompt = PromptTemplate(
template="生成一个笑话。\n{format_instructions}\n问题: {question}",
input_variables=["question"],
partial_variables={
"format_instructions": output_parser.get_format_instructions()
}
)
# 初始化模型
API_KEY = "sk-24b434dae8c044e826" # 请替换为有效API密钥
model = ChatOpenAI(
model_name="deepseek-chat",
api_key=API_KEY,
base_url="https://api.deepseek.com/v1"
)
配置并初始化 ChatOpenAI 模型,使用 deepseek-chat 模型,需要替换为有效的 API 密钥。
# 构建调用链
chain = prompt | model | output_parser
调用链条处理问题 "为什么程序员喜欢黑暗?",传入问题参数。
# 输出结果
print("开头:", response.setup)
print("笑点:", response.punchline)
打印解析后的结果,分别输出笑话的开头和笑点。
预期输出示例
开头:为什么程序员喜欢黑暗?
笑点:因为他们讨厌光明(bug)!

浙公网安备 33010602011771号