Tutorials · Claude Agent SDK · examples / python / 03_multi_turn.pyExample code

Example code · python

03_multi_turn.py

Multi-turn conversation with ClaudeSDKClient. The second turn relies on the first.

Raw fileDownload all examples (zip)See its output →

Used in Part 1 · Multi-turn with ClaudeSDKClient

"""03: Multi-turn conversation with ClaudeSDKClient. The second turn relies on the first."""

import asyncio

from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ClaudeSDKClient, ResultMessage, TextBlock
from demo_util import PROJECT


def print_response(message):
    if isinstance(message, AssistantMessage):
        for block in message.content:
            if isinstance(block, TextBlock):
                print(f"Claude: {block.text}")
    elif isinstance(message, ResultMessage):
        print(f"[done: {message.subtype}, turns={message.num_turns}, cost=${message.total_cost_usd:.4f}]\n")


async def main():
    options = ClaudeAgentOptions(cwd=PROJECT, allowed_tools=["Read", "Glob", "Grep"], max_turns=6)

    async with ClaudeSDKClient(options=options) as client:
        await client.query("Which function in src/app.py has a SQL injection bug? Name it only.")
        async for message in client.receive_response():
            print_response(message)

        # No session ID handling needed: the client continues the same session.
        await client.query("Show me the one-line fix for that function, as a code snippet only.")
        async for message in client.receive_response():
            print_response(message)


asyncio.run(main())

33 lines · Back to the folder