使用Claude处理图表和幻灯片:实用技巧与模式

本教程面向有编程基础的AI工程开发者,深入讲解如何利用Claude的视觉与PDF支持能力处理图表、图形及幻灯片。内容涵盖API调用方法、PDF文档摄取、提高图表分析准确性的技巧,以及将幻灯片转化为高质量文本叙述的完整流程。通过实际代码示例,展示如何构建可复用的处理管线,并讨论常见陷阱与优化策略,帮助开发者高效落地多模态文档分析任务。

技术背景

在金融、科研、商业分析等领域,大量信息以图表、图形和幻灯片形式呈现。传统文本提取方法(如PyPDF)无法捕获视觉元素中的关键数据,导致信息丢失。Claude具备强大的视觉理解能力,结合PDF支持功能,可直接解析文档中的图表和图形,回答复杂问题。本教程旨在指导开发者利用Claude API实现多模态文档分析,解决实际工程中的信息提取与理解难题。

核心原理

Claude的PDF支持功能在解析文档时,同时利用提取的文本和视觉信息,从而能够理解图表、图形等非文本内容。其核心在于多模态模型的视觉编码器将页面图像转换为特征表示,与文本信息融合,实现跨模态推理。对于幻灯片,直接使用PDF可能受限于页数(100页)和嵌入兼容性,因此采用“叙述生成”策略:让Claude逐页详细描述幻灯片内容,生成结构化文本,再用于下游任务(如RAG)。此方法利用Claude的视觉能力,将视觉信息转化为高质量文本,弥补纯文本提取的不足。

架构分析

整体架构分为三个层次:1)数据摄取层:读取PDF文件,Base64编码后通过API传输;2)模型推理层:调用Claude API,支持文档与文本混合输入,返回文本响应;3)后处理层:解析模型输出(如正则提取叙述),供下游使用。关键设计决策包括:使用beta头启用PDF功能,选择支持PDF的模型(claude-sonnet-4-6),以及采用“叙述-问答”两阶段模式,先完整叙述再针对性提问,以提高复杂文档的问答准确性。

完整实战教程

使用图表、图形和幻灯片

Claude 在处理图表、图形以及更广泛的幻灯片方面具有强大的能力。根据您的具体使用场景,有许多技巧和窍门可供利用。本指南将向您展示使用 Claude 处理这些材料的常见模式。

图表和图形

在大多数情况下,使用Claude处理图表和图形很简单。让我们逐步了解如何摄取它们并将其传递给Claude,以及一些提高结果的常见技巧。

摄取并调用 Claude API

将图表和图形传递给 Claude 的最佳方式是利用其视觉能力和 PDF 支持功能。也就是说,给 Claude 一份包含图表或图形的 PDF 文档,并附上关于它的文本问题。

目前,只有 claude-sonnet-4-6 支持 PDF 功能。由于该功能仍处于测试阶段,你需要为其提供 pdfs-2024-09-25 测试版标头。

# Install and create the Anthropic client.
%pip install anthropic
import base64

from anthropic import Anthropic

# While PDF support is in beta, you must pass in the correct beta header
client = Anthropic(default_headers={"anthropic-beta": "pdfs-2024-09-25"})
# For now, only claude-sonnet-4-6 supports PDFs
MODEL_NAME = "claude-sonnet-4-6"
# Make a useful helper function.
def get_completion(messages):
    response = client.messages.create(
        model=MODEL_NAME, max_tokens=8192, temperature=0, messages=messages
    )
    return response.content[0].text
# To start, we'll need a PDF. We will be using the .pdf document located at cvna_2021_annual_report.pdf.
# Start by reading in the PDF and encoding it as base64.
with open("./documents/cvna_2021_annual_report.pdf", "rb") as pdf_file:
    binary_data = pdf_file.read()
    base_64_encoded_data = base64.b64encode(binary_data)
    base64_string = base_64_encoded_data.decode("utf-8")

让我们看看如何将这份文档连同简单的问题一起传递给模型。

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "document",
                "source": {
                    "type": "base64",
                    "media_type": "application/pdf",
                    "data": base64_string,
                },
            },
            {"type": "text", "text": "What's in this document? Answer in a single sentence."},
        ],
    }
]

print(get_completion(messages))

这已经很不错了!现在让我们问它一些更有用的问题。

questions = [
    "What was CVNA revenue in 2020?",
    "How many additional markets has Carvana added since 2014?",
    "What was 2016 revenue per retail unit sold?",
]

for index, question in enumerate(questions):
    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {
                        "type": "base64",
                        "media_type": "application/pdf",
                        "data": base64_string,
                    },
                },
                {"type": "text", "text": question},
            ],
        }
    ]

    print(f"\n----------Question {index + 1}----------")
    print(get_completion(messages))

如您所见,Claude 能够回答关于图表和图形的相当详细的问题。然而,有一些技巧和窍门可以帮助您充分利用它。

幻灯片演示文稿

既然我们已经知道Claude是图表和图形的大师,那么很自然地将其扩展到图表和图形的真正主场——幻灯片演示文稿!

幻灯片是许多领域(包括金融服务)的关键信息来源。虽然你可以使用像PyPDF这样的包从幻灯片中提取文本,但由于幻灯片通常包含大量图表和图形,这往往不是一个好的选择,因为模型将难以获取它们真正需要的信息。

因此,PDF支持功能可以成为一个很好的替代方案。它在处理PDF文档时,会同时使用提取的文本和视觉信息。在本节中,我们将介绍如何在Claude中使用PDF文档来审阅幻灯片,以及如何处理这种方法的一些常见陷阱。

将典型的幻灯片演示文稿导入 Claude 的最佳方式是将其下载为 PDF,然后直接提供给 Claude。

# Open the multi-page PDF document the same way we did earlier.
with open("./documents/twilio_q4_2023.pdf", "rb") as pdf_file:
    binary_data = pdf_file.read()
    base_64_encoded_data = base64.b64encode(binary_data)
    base64_string = base_64_encoded_data.decode("utf-8")
# Now let's pass the document directly to Claude. Note that Claude will process both the text and visual elements of the document.
question = "What was Twilio y/y revenue growth for fiscal year 2023?"
content = [
    {
        "type": "document",
        "source": {"type": "base64", "media_type": "application/pdf", "data": base64_string},
    },
    {"type": "text", "text": question},
]

messages = [{"role": "user", "content": content}]

print(get_completion(messages))

这种方法是一个很好的入门方式,并且在某些用例中提供了最佳性能。然而,它也有一些限制。

幸运的是,我们可以利用Claude的视觉能力,以文本形式获得比普通PDF文本提取更高质量的幻灯片表示。

我们发现最好的方法是让Claude从头到尾顺序叙述整个演示文稿,将当前幻灯片及其之前的叙述传递给它。让我们看看如何实现。

# Define a prompt for narrating our slide deck. We would adjut this prompt based on the nature of the deck, but keep the structure largely the same.
prompt = """
You are the Twilio CFO, narrating your Q4 2023 earnings presentation.

The entire earnings presentation document is provided to you.
Please narrate this presentation from Twilio's Q4 2023 Earnings as if you were the presenter. Do not talk about any things, especially acronyms, if you are not exactly sure you know what they mean.

Do not leave any details un-narrated as some of your viewers are vision-impaired, so if you don't narrate every number they won't know the number.

Structure your response like this:
<narration>
    <page_narration id=1>
    [Your narration for page 1]
    </page_narration>

    <page_narration id=2>
    [Your narration for page 2]
    </page_narration>

    ... and so on for each page
</narration>

Use excruciating detail for each page, ensuring you describe every visual element and number present. Show the full response in a single message.
"""
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "document",
                "source": {
                    "type": "base64",
                    "media_type": "application/pdf",
                    "data": base64_string,
                },
            },
            {"type": "text", "text": prompt},
        ],
    }
]

# Now we use our prompt to narrate the entire deck. Note that this may take a few minutes to run (often up to 10).
completion = get_completion(messages)
import re

# Next we'll parse the response from Claude using regex
pattern = r"<narration>(.*?)</narration>"
match = re.search(pattern, completion.strip(), re.DOTALL)
if match:
    narration = match.group(1)
else:
    raise ValueError("No narration available. Likely due to the model response being truncated.")

现在我们有了基于文本的叙述(虽然远非完美,但已经相当不错),我们就可以将这个卡片组用于任何纯文本工作流了,包括向量搜索!

作为最后的健全性检查,让我们向这个仅叙述的设置提出几个问题!

questions = [
    "What percentage of q4 total revenue was the Segment business line?",
    "Has the rate of growth of quarterly revenue been increasing or decreasing? Give just an answer.",
    "What was acquisition revenue for the year ended december 31, 2023 (including negative revenues)?",
]

for index, question in enumerate(questions):
    prompt = f"""You are an expert financial analyst analyzing a transcript of Twilio's earnings call.
Here is the transcript:
<transcript>
{narration}
</transcript>

Please answer the following question:
<question>
{question}
</question>"""
    messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}]

    print(f"\n----------Question {index + 1}----------")
    print(get_completion(messages))

看起来不错!掌握了这些技巧,你就可以开始将模型应用于图表和图形密集型内容(如幻灯片)了。

常见问题

常见错误:1)未设置beta头导致PDF功能不可用,需添加'anthropic-beta: pdfs-2024-09-25';2)使用不支持的模型,需确保模型为claude-sonnet-4-6;3)PDF页数超过100页导致请求失败,需拆分文档或使用叙述方法;4)模型算术错误,可提供计算器工具或要求分步计算;5)叙述输出被截断,需增加max_tokens或分段生成。排查方法:检查API错误信息,验证Base64编码正确性,测试小样本PDF,逐步调试提示词。

企业应用扩展

生产环境优化:1)使用异步调用或批处理提高吞吐量;2)缓存叙述结果,避免重复计算;3)对于超长文档,采用分页叙述并合并;4)结合向量数据库存储叙述文本,实现语义搜索;5)针对特定领域微调提示词,提升准确性;6)监控API调用成本,优化token使用。可扩展场景:自动生成幻灯片摘要、财务报告分析、教育材料讲解等。

总结

本教程面向有编程基础的AI工程开发者,深入讲解如何利用Claude的视觉与PDF支持能力处理图表、图形及幻灯片。内容涵盖API调用方法、PDF文档摄取、提高图表分析准确性的技巧,以及将幻灯片转化为高质量文本叙述的完整流程。通过实际代码示例,展示如何构建可复用的处理管线,并讨论常见陷阱与优化策略,帮助开发者高效落地多模态文档分析任务。

内容来源与验证

继续系统学习

站内还有更多完整实战教程

加入会员,解锁全部教程、完整代码与持续更新内容。

加入会员
查看全部图像与多模态教程