跳到内容

使用 Gemini 和结构化输出消除幻觉

在本文中,我们将探讨如何使用 Google 的 Gemini 模型和 Instructor 从 PDF 生成准确的引用。这种方法确保答案基于 PDF 的实际内容,从而降低幻觉的风险。

在此示例中,我们将使用 Nvidia 10k 报告,您可以在此链接下载。

简介

处理 PDF 时,确保任何答案或见解直接链接到源材料至关重要。这在用户需要验证信息来源的应用中尤为重要,例如法律或学术环境。

我们在此使用 PyMuPDF 处理 PDF 解析,但您可以使用任何其他库。最终,当您的引用变得更复杂时,您将需要投入更多时间来根据文档验证 PDF 引用。

设置环境

首先,让我们使用必要的库来设置环境

pip install "instructor[google-generativeai]" pymupdf

然后导入必要的库


定义我们的数据模型

我们将使用 Pydantic 定义引文和答案的数据模型

class Citation(BaseModel):
    reason_for_relevance: str
    text: list[str]
    page_number: int


class Answer(BaseModel):
    chain_of_thought: str
    citations: list[Citation]
    answer: str

初始化 Gemini 客户端

接下来,我们将使用 Instructor 设置 Gemini 客户端

client = instructor.from_gemini(
    client=genai.GenerativeModel(
        model_name="models/gemini-1.5-pro-latest",
    )
)

处理 PDF

要分析 PDF 并生成引文,请按照以下步骤操作

pdf_path = "./10k.pdf"
doc = pymupdf.open(pdf_path)

# Upload the PDF
file = genai.upload_file(pdf_path)

# Wait for file to finish processing
while file.state != File.State.ACTIVE:
    time.sleep(1)
    file = genai.get_file(file.name)
    print(f"File is still uploading, state: {file.state}")

resp: Answer = client.chat.completions.create(
    messages=[
        {
            "role": "system",
            "content": "You are a helpful assistant that can answer questions about the provided pdf file. You will be given a question and a pdf file. Your job is to answer the question using the information in the pdf file. Provide all citations that are relevant to the question and make sure that the coordinates are accurate.",
        },
        {
            "role": "user",
            "content": [
                "What were all of the export restrictions announced by the USG in 2023? What chips did they affect?",
                file,
            ],
        },
    ],
    response_model=Answer,
)

print(resp)
# Answer(
#     chain_of_thought="The question asks about export restrictions in 2023. Page 25 mentions the USG announcing licensing requirements for A100 and H100 chips in August 2022, and additional licensing requirements for a subset of these products in July 2023.",
#     citations=[
#         Citation(
#             reason_for_relevance="Describes the export licensing requirements and which chips they affect.",
#             text=[
#                 "In August 2022, the U.S. government, or the USG, announced licensing requirements that, with certain exceptions, impact exports to China (including Hong",
#                 "Kong and Macau) and Russia of our A100 and H100 integrated circuits, DGX or any other systems or boards which incorporate A100 or H100 integrated circuits.",
#                 "In July 2023, the USG informed us of an additional licensing requirement for a subset of A100 and H100 products destined to certain customers and other",
#                 "regions, including some countries in the Middle East.",
#             ],
#             page_number=25,
#         )
#     ],
#     answer="In 2023, the U.S. government (USG) announced new licensing requirements for the export of certain chips to China, Russia, and other countries.  These chips included the A100 and H100 integrated circuits, the DGX system, and any other systems or boards incorporating the A100 or H100 chips.",
# )

在 PDF 中高亮引用

获得引文后,您可以在 PDF 中高亮它们

for citation in resp.citations:
    page = doc.load_page(citation.page_number - 1)
    for text in citation.text:
        text_instances = page.search_for(text)
        for instance in text_instances:
            page.add_highlight_annot(instance)

doc.save("./highlighted.pdf")
doc.close()

在我们的例子中,我们可以看到引文准确,答案正确。

Gemini Citations

为什么使用结构化输出?

使用结构化输出的一个显著优势是能够轻松可靠地处理复杂的数据提取任务。在处理原始补全字符串或 JSON 数据时,开发者经常面临与解析复杂性和代码可维护性相关的挑战。

随着时间的推移,这只会变得容易出错、难以迭代且无法维护。相反,通过利用 pydantic,您可以获得用于验证和解析数据的最佳工具之一。

  1. 定义便捷:Pydantic 允许您轻松地定义具有特定字段的数据模型。这使得理解和维护数据结构变得容易。
  2. 强大的验证:使用 Pydantic,您可以构建验证器来测试各种边缘情况,确保您的数据准确可靠。这在处理 PDF 和引文时特别有用,因为您可以验证提取的数据,而无需担心底层语言模型。
  3. 关注点分离:通过使用结构化输出,语言模型的作用被简化为单个函数调用。这种分离使您能够专注于构建可靠高效的数据处理管道,而无需陷入语言模型的复杂细节。

总而言之,使用 Pydantic 的结构化输出提供了一种强大且符合人体工程学的方式来管理复杂的数据提取任务。它们提高了可靠性,简化了代码维护,并使开发者能够更轻松地构建更好的应用程序。

结论

通过使用 Gemini 和 Instructor,您可以从 PDF 生成准确的引文,确保您的答案基于源材料。这种方法对于需要高精度和可追溯性的应用来说是无价的。

立即尝试 instructor,看看如何构建可靠的应用。只需运行 pip install instructor 或查看我们的入门指南