Skip to content
LlamaIndex 文档版本 跟随上游 源快照 c0395578 更新于 2026-10-15

提示

本指南介绍的是一种已弃用的、在 RAG 工作流中抽取结构化输出的方法。更多细节请看我们的结构化输出入门指南。

使用 index.as_query_engine() 及其底层的 RetrieverQueryEngine,我们无需额外的 LLM 调用就能得到结构化的 pydantic 输出(这与典型的输出解析器不同。)

每个查询引擎都支持集成的结构化响应,只需在 RetrieverQueryEngine 中使用下列 response_mode:

  • refine
  • compact
  • tree_summarize
  • accumulate(beta,需要额外解析才能转成对象)
  • compact_accumulate(beta,需要额外解析才能转成对象)

在底层,会根据你配置的 LLM 选用 OpenAIPydanitcProgam 或 LLMTextCompletionProgram。如果存在中间的 LLM 响应(即 refine 或 tree_summarize 涉及多次 LLM 调用时),那个 pydantic 对象会以 JSON 形式注入下一个 LLM 提示词。

使用方式

首先,你需要定义想要抽取的对象。

from typing import List
from pydantic import BaseModel

class Biography(BaseModel):
    """Data model for a biography."""

    name: str
    best_known_for: List[str]
    extra_info: str

然后,创建你的查询引擎。

query_engine = index.as_query_engine(
    response_mode="tree_summarize", output_cls=Biography
)

最后,你就能获取响应并查看输出。

response = query_engine.query("Who is Paul Graham?")

print(response.name)
# > 'Paul Graham'
print(response.best_known_for)
# > ['working on Bel', 'co-founding Viaweb', 'creating the programming language Arc']
print(response.extra_info)
# > "Paul Graham is a computer scientist, entrepreneur, and writer. He is best known      for ..."

模块

详细用法见下面的 notebook:

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。