如何从模型中返回结构化数据:实现精准的数据提取

引言

在现代应用中,从文本中提取结构化数据以便插入到数据库或用于其他下游系统变得越来越重要。无论是为了提高数据可用性还是改善数据分析的准确性,结构化数据的获取都至关重要。本文将介绍如何使用AI模型返回符合特定模式的输出,并提供实际的代码示例。

主要内容

1. 使用 with_structured_output() 方法

支持的模型

有很多支持这个方法的模型,包括OpenAI、Anthropic、Azure、Google等。这个方法利用模型的原生API功能来实现输出的结构化。

定义输出模式

你可以使用 TypedDict 类、JSON SchemaPydantic 类来定义模式。本文将重点介绍使用 Pydantic 类的优势:确保模型生成的输出被验证,如缺少字段或字段类型错误将会报错。

Pydantic 示例

from langchain_core.pydantic_v1 import BaseModel, Field
from typing import Optional

class Joke(BaseModel):
    """Joke to tell user."""
    setup: str = Field(description="The setup of the joke")
    punchline: str = Field(description="The punchline to the joke")
    rating: Optional[int] = Field(default=None, description="How funny the joke is, from 1 to 10")

# 使用API代理服务提高访问稳定性
llm = ChatOpenAI(base_url="{AI_URL}")

structured_llm = llm.with_structured_output(Joke)
response = structured_llm.invoke("Tell me a joke about cats")
print(response)

2. 使用 TypedDictJSON Schema

如果不需要Pydantic的验证功能,可以使用 TypedDict 或者 JSON Schema 来定义输出模式。

from typing_extensions import Annotated, TypedDict

class Joke(TypedDict):
    setup: Annotated[str, ..., "The setup of the joke"]
    punchline: Annotated[str, ..., "The punchline of the joke"]
    rating: Annotated[Optional[int], None, "How funny the joke is, from 1 to 10"]

structured_llm = llm.with_structured_output(Joke)
response = structured_llm.invoke("Tell me a joke about cats")
print(response)

3. 选择多种模式输出

通过定义一个父级模式,你可以让模型在多种输出模式中进行选择。

4. 处理流式输出

通过对字典类型的输出进行处理,支持流式输出。

5. Few-shot 提示

通过在提示中添加示例,尤其在处理复杂模式时,这种方法非常有用。

常见问题和解决方案

  • API访问问题:在某些网络受限的地区,建议使用API代理服务来提高访问的稳定性。
  • 输出验证失败:确保使用了正确的模式定义和字段类型。

总结与进一步学习资源

通过使用 with_structured_output() 方法和选择合适的输出模式,可以有效地从AI模型中提取结构化数据。这为实现更灵活和可靠的数据集成能力奠定了基础。读者可以进一步研究Pydantic的详细用法和LangChain的文档。

参考资料

  1. LangChain Documentation
  2. Pydantic Documentation

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

—END—

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值