Skip to main content
Make your Claude-based agents remember previous turns so they can build and refine things across a conversation. Short-lived calls to query work well for one-off tasks: you ask, Claude answers, the session ends, and the model forgets everything. But many workflows—like iteratively crafting infrastructure templates or incrementally editing code—need memory. That’s where the stateful client comes in: it preserves the conversation so each new turn can reference everything that came before.
A split infographic titled "From Forgetful to Stateful" comparing a single-turn query (left) that forgets context and returns "What bucket? I have no memory of that." with a multi-turn client (right) that retains context and successfully adds "AES256 to your bucket." The panels show example conversation bubbles about creating an S3 bucket and adding encryption, highlighting "Memory wiped between calls" versus "Context kept across every turn."

Stateful client: ClaudeSDKClient

Use ClaudeSDKClient when you need cross-turn memory. Open the client with an async context manager:
  • Enter the session with async with ClaudeSDKClient(...) to start a stateful connection.
  • Exit the context to shut the session down cleanly.
Within that context the pattern intentionally splits into two steps:
  1. Send user instructions with client.query(...).
  2. Read the assistant’s replies using client.receive_response().
This split (send, then receive) lets the session remain open across many turns. The fused query helper performs both steps at once for short-lived interactions; the stateful client separates them so the conversation can accumulate.

Minimal send/receive example

How the memory works — and its cost

Every time you call client.query, the SDK includes the full conversation history in the request payload. That means:
  • Turn 1 sends one message.
  • Turn 2 sends turn 1 + new message.
  • Turn N sends all N messages.
Because the full history is sent on every call, Claude can recall previous facts (e.g., “Alex”, favorite color, or earlier template details) without you repeating them. That makes iterative workflows natural: the model edits what it created earlier rather than starting from scratch. But there’s a tradeoff: the request payload grows every turn, which increases token usage, latency, and cost—and eventually risks hitting the model’s context window.
Preserving full conversation history improves continuity but increases token usage and latency. Monitor the size of your history and consider summarizing, pruning, or checkpointing older turns to control costs and avoid context limits.

Safety controls: permission mode and allowed tools

Before Claude can modify files or run commands, decide what it’s allowed to do. The SDK exposes two complementary controls:
  • Permission mode (how freely Claude may act), e.g., acceptEdits to auto-approve file edits or default for a more cautious, confirmation-first posture.
  • Allowed tools (a whitelist of actions Claude may take), e.g., Write, Bash, etc. An empty list means the agent can only provide guidance.
Together they enable safe, production-ready agents. Use stricter modes and minimal tool sets for sensitive environments; relax them in trusted automation pipelines.

Iterative infrastructure building (practical payoff)

With a stateful client you can grow a single template across multiple turns. For example:
  • Turn 1: “Create a starter S3 bucket and save it as s3template.yaml.”
  • Turn 2: “Enable versioning and AES-256 encryption.”
  • Turn 3: “Add lifecycle rules, public access block, and tags.”
Because the agent keeps the earlier file in its conversation history, it edits that same file rather than re-creating or duplicating it. Here’s a representative CloudFormation snippet Claude might produce and refine across turns:
This single-file, multi-turn workflow is far more ergonomic than copying and pasting YAML into each prompt for one-off query calls.

Interactive builder pattern

Wrap the stateful loop in a user input loop and you get an interactive builder: open the client once, then repeatedly accept user instructions until the session ends.
Swap the initial prompt, output paths, and allowed tools and this skeleton becomes a code generator, config wizard, or documentation authoring assistant.

Summary and next steps

Use ClaudeSDKClient when conversation continuity matters: it preserves history so the agent can iteratively build, edit, and refine artifacts across multiple turns. Balance that convenience against token growth and latency by pruning or summarizing history where appropriate, and apply permission modes plus a minimal allowed tools list to keep agents safe in production. Next, you’ll learn how to package common capabilities into reusable components so agents can load and run them on demand.

Watch Video

Practice Lab