File Upload

Upload and reference files using Anthropic's Files API in Kern.

With Anthropic's Files API, you can upload files and later reference them in other API calls. This is handy when a file is referenced multiple times in the same flow.

Usage

Upload a file

Initialize the Anthropic client and use client.beta.files.upload:

1from anthropic import Anthropic
2
3file_path = Path("path/to/your/file.pdf")
4
5client = Anthropic()
6uploaded_file = client.beta.files.upload(file=file_path)

Initialize the Claude model

When initializing the Claude model, pass the necessary beta header:

1from kern.agent import Agent
2from kern.models.anthropic import Claude
3
4agent = Agent(
5 model=Claude(
6 id="claude-opus-4-20250514",
7 betas=["files-api-2025-04-14"],
8 )
9)

Reference the file

You can now reference the uploaded file when interacting with your Kern agent:

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

Notice there are some storage limits attached to this feature. You can read more about that on Anthropic's docs.

Working example

1from pathlib import Path
2
3from kern.agent import Agent
4from kern.media import File
5from kern.models.anthropic import Claude
6from kern.utils.media import download_file
7from anthropic import Anthropic
8
9pdf_path = Path(__file__).parent.joinpath("ThaiRecipes.pdf")
10
11# Download the file using the download_file function
12download_file(
13 "https://kern-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf", str(pdf_path)
14)
15
16# Initialize Anthropic client
17client = Anthropic()
18
19# Upload the file to Anthropic
20uploaded_file = client.beta.files.upload(
21 file=Path(pdf_path),
22)
23
24if uploaded_file is not None:
25 agent = Agent(
26 model=Claude(
27 id="claude-opus-4-20250514",
28 betas=["files-api-2025-04-14"],
29 ),
30 markdown=True,
31 )
32
33 agent.print_response(
34 "Summarize the contents of the attached file.",
35 files=[File(external=uploaded_file)],
36 )