|
| 1 | +"""Claude Agent SDK multi-turn conversation with history, tracked by PostHog.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import os |
| 5 | + |
| 6 | +from claude_agent_sdk import AssistantMessage, ResultMessage |
| 7 | +from claude_agent_sdk.types import ClaudeAgentOptions, TextBlock, ToolUseBlock |
| 8 | +from posthog import Posthog |
| 9 | +from posthog.ai.claude_agent_sdk import PostHogClaudeSDKClient |
| 10 | + |
| 11 | +posthog = Posthog( |
| 12 | + os.environ["POSTHOG_API_KEY"], |
| 13 | + host=os.environ.get("POSTHOG_HOST", "https://us.i.posthog.com"), |
| 14 | +) |
| 15 | + |
| 16 | + |
| 17 | +async def main(): |
| 18 | + options = ClaudeAgentOptions( |
| 19 | + max_turns=5, |
| 20 | + permission_mode="plan", |
| 21 | + ) |
| 22 | + |
| 23 | + async with PostHogClaudeSDKClient( |
| 24 | + options, |
| 25 | + posthog_client=posthog, |
| 26 | + posthog_distinct_id="example-user", |
| 27 | + posthog_properties={"example": "multi_turn"}, |
| 28 | + ) as client: |
| 29 | + # Turn 1 |
| 30 | + print("> What is the capital of France?") |
| 31 | + await client.query("What is the capital of France? Reply in one sentence.") |
| 32 | + async for message in client.receive_response(): |
| 33 | + if isinstance(message, AssistantMessage): |
| 34 | + for block in message.content: |
| 35 | + if isinstance(block, TextBlock): |
| 36 | + print(f" {block.text}") |
| 37 | + elif isinstance(message, ResultMessage): |
| 38 | + print(f" [{message.num_turns} turns, ${message.total_cost_usd:.4f}]") |
| 39 | + |
| 40 | + # Turn 2 — has full conversation history |
| 41 | + print("\n> And what language do they speak there?") |
| 42 | + await client.query("And what language do they speak there? Reply in one sentence.") |
| 43 | + async for message in client.receive_response(): |
| 44 | + if isinstance(message, AssistantMessage): |
| 45 | + for block in message.content: |
| 46 | + if isinstance(block, TextBlock): |
| 47 | + print(f" {block.text}") |
| 48 | + elif isinstance(message, ResultMessage): |
| 49 | + print(f" [{message.num_turns} turns, ${message.total_cost_usd:.4f}]") |
| 50 | + |
| 51 | + # Turn 3 — still has context from both previous turns |
| 52 | + print("\n> How do you say 'hello' in that language?") |
| 53 | + await client.query("How do you say 'hello' in that language? Reply in one sentence.") |
| 54 | + async for message in client.receive_response(): |
| 55 | + if isinstance(message, AssistantMessage): |
| 56 | + for block in message.content: |
| 57 | + if isinstance(block, TextBlock): |
| 58 | + print(f" {block.text}") |
| 59 | + elif isinstance(message, ResultMessage): |
| 60 | + print(f" [{message.num_turns} turns, ${message.total_cost_usd:.4f}]") |
| 61 | + |
| 62 | + |
| 63 | +asyncio.run(main()) |
| 64 | +posthog.shutdown() |
0 commit comments