-
Notifications
You must be signed in to change notification settings - Fork 3
feat: add Claude Agent SDK test script and Makefile targets #52
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
andrewm4894
wants to merge
5
commits into
main
Choose a base branch
from
feat/claude-agent-sdk-provider
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+216
−1
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c4ecfc1
feat: add Claude Agent SDK test script
andrewm4894 becb126
chore: add Makefile targets and docs for Claude Agent SDK test
andrewm4894 ff7c20f
chore: add uv exclude-newer for supply chain safety
andrewm4894 2389f5b
fix: run uv sync before installing local SDK
andrewm4894 921746b
feat: use PostHogClaudeSDKClient for stateful interactive mode
andrewm4894 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| #!/usr/bin/env python3 | ||
| """ | ||
| Claude Agent SDK test script for PostHog LLM Analytics. | ||
|
|
||
| Tests the posthog.ai.claude_agent_sdk integration by running a multi-turn | ||
| conversation with tool calls. Sends $ai_generation, $ai_span, and $ai_trace | ||
| events to the configured PostHog instance. | ||
|
|
||
| Usage: | ||
| uv run scripts/test_claude_agent_sdk.py | ||
| uv run scripts/test_claude_agent_sdk.py --prompt "What files are in the current directory?" | ||
| uv run scripts/test_claude_agent_sdk.py --interactive | ||
| """ | ||
|
|
||
| import argparse | ||
| import asyncio | ||
| import os | ||
| import sys | ||
|
|
||
| from dotenv import load_dotenv | ||
|
|
||
| load_dotenv() | ||
|
|
||
|
|
||
| def _check_deps(): | ||
| missing = [] | ||
| try: | ||
| import claude_agent_sdk # noqa: F401 | ||
| except ImportError: | ||
| missing.append("claude-agent-sdk") | ||
| try: | ||
| import posthog # noqa: F401 | ||
| except ImportError: | ||
| missing.append("posthog") | ||
| try: | ||
| from posthog.ai.claude_agent_sdk import query # noqa: F401 | ||
| except ImportError: | ||
| missing.append("posthog (with claude_agent_sdk integration — needs posthog>=7.10.0)") | ||
| if missing: | ||
| print(f"Missing dependencies: {', '.join(missing)}") | ||
| print("Install with: uv add claude-agent-sdk posthog") | ||
| sys.exit(1) | ||
|
|
||
|
|
||
| def _setup_posthog(): | ||
| from posthog import Posthog | ||
|
|
||
| api_key = os.environ.get("POSTHOG_API_KEY") | ||
| host = os.environ.get("POSTHOG_HOST", "https://us.i.posthog.com") | ||
| if not api_key: | ||
| print("POSTHOG_API_KEY not set in environment. Events won't be sent.") | ||
| return None | ||
| return Posthog(api_key, host=host) | ||
|
|
||
|
|
||
| async def run_query(prompt: str, posthog_client, distinct_id: str, extra_props: dict): | ||
| from claude_agent_sdk import ClaudeAgentOptions, AssistantMessage, ResultMessage | ||
| from claude_agent_sdk.types import TextBlock, ToolUseBlock, StreamEvent | ||
| from posthog.ai.claude_agent_sdk import query | ||
|
|
||
| options = ClaudeAgentOptions( | ||
| max_turns=10, | ||
| allowed_tools=["Read", "Glob", "Grep", "Bash"], | ||
| permission_mode="bypassPermissions", | ||
| ) | ||
|
|
||
| print(f"\n> {prompt}\n") | ||
|
|
||
| async for message in query( | ||
| prompt=prompt, | ||
| options=options, | ||
| posthog_client=posthog_client, | ||
| posthog_distinct_id=distinct_id, | ||
| posthog_properties=extra_props, | ||
| ): | ||
| if isinstance(message, AssistantMessage): | ||
| for block in message.content: | ||
| if isinstance(block, TextBlock): | ||
| print(f" {block.text[:300]}") | ||
| elif isinstance(block, ToolUseBlock): | ||
| print(f" [tool] {block.name}({list(block.input.keys())})") | ||
| elif isinstance(message, StreamEvent): | ||
| event_type = message.event.get("type") | ||
| if event_type == "message_start": | ||
| print(" [streaming...]") | ||
| elif isinstance(message, ResultMessage): | ||
| print(f"\n --- Result ---") | ||
| print(f" Cost: ${message.total_cost_usd}") | ||
| print(f" Turns: {message.num_turns}") | ||
| print(f" Duration: {message.duration_ms}ms") | ||
| print(f" Error: {message.is_error}") | ||
|
|
||
|
|
||
| async def run_interactive(posthog_client, distinct_id: str): | ||
| from claude_agent_sdk import ClaudeAgentOptions, AssistantMessage, ResultMessage | ||
| from claude_agent_sdk.types import TextBlock, ToolUseBlock | ||
| from posthog.ai.claude_agent_sdk import PostHogClaudeSDKClient | ||
|
|
||
| options = ClaudeAgentOptions( | ||
| max_turns=10, | ||
| allowed_tools=["Read", "Glob", "Grep", "Bash"], | ||
| permission_mode="bypassPermissions", | ||
| ) | ||
|
|
||
| print("\nClaude Agent SDK — Interactive Mode (stateful, multi-turn)") | ||
| print("Type 'quit' to exit\n") | ||
|
|
||
| async with PostHogClaudeSDKClient( | ||
| options, | ||
| posthog_client=posthog_client, | ||
| posthog_distinct_id=distinct_id, | ||
| posthog_properties={"app": "llm-analytics-apps", "mode": "interactive"}, | ||
| ) as client: | ||
| while True: | ||
| try: | ||
| prompt = input("> ").strip() | ||
| if not prompt: | ||
| continue | ||
| if prompt.lower() in ("quit", "exit", "q"): | ||
| break | ||
|
|
||
| await client.query(prompt) | ||
| async for message in client.receive_response(): | ||
| if isinstance(message, AssistantMessage): | ||
| for block in message.content: | ||
| if isinstance(block, TextBlock): | ||
| print(f" {block.text[:500]}") | ||
| elif isinstance(block, ToolUseBlock): | ||
| print(f" [tool] {block.name}") | ||
| elif isinstance(message, ResultMessage): | ||
| print(f" [{message.num_turns} turns, ${message.total_cost_usd:.4f}]") | ||
| print() | ||
|
|
||
| except KeyboardInterrupt: | ||
| break | ||
| except Exception as e: | ||
| print(f" [error] {e}") | ||
|
|
||
|
|
||
| def main(): | ||
| parser = argparse.ArgumentParser(description="Test Claude Agent SDK + PostHog LLM Analytics") | ||
| parser.add_argument( | ||
| "--prompt", | ||
| default="List the files in the current directory and tell me what this project is about. Be brief.", | ||
| help="Prompt to send", | ||
| ) | ||
| parser.add_argument("--interactive", "-i", action="store_true", help="Interactive chat mode") | ||
| parser.add_argument( | ||
| "--distinct-id", | ||
| default=os.environ.get("POSTHOG_DISTINCT_ID", "claude-agent-sdk-test"), | ||
| help="PostHog distinct ID", | ||
| ) | ||
| args = parser.parse_args() | ||
|
|
||
| _check_deps() | ||
| posthog_client = _setup_posthog() | ||
| distinct_id = args.distinct_id | ||
|
|
||
| extra_props = { | ||
| "app": "llm-analytics-apps", | ||
| "script": "test_claude_agent_sdk", | ||
| } | ||
|
|
||
| if args.interactive: | ||
| asyncio.run(run_interactive(posthog_client, distinct_id)) | ||
| else: | ||
| asyncio.run(run_query(args.prompt, posthog_client, distinct_id, extra_props)) | ||
|
|
||
| if posthog_client: | ||
| posthog_client.shutdown() | ||
| print("\nPostHog events flushed.") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
install-local-sdkrunsuv pip install -e ../posthog-python, butuv pip installrequires an existing virtual environment; on a clean checkout this fails with “No virtual environment found” before the local SDK is installed. Because the new docs instruct this as the first Claude integration step, the documented workflow is blocked for first-time users. Have this target create/sync.venv(or otherwise guarantee an env) before invokinguv pip install.Useful? React with 👍 / 👎.