使用AI模型返回结构化数据:确保一致性和可靠性

220 阅读3分钟

使用AI模型返回结构化数据:确保一致性和可靠性

在现代应用中,从AI模型获取结构化数据具有重要意义。无论是将文本数据提取到数据库中,还是为下游系统提供数据支持,获取一致的结构化输出都是关键。本指南将介绍几种实现AI模型结构化输出的策略,并提供相应的代码示例,以帮助开发者有效地利用这些技术。

1. 引言

本文主要探讨如何从AI模型中返回结构化数据。我们将讨论几种不同的方法,包括Pydantic类、TypedDict和JSON Schema。此外,我们还将探讨潜在的挑战以及解决方案。

2. 主要内容

2.1 使用 .with_structured_output() 方法

.with_structured_output() 是获取结构化输出的简单且可靠的方法。它适用于支持工具/函数调用或JSON模式的模型,可以通过提供输出属性的名称、类型和描述的模式来规范输出。

2.2 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代理服务提高访问稳定性
structured_llm = llm.with_structured_output(Joke)
structured_llm.invoke("Tell me a joke about cats")

# 输出:
# Joke(setup='Why was the cat sitting on the computer?', punchline='Because it wanted to keep an eye on the mouse!', rating=7)

2.3 TypedDict 或 JSON Schema

如果不需要验证,可以使用TypedDict类定义模式。此外,还可以使用JSON Schema字典直接定义输出格式。

from typing_extensions import Annotated, TypedDict

class Joke(TypedDict):
    """Joke to tell user."""
    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"]

# 使用API代理服务提高访问稳定性
structured_llm = llm.with_structured_output(Joke)
structured_llm.invoke("Tell me a joke about cats")

# 输出:
# {'setup': 'Why was the cat sitting on the computer?', 'punchline': 'Because it wanted to keep an eye on the mouse!', 'rating': 7}

3. 代码示例:选择多种模式

当需要让模型从多种模式中进行选择时,可以创建一个具有 Union 类型属性的父模式。

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

class Joke(BaseModel):
    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")

class ConversationalResponse(BaseModel):
    response: str = Field(description="A conversational response to the user's query")

class Response(BaseModel):
    output: Union[Joke, ConversationalResponse]

# 使用API代理服务提高访问稳定性
structured_llm = llm.with_structured_output(Response)
structured_llm.invoke("Tell me a joke about cats")

# 输出:
# Response(output=Joke(setup='Why was the cat sitting on the computer?', punchline='To keep an eye on the mouse!', rating=8))

4. 常见问题和解决方案

  • 问题:模型生成输出不符合预期的结构。
    • 解决方案:使用Pydantic类进行严格验证,确保输出结构的正确性。
  • 问题:由于网络限制导致API访问不稳定。
    • 解决方案:在API调用中使用API代理服务以提高访问稳定性。

5. 总结和进一步学习资源

通过使用结构化输出的方法,可以大大提高AI模型生成数据的一致性和可靠性。可以考虑进一步学习以下资源:

6. 参考资料

  • LangChain 官方文档
  • Pydantic 官方文档
  • JSON Schema 官方文档

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

---END---