stateprime 1.0.0
Local-first, production-ready AI agent tracing SDK with Ed25519 signing and PII redaction
License: MIT
Requires Python: >=3.8
Keywords: AI, tracing, agents, LLM, observability, cryptography, OpenTelemetry

# StatePrime SDK v1.0

**Verifiable Tracing for AI Agents — 100% Local, Open-Source, Production-Ready**

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![Local-First](https://img.shields.io/badge/Local--First-100%25-green.svg)](#security)

## What is StatePrime?

StatePrime is a lightweight, open-source SDK for tracing AI agent decision-making. It runs **100% locally** by default — no cloud dependency, no data ever leaves your machine. Perfect for building verifiable, auditable agent workflows.

**Core Value**: See exactly what your agents did, why they did it, and prove it with cryptographic signatures.

### One-Line Integration

```python
from stateprime import StatePrime

sp = StatePrime()

@sp.traceable(agent_id="researcher")
def research(topic: str):
    return {"findings": f"Research on {topic}"}

trace, result = research("AI agents in 2026")
print(sp.replay(trace['id']))  # See full execution with signatures
```

## Key Features

- ✅ **100% Local** — All traces stored in SQLite on your machine. Zero cloud calls.
- ✅ **Single-File SDK** — Copy `stateprime.py` into your project. No complex dependencies.
- ✅ **One-Line Integration** — Add `@sp.traceable` to any function (sync or async).
- ✅ **Cryptographic Signing** — Ed25519 signatures on every step for non-repudiation.
- ✅ **Multi-Agent Workflows** — Link agents with parent-child trace relationships.
- ✅ **PII Redaction** — Auto-detect and mask emails, phone numbers, credit cards, SSNs.
- ✅ **Export Options** — Export traces as JSON, CSV, or Markdown for compliance.
- ✅ **Performance Tracking** — Latency per step, total execution time.
- ✅ **Production Ready** — Error handling, type hints, comprehensive comments.

## Security & Privacy

**StatePrime is designed with privacy as a core principle:**

- 🔒 **Local-Only**: By default, no network calls. All traces stored in SQLite database locally.
- 🔐 **Cryptographic**: Ed25519 signatures prove traces haven't been tampered with.
- 🚫 **No Phone-Home**: Zero telemetry, zero cloud dependency.
- 🎯 **Minimal Dependencies**: Only `cryptography` (well-maintained, open-source).

**Note on Cloud Mode**: Future versions may support optional cloud sync (not implemented yet). When enabled, you will have full control over whether data is transmitted.

## Quick Start (3 minutes)

### 1. Install

**Option A: Copy-paste (fastest)**
```bash
# Just copy stateprime.py into your project
cp stateprime.py /path/to/your/project/
```

**Option B: pip install (coming soon)**
```bash
pip install stateprime
```

### 2. Initialize

```python
from stateprime import StatePrime

# Create SDK instance (stores traces in traces.db)
sp = StatePrime()
```

### 3. Trace a Function

```python
@sp.traceable(agent_id="my_agent", intent="Analyze data", reasoning="Step 1 of workflow")
def analyze(data: dict) -> dict:
    """Your function here."""
    return {"analysis": "..."}

# Call it
trace, result = analyze({"value": 42})

# See what happened
print(sp.replay(trace['id']))
```

### 4. Export Traces

```python
# Export for compliance
json_export = sp.export_trace(trace['id'], format="json")
csv_export = sp.export_trace(trace['id'], format="csv")
markdown_export = sp.export_trace(trace['id'], format="markdown")

# PII redaction
clean_data = sp.redact_pii({"email": "user@example.com"})  # → {"email": "[EMAIL]"}
```

## Usage Examples

### Single-Agent Workflow

```python
from stateprime import StatePrime

sp = StatePrime()

@sp.traceable(agent_id="researcher")
def research(topic: str):
    # Your code here
    return {"findings": f"Researched {topic}"}

@sp.traceable(agent_id="analyzer")
def analyze(findings: dict):
    # Your code here
    return {"analysis": f"Analysis: {findings}"}

# Execute
trace1, res1 = research("AI agents")
trace2, res2 = analyze(res1)

# View execution chain
print(sp.replay(trace2['id']))
```

### Multi-Agent Workflow (Parent-Child Linkage)

```python
@sp.traceable(agent_id="researcher")
def research(topic: str):
    return {"findings": f"Research: {topic}"}

@sp.traceable(agent_id="executor")
def execute(findings: dict, parent_id: int = None):
    # Pass parent_id to link traces
    return {"action": f"Executed based on {findings}"}

# Execute and link
trace1, res1 = research("AI")
plan_dict = sp.save_trace({
    'tool': 'execute',
    'agent_id': 'executor',
    'intent': 'Execute findings',
    'reasoning': 'Next in workflow',
    'input': res1,
    'output': {},
    'timestamp': time.time(),
    'latency_ms': 0
}, parent_id=trace1['id'])

# View linked chain
print(sp.replay(plan_dict))
```

### LangGraph Integration

```python
from stateprime import StatePrime, langgraph_node_wrapper
from langgraph.graph import StateGraph

sp = StatePrime()

def my_node(state):
    # Your LangGraph node logic
    return {"result": "..."}

# Wrap the node
traced_node = langgraph_node_wrapper(sp, my_node, agent_id="graph_node")

# Use in your graph
graph = StateGraph(...)
graph.add_node("my_node", traced_node)
```

### CrewAI Integration

```python
from stateprime import StatePrime, CrewTracedTask
from crewai import Agent, Crew

sp = StatePrime()

agent = Agent(role="Researcher", ...)

traced_task = CrewTracedTask(
    sp,
    name="research_task",
    description="Research AI agents",
    agent=agent,
    expected_output="Research report"
)

crew = Crew(agents=[agent], tasks=[traced_task.get_task()])
result = crew.kickoff()

# Trace the result
traced_task.trace_result(result)
```

### AutoGen Integration

```python
from stateprime import StatePrime, AutoGenTracedAssistant

sp = StatePrime()

assistant = AutoGenTracedAssistant(
    sp,
    name="assistant",
    system_message="You are a helpful assistant.",
    agent_id="autogen_assistant"
)

agent = assistant.get_agent()

# Use your agent...
message = "What is AI?"
response = agent.get_response(message)

# Trace the message
assistant.trace_message(message, response)
```

### Async Functions

```python
import asyncio

sp = StatePrime()

@sp.traceable(agent_id="async_agent")
async def fetch_data(url: str):
    # Async code here
    return {"data": "..."}

# Use it
async def main():
    trace, result = await fetch_data("https://api.example.com")
    print(sp.replay(trace['id']))

asyncio.run(main())
```

### PII Redaction

```python
sp = StatePrime()

# Redact sensitive data
sensitive = {
    "email": "user@example.com",
    "phone": "555-123-4567",
    "ssn": "123-45-6789",
    "card": "4532-1234-5678-9123",
    "text": "Contact: john@example.com"
}

clean = sp.redact_pii(sensitive)
# Result: {
#     "email": "[EMAIL]",
#     "phone": "[PHONE]",
#     "ssn": "[SSN]",
#     "card": "[CC]",
#     "text": "Contact: [EMAIL]"
# }
```

### Export & Compliance

```python
sp = StatePrime()

# ... run your traces ...

# Export full trace chain
trace_id = 1

# JSON (machine-readable)
json_data = sp.export_trace(trace_id, format="json")

# CSV (spreadsheet-ready)
csv_data = sp.export_trace(trace_id, format="csv")

# Markdown (human-readable)
md_data = sp.export_trace(trace_id, format="markdown")
```

## API Reference

### Core Class: `StatePrime`

#### `__init__(db_path="traces.db", local_only=True)`
Initialize SDK. `local_only=True` enforces local-only mode (recommended for security).

#### `@traceable(agent_id="default", intent="", reasoning="")`
Decorator to trace function execution. Returns `(trace_dict, result)`.

#### `save_trace(trace_dict, parent_id=None) -> int`
Save trace to database. Returns trace_id. Pass `parent_id` to link to parent trace.

#### `replay(trace_id) -> str`
Generate human-readable execution replay. Shows full chain, latencies, signatures.

#### `get_trace_chain(trace_id) -> List[Trace]`
Get list of traces from root to specified trace. Useful for custom visualization.

#### `export_trace(trace_id, format="json") -> str`
Export trace chain as JSON, CSV, or Markdown.

#### `redact_pii(obj) -> Any`
Recursively redact PII from object. Handles emails, phones, SSNs, credit cards.

#### `get_stats() -> Dict`
Get performance stats: total traces, total latency, average latency, unique agents.

### Framework Adapters

#### `langgraph_node_wrapper(sp, node_func, agent_id)`
Wrap LangGraph node to trace execution.

#### `CrewTracedTask(sp, name, description, agent, expected_output)`
Wrapper for CrewAI Task with tracing.

#### `AutoGenTracedAssistant(sp, name, system_message, agent_id)`
Wrapper for AutoGen ConversableAgent with tracing.

## Performance

StatePrime is designed to be lightweight:

- **Decorator overhead**: <1ms per traced function (mainly serialization + signing)
- **Database**: SQLite with indexed queries (millisecond lookups)
- **Memory**: Minimal — no in-memory caching, all traces in DB
- **Storage**: ~1KB per trace in SQLite (compressed on disk)

**Example**: Tracing a 10-step workflow adds ~10ms overhead total.

## Database Schema

StatePrime uses SQLite with the following schema:

```sql
CREATE TABLE traces (
    id INTEGER PRIMARY KEY,           -- Auto-increment trace ID
    parent_id INTEGER DEFAULT NULL,   -- Links to parent trace (multi-agent)
    agent_id TEXT NOT NULL,           -- Agent executing this step
    intent TEXT,                      -- Agent's goal
    reasoning TEXT,                   -- Why it did this
    tool TEXT NOT NULL,               -- Function/tool name
    input_data TEXT,                  -- JSON input
    output_data TEXT,                 -- JSON output
    timestamp REAL NOT NULL,          -- Unix timestamp
    signature TEXT NOT NULL,          -- Ed25519 (hex-encoded)
    latency_ms REAL NOT NULL,         -- Execution time
    created_at TIMESTAMP              -- DB insertion time
);
```

No authentication or encryption is built-in (it's local). For sensitive data, use:
- Disk-level encryption (e.g., LUKS on Linux)
- File permissions (readable by owner only)
- PII redaction via `redact_pii()`

## Roadmap

### v1.0 (Current)
- ✅ Core tracing SDK
- ✅ Ed25519 signing
- ✅ SQLite storage
- ✅ Export (JSON/CSV/Markdown)
- ✅ PII redaction
- ✅ Framework adapters (LangGraph, CrewAI, AutoGen)

### v1.1 (Planned)
- 🔄 Visualization (web UI for trace graphs)
- 🔄 Advanced query API (filter by agent, date, etc.)
- 🔄 Batch operations (export multiple traces)
- 🔄 Import from other tools (LangSmith, etc.)

### v2.0 (Future)
- 🔄 Optional cloud sync (user-controlled, opt-in)
- 🔄 Distributed tracing (multi-machine workflows)
- 🔄 Real-time streaming (websocket support)
- 🔄 OpenTelemetry integration

## Demo & Community

- **Try it online**: [StatePrime Demo on Hugging Face Spaces](https://huggingface.co/spaces) (preview only)
- **GitHub**: [stateprime/stateprime](https://github.com) (coming soon)
- **Discussions**: GitHub Discussions (coming soon)
- **Issues**: GitHub Issues (coming soon)

## License

MIT License — Use freely in commercial and personal projects.

## Contributing

We welcome contributions! (Repo coming soon on GitHub)

Guidelines:
- Keep single-file philosophy (or ensure easy integration)
- Maintain local-first principle
- Add tests for new features
- Document with docstrings and examples

## FAQ

**Q: Does StatePrime send data to the cloud?**  
A: No. By default, everything runs locally in SQLite. No cloud calls, no telemetry.

**Q: Why Ed25519 signatures?**  
A: Non-repudiation — once you trace something, you can't deny you did it. Great for compliance.

**Q: How is this different from LangSmith/Helicone?**  
A: StatePrime is local-first and open-source. LangSmith/Helicone are cloud services. Use StatePrime for privacy, them for hosted features.

**Q: Can I use this in production?**  
A: Yes! It's designed for production. Use PII redaction for sensitive data.

**Q: What if I have 1000s of traces?**  
A: SQLite handles millions of records fine. Consider archiving old traces to separate databases.

**Q: How do I delete traces?**  
A: Traces are immutable (crypto-signed). Delete the entire `traces.db` file to start fresh.

## Support

- **Questions**: Open an issue on GitHub (repo coming soon)
- **Bugs**: GitHub Issues with minimal reproduction
- **Features**: GitHub Discussions

## Citation

If you use StatePrime in research or production, please cite:

```bibtex
@software{stateprime2026,
  title={StatePrime: Verifiable Tracing for AI Agents},
  author={StatePrime Contributors},
  year={2026},
  url={https://github.com/stateprime/stateprime}
}
```

---

**Get Started Now**: Copy `stateprime.py` into your project and add `@sp.traceable` to your functions! 🚀