python-langchain框架(1-12 返回json-格式解析器)

张开发
2026/4/3 19:02:56 15 分钟阅读
python-langchain框架(1-12 返回json-格式解析器)
看如下代码1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162fromlangchain.promptsimportPromptTemplatefromlangchain_openaiimportChatOpenAIfromlangchain_core.output_parsersimportJsonOutputParserfromlangchain_core.pydantic_v1importBaseModel, Fieldimportos# 定义您想要的数据结构。classBook(BaseModel):title:strField(description书名)author:strField(description作者)description:strField(description书的简介)# Set up a parser inject instructions into the prompt template.output_parserJsonOutputParser(pydantic_objectBook)format_instructionsoutput_parser.get_format_instructions()print(原版提示词)print(format_instructions)print(#############)#改成中文提示词format_instructions输出应格式化为符合以下 JSON 结构的 JSON 实例。JSON结构{title: 书的标题,author: 作者,description: 书的简介}promptPromptTemplate(template{format_instructions}\n{query}\n,input_variables[query],partial_variables{format_instructions: format_instructions},)# 初始化聊天模型使用DeepSeek APIllmChatOpenAI(api_keyos.getenv(DEEPSEEK_API_KEY),# 从环境变量读取API密钥base_urlos.getenv(BASE_URL),# 从环境变量读取API基础URL如 https://api.deepseek.commodeldeepseek-v3:671b,# 指定使用的模型版本temperature0.7,# 生成随机性控制0.7 适中创造性max_tokens1024# 单次响应最大token数)chainprompt | llm | output_parserprint(--------------)# 以及旨在提示语言模型填充数据结构的查询。query请给我介绍2本学习中国历史的经典书籍resultchain.invoke({query: query})print(result)#流式输出# for s in chain.stream({query: query}):# print(s)输出12345678910111213原版提示词The output should be formatted as a JSON instance that conforms to the JSON schema below.As an example,forthe schema {properties: {foo: {title:Foo,description:a list of strings,type:array,items: {type:string}}},required: [foo]}theobject{foo: [bar,baz]}isa well-formatted instance of the schema. Theobject{properties: {foo: [bar,baz]}}isnotwell-formatted.Hereisthe output schema:{properties: {title: {title:Title,description:\u4e66\u540d,type:string},author: {title:Author,description:\u4f5c\u8005,type:string},description: {title:Description,description:\u4e66\u7684\u7b80\u4ecb,type:string}},required: [title,author,description]}#############--------------[{title:中国通史,author:吕思勉,description:《中国通史》是吕思勉先生的代表作之一系统全面地介绍了中国从远古时代到近代的历史发展脉络。该书内容详实分析深入是学习中国历史的经典入门书籍。}, {title:万历十五年,author:黄仁宇,description:《万历十五年》是黄仁宇先生的经典著作以明朝万历十五年为切入点通过细致入微的历史分析展现了当时社会的政治、经济和文化状况。该书视角独特文笔流畅深受读者喜爱。}]

更多文章