Files
claude-code-api/examples/basic_usage.py
T

47 lines
1.3 KiB
Python

"""Minimal end-to-end example: one turn against a real `claude` CLI.
Prerequisites:
1. `claude` is on PATH and the user is logged in (`claude /login` once).
2. Your subscription is healthy (no rate limit, no auth block).
Run:
python examples/basic_usage.py
"""
from __future__ import annotations
import asyncio
import os
from pathlib import Path
from claude_code_api import (
AssistantMessage,
BackendOptions,
ClaudeCodeBackend,
ResultMessage,
TextBlock,
)
CWD = Path(os.environ.get("CLAUDE_CODE_CWD", Path.cwd())).resolve()
async def main() -> None:
opts = BackendOptions(cwd=str(CWD), dangerously_skip_permissions=True)
async with ClaudeCodeBackend(opts) as backend:
async for event in backend.complete(
[{"role": "user", "content": "Reply with the single word: OK"}]
):
if isinstance(event, AssistantMessage):
for block in event.content:
if isinstance(block, TextBlock):
print(f"[assistant] {block.text.strip()}")
elif isinstance(event, ResultMessage):
print(
f"[result] stop_reason={event.stop_reason} "
f"duration_ms={event.duration_ms}"
)
if __name__ == "__main__":
asyncio.run(main())