提高模型输出效率:如何让模型返回结构化数据

149 阅读3分钟
# 提高模型输出效率:如何让模型返回结构化数据

在许多应用场景中,特别是需要从文本中提取数据以插入数据库或其他下游系统中时,让AI模型返回结构化数据是非常有用的。这篇文章将带你了解几种从模型获取结构化输出的方法。

## 1. 引言

结构化数据是指按照预先定义的格式组织和存储的信息。使用结构化数据,我们可以在不同的系统之间更有效地传输和存储信息。这篇文章的目的是介绍如何配置语言模型以返回符合特定架构的输出。

## 2. 主要内容

### 2.1 `.with_structured_output()` 方法

`with_structured_output()` 方法是获取结构化输出的最简单和最可靠的方式。它适用于提供结构化输出的原生API(如工具/函数调用或JSON模式)的模型。此方法接受一个架构作为输入,该架构指定所需输出属性的名称、类型和描述。返回的将是一个符合所提供架构的对象。

### 2.2 Pydantic类

使用Pydantic类时,模型生成的输出将会被验证。如果缺少任何必需字段或字段类型错误,Pydantic会引发错误。以下是一个使用Pydantic类的示例:

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

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")

2.3 TypedDict 或 JSON Schema

如果不想使用Pydantic,或不需要验证参数,或想流式传输模型输出,可以使用TypedDict类或JSON Schema。以下是TypedDict的示例:

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")

3. 代码示例

以下是一个完整的使用Pydantic类来生成结构化输出的示例:

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

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)
result = structured_llm.invoke("Tell me a joke about cats")
print(result)

4. 常见问题和解决方案

  • 如何处理验证错误? 如果使用Pydantic并发现输出不符合预期,可以使用 try-except 块来捕获异常,记录错误详情以便于调试。
  • 如果模型不支持with_structured_output()怎么办? 对于不支持此方法的模型,需要手动在Prompt中指定格式,并使用输出解析器提取结构化响应。

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

使用结构化输出可以显著提高从AI模型获取和使用信息的效率。为了进一步提升效率,可以研究更多关于Pydantic和LangChain的材料:

6. 参考资料

  1. LangChain Documentation: LangChain GitHub
  2. Pydantic Documentation: Pydantic

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

---END---