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.3.0.tar.gz (10.7 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.3.0-py3-none-any.whl (9.4 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: statebase-0.3.0.tar.gz
  • Upload date:
  • Size: 10.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for statebase-0.3.0.tar.gz
Algorithm Hash digest
SHA256 a140228fda7e510082c303f67057e620e2929e15e1e5dfc76fd39919e4ff87db
MD5 0afcaf65487b5b2387a966469d3ef969
BLAKE2b-256 71086ef70854729a498cf35bec3912d81bdb6453071142a4c9cbf3a9077c9b29

See more details on using hashes here.

File details

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

File metadata

  • Download URL: statebase-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 9.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for statebase-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 6ee18bcd77c667e308c75dd44cfef9862cdafdf93d1414f320b907bd47b87f50
MD5 76ed93a6d3aef9f13ecb2cd52a5659fe
BLAKE2b-256 6025b8330d6dc971394d5f3cb02ba5e34feccd6ccd31b58cd0a1d46c37161df4

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