主题
提示
本指南介绍的是一种已弃用的、在 RAG 工作流中抽取结构化输出的方法。更多细节请看我们的结构化输出入门指南。
使用 index.as_query_engine() 及其底层的 RetrieverQueryEngine,我们无需额外的 LLM 调用就能得到结构化的 pydantic 输出(这与典型的输出解析器不同。)
每个查询引擎都支持集成的结构化响应,只需在 RetrieverQueryEngine 中使用下列 response_mode:
refinecompacttree_summarizeaccumulate(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: str1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
然后,创建你的查询引擎。
query_engine = index.as_query_engine(
response_mode="tree_summarize", output_cls=Biography
)1
2
3
2
3
最后,你就能获取响应并查看输出。
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 ..."1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
模块
详细用法见下面的 notebook: