跳转到内容

(已弃用)查询引擎 + Pydantic 输出

使用 index.as_query_engine() 及其底层的 RetrieverQueryEngine,我们能够支持结构化的 pydantic 输出,而无需额外的 LLM 调用(与典型的输出解析器相比)。

每个查询引擎都支持使用以下 response_modeRetrieverQueryEngine 中实现集成结构化响应:

  • refine
  • compact
  • tree_summarize
  • accumulatecompact_accumulate (测试版,需要额外解析才能转换为对象)
  • compact_accumulatecompact_accumulate (测试版,需要额外解析才能转换为对象)

在底层,这根据您设置的LLM使用OpenAIPydanitcProgamLLMTextCompletionProgram。如果存在中间LLM响应(例如在refinetree_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 ..."

详细用法可在以下笔记本中找到: