底层结构化数据提取
如果你的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 outputsprint(outputs[0])这与 structured_predict 相同,如果大语言模型具备工具调用API。然而,如果大语言模型支持,您可以选择允许多次工具调用。这样可以从同一输入中提取多个对象,如以下示例所示:
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 outputsprint(outputs)如果您的目标是从单个LLM调用中提取多个Pydantic对象,以下是具体操作方法。
如果出于某些原因,LlamaIndex 所有简化提取的尝试对您都不起作用,您可以放弃它们,直接提示大型语言模型并自行解析输出,如下所示:
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性能,请查阅本指南!