当前位置: 首页 > news >正文

《Learning Langchain》阅读笔记3-基于 Gemini 的 Langchain如何从LLMs中获取特定格式

纯文本输出是有用的,但在某些情况下,我们需要 LLM 生成结构化输出,即以机器可读格式(如 JSON、XML 或 CSV)或甚至以编程语言(如 Python 或 JavaScript)生成的输出。当我们打算将该输出传递给其他代码时,这非常有用,使 LLM 可以在更大的应用程序中发挥作用。

调试步骤

import getpass
import osif "GOOGLE_API_KEY" not in os.environ:os.environ["GOOGLE_API_KEY"] = getpass.getpass("Enter your Google AI API key: ")
import os
import requestsos.environ['HTTP_PROXY'] = 'http://127.0.0.1:7890'
os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:7890'r = requests.get("https://www.google.com")
print(r.status_code)  # 能返回 200 就说明代理成功了
from langchain_google_genai import ChatGoogleGenerativeAIllm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-001",  # 或其他可用模型
)print(llm.invoke("你好呀!你现在通了吗?").content)
你好!我一直在线,随时待命。所以,是的,我可以说是“通了”!有什么我可以帮助你的吗?

JSON Output:JSON输出

使用 LLM 生成的最常见格式是 JSON,然后可以将其用于,例如:

  • 将它发送到前端代码

  • 将其保存到数据库中

# openai API
from langchain_openai import ChatOpenAI
from langchain_core.pydantic_v1 import BaseModelclass AnswerWithJustification(BaseModel):'''An answer to the user question along with justification for the answer.'''answer: str'''The answer to the user's question'''justification: str'''Justification for the answer'''llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0)
structured_llm = llm.with_structured_output(AnswerWithJustification)
structured_llm.invoke("What weighs more, a pound of bricks or a pound of feathers")

输出为:

{answer: "They weigh the same", justification: "Both a pound of bricks and a pound of feathers weigh one pound. The weight is the same, but the volu"... 42 more characters
}

我们使用gemini API来复现

但是langchain_core.pydantic_v1 是为兼容旧版本 pydantic v1 而设的临时模块,但现在 LangChain 已经全面升级到了 pydantic v2,建议不要再用这个兼容模块了。

from langchain_core.pydantic_v1 import BaseModel出现了红色的提示报错。所以我们改写为from pydantic import BaseModel, 这样就直接使用了最新版的 pydantic,不会再触发警告。

from langchain_google_genai import ChatGoogleGenerativeAI
from pydantic import BaseModelclass AnswerWithJustification(BaseModel):'''An answer to the user question along with justification for the answer.'''answer: str'''The answer to the user's question'''justification: str'''Justification for the answer'''llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash-001",  # 或其他可用模型temperature=0 # 让输出更确定、更稳定(不会随机发挥)
)structured_llm = llm.with_structured_output(AnswerWithJustification)structured_llm.invoke("What weighs more, a pound of bricks or a pound of feathers")
AnswerWithJustification(answer='They weigh the same.', justification='A pound is a unit of weight, so a pound of bricks and a pound of feathers weigh the same amount..')

总体目标:
让大语言模型(LLM)返回结构化的数据(JSON),并且符合你自定义的格式(schema)。

第一步:定义了一个“结构模板”(schema):

class AnswerWithJustification(BaseModel):answer: strjustification: str

这就是你希望模型返回的数据格式 —— 一个包含两个字段的 JSON:

{"answer": "...","justification": "..."
}

第二步:让 LLM “知道” 要用这个格式

structured_llm = llm.with_structured_output(AnswerWithJustification)

第三步:使用这个结构化模型去提问

structured_llm.invoke("What weighs more, a pound of bricks or a pound of feathers?")

这一步就是真正向模型提问。模型在回答前,会参考你定义的 schema,生成符合格式的 JSON 数据。

首先将 schema 转为 JSON Schema,把你的 Python 模板类转成 JSON 格式的规则。然后发给LLM,告诉模型“你输出要符合这个格式”。最后验证输出,模型生成后再校验是否合规,确保你收到的数据符合格式。

你就像是在说:

“AI,你回答我的时候,不能随便写一段文字,必须照着我这张表格来写,字段名和格式都要对上!”

Other Machine-Readable Formats with Output Parsers:其他带有输出解析器的机器可读格式

输出解析器是干嘛的?

输出解析器是帮助大语言模型(LLM)把结果以特定格式输出的一种工具。它有两个主要功能:

  1. 提供格式说明(Providing format instructions)

你可以用解析器给提示(prompt)加上一些额外的说明,比如告诉模型:

“请把结果输出成 XML 格式” 或
“请生成一个 JSON 对象,字段有 name 和 age”

这样模型就知道你想要的输出长什么样。

  1. 验证和解析输出(Validating and parsing output)

LLM 返回结果后,输出解析器还可以:

把普通文本转换成结构化格式(如列表、XML、JSON等);

校验格式是否正确;

修复模型输出中不完整或多余的内容。

这是一个输出解析器的工作示例

from langchain_core.output_parsers import CommaSeparatedListOutputParserparser = CommaSeparatedListOutputParser()items = parser.invoke("apple, banana, cherry")print(items)
['apple', 'banana', 'cherry']

LangChain 为各种用例提供了多种输出解析器,包括 CSV、XML 等。在下一节中,我们将了解如何将输出解析器与模型和提示组合使用。

相关文章:

  • 【Mamba】MambaVision论文阅读
  • MCP(Model Context Protocol 模型上下文协议)科普
  • 【数据融合实战手册·实战篇】二维赋能三维的5种高阶玩法:手把手教你用Mapmost打造智慧城市标杆案例
  • STM32F407的引脚说明
  • C++ `shared_ptr` 多线程使用
  • OrangePi 5 Pro vs OrangePi AI Pro 详细对比分析
  • 基于CNN与VGG16的图像识别快速实现指南
  • spring:加载配置类
  • es 混合检索多向量
  • Unity-微信截图功能简单复刻-01实现思路
  • http://noi.openjudge.cn/——2.5基本算法之搜索——1998:寻找Nemo
  • 模拟量和数字量的区别
  • #手动控制windows更新时间(非常安全,可随时恢复)
  • 热门与冷门并存,25西电—电子工程学院(考研录取情况)
  • 高阶数据结构 图 (上)
  • 在PyCharm中部署AI模型的完整指南
  • 人脸识别联合行为检测的办公管理新模式
  • 《AI大模型应知应会100篇》第24篇:限定输出格式:如何让AI回答更加结构化
  • IcePlayer音乐播放器项目分析及学习指南
  • C++_设计模式\_观察者模式(Observer Pattern)
  • 美伊就核问题在罗马开展第二轮间接谈判
  • 网络社群的早期历史及其启示
  • 推动中阿合作“向新而行”,这场论坛在上海松江举行
  • 凭春晚分会场爆火的无锡,为何请来了上海主流媒体和网络大V
  • 龚桢梽任广东省发展和改革委员会副主任
  • 提升青春期+亲子含量:社区商业综合体这样用好“二次元”