主题
如果你的 LLM 支持工具调用,而你想对 LlamaIndex 的抽取过程有更直接的控制,可以直接对 LLM 使用 chat_with_tools。如果你的 LLM 不支持工具调用,也可以直接指示 LLM、然后自己解析输出。两种做法下面都演示。
直接调用工具
from llama_index.core.program.function_program import get_function_tool
tool = get_function_tool(Invoice)
resp = llm.chat_with_tools(
[tool],
# chat_history=chat_history, # can optionally pass in chat history instead of user_msg
user_msg="Extract an invoice from the following text: " + text,
tool_required=True, # can optionally force the tool call
)
tool_calls = llm.get_tool_calls_from_response(
resp, error_on_no_tool_calls=False
)
outputs = []
for tool_call in tool_calls:
if tool_call.tool_name == "Invoice":
outputs.append(Invoice(**tool_call.tool_kwargs))
# use your outputs
print(outputs[0])在 LLM 具备工具调用 API 时,这与 structured_predict 完全等价。不过若 LLM 支持,你还可以选择允许多次工具调用——效果就是从同一份输入里抽取多个对象,就像这个例子:
from llama_index.core.program.function_program import get_function_tool
tool = get_function_tool(LineItem)
resp = llm.chat_with_tools(
[tool],
user_msg="Extract line items from the following text: " + text,
allow_parallel_tool_calls=True,
)
tool_calls = llm.get_tool_calls_from_response(
resp, error_on_no_tool_calls=False
)
outputs = []
for tool_call in tool_calls:
if tool_call.tool_name == "LineItem":
outputs.append(LineItem(**tool_call.tool_kwargs))
# use your outputs
print(outputs)如果你的目标就是一次 LLM 调用里抽出多个 Pydantic 对象,做法就是这个。
直接提示
如果 LlamaIndex 为降低抽取难度所提供的各种手段都不合你意,你也可以完全抛开它们,直接给 LLM 写提示词、自己解析输出,就像这样:
schema = Invoice.model_json_schema()
prompt = "Here is a JSON schema for an invoice: " + json.dumps(
schema, indent=2
)
prompt += (
"""
Extract an invoice from the following text.
Format your output as a JSON object according to the schema above.
Do not include any other text than the JSON object.
Omit any markdown formatting. Do not include any preamble or explanation.
"""
+ text
)
response = llm.complete(prompt)
print(response)
invoice = Invoice.model_validate_json(response.text)
pprint(invoice)恭喜!关于 LlamaIndex 的结构化数据抽取,你已经学完了全部内容。
其他指南
想更深入地了解 LlamaIndex 的结构化数据抽取,可以看下面这几篇:
彩蛋
如果你还想了解如何用结构化输入来提升 LLM 的表现,别错过这篇指南!