Metadata-Version: 2.4
Name: chaukas-sdk
Version: 0.1.0
Summary: One-line instrumentation for agent building SDKs
Author-email: Chaukas <2153483+ranesidd@users.noreply.github.com>
License: Apache License
        Version 2.0, January 2004
        http://www.apache.org/licenses/
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
        1. Definitions.
        
           "License" shall mean the terms and conditions for use, reproduction,
           and distribution as defined by Sections 1 through 9 of this document.
        
           "Licensor" shall mean the copyright owner or entity granting the License.
        
           "Legal Entity" shall mean the union of the acting entity and all
           other entities that control, are controlled by, or are under common
           control with that entity. For the purposes of this definition,
           "control" means (i) the power, direct or indirect, to cause the
           direction or management of such entity, whether by contract or
           otherwise, or (ii) ownership of fifty percent (50%) or more of the
           outstanding shares, or (iii) beneficial ownership of such entity.
        
           "You" (or "Your") shall mean an individual or Legal Entity
           exercising permissions granted by this License.
        
           "Source" shall mean the preferred form for making modifications,
           including but not limited to software source code, documentation
           source, and configuration files.
        
           "Object" shall mean any form resulting from mechanical
           transformation or translation of a Source form, including but
           not limited to compiled object code, generated documentation,
           and conversions to other media types.
        
           "Work" shall mean the work of authorship, whether in Source or
           Object form, made available under the License, as indicated by a
           copyright notice that is included in or attached to the work
           (which shall not include contributions aggregated with other works).
        
           "Derivative Works" shall mean any work, whether in Source or Object
           form, that is based upon (or derived from) the Work and for which the
           editorial revisions, annotations, elaborations, or other modifications
           represent, as a whole, an original work of authorship. For the purposes
           of this License, Derivative Works shall not include works that remain
           separable from, or merely link (or bind by name) to the interfaces of,
           the Work and derivative works thereof.
        
           "Contribution" shall mean any work of authorship, including
           the original version of the Work and any modifications or additions
           to that Work or Derivative Works thereof, that is intentionally
           submitted to Licensor for inclusion in the Work by the copyright owner
           or by an individual or Legal Entity authorized to submit on behalf of
           the copyright owner. For the purposes of this definition, "submitted"
           means any form of electronic, verbal, or written communication sent
           to the Licensor or its representatives, including but not limited to
           communication on electronic mailing lists, source code control
           systems, and issue tracking systems that are managed by, or on behalf
           of, the Licensor for the purpose of discussing and improving the Work,
           but excluding communication that is conspicuously marked or otherwise
           designated in writing by the copyright owner as "Not a Contribution."
        
           "Contributor" shall mean Licensor and any individual or Legal Entity
           on behalf of whom a Contribution has been received by Licensor and
           subsequently incorporated within the Work.
        
        2. Grant of Copyright License. Subject to the terms and conditions of
           this License, each Contributor hereby grants to You a perpetual,
           worldwide, non-exclusive, no-charge, royalty-free, irrevocable
           copyright license to use, reproduce, modify, merge, publish,
           distribute, sublicense, and/or sell copies of the Work, and to
           permit persons to whom the Work is furnished to do so, subject to
           the following conditions:
        
           The above copyright notice and this permission notice shall be
           included in all copies or substantial portions of the Work.
        
        3. Grant of Patent License. Subject to the terms and conditions of
           this License, each Contributor hereby grants to You a perpetual,
           worldwide, non-exclusive, no-charge, royalty-free, irrevocable
           (except as stated in this section) patent license to make, have made,
           use, offer to sell, sell, import, and otherwise transfer the Work,
           where such license applies only to those patent claims licensable
           by such Contributor that are necessarily infringed by their
           Contribution(s) alone or by combination of their Contribution(s)
           with the Work to which such Contribution(s) was submitted. If You
           institute patent litigation against any entity (including a
           cross-claim or counterclaim in a lawsuit) alleging that the Work
           or a Contribution incorporated within the Work constitutes direct
           or contributory patent infringement, then any patent licenses
           granted to You under this License for that Work shall terminate
           as of the date such litigation is filed.
        
        4. Redistribution. You may reproduce and distribute copies of the
           Work or Derivative Works thereof in any medium, with or without
           modifications, and in Source or Object form, provided that You
           meet the following conditions:
        
           (a) You must give any other recipients of the Work or
               Derivative Works a copy of this License; and
        
           (b) You must cause any modified files to carry prominent notices
               stating that You changed the files; and
        
           (c) You must retain, in the Source form of any Derivative Works
               that You distribute, all copyright, trademark, patent,
               attribution and other notices from the Source form of the Work,
               excluding those notices that do not pertain to any part of
               the Derivative Works; and
        
           (d) If the Work includes a "NOTICE" file as part of its
               distribution, then any Derivative Works that You distribute must
               include a readable copy of the attribution notices contained
               within such NOTICE file, excluding those notices that do not
               pertain to any part of the Derivative Works, in at least one
               of the following places: within a NOTICE file distributed
               as part of the Derivative Works; within the Source form or
               documentation, if provided along with the Derivative Works; or,
               within a display generated by the Derivative Works, if and
               wherever such third-party notices normally appear. The contents
               of the NOTICE file are for informational purposes only and
               do not modify the License. You may add Your own attribution
               notices within Derivative Works that You distribute, alongside
               or as an addendum to the NOTICE text from the Work, provided
               that such additional attribution notices cannot be construed
               as modifying the License.
        
           You may add Your own copyright notice to Your modifications and
           may provide additional or different license terms and conditions
           for use, reproduction, or distribution of Your modifications, or
           for any such Derivative Works as a whole, provided Your use,
           reproduction, and distribution of the Work otherwise complies with
           the conditions stated in this License.
        
        5. Submission of Contributions. Unless You explicitly state otherwise,
           any Contribution intentionally submitted for inclusion in the Work
           by You to the Licensor shall be under the terms and conditions of
           this License, without any additional terms or conditions.
           Notwithstanding the above, nothing herein shall supersede or modify
           the terms of any separate license agreement you may have executed
           with Licensor regarding such Contributions.
        
        6. Trademarks. This License does not grant permission to use the trade
           names, trademarks, service marks, or product names of the Licensor,
           except as required for reasonable and customary use in describing the
           origin of the Work and reproducing the content of the NOTICE file.
        
        7. Disclaimer of Warranty. Unless required by applicable law or
           agreed to in writing, Licensor provides the Work (and each
           Contributor provides its Contributions) on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
           implied, including, without limitation, any warranties or conditions
           of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
           PARTICULAR PURPOSE. You are solely responsible for determining the
           appropriateness of using or redistributing the Work and assume any
           risks associated with Your exercise of permissions under this License.
        
        8. Limitation of Liability. In no event and under no legal theory,
           whether in tort (including negligence), contract, or otherwise,
           unless required by applicable law (such as deliberate and grossly
           negligent acts) or agreed to in writing, shall any Contributor be
           liable to You for damages, including any direct, indirect, special,
           incidental, or consequential damages of any character arising as a
           result of this License or out of the use or inability to use the
           Work (including but not limited to damages for loss of goodwill,
           work stoppage, computer failure or malfunction, or any and all
           other commercial damages or losses), even if such Contributor
           has been advised of the possibility of such damages.
        
        9. Accepting Warranty or Additional Conditions. When redistributing
           the Work or Derivative Works thereof, You may choose to offer,
           and charge a fee for, acceptance of support, warranty, indemnity,
           or other liability obligations and/or rights consistent with this
           License. However, in accepting such obligations, You may act only
           on Your own behalf and on Your sole responsibility, not on behalf
           of any other Contributor, and only if You agree to indemnify,
           defend, and hold each Contributor harmless for any liability
           incurred by, or claims asserted against, such Contributor by reason
           of your accepting any such warranty or additional conditions.
        
        END OF TERMS AND CONDITIONS
        
        APPENDIX: How to apply the Apache License to your work.
        
           To apply the Apache License to your work, attach the following
           boilerplate notice, with the fields enclosed by brackets "[]"
           replaced with your own identifying information. (Don't include
           the brackets!)  The text should be enclosed in comment characters
           for the file format. You may also include this line in the source
           code files themselves, where appropriate.
        
        Copyright [yyyy] [name of copyright owner]
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
            http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
        
Project-URL: Homepage, https://chaukas.ai
Project-URL: Repository, https://github.com/chaukasai/chaukas-sdk
Project-URL: Documentation, https://github.com/chaukasai/chaukas-sdk#readme
Project-URL: Issues, https://github.com/chaukasai/chaukas-sdk/issues
Project-URL: Changelog, https://github.com/chaukasai/chaukas-sdk/blob/main/CHANGELOG.md
Project-URL: Spec, https://github.com/chaukasai/chaukas-spec
Keywords: ai,agents,observability,instrumentation,tracing,openai,crewai,langchain,monitoring,telemetry,llm,agentic,chaukas-spec
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: chaukas-spec-client>=1.0.0
Requires-Dist: wrapt>=1.14.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: httpx>=0.24.0
Requires-Dist: typing-extensions>=4.0.0
Requires-Dist: protobuf>=5.26.0
Requires-Dist: grpcio>=1.50.0
Requires-Dist: uuid6>=2024.1.12
Requires-Dist: aiofiles>=23.0.0
Provides-Extra: openai
Requires-Dist: openai-agents<1.0.0,>=0.5.0; extra == "openai"
Provides-Extra: google
Requires-Dist: adk; extra == "google"
Provides-Extra: crewai
Requires-Dist: crewai<2.0.0,>=1.4.1; extra == "crewai"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-mock>=3.10.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: isort>=5.12.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

<div align="center">

# 🔍 Chaukas SDK

**One line to instrument your agent and capture every event in an immutable, queryable audit trail.**

*Open-source SDK implementing [chaukas-spec](https://github.com/chaukasai/chaukas-spec) for standardized agent instrumentation*

[![PyPI version](https://badge.fury.io/py/chaukas-sdk.svg)](https://badge.fury.io/py/chaukas-sdk)
[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Tests](https://img.shields.io/badge/tests-passing-brightgreen.svg)]()
[![Coverage](https://img.shields.io/badge/coverage-90%25-brightgreen.svg)]()

[Quick Start](#-quick-start) • [Documentation](#-documentation) • [Examples](#-examples) • [chaukas-spec](#-supported-frameworks) • [Community](#-community)

</div>

---

## 🎯 Why Chaukas?

Building AI agents is hard. **Understanding what they're doing is harder.**

Chaukas SDK is an **open-source SDK** that implements the **[chaukas-spec](https://github.com/chaukasai/chaukas-spec)** — a standardized event schema for AI agent instrumentation. It gives you X-ray vision into your AI agents with **zero configuration**:

```python
import chaukas
chaukas.enable_chaukas()  # That's it. You're done.

# Your existing agent code works unchanged
agent = Agent(name="assistant", model="gpt-4")
result = await agent.run(messages=[...])
```

**Instantly get:**
- 🎯 Complete execution traces with distributed tracing
- 🔄 Automatic retry detection and tracking
- 🛠️ Tool call monitoring and performance metrics
- 🤝 Multi-agent handoff visualization
- 🚨 Error tracking with full context
- 📊 LLM token usage and cost tracking
- 🔐 Policy enforcement and compliance logs
- 🎨 Beautiful, queryable event streams

## ✨ What Makes Chaukas Different

| Feature | Chaukas | Traditional APM | Manual Logging |
|---------|---------|-----------------|----------------|
| **Setup Time** | 1 line | Hours | Days |
| **Code Changes** | Zero | Extensive | Everywhere |
| **Agent-Native** | ✅ 100% | ❌ Adapted | ❌ Custom |
| **Event Coverage** | 🎉 [19/19 chaukas-spec](https://github.com/chaukasai/chaukas-spec) | ⚠️ Partial | 🤷 Up to you |
| **Standardized Schema** | ✅ [chaukas-spec](https://github.com/chaukasai/chaukas-spec) | ❌ Proprietary | ❌ None |
| **Multi-Agent Tracking** | ✅ Built-in | ❌ Manual | ❌ Complex |
| **MCP Protocol** | ✅ Native | ❌ No support | ❌ Manual |
| **Distributed Tracing** | ✅ Automatic | ⚠️ Requires setup | ❌ Hard |
| **Type Safety** | ✅ Full | ⚠️ Partial | ❌ None |

## 🚀 Quick Start

### Installation

```bash
pip install chaukas-sdk
```

### Configuration

Set your environment variables (or pass them programmatically):

```bash
export CHAUKAS_TENANT_ID="your-tenant"
export CHAUKAS_PROJECT_ID="your-project"
export CHAUKAS_ENDPOINT="https://api.chaukas.ai"
export CHAUKAS_API_KEY="your-api-key"
```

### Usage

#### OpenAI Agents

```python
import chaukas
from openai import OpenAI
from openai.agents import Agent

# Enable instrumentation
chaukas.enable_chaukas()

# Your code works exactly as before
client = OpenAI()
agent = Agent(
    name="data-analyst",
    instructions="You are a helpful data analyst.",
    model="gpt-4o",
    client=client
)

result = await agent.run(
    messages=[{"role": "user", "content": "Analyze Q4 revenue"}]
)

# Chaukas automatically captures:
# ✅ Session start/end
# ✅ Agent lifecycle
# ✅ LLM invocations with tokens
# ✅ Tool calls and results
# ✅ Errors and retries
# ✅ Policy decisions
# ✅ State changes
```

#### CrewAI

```python
import chaukas
from crewai import Agent, Task, Crew, Process

chaukas.enable_chaukas()

# Define your crew
researcher = Agent(
    role="Senior Research Analyst",
    goal="Uncover cutting-edge developments in AI",
    backstory="You're an expert at finding insights",
    verbose=True
)

task = Task(
    description="Research latest AI trends",
    agent=researcher,
    expected_output="A comprehensive report"
)

crew = Crew(
    agents=[researcher],
    tasks=[task],
    process=Process.sequential
)

# Full observability out of the box
result = crew.kickoff()
```

#### Google ADK

```python
import chaukas
from adk import Agent

chaukas.enable_chaukas()

agent = Agent(name="assistant")
response = agent.run("Hello!")
```

## 📊 Supported Frameworks

Chaukas SDK implements the **[chaukas-spec](https://github.com/chaukasai/chaukas-spec)** — a standardized event schema with **19 event types** for AI agent observability.

| Framework | Version | Events | Status | Notes |
|-----------|---------|--------|--------|-------|
| **[OpenAI Agents](https://github.com/openai/openai-agents-python)** | `>=0.5.0,<1.0.0` | 🎉 **19/19** | 🟢 Production | Session mgmt, MCP protocol, policy tracking, state updates, retries |
| **[CrewAI](https://github.com/crewAIInc/crewAI)** | `>=1.4.1,<2.0.0` | 🎉 **19/19** | 🟢 Production | Event bus integration, multi-agent handoffs, knowledge sources, guardrails, flows |
| **[Google ADK](https://github.com/google/adk-python)** | Latest | 🚧 **5/19** | 🟡 Under Construction | Basic agent & LLM tracking |

**Coming Soon**: LangChain, LangGraph, AutoGen, Microsoft Semantic Kernel

*All frameworks implementing the complete [chaukas-spec](https://github.com/chaukasai/chaukas-spec) capture all 19 event types*

## 🎨 Event Types (chaukas-spec)

The **[chaukas-spec](https://github.com/chaukasai/chaukas-spec)** defines **19 standardized event types** for AI agent observability. Chaukas SDK captures all of them automatically:

### 🎭 Agent Lifecycle
```python
SESSION_START       # User session begins
SESSION_END         # Session completes
AGENT_START         # Agent begins execution
AGENT_END           # Agent finishes
AGENT_HANDOFF       # Control transfers between agents
```

### 🧠 Model Operations
```python
MODEL_INVOCATION_START  # LLM call initiated
MODEL_INVOCATION_END    # LLM responds (includes tokens, cost)
```

### 🛠️ Tool Execution
```python
TOOL_CALL_START     # Tool execution begins
TOOL_CALL_END       # Tool completes with result
MCP_CALL_START      # Model Context Protocol call starts
MCP_CALL_END        # MCP operation completes
```

### 💬 I/O Tracking
```python
INPUT_RECEIVED      # User input captured
OUTPUT_EMITTED      # Agent output generated
```

### 🚨 Operational Intelligence
```python
ERROR               # Error with full context
RETRY               # Automatic retry detected (rate limits, timeouts)
POLICY_DECISION     # Content filtering, guardrails enforced
DATA_ACCESS         # Knowledge base, file, or API access
STATE_UPDATE        # Agent configuration changes
SYSTEM_EVENT        # Framework initialization, shutdown
```

## 🔥 Advanced Features

### Distributed Tracing

Every event includes full trace context:

```python
{
  "event_id": "019a6700-adb9-718d-0bc9-0000415845aa",
  "session_id": "019a6700-adb7-7a30-a548-000077453f71",
  "trace_id": "019a6700-adb7-7ef3-1e46-0000ae993c28",
  "span_id": "019a6700-adb9-706a-0a26-000073699939",
  "parent_span_id": "019a6700-adb7-7b27-1858-0000ee8d895b",
  "type": "EVENT_TYPE_TOOL_CALL_END",
  "agent_id": "data-analyst",
  "timestamp": "2025-01-08T12:34:56.789Z"
}
```

Visualize complete request flows across:
- Multiple agents
- LLM calls
- Tool invocations
- External API calls

### Intelligent Retry Detection

Chaukas automatically detects and tracks retries:

```python
# Your code
try:
    result = await agent.run(messages)
except RateLimitError:
    await asyncio.sleep(2)  # Exponential backoff
    result = await agent.run(messages)  # Retry

# Chaukas captures:
# 1. ERROR event (rate limit)
# 2. RETRY event (attempt 1, exponential strategy, 2000ms delay)
# 3. MODEL_INVOCATION_START (retry attempt)
# 4. MODEL_INVOCATION_END (success)
```

### MCP Protocol Support

**Only SDK with native MCP instrumentation:**

```python
from agents import Agent
from agents.mcp import MCPServerStreamableHttp

# MCP server setup
mcp_server = MCPServerStreamableHttp(
    url="http://localhost:8000",
    server_name="documentation-server"
)

agent = Agent(
    name="doc-agent",
    model="gpt-4o",
    mcp_servers=[mcp_server]
)

# Chaukas captures:
# - MCP_CALL_START (get_prompt request)
# - MCP_CALL_END (prompt retrieved, 245ms)
# - Full request/response payloads
```

### Policy Decision Tracking

Monitor content filtering and guardrails:

```python
# When OpenAI filters content
response = await agent.run(messages)

# Chaukas automatically captures:
{
  "type": "EVENT_TYPE_POLICY_DECISION",
  "policy_id": "openai_content_policy",
  "outcome": "blocked",
  "rule_ids": ["content_filter"],
  "rationale": "Response blocked due to: content_filter",
  "finish_reason": "content_filter"
}
```

### State Change Tracking

Track agent configuration changes:

```python
# Agent configuration updated
agent.temperature = 0.7
agent.instructions = "Be more creative"

# Chaukas captures the diff:
{
  "type": "EVENT_TYPE_STATE_UPDATE",
  "state_update": {
    "temperature": {"old": 0.3, "new": 0.7},
    "instructions": {
      "old": "Be precise",
      "new": "Be more creative"
    }
  }
}
```

### Multi-Agent Handoffs

Visualize agent collaboration:

```python
# CrewAI agent handoff
task.context = [previous_task]

# Chaukas captures:
{
  "type": "EVENT_TYPE_AGENT_HANDOFF",
  "from_agent_id": "researcher",
  "to_agent_id": "writer",
  "handoff_reason": "task_delegation",
  "context_data": {...}
}
```

## ⚙️ Configuration

### Environment Variables

#### Required
```bash
CHAUKAS_TENANT_ID       # Your tenant identifier
CHAUKAS_PROJECT_ID      # Your project identifier
CHAUKAS_ENDPOINT        # API endpoint (api mode)
CHAUKAS_API_KEY         # Authentication key (api mode)
```

#### Optional
```bash
CHAUKAS_OUTPUT_MODE="api"              # "api" or "file"
CHAUKAS_OUTPUT_FILE="events.jsonl"     # File path (file mode)
CHAUKAS_BATCH_SIZE=20                  # Events per batch
CHAUKAS_MAX_BATCH_BYTES=262144         # Max batch size (256KB)
CHAUKAS_FLUSH_INTERVAL=5.0             # Auto-flush interval (seconds)
CHAUKAS_TIMEOUT=30.0                   # Request timeout (seconds)
CHAUKAS_BRANCH="main"                  # Git branch for context
CHAUKAS_TAGS="prod,us-east-1"          # Custom tags
```

#### Framework-Specific
```bash
CREWAI_DISABLE_TELEMETRY=true  # Disable CrewAI's telemetry
```

### Programmatic Configuration

```python
import chaukas

chaukas.enable_chaukas(
    tenant_id="acme-corp",
    project_id="production",
    endpoint="https://observability.acme.com",
    api_key="sk-proj-...",
    session_id="custom-session-123",  # Optional custom session
    config={
        "auto_detect": True,          # Auto-detect installed SDKs
        "enabled_integrations": [     # Or specify explicitly
            "openai_agents",
            "crewai"
        ],
        "batch_size": 20,             # Default batch size
        "flush_interval": 10.0,
        "timeout": 60.0,
    }
)
```

### File Output Mode (Development)

Perfect for local development and testing:

```python
import os
os.environ["CHAUKAS_OUTPUT_MODE"] = "file"
os.environ["CHAUKAS_OUTPUT_FILE"] = "agent_events.jsonl"

import chaukas
chaukas.enable_chaukas()

# Events written to agent_events.jsonl
# Analyze with: cat agent_events.jsonl | jq .type | sort | uniq -c
```

## 📖 Examples

### Example 1: Debug LLM Token Usage

```python
import chaukas
chaukas.enable_chaukas()

# Run your agent
result = await agent.run(messages)

# Query events:
# cat events.jsonl | jq 'select(.type=="EVENT_TYPE_MODEL_INVOCATION_END") | .model_invocation.usage'

# Output:
{
  "prompt_tokens": 234,
  "completion_tokens": 456,
  "total_tokens": 690,
  "estimated_cost_usd": 0.0207
}
```

### Example 2: Track Multi-Agent Workflow

```python
import chaukas
from crewai import Agent, Task, Crew, Process

chaukas.enable_chaukas()

# Define a multi-agent crew
researcher = Agent(role="Researcher", goal="Find insights")
writer = Agent(role="Writer", goal="Write report")

research_task = Task(description="Research AI trends", agent=researcher)
writing_task = Task(
    description="Write report",
    agent=writer,
    context=[research_task]  # Handoff point
)

crew = Crew(agents=[researcher, writer], tasks=[research_task, writing_task])
result = crew.kickoff()

# Chaukas captures:
# 1. SESSION_START
# 2. AGENT_START (researcher)
# 3. MODEL_INVOCATION_* (researcher's LLM calls)
# 4. AGENT_END (researcher)
# 5. AGENT_HANDOFF (researcher → writer)
# 6. AGENT_START (writer)
# 7. MODEL_INVOCATION_* (writer's LLM calls)
# 8. AGENT_END (writer)
# 9. SESSION_END
```

### Example 3: Monitor Tool Execution

```python
import chaukas
from openai import OpenAI
from openai.agents import Agent

chaukas.enable_chaukas()

def search_database(query: str) -> str:
    """Search the product database."""
    # Slow database query
    import time
    time.sleep(2)
    return f"Results for: {query}"

agent = Agent(
    name="support-agent",
    model="gpt-4o",
    tools=[search_database]
)

result = await agent.run(messages=[
    {"role": "user", "content": "Find product XYZ"}
])

# Chaukas captures tool performance:
# TOOL_CALL_START → TOOL_CALL_END
# Duration: 2.1s (flag for optimization!)
```

### Example 4: Detect Rate Limit Issues

```python
import chaukas
chaukas.enable_chaukas()

# Your code encounters rate limits
for i in range(100):
    try:
        result = await agent.run(messages)
    except RateLimitError as e:
        await asyncio.sleep(2 ** i)  # Exponential backoff
        continue

# Query retry events:
# cat events.jsonl | jq 'select(.type=="EVENT_TYPE_RETRY")'

# Output shows patterns:
# - 15 retries in last hour
# - Average backoff: 4.2s
# - All due to rate limits (429)
# → Action: Implement request throttling
```

## 🏗️ Architecture

### How It Works

```
┌─────────────────────────────────────────────────────────────┐
│  Your Application                                           │
│                                                             │
│  ┌─────────────┐         ┌──────────────┐                   │
│  │ OpenAI      │         │   CrewAI     │                   │
│  │ Agent       │         │   Crew       │                   │
│  └──────┬──────┘         └──────┬───────┘                   │
│         │                       │                           │
│         └───────────┬───────────┘                           │
│                     │                                       │
│         ┌───────────▼───────────┐                           │
│         │  Chaukas SDK          │   (Monkey patching)       │
│         │  - Auto-detection     │                           │
│         │  - Event capture      │                           │
│         │  - Distributed trace  │                           │
│         └───────────┬───────────┘                           │
│                     │                                       │
└─────────────────────┼──────────────────────────────────────┘
                      │
          ┌───────────▼───────────┐
          │  Intelligent Batching │
          │  - Adaptive sizing    │
          │  - Auto-retry         │
          │  - Memory-efficient   │
          └───────────┬───────────┘
                      │
          ┌───────────▼───────────┐
          │   Transmission        │
          │   - gRPC (API mode)   │
          │   - File (Dev mode)   │
          └───────────┬───────────┘
                      │
          ┌───────────▼───────────┐
          │  Chaukas Platform     │
          │  - Storage            │
          │  - Querying           │
          │  - Visualization      │
          └───────────────────────┘
```

### Event Flow

```python
Agent.run() called
    │
    ├─→ SESSION_START (first call)
    │
    ├─→ AGENT_START
    │
    ├─→ INPUT_RECEIVED (user message)
    │
    ├─→ MODEL_INVOCATION_START
    │   │
    │   └─→ [LLM processes]
    │
    ├─→ MODEL_INVOCATION_END (with tokens)
    │
    ├─→ TOOL_CALL_START (if tools requested)
    │   │
    │   └─→ [Tool executes]
    │
    ├─→ TOOL_CALL_END (with result)
    │
    ├─→ OUTPUT_EMITTED (agent response)
    │
    ├─→ AGENT_END
    │
    └─→ SESSION_END (on cleanup)
```

### Distributed Tracing Hierarchy

```
Session (lifetime of user interaction)
  │
  ├─ Trace (single request/response)
  │   │
  │   ├─ Agent Span (agent execution)
  │   │   │
  │   │   ├─ LLM Span (model call)
  │   │   │
  │   │   ├─ Tool Span (tool execution)
  │   │   │   │
  │   │   │   └─ MCP Span (MCP protocol call)
  │   │   │
  │   │   └─ Tool Span (another tool)
  │   │
  │   └─ Agent Span (handoff to second agent)
  │       │
  │       └─ LLM Span
  │
  └─ Trace (follow-up request)
      └─ ...
```

## 🎯 Use Cases

### Production Monitoring
- Track agent reliability and uptime
- Monitor LLM token costs in real-time
- Detect performance regressions
- Alert on error spikes

### Debugging & Development
- Reproduce issues with full trace context
- Understand agent decision-making
- Optimize tool execution performance
- Test multi-agent workflows

### Compliance & Audit
- Immutable audit trail of all interactions
- Track policy enforcement decisions
- Monitor data access patterns
- Generate compliance reports

### Cost Optimization
- Identify expensive LLM calls
- Track token usage by agent/model
- Find opportunities for caching
- Optimize prompt engineering

## 🔧 Batching & Performance

### Adaptive Batching

Chaukas implements intelligent batching to optimize performance:

```python
┌─────────────────────────────────────────┐
│  Event Buffer                           │
│                                         │
│  Events accumulate until:              │
│  • batch_size reached (default: 20)    │
│  • max_batch_bytes reached (256KB)     │
│  • flush_interval elapsed (5s)         │
└─────────────┬───────────────────────────┘
              │
              ▼
    ┌─────────────────┐
    │ Send to Server  │
    └────┬────────────┘
         │
    Success? ────Yes──→ ✅ Done
         │
        No (503)
         │
         ▼
    ┌────────────────────┐
    │ Split batch in half│
    │ Retry both halves  │
    └────────────────────┘
```

### Performance Characteristics

- **Overhead**: < 1% CPU impact
- **Memory**: ~10MB for 1000 events buffered
- **Latency**: < 5ms per event capture
- **Network**: Batched transmission reduces API calls by 95%

### Tuning for Your Use Case

```python
# High-volume production (optimize throughput)
chaukas.enable_chaukas(config={
    "batch_size": 200,
    "max_batch_bytes": 1_048_576,  # 1MB
    "flush_interval": 30.0
})

# Real-time debugging (optimize latency)
chaukas.enable_chaukas(config={
    "batch_size": 1,
    "flush_interval": 0.1
})

# Memory-constrained (optimize memory)
chaukas.enable_chaukas(config={
    "batch_size": 10,
    "max_batch_bytes": 65536,  # 64KB
    "flush_interval": 2.0
})
```

## 🐛 Troubleshooting

### Common Issues

#### CrewAI "Service Unavailable" Errors

**Problem**: Seeing "Transient error Service Unavailable" when using CrewAI

**Cause**: CrewAI's built-in telemetry trying to send data to their servers

**Solution**:
```bash
export CREWAI_DISABLE_TELEMETRY=true
```

This only disables CrewAI's telemetry. Chaukas continues capturing events normally.

#### Events Not Appearing

**Problem**: No events in output file or API

**Solution**:
```python
# Enable debug logging
import logging
logging.basicConfig(level=logging.DEBUG)
logging.getLogger("chaukas.sdk").setLevel(logging.DEBUG)

# Verify configuration
import chaukas
chaukas.enable_chaukas()
print(chaukas.get_config())  # Check settings

# Force flush before exit
chaukas.flush()
chaukas.disable_chaukas()
```

#### High Memory Usage

**Problem**: Memory consumption increasing over time

**Cause**: Large batches accumulating

**Solution**:
```python
# Reduce batch size and increase flush frequency
chaukas.enable_chaukas(config={
    "batch_size": 10,
    "max_batch_bytes": 65536,
    "flush_interval": 1.0
})
```

#### 503 Errors from API

**Problem**: Server returning "high memory" errors

**Cause**: Batches too large

**Solution**: SDK automatically splits batches and retries. If persistent:
```python
chaukas.enable_chaukas(config={
    "max_batch_bytes": 131072,  # Reduce to 128KB
    "batch_size": 50             # Smaller batch count
})
```

## 📚 Documentation

- **[chaukas-spec](https://github.com/chaukasai/chaukas-spec)** - Standardized event schema (19 event types)
- **[Examples Repository](./examples)** - Complete working examples for OpenAI, CrewAI, and Google ADK
- **[OpenAI Examples](./examples/openai)** - OpenAI Agents integration examples and guides
- **[CrewAI Examples](./examples/crewai)** - CrewAI integration examples and guides
- **[Google ADK Examples](./examples/adk)** - Google ADK integration examples

## 🧪 Development

### Setup

```bash
git clone https://github.com/chaukasai/chaukas-sdk
cd chaukas-sdk
pip install -e ".[dev]"
```

### Running Tests

```bash
# All tests
pytest

# With coverage
pytest --cov=chaukas

# Specific test file
pytest tests/test_openai_events.py -v

# Watch mode
pytest-watch
```

### Code Quality

```bash
# Format code
black src/ tests/ examples/

# Sort imports
isort src/ tests/ examples/

# Type checking
mypy src/chaukas/

# Run all checks
make lint
```

### Running Examples

```bash
# OpenAI Agents example
python examples/openai/openai_comprehensive_example.py

# CrewAI example
python examples/crewai/crewai_example.py

# Analyze captured events
cat events.jsonl | jq .type | sort | uniq -c
```

## 🤝 Contributing

We welcome contributions from the community! Whether you're:

- 🐛 Reporting bugs
- 💡 Requesting features
- 📖 Improving documentation
- 🔧 Contributing code
- ❓ Asking questions

Please read our [Contributing Guide](CONTRIBUTING.md) for detailed guidelines on:
- Setting up your development environment
- Coding standards and best practices
- Testing requirements
- Pull request process

### Quick Start for Contributors

1. **Fork and clone** the repository
2. **Install dependencies**: `pip install -e ".[dev]"`
3. **Make your changes** following our [coding standards](CONTRIBUTING.md#code-style)
4. **Run tests**: `make test && make lint`
5. **Submit a PR** using our [PR template](.github/PULL_REQUEST_TEMPLATE.md)

### Report Issues

Found a bug or have a feature request? Please use our issue templates:
- [Bug Report](.github/ISSUE_TEMPLATE/bug_report.yml)
- [Feature Request](.github/ISSUE_TEMPLATE/feature_request.yml)
- [Question](.github/ISSUE_TEMPLATE/question.yml)

### Community Guidelines

Please follow our [Code of Conduct](CODE_OF_CONDUCT.md) to keep our community welcoming and inclusive.

For security vulnerabilities, please see our [Security Policy](SECURITY.md).

## 🌟 Community

- **[GitHub Discussions](https://github.com/chaukasai/chaukas-sdk/discussions)** - Ask questions, share ideas
- **[GitHub Issues](https://github.com/chaukasai/chaukas-sdk/issues)** - Bug reports and feature requests

## 📬 Support

- **[GitHub Issues](https://github.com/chaukasai/chaukas-sdk/issues)** - Bug reports and feature requests
- **[Email](mailto:2153483+ranesidd@users.noreply.github.com)** - Direct support
- **[Examples](./examples)** - Working code examples and guides

## 📄 License

Apache 2.0 License - see [LICENSE](LICENSE) file for details

---

<div align="center">

**Built with ❤️ by the Chaukas team**

[Website](https://chaukas.ai) • [chaukas-spec](https://github.com/chaukasai/chaukas-spec) • [GitHub](https://github.com/chaukasai/chaukas-sdk)

</div>
