# Python SDK: Agent Integration

This guide covers Pythonic patterns for integrating Keito with AI agents.

## Context Manager Pattern

The recommended approach — a `with` block that handles start, stop, and expense logging automatically:

```python
from keito import Keito

client = Keito()

with client.track_agent_work(
    project_id="prj_abc",
    task_id="tsk_001",
    agent_id="research-bot-03",
    model="claude-opus-4-6",
) as session:
    # Your agent does work here
    result = agent.run("Analyse Q4 billing data")

    # Report token usage — logged as LLM expense on exit
    session.report_tokens(input=18000, output=6000)
    session.set_notes("Analysed Q4 billing trends and generated summary")

# Time entry and LLM expense are created automatically
print(f"Tracked {session.hours:.2f}h, {session.total_tokens_k:.1f}k tokens")
```

If an exception is raised inside the `with` block, the time entry is automatically discarded (deleted).

## Decorator Pattern

For agent tool functions that should be tracked automatically:

```python
from keito import track

@track(project_id="prj_abc", task_id="tsk_001")
async def review_pull_request(pr_url: str) -> str:
    """Agent reviews a PR — time and cost tracked automatically."""
    response = await agent.review(pr_url)
    return response.summary
```

## Async Client

For high-throughput agent work, use the async client:

```python
from keito import AsyncKeito

client = AsyncKeito()

async with client.track_agent_work(
    project_id="prj_abc",
    agent_id="batch-processor",
    model="claude-sonnet-4-6",
) as session:
    results = await asyncio.gather(*[
        process_item(item) for item in items
    ])
    session.report_tokens(input=total_input, output=total_output)
```

## Metadata Best Practices

- Always include `agent_id` and `session_id`.
- Use `session_id` to correlate time entries with their LLM expenses.
- Keep metadata under 4KB.
- Include `model` for cost analysis across different LLMs.
- Don't store sensitive data in metadata — it's visible in reports.