使用 Anthropic 的 Files API,您可以上传文件并在其他 API 调用中引用它们。 当同一流程中多次引用文件时,这会很方便。

用法

1

上传文件

初始化 Anthropic 客户端并使用 client.beta.files.upload

from anthropic import Anthropic

file_path = Path("path/to/your/file.pdf")

client = Anthropic()
uploaded_file = client.beta.files.upload(file=file_path)
2

初始化 Claude 模型

初始化 Claude 模型时,传递必要的 beta 标头:

from agno.agent import Agent
from agno.models.anthropic import Claude

agent = Agent(
    model=Claude(
        id="claude-opus-4-20250514",
        default_headers={"anthropic-beta": "files-api-2025-04-14"},
    )
)
3

引用文件

您现在可以在与 Agno 代理交互时引用已上传的文件:

agent.print_response(
    "Summarize the contents of the attached file.",
    files=[File(external=uploaded_file)],
)

请注意,此功能附带一些存储限制。您可以在 Anthropic 的文档中了解更多相关信息。

工作示例

cookbook/models/anthropic/pdf_input_file_upload.py
from pathlib import Path

from agno.agent import Agent
from agno.media import File
from agno.models.anthropic import Claude
from agno.utils.media import download_file
from anthropic import Anthropic

pdf_path = Path(__file__).parent.joinpath("ThaiRecipes.pdf")

# 使用 download_file 函数下载文件
download_file(
    "https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", str(pdf_path)
)

# 初始化 Anthropic 客户端
client = Anthropic()

# 将文件上传到 Anthropic
uploaded_file = client.beta.files.upload(
    file=Path(pdf_path),
)

if uploaded_file is not None:
    agent = Agent(
        model=Claude(
            id="claude-opus-4-20250514",
            default_headers={"anthropic-beta": "files-api-2025-04-14"},
        ),
        markdown=True,
    )

    agent.print_response(
        "Summarize the contents of the attached file.",
        files=[File(external=uploaded_file)],
    )