Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out

A refund claim arrives with a receipt photo and an invoice PDF. Send each file as its own typed content block, then read the thinking block and the text block that come back, and pass the thinking block back whole on the next turn.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Send a photo as an image block and a PDF as a document block, in front of the text question
  • Choose a source for a file: base64, a URL or a file id
  • Read the thinking block and the text block in a response, with display summarized or omitted
  • Send the assistant turn back unchanged, thinking block and signature included

Before you start

  • The Claude Messages API: your first call
  • Basic Python

A support agent handles refund claims all day. Today a claim arrives with a photo of the receipt, the invoice as a PDF, the question refund or not?, and one more wish: show me how you decided.

Plain text can't carry a photo. So every piece gets its own content block, and each block says what it is. Claude reads blocks, and it answers in blocks too: a thinking block with its reasoning, then a text block with the answer.

The output below comes from the lecture project, where a stand-in model (an httpx mock transport) answers and checks the shape of every request. Replies start with test model reply; the signature and token numbers are made up for the demo.

A claim folder with labels

Think of a claim folder on a desk. The photo of the receipt goes in as an image. The invoice sheet goes in as a document. The note with the question goes in as text. Every item says what it is, so the picture stays a picture. In the API, content is a list, and each block carries its own type.

Typed blocks in, typed blocks out Request: user content image (receipt.png) or document (invoice.pdf) text: the question the file block comes first Response: content thinking summary (or "") + signature text: the answer show the text block to the customer; keep the thinking block whole
A content list goes down, a content list comes back.

inputs.py: a photo and a PDF as blocks

"""Hand Claude a photo and a PDF: each travels as a content block beside the text."""
import base64
from pathlib import Path

from anthropic import Anthropic, DefaultHttpxClient

import stand_in


def make_client():
    http = DefaultHttpxClient(transport=stand_in.mock_transport())
    return Anthropic(api_key="test-key", http_client=http)


def encode(path):
    return base64.standard_b64encode(Path(path).read_bytes()).decode()


def image_block(path):
    source = {"type": "base64", "media_type": "image/png", "data": encode(path)}
    return {"type": "image", "source": source}


def image_url_block(url):
    return {"type": "image", "source": {"type": "url", "url": url}}


def pdf_block(path):
    kind = "application/pdf"
    source = {"type": "base64", "media_type": kind, "data": encode(path)}
    return {"type": "document", "source": source}


def ask_about(client, block, question):
    content = [block, {"type": "text", "text": question}]
    return client.messages.create(
        model=stand_in.MODEL,
        max_tokens=512,
        messages=[{"role": "user", "content": content}],
    )
  • An image block holds a source. With base64, the bytes of the file ride inside the request, and media_type names the format: JPEG, PNG, GIF or WebP.
  • A PDF is different: it goes in as a document block with media_type application/pdf.
  • If the file is hosted, point at a URL source instead.
  • In ask_about, the file block comes first and the question after it.

Base64, a link or a file id

A file can reach Claude in three ways. The block type stays the same; only the source changes.

SourceWhat travelsWhen it fits
base64The bytes, inside the requestA file you hold right now
urlA link to a file hosted onlineThe file is already public on the web
file (a file id)An id from the Files API, uploaded onceThe same file is used in many requests

A PDF can run to 600 pages; the page limit is lower on models with a smaller context window. Uploading once with the Files API, and which block a file type needs, are covered in Getting data into Claude: documents, the Files API and search results.

Here is what the three media calls sent and got back:

image call
blocks sent: image, text
source: base64 image/png
reply: test model reply: the photo shows a cafe receipt.
pdf call
blocks sent: document, text
source: base64 application/pdf
reply: test model reply: the document is an invoice.
url call
blocks sent: image, text
source: url

The stand-in checks the shape before it replies: a file block first, a text block last, valid base64, and a media type it accepts.

thinking.py: a thinking block, then the answer

Now the wish to see how the agent decided. We turn on adaptive thinking and ask for the reasoning summary to be shown, in the thinking field of the request. (How adaptive thinking and effort work as dials, and when thinking is worth its tokens, is in Adaptive thinking and effort in Claude. Here we focus on reading what comes back.)

"""Ask for reasoning, read the blocks that come back, keep them for later."""
import anthropic

import stand_in

SUMMARIZED = {"type": "adaptive", "display": "summarized"}


def ask_thinking(client, question, thinking=SUMMARIZED):
    return client.messages.create(
        model=stand_in.MODEL,
        max_tokens=2048,
        thinking=thinking,
        messages=[{"role": "user", "content": question}],
    )


def split_blocks(message):
    thoughts, answer = [], []
    for block in message.content:
        if block.type == "thinking":
            thoughts.append(block)
        elif block.type == "text":
            answer.append(block.text)
    return thoughts, "".join(answer)

The response content is a list of two blocks. First the thinking block: a summary of the reasoning in its thinking field, and a signature. Then the text block, the answer we show the customer.

The display setting changes only what you can see:

  • "summarized": the thinking field holds a readable summary.
  • "omitted": the thinking field is an empty string.

Either way the signature comes along, and the thinking is billed the same. On the model used here, Claude Sonnet 5.5, the default is omitted, so the project opts in to summarized.

thinking summarized
content blocks: thinking, text
thinking: test model reply: a summary of the reasoning.
answer: test model reply: start with the refund, then the delivery.
signature: sig_test_01
thinking omitted
content blocks: thinking, text
thinking text: ''
signature: sig_test_01

The next turn: send the thinking block back whole

When the conversation continues, the assistant turn goes back exactly as it came: message.content, thinking blocks included. Never edit them, never drop them.

def follow_up(client, question, message, next_question):
    # the assistant turn goes back as it came, thinking blocks included
    return client.messages.create(
        model=stand_in.MODEL,
        max_tokens=2048,
        thinking=SUMMARIZED,
        messages=[
            {"role": "user", "content": question},
            {"role": "assistant", "content": message.content},
            {"role": "user", "content": next_question},
        ],
    )


def manual_budget(client, question):
    old_way = {"type": "enabled", "budget_tokens": 1024}
    try:
        return ask_thinking(client, question, old_way)
    except anthropic.BadRequestError as err:
        return err

manual_budget shows the old way: type: "enabled" with budget_tokens. The newest models, Sonnet 5.5 among them, answer it with a 400, so code should use adaptive thinking instead.

next turn
assistant blocks sent: thinking, text
signature unchanged: yes
manual budget
status: 400 invalid_request_error

Common mistakes

  • Pasting the image data into the text. A photo needs its own image block with a source and a media type.
  • Sending a PDF as an image block. A PDF is a document block.
  • Putting the question before the file. The file block goes first, the text after it.
  • Turning on thinking with budget_tokens. The newest models reject it with a 400; use {"type": "adaptive"}.
  • Expecting a summary without asking. If the default is omitted, the thinking text is empty; set display: "summarized".
  • Showing the thinking block to the customer. Show the text block.
  • Dropping or editing thinking blocks in the history. Send message.content back unchanged, signature included.

Quick recap

PieceHow it travels
Photoimage block, source base64 (JPEG, PNG, GIF, WebP), URL or file id
PDFdocument block, application/pdf
Questiontext block, after the file block
Reasoningthinking: {"type": "adaptive", "display": "summarized"}
ResponseA thinking block (summary or "", signature), then a text block
Next turnThe assistant content goes back whole

Try it yourself

Add a jpeg_block to inputs.py that reads a .jpg file and sets image/jpeg. Then change follow_up to send only the text block of the assistant turn, and run it against the stand-in. Which check fails, and what would the real API lose without the thinking block?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 16 of 66

Previous
Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
Next post
Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Related posts

The Claude Messages API: Your First Call, Field by Field

One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.

Claude Tool Use: How tool_use and tool_result Work in the Messages API

Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.

Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared

Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.

Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move

Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.

On this page

  • A claim folder with labels
  • inputs.py: a photo and a PDF as blocks
  • Base64, a link or a file id
  • thinking.py: a thinking block, then the answer
  • The next turn: send the thinking block back whole
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.