Skip to main content

The Reliability Layer for Production AI Agents

Project description

StateBase Python SDK

Official Python client for StateBase API

PyPI version Python 3.8+ License: MIT

DocumentationAPI ReferenceExamplesChangelog


Installation

pip install statebase

Requirements

  • Python 3.8 or higher
  • requests library (automatically installed)

Quick Start

from statebase import StateBase

# Initialize client
sb = StateBase(api_key="sb_live_xxxxxxxx")

# Create a session
session = sb.sessions.create(
    agent_id="customer-support",
    initial_state={"status": "new", "user_id": "user_123"}
)

# Update state
sb.sessions.update_state(
    session_id=session.id,
    state={"status": "in_progress"},
    reasoning="User provided ticket details"
)

# Add a conversation turn
turn = sb.sessions.add_turn(
    session_id=session.id,
    input="My order hasn't arrived",
    output="I'll help you track your order. Can you provide the order number?"
)

# Search memories
memories = sb.memory.search(
    query="user communication preferences",
    session_id=session.id
)

# Rollback if needed
sb.sessions.rollback(
    session_id=session.id,
    version=-1,
    reason="Agent made an error"
)

Features

✅ Complete API Coverage

  • Sessions (create, read, update, delete)
  • State management with versioning
  • Conversation turns
  • Semantic memory (add, search)
  • Decision traces
  • Instant rollback

✅ Developer-Friendly

  • Type hints for all methods
  • Comprehensive error handling
  • Automatic retries with exponential backoff
  • Request/response logging (optional)

✅ Production-Ready

  • Connection pooling
  • Timeout configuration
  • Rate limit handling
  • Async support (optional)

Usage

Authentication

from statebase import StateBase

# Option 1: Pass API key directly
sb = StateBase(api_key="sb_live_xxxxxxxx")

# Option 2: Use environment variable
# Set STATEBASE_API_KEY in your environment
sb = StateBase()

# Option 3: Custom base URL (for self-hosted)
sb = StateBase(
    api_key="your_key",
    base_url="https://your-instance.com"
)

Sessions

# Create session
session = sb.sessions.create(
    agent_id="support-bot",
    initial_state={"user": "alice"},
    ttl_seconds=86400  # 24 hours
)

# Get session
session = sb.sessions.get(session_id="sess_abc123")

# Update state
sb.sessions.update_state(
    session_id="sess_abc123",
    state={"step": "collect_info"},
    reasoning="Moved to next step"
)

# Delete session
sb.sessions.delete(session_id="sess_abc123")

# List sessions
sessions = sb.sessions.list(
    agent_id="support-bot",
    limit=10
)

Conversation Turns

# Add turn
turn = sb.sessions.add_turn(
    session_id="sess_abc123",
    input="What's my order status?",
    output="Your order #12345 is out for delivery",
    metadata={"model": "gpt-4", "tokens": 150}
)

# Get turn history
turns = sb.sessions.get_turns(
    session_id="sess_abc123",
    limit=20
)

Memory

# Add memory
memory = sb.memory.add(
    session_id="sess_abc123",
    content="User prefers email over SMS",
    type="preference",
    tags=["communication", "preference"]
)

# Search memories
results = sb.memory.search(
    query="how does user want to be contacted?",
    session_id="sess_abc123",
    top_k=5,
    threshold=0.7
)

# Get memory by ID
memory = sb.memory.get(memory_id="mem_xyz789")

# Delete memory
sb.memory.delete(memory_id="mem_xyz789")

Rollback

# Rollback to previous version
sb.sessions.rollback(
    session_id="sess_abc123",
    version=-1,  # or specific version number like 5
    reason="Agent hallucinated"
)

# Rollback to specific version
sb.sessions.rollback(
    session_id="sess_abc123",
    version=3,
    reason="Revert to known good state"
)

Traces

# List traces for a session
traces = sb.traces.list(
    session_id="sess_abc123",
    limit=100
)

# Get specific trace
trace = sb.traces.get(trace_id="trace_123")

# Filter traces by action
traces = sb.traces.list(
    session_id="sess_abc123",
    action="state_update"
)

Advanced Usage

Error Handling

from statebase import StateBase, StateBaseException

sb = StateBase(api_key="your_key")

try:
    session = sb.sessions.create(agent_id="bot")
except StateBaseException as e:
    print(f"Error: {e.message}")
    print(f"Code: {e.error_code}")
    print(f"Details: {e.details}")

Custom Configuration

sb = StateBase(
    api_key="your_key",
    base_url="https://api.statebase.org",
    timeout=30,  # seconds
    max_retries=3,
    retry_delay=1.0,  # seconds
    enable_logging=True
)

Async Support

from statebase import AsyncStateBase

async def main():
    sb = AsyncStateBase(api_key="your_key")
    
    session = await sb.sessions.create(
        agent_id="async-bot"
    )
    
    await sb.sessions.update_state(
        session_id=session.id,
        state={"status": "processing"}
    )

# Run with asyncio
import asyncio
asyncio.run(main())

Context Manager

with StateBase(api_key="your_key") as sb:
    session = sb.sessions.create(agent_id="bot")
    # Automatically handles cleanup

Integration Examples

With LangChain

from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from statebase import StateBase

sb = StateBase(api_key="your_key")
llm = ChatOpenAI()

# Create session
session = sb.sessions.create(agent_id="langchain-bot")

# Your LangChain agent logic
def chat(message: str):
    # Get context from StateBase
    turns = sb.sessions.get_turns(session.id, limit=10)
    context = "\n".join([f"User: {t.input}\nBot: {t.output}" for t in turns])
    
    # Call LLM
    response = llm.predict(f"{context}\nUser: {message}\nBot:")
    
    # Save turn
    sb.sessions.add_turn(
        session_id=session.id,
        input=message,
        output=response
    )
    
    return response

With OpenAI

from openai import OpenAI
from statebase import StateBase

client = OpenAI()
sb = StateBase(api_key="your_key")

session = sb.sessions.create(agent_id="openai-bot")

def chat(message: str):
    # Add user message
    sb.sessions.add_turn(
        session_id=session.id,
        input=message,
        output=""  # Will update after LLM response
    )
    
    # Call OpenAI
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": message}]
    )
    
    output = response.choices[0].message.content
    
    # Update with response
    sb.sessions.update_state(
        session_id=session.id,
        state={"last_response": output}
    )
    
    return output

API Reference

Client

class StateBase:
    def __init__(
        self,
        api_key: str = None,
        base_url: str = "https://api.statebase.org",
        timeout: int = 30,
        max_retries: int = 3,
        retry_delay: float = 1.0,
        enable_logging: bool = False
    )

Sessions

sb.sessions.create(agent_id: str, initial_state: dict = None, ttl_seconds: int = None) -> Session
sb.sessions.get(session_id: str) -> Session
sb.sessions.update_state(session_id: str, state: dict, reasoning: str = None) -> Session
sb.sessions.delete(session_id: str) -> None
sb.sessions.list(agent_id: str = None, limit: int = 10) -> List[Session]
sb.sessions.add_turn(session_id: str, input: str, output: str, metadata: dict = None) -> Turn
sb.sessions.get_turns(session_id: str, limit: int = 20) -> List[Turn]
sb.sessions.rollback(session_id: str, version: int, reason: str = None) -> Session

Memory

sb.memory.add(session_id: str, content: str, type: str = "general", tags: List[str] = None) -> Memory
sb.memory.search(query: str, session_id: str = None, top_k: int = 5, threshold: float = 0.7) -> List[Memory]
sb.memory.get(memory_id: str) -> Memory
sb.memory.delete(memory_id: str) -> None

Traces

sb.traces.list(session_id: str, limit: int = 100, action: str = None) -> List[Trace]
sb.traces.get(trace_id: str) -> Trace

Development

Setup

# Clone repository
git clone https://github.com/StateBase/statebase-python.git
cd statebase-python

# Create virtual environment
python -m venv venv
source venv/bin/activate

# Install dependencies
pip install -e ".[dev]"

Testing

# Run tests
pytest

# Run with coverage
pytest --cov=statebase

# Run specific test
pytest tests/test_sessions.py

Code Quality

# Format code
black statebase tests

# Sort imports
isort statebase tests

# Lint
flake8 statebase tests

# Type check
mypy statebase

Support


License

MIT License - see LICENSE file for details.


Changelog

See CHANGELOG.md for version history.


Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

statebase-0.4.0.tar.gz (11.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

statebase-0.4.0-py3-none-any.whl (10.0 kB view details)

Uploaded Python 3

File details

Details for the file statebase-0.4.0.tar.gz.

File metadata

  • Download URL: statebase-0.4.0.tar.gz
  • Upload date:
  • Size: 11.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.11

File hashes

Hashes for statebase-0.4.0.tar.gz
Algorithm Hash digest
SHA256 0d3ed426e2c364ba21dbc883b7bbd1d03974d3260ba58c3b67d706b139cb9600
MD5 d803b8282e8f27643985064aef3ce8f8
BLAKE2b-256 a6783c5236faa8814b8cbc4b9f718a360784437703d2523aff87f279aabbe72d

See more details on using hashes here.

File details

Details for the file statebase-0.4.0-py3-none-any.whl.

File metadata

  • Download URL: statebase-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 10.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.11

File hashes

Hashes for statebase-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2e1303b454a9554f123a3348e9af9118ab002a3d5c680244a8f91095838de5af
MD5 917753c551b0c08386b7d0d9a25eba9b
BLAKE2b-256 3a28dbe3c720ff1b588e97773b2e802a071c542ac7a5252816d4fdad4d3aa0ef

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page