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

在 LlamaIndex 里抽取结构化数据最高层的方式,是实例化一个结构化 LLM(Structured LLM)。先把我们的 Pydantic 类照之前的写法建好:

from datetime import datetime
from pydantic import BaseModel, Field

class LineItem(BaseModel):
    """A line item in an invoice."""

    item_name: str = Field(description="The name of this item")
    price: float = Field(description="The price of this item")

class Invoice(BaseModel):
    """A representation of information from an invoice."""

    invoice_id: str = Field(
        description="A unique identifier for this invoice, often a number"
    )
    date: datetime = Field(description="The date this invoice was created")
    line_items: list[LineItem] = Field(
        description="A list of all the items in this invoice"
    )

如果你是第一次用 LlamaIndex,先把依赖装上:

  • pip install llama-index-core llama-index-llms-openai 安装 LLM(为简单起见我们用 OpenAI,你随时可以换成别的)
  • 申请一个 OpenAI API key,并把它设置为环境变量 OPENAI_API_KEY
  • pip install llama-index-readers-file 安装 PDFReader
    • 注:想要更好的 PDF 解析效果,我们推荐 LlamaParse

现在读入一张真实发票的文本:

from llama_index.readers.file import PDFReader
from pathlib import Path

pdf_reader = PDFReader()
documents = pdf_reader.load_data(file=Path("./uber_receipt.pdf"))
text = documents[0].text

接着实例化一个 LLM、把 Pydantic 类交给它,然后用发票的纯文本请它 complete:

from llama_index.llms.openai import OpenAI

llm = OpenAI(model="gpt-4o")
sllm = llm.as_structured_llm(Invoice)

response = sllm.complete(text)

response 是一个 LlamaIndex 的 CompletionResponse,有两个属性:text 和 raw。text 里存放的是经 Pydantic 整理后的响应的 JSON 序列化形式:

json_response = json.loads(response.text)
print(json.dumps(json_response, indent=2))
{
    "invoice_id": "Visa \u2022\u2022\u2022\u20224469",
    "date": "2024-10-10T19:49:00",
    "line_items": [
        {"item_name": "Trip fare", "price": 12.18},
        {"item_name": "Access for All Fee", "price": 0.1},
        {"item_name": "CA Driver Benefits", "price": 0.32},
        {"item_name": "Booking Fee", "price": 2.0},
        {"item_name": "San Francisco City Tax", "price": 0.21},
    ],
}

请注意,这张发票没有 ID,于是 LLM 尽力而为,用了信用卡号。Pydantic 校验并不是一纸保证书!

响应里的 raw 属性(说法有点绕)存放的就是那个 Pydantic 对象本身:

from pprint import pprint

pprint(response.raw)
Invoice(
    invoice_id="Visa ••••4469",
    date=datetime.datetime(2024, 10, 10, 19, 49),
    line_items=[
        LineItem(item_name="Trip fare", price=12.18),
        LineItem(item_name="Access for All Fee", price=0.1),
        LineItem(item_name="CA Driver Benefits", price=0.32),
        LineItem(item_name="Booking Fee", price=2.0),
        LineItem(item_name="San Francisco City Tax", price=0.21),
    ],
)

注意 Pydantic 在这里创建的是一个完整的 datetime 对象,而不只是把一个字符串做了翻译。

结构化 LLM 的行为与普通 LLM 类完全一致:你可以调用 chat、stream、achat、astream 等,它在每种情况下都会返回 Pydantic 对象。你也可以把这个结构化 LLM 作为参数传给 VectorStoreIndex.as_query_engine(llm=sllm),它就会自动以结构化对象来回答你的 RAG 查询。

结构化 LLM 替你包揽了全部的提示词工作。如果你想更掌控提示词本身,请继续看结构化预测。

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