Skip to main content
GET
/
v1
/
traces
Traces API
curl --request GET \
  --url https://api.statebase.org/v1/traces

Traces API

Traces provide a complete audit trail of every operation in StateBase. Use traces for debugging, compliance, analytics, and understanding agent behavior.

What Gets Traced?

Every API operation creates a trace:
OperationTrace ActionInformation Logged
Create sessionsession.createdagent_id, user_id, initial_state
Update statestate.updatedreasoning, state_diff, version
Add turnturn.addedinput, output, reasoning, metadata
Add memorymemory.createdcontent, type, tags
Rollbackstate.rolled_backfrom_version, to_version, reason
Fork sessionsession.forkedsource_session, fork_version
Delete sessionsession.deletedsession_id, reason

List Traces

GET /v1/traces Lists all traces with optional filtering.

Query Parameters

ParameterTypeRequiredDescription
session_idstringNoFilter by session
user_idstringNoFilter by user
actionstringNoFilter by action type (e.g., "state.updated")
created_afterstringNoISO 8601 timestamp (only traces after this time)
created_beforestringNoISO 8601 timestamp (only traces before this time)
limitintegerNoMax results (default: 20, max: 100)
starting_afterstringNoTrace ID for pagination

Response

FieldTypeDescription
dataarrayArray of trace objects
has_morebooleanWhether more results exist

Trace Object

FieldTypeDescription
idstringUnique trace ID
session_idstringAssociated session (if applicable)
user_idstringAssociated user (if applicable)
actionstringAction type (e.g., "state.updated")
actorstringWho performed the action (API key prefix)
timestampstringISO 8601 timestamp
detailsobjectAction-specific details
metadataobjectCustom metadata

Example

curl "https://api.statebase.org/v1/traces?session_id=sess_abc123&limit=10" \
  -H "X-API-Key: sb_your_key"

Get Trace

GET /v1/traces/{trace_id} Retrieves a specific trace by ID.

Path Parameters

ParameterTypeRequiredDescription
trace_idstring✅ YesTrace ID

Example

curl https://api.statebase.org/v1/traces/trace_xyz789 \
  -H "X-API-Key: sb_your_key"

Trace Actions Reference

Session Actions

ActionDescriptionDetails Fields
session.createdNew session createdagent_id, user_id, initial_state
session.updatedSession metadata updatedmetadata_diff, ttl_seconds
session.deletedSession deletedreason, turn_count, memory_count
session.forkedSession forkedsource_session_id, fork_version
session.expiredSession TTL expiredttl_seconds, last_activity

State Actions

ActionDescriptionDetails Fields
state.updatedState changedreasoning, state_diff, version
state.rolled_backState revertedfrom_version, to_version, reason

Turn Actions

ActionDescriptionDetails Fields
turn.addedConversation turn loggedturn_number, input_type, output_type, reasoning

Memory Actions

ActionDescriptionDetails Fields
memory.createdMemory addedcontent_preview, type, tags, embedded
memory.updatedMemory modifiedcontent_changed, tags_changed
memory.deletedMemory removedcontent_preview, reason

Common Use Cases

1. Debugging Production Issues

# Find all traces for a failed session
traces = sb.traces.list(
    session_id="sess_failed_123",
    limit=100
)

# Look for errors or rollbacks
for trace in traces:
    if trace.action == "state.rolled_back":
        print(f"Rollback detected at {trace.timestamp}")
        print(f"Reason: {trace.details['reason']}")
        print(f"From version {trace.details['from_version']} to {trace.details['to_version']}")

2. Audit Trail for Compliance

# Get all operations by a specific user
user_traces = sb.traces.list(
    user_id="user_123",
    created_after="2026-01-01T00:00:00Z",
    created_before="2026-01-31T23:59:59Z",
    limit=1000
)

# Generate audit report
for trace in user_traces:
    print(f"{trace.timestamp} | {trace.action} | {trace.actor}")

3. Performance Monitoring

# Analyze response times
traces = sb.traces.list(
    action="turn.added",
    created_after="2026-01-31T00:00:00Z",
    limit=100
)

latencies = [trace.metadata.get("latency_ms", 0) for trace in traces]
avg_latency = sum(latencies) / len(latencies)
max_latency = max(latencies)

print(f"Average latency: {avg_latency:.0f}ms")
print(f"Max latency: {max_latency:.0f}ms")

if avg_latency > 2000:
    alert_team("High average latency detected")

4. Root Cause Analysis

# Find what led to a specific error
error_trace = sb.traces.get(trace_id="trace_error_123")
error_time = error_trace.timestamp

# Get all traces before the error
prior_traces = sb.traces.list(
    session_id=error_trace.session_id,
    created_before=error_time,
    limit=20
)

# Analyze sequence of events
for trace in reversed(prior_traces):
    print(f"{trace.action}: {trace.details.get('reasoning', 'N/A')}")

5. Rollback Frequency Analysis

# Track how often agents need rollbacks
rollbacks = sb.traces.list(
    action="state.rolled_back",
    created_after="2026-01-24T00:00:00Z",  # Last 7 days
    limit=1000
)

total_sessions = count_sessions_last_7_days()
rollback_rate = len(rollbacks) / total_sessions

print(f"Rollback rate: {rollback_rate:.1%}")

if rollback_rate > 0.05:  # More than 5%
    alert_engineering("High rollback rate - agent needs improvement")

Filtering by Time Range

Get traces within a specific time window:
from datetime import datetime, timedelta

# Last 24 hours
yesterday = datetime.now() - timedelta(days=1)

traces = sb.traces.list(
    created_after=yesterday.isoformat(),
    limit=100
)

Exporting Traces

Export traces for external analysis:
import csv

# Get all traces for a session
traces = sb.traces.list(session_id="sess_abc123", limit=1000)

# Export to CSV
with open('traces.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['Timestamp', 'Action', 'Actor', 'Details'])
    
    for trace in traces:
        writer.writerow([
            trace.timestamp,
            trace.action,
            trace.actor,
            json.dumps(trace.details)
        ])

Best Practices

✅ Do This

  • Use traces for debugging (not just logging)
  • Set up alerts on critical actions (rollbacks, errors)
  • Export traces for long-term storage (compliance)
  • Filter by time range (don’t fetch everything)
  • Include reasoning in all operations (shows up in traces)

❌ Avoid This

  • Don’t ignore rollback patterns (they indicate issues)
  • Don’t fetch traces without filters (use pagination)
  • Don’t store sensitive data in trace details
  • Don’t delete traces (they’re your audit trail)

Retention Policy

TierTrace Retention
Free7 days
Pro90 days
EnterpriseCustom (up to 7 years)
Recommendation: Export critical traces for long-term storage.

Webhooks

Subscribe to trace events in real-time:
EventDescription
trace.createdNew trace logged
trace.rollbackState rollback occurred
trace.errorError trace logged
Configure in Dashboard → Webhooks.

Error Responses

Status CodeError CodeDescription
400invalid_requestInvalid filter parameters
404trace_not_foundTrace doesn’t exist or expired
429rate_limit_exceededToo many requests

Next Steps


Key Takeaway: Traces are your black box recorder. When things go wrong, traces tell you exactly what happened and why.