Metadata-Version: 2.4
Name: agnost
Version: 0.2.1
Summary: Python SDK for Agnost AI, which monitors AI agents in production: chat agents, voice agents, copilots and MCP servers.
Author-email: Agnost AI <founders@agnost.ai>
License: MIT
Project-URL: Homepage, https://agnost.ai
Project-URL: Documentation, https://docs.agnost.ai/python-conversation
Keywords: agnost,ai-agents,agent-monitoring,llm-observability,observability,opentelemetry,llm-evaluation,voice-agents,chatbots,llm
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
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: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.7
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.25.0
Provides-Extra: openai-agents
Requires-Dist: openai-agents>=0.1.0; python_version >= "3.10" and extra == "openai-agents"
Provides-Extra: dev
Requires-Dist: pytest>=6.0; extra == "dev"
Requires-Dist: tomli>=1.1.0; python_version < "3.11" and extra == "dev"

# Agnost AI Python SDK

[![PyPI version](https://badge.fury.io/py/agnost.svg)](https://badge.fury.io/py/agnost)
[![Python](https://img.shields.io/pypi/pyversions/agnost.svg)](https://pypi.org/project/agnost/)

Send your AI agent's conversations, tool calls and events to [Agnost AI](https://agnost.ai), which monitors AI agents in production. It judges whole conversations to catch failures, frustrated users and broken tool calls, alerts in Slack, and opens pull requests with fixes tested against past runs.

## Installation

```bash
pip install agnost
```

Requires Python 3.7 or newer; the optional OpenAI Agents integration
(`pip install "agnost[openai-agents]"`) requires Python 3.10 or newer. To
monitor an MCP server's tool calls, use
[`agnost-mcp`](https://pypi.org/project/agnost-mcp/) instead.

## Basic Usage

```python
import agnost

# Initialize with your organization ID
agnost.init("your-org-id")

# Track an AI interaction
agnost.track(
    user_id="user_123",
    input="What is the weather?",
    output="The weather is sunny.",
    agent_name="weather-agent"
)

# Events are sent in the background; deliver anything still queued before exit
agnost.shutdown()
```

Runnable versions of this and a multi-turn chatbot are in
[`examples/`](./examples).

## API Reference

### `init(write_key, **config)`

Initialize the SDK with your organization ID.

```python
agnost.init("your-org-id")

# With custom configuration
agnost.init(
    "your-org-id",
    endpoint="https://api.agnost.ai",
    debug=True
)
```

### `track(user_id, ...)`

Record an AI interaction event.

```python
event_id = agnost.track(
    user_id="user_123",         # Optional: User identifier
    input="What is the weather?",
    output="The weather is sunny.",
    agent_name="weather-agent",  # Defaults to "default" if not provided
    conversation_id="conv_abc",  # Group related events
    properties={"temperature": "0.7"},
    latency=1500                 # Execution time in ms
)
```

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `user_id` | `str` | No | User identifier (default: "") |
| `input` | `str` | No | Input text/prompt |
| `output` | `str` | No | Output/response text. **When `success=False`, this is the error message** |
| `agent_name` | `str` | No | Agent name (default: "default") |
| `conversation_id` | `str` | No | Conversation ID for grouping |
| `properties` | `dict` | No | Additional event properties |
| `timestamp` | `datetime` | No | Event timestamp (defaults to now) |
| `success` | `bool` | No | Whether successful (default: `True`). Set to `False` for errors |
| `latency` | `int` | No | Execution time in milliseconds |

**Important**: When tracking errors (`success=False`), put the error message in the `output` parameter.

### `identify(user_id, traits)`

Associate user characteristics with a user ID.

```python
agnost.identify("user_123", {
    "name": "John Doe",
    "email": "john@example.com",
    "age": 30,
    "plan": "paid"
})
```

### `begin(user_id, ...)`

Begin a partial interaction for deferred completion. Use this when the output is not immediately available.

**✨ NEW: Automatic latency tracking** - Latency is now automatically calculated from `begin()` to `end()`!

```python
# Pass input directly (recommended)
interaction = agnost.begin(
    user_id="user_123",
    agent_name="weather-agent",
    input="What is the weather?"
)
if interaction is None:
    raise RuntimeError("Agnost is not initialized. Call agnost.init() first.")

interaction.set_property("temperature", "0.7")

# ... do async work ...

interaction.end(output="The weather is sunny.")
# ✅ Latency automatically calculated! (~duration from begin to end)
```

**Alternative: Set input later:**
```python
interaction = agnost.begin(
    user_id="user_123",
    agent_name="weather-agent"
)
if interaction is None:
    raise RuntimeError("Agnost is not initialized. Call agnost.init() first.")
interaction.set_input("What is the weather?")
interaction.end(output="The weather is sunny.")
```

**Manual latency override (optional):**
```python
interaction.end(
    output="The weather is sunny.",
    latency=1500  # Override auto-calculation if needed
)
```

**Interaction Methods:**

| Method | Description |
|--------|-------------|
| `set_input(text)` | Set the input text (optional if passed to `begin()`) |
| `set_properties(dict)` | Set multiple properties |
| `set_property(key, value)` | Set a single property |
| `end(output, success, latency)` | Complete the interaction. **When `success=False`, `output` is the error message.** Latency is auto-calculated if not provided |

### `flush()`

Manually flush all queued events.

```python
agnost.flush()
```

### `shutdown()`

Shutdown the SDK and flush remaining events. `init()` also registers an
`atexit` handler, so a normal interpreter exit flushes too; call `shutdown()`
yourself when the process may end another way (for example a serverless
handler that is frozen after returning).

```python
agnost.shutdown()
```

### `set_debug_logs(enabled)`

Enable or disable debug logging.

```python
agnost.set_debug_logs(True)  # See queued events
```

## Configuration

You can customize the SDK behavior using the configuration object:

```python
import agnost
from agnost import ConversationConfig

# Create a custom configuration
config = ConversationConfig(
    endpoint="https://api.agnost.ai",
    debug=False
)

# Apply the configuration
agnost.init("your-org-id", config=config)
```

### Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `endpoint` | `str` | `"https://api.agnost.ai"` | API endpoint URL |
| `debug` | `bool` | `False` | Enable debug logging |

## Advanced Usage

### Conversation Tracking

Group related events using `conversation_id`:

```python
import uuid

conversation_id = "conv_" + str(uuid.uuid4())

# First message
agnost.track(
    user_id="user_123",
    input="Hello!",
    output="Hi there! How can I help?",
    agent_name="support-bot",
    conversation_id=conversation_id
)

# Follow-up message
agnost.track(
    user_id="user_123",
    input="What's the weather?",
    output="The weather is sunny.",
    agent_name="support-bot",
    conversation_id=conversation_id
)
```

### Direct Client Instantiation

For multiple clients or advanced use cases:

```python
from agnost import ConversationClient

client = ConversationClient()
client.init("your-org-id")

client.track_ai(
    user_id="user_123",
    output="Hello!",
    agent_name="greeting-bot"
)

client.shutdown()
```

### Error Handling

When tracking errors, set `success=False` and pass the error message as the `output`:

```python
# Track failed interactions
agnost.track(
    user_id="user_123",
    input="Generate an image",
    output="Rate limit exceeded",  # Error message as output
    success=False,
    agent_name="image-agent"
)

# With begin() and end()
interaction = agnost.begin(
    user_id="user_123",
    agent_name="image-agent",
    input="Generate an image"
)
if interaction is None:
    raise RuntimeError("Agnost is not initialized. Call agnost.init() first.")

try:
    result = generate_image()
    interaction.end(output=result)
except Exception as e:
    # Error message goes in output when success=False
    interaction.end(output=str(e), success=False)
```

## OpenAI Agents SDK

`agnost` includes a native tracing processor for the
[OpenAI Agents SDK](https://openai.github.io/openai-agents-python/):

```bash
pip install "agnost[openai-agents]"
```

```python
from agents import RunConfig, Runner
from agnost.integrations.openai_agents import instrument

processor = instrument(org_id="your-org-id")  # keeps OpenAI's default exporter

Runner.run_sync(agent, "Hello", run_config=RunConfig(
    group_id="conv-123",                 # conversation ID
    trace_metadata={"user_id": "u-42"},  # user ID
))
```

Each run becomes one conversation turn, with agents, tools, model calls,
handoffs, and guardrails as child events. See the
[guide](https://docs.agnost.ai/openai-agents) for configuration, captured data,
and flush/shutdown behavior.

## Examples

[`examples/`](./examples) has a quickstart and an interactive chatbot. Every
release runs them against the built wheel:

```bash
pip install -r examples/requirements.txt
AGNOST_ORG_ID=<your-org-id> python examples/quickstart.py
```

## Contact

For support or questions, contact the founders: [founders@agnost.ai](mailto:founders@agnost.ai)
