Sessions API
curl --request POST \
--url https://api.statebase.org/v1/sessionsimport requests
url = "https://api.statebase.org/v1/sessions"
response = requests.post(url)
print(response.text)const options = {method: 'POST'};
fetch('https://api.statebase.org/v1/sessions', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.statebase.org/v1/sessions",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://api.statebase.org/v1/sessions"
req, _ := http.NewRequest("POST", url, nil)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.statebase.org/v1/sessions")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.statebase.org/v1/sessions")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
response = http.request(request)
puts response.read_bodyAPI Reference
Sessions API
Complete REST API reference for managing agent sessions
POST
/
v1
/
sessions
Sessions API
curl --request POST \
--url https://api.statebase.org/v1/sessionsimport requests
url = "https://api.statebase.org/v1/sessions"
response = requests.post(url)
print(response.text)const options = {method: 'POST'};
fetch('https://api.statebase.org/v1/sessions', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.statebase.org/v1/sessions",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"net/http"
"io"
)
func main() {
url := "https://api.statebase.org/v1/sessions"
req, _ := http.NewRequest("POST", url, nil)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.statebase.org/v1/sessions")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.statebase.org/v1/sessions")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
response = http.request(request)
puts response.read_bodySessions API
Sessions are the top-level containers for all agent interactions. They persist state, memory, and conversation history.Authentication
All API requests require authentication via API key:curl https://api.statebase.org/v1/sessions \
-H "X-API-Key: sb_your_api_key_here"
X-API-Key: sb_<your_key>Get your API key: Dashboard → API Keys
Create Session
POST /v1/sessions
Creates a new session for an agent. Sessions are isolated containers that store state, memory, and conversation history.
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
agent_id | string | ✅ Yes | Unique identifier for your agent (e.g., customer-support-v1) |
user_id | string | No | User identifier for multi-tenant isolation |
initial_state | object | No | Starting state (default: {}) |
metadata | object | No | Custom metadata (e.g., {"env": "prod", "version": "1.2"}) |
ttl_seconds | integer | No | Session lifetime in seconds (default: 86400 = 24h, max: 2592000 = 30 days) |
Response
| Field | Type | Description |
|---|---|---|
id | string | Unique session ID (format: sess_<12_chars>) |
agent_id | string | Agent identifier |
user_id | string | User identifier (if provided) |
created_at | string | ISO 8601 timestamp |
updated_at | string | ISO 8601 timestamp |
state | object | Current session state |
metadata | object | Custom metadata |
memory_count | integer | Number of memories attached to this session |
turn_count | integer | Number of conversation turns |
ttl_expires_at | string | ISO 8601 timestamp when session expires |
Example
curl -X POST https://api.statebase.org/v1/sessions \
-H "X-API-Key: sb_your_key" \
-H "Content-Type: application/json" \
-d '{
"agent_id": "customer-support",
"user_id": "user_123",
"initial_state": {
"status": "new",
"priority": "normal"
},
"metadata": {
"channel": "web",
"region": "us-west"
},
"ttl_seconds": 3600
}'
from statebase import StateBase
sb = StateBase(api_key="sb_your_key")
session = sb.sessions.create(
agent_id="customer-support",
user_id="user_123",
initial_state={
"status": "new",
"priority": "normal"
},
metadata={
"channel": "web",
"region": "us-west"
}
)
print(session.id) # sess_a1b2c3d4e5f6
import { StateBase } from '@statebase/node';
const sb = new StateBase({ apiKey: 'sb_your_key' });
const session = await sb.sessions.create({
agentId: 'customer-support',
userId: 'user_123',
initialState: {
status: 'new',
priority: 'normal'
},
metadata: {
channel: 'web',
region: 'us-west'
}
});
console.log(session.id); // sess_a1b2c3d4e5f6
{
"object": "session",
"id": "sess_a1b2c3d4e5f6",
"agent_id": "customer-support",
"user_id": "user_123",
"created_at": "2026-01-31T04:00:00Z",
"updated_at": "2026-01-31T04:00:00Z",
"state": {
"status": "new",
"priority": "normal"
},
"metadata": {
"channel": "web",
"region": "us-west"
},
"memory_count": 0,
"turn_count": 0,
"ttl_expires_at": "2026-01-31T05:00:00Z"
}
Error Responses
| Status Code | Error Code | Description |
|---|---|---|
| 400 | invalid_request | Missing required fields or invalid data types |
| 401 | authentication_failed | Invalid or missing API key |
| 429 | rate_limit_exceeded | Too many requests (default: 100/min) |
| 500 | internal_error | Server error (contact support if persists) |
Get Session
GET /v1/sessions/{session_id}
Retrieves a session by ID, including current state and metadata.
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
session_id | string | ✅ Yes | Session ID (e.g., sess_a1b2c3d4e5f6) |
Response
Same structure as Create Session response.Example
curl https://api.statebase.org/v1/sessions/sess_a1b2c3d4e5f6 \
-H "X-API-Key: sb_your_key"
session = sb.sessions.get(session_id="sess_a1b2c3d4e5f6")
print(session.state)
const session = await sb.sessions.get('sess_a1b2c3d4e5f6');
console.log(session.state);
Error Responses
| Status Code | Error Code | Description |
|---|---|---|
| 404 | session_not_found | Session doesn’t exist or has expired |
| 401 | authentication_failed | Invalid API key |
Get Session Context
POST /v1/sessions/{session_id}/context
The most important endpoint for building agents. Returns everything your agent needs in one call:
- Current state
- Relevant memories (via semantic search)
- Recent conversation turns
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
session_id | string | ✅ Yes | Session ID |
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
query | string | No | Search query for semantic memory retrieval (usually the user’s current message) |
memory_limit | integer | No | Max memories to return (default: 5, max: 20) |
turn_limit | integer | No | Max recent turns to return (default: 10, max: 50) |
Response
| Field | Type | Description |
|---|---|---|
state | object | Current session state |
memories | array | Relevant memories (sorted by similarity score) |
recent_turns | array | Recent conversation turns (newest first) |
Example
curl -X POST https://api.statebase.org/v1/sessions/sess_abc123/context \
-H "X-API-Key: sb_your_key" \
-H "Content-Type: application/json" \
-d '{
"query": "What did I tell you about my preferences?",
"memory_limit": 5,
"turn_limit": 10
}'
context = sb.sessions.get_context(
session_id="sess_abc123",
query="What did I tell you about my preferences?",
memory_limit=5,
turn_limit=10
)
# Use in your agent
prompt = f"""
Current state: {context['state']}
Relevant memories: {context['memories']}
Recent conversation: {context['recent_turns']}
User: {user_message}
"""
const context = await sb.sessions.getContext('sess_abc123', {
query: 'What did I tell you about my preferences?',
memoryLimit: 5,
turnLimit: 10
});
// Use in your agent
const prompt = `
Current state: ${JSON.stringify(context.state)}
Relevant memories: ${JSON.stringify(context.memories)}
Recent conversation: ${JSON.stringify(context.recentTurns)}
User: ${userMessage}
`;
{
"state": {
"user_preferences": {
"communication_style": "concise",
"language": "python"
},
"current_task": "code_review"
},
"memories": [
{
"id": "mem_xyz789",
"content": "User prefers concise responses without long explanations",
"type": "preference",
"score": 0.94,
"created_at": "2026-01-30T10:00:00Z"
},
{
"id": "mem_abc456",
"content": "User is a Python developer working on FastAPI projects",
"type": "fact",
"score": 0.87,
"created_at": "2026-01-29T15:30:00Z"
}
],
"recent_turns": [
{
"id": "turn_123",
"input": {"type": "text", "content": "Review this code"},
"output": {"type": "text", "content": "Here's my review..."},
"created_at": "2026-01-31T03:45:00Z"
}
]
}
Update Session State
POST /v1/sessions/{session_id}/state
Updates the session’s state. Creates a new state version for rollback capability.
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
session_id | string | ✅ Yes | Session ID |
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
state | object | ✅ Yes | New state (replaces current state entirely) |
reasoning | string | No | Why this update was made (for debugging) |
Response
Returns updated session object.Example
curl -X POST https://api.statebase.org/v1/sessions/sess_abc123/state \
-H "X-API-Key: sb_your_key" \
-H "Content-Type: application/json" \
-d '{
"state": {
"status": "in_progress",
"current_step": "gathering_requirements"
},
"reasoning": "User provided initial requirements"
}'
sb.sessions.update_state(
session_id="sess_abc123",
state={
"status": "in_progress",
"current_step": "gathering_requirements"
},
reasoning="User provided initial requirements"
)
await sb.sessions.updateState('sess_abc123', {
state: {
status: 'in_progress',
currentStep: 'gathering_requirements'
},
reasoning: 'User provided initial requirements'
});
Rollback Session
POST /v1/sessions/{session_id}/rollback
Reverts session state to a previous version. Creates a new version with the restored state.
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
session_id | string | ✅ Yes | Session ID |
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
version | integer | ✅ Yes | State version to roll back to (0 = initial state) |
Example
curl -X POST https://api.statebase.org/v1/sessions/sess_abc123/rollback \
-H "X-API-Key: sb_your_key" \
-H "Content-Type: application/json" \
-d '{"version": 3}'
# Roll back to version 3
restored_state = sb.sessions.rollback(
session_id="sess_abc123",
version=3
)
const restoredState = await sb.sessions.rollback('sess_abc123', 3);
Fork Session
POST /v1/sessions/{session_id}/fork
Creates a new session starting from a specific version of an existing session. Useful for debugging and “what-if” scenarios.
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
session_id | string | ✅ Yes | Source session ID |
Request Body
| Field | Type | Required | Description |
|---|---|---|---|
version | integer | No | State version to fork from (default: latest) |
Response
Returns new session object with metadata indicating it was forked.Example
curl -X POST https://api.statebase.org/v1/sessions/sess_abc123/fork \
-H "X-API-Key: sb_your_key" \
-H "Content-Type: application/json" \
-d '{"version": 5}'
# Fork from version 5
forked_session = sb.sessions.fork(
session_id="sess_abc123",
version=5
)
print(forked_session.id) # sess_xyz789 (new ID)
print(forked_session.metadata) # {"forked_from": "sess_abc123", "forked_version": 5}
const forkedSession = await sb.sessions.fork('sess_abc123', 5);
console.log(forkedSession.id); // sess_xyz789
List Sessions
GET /v1/sessions
Lists all sessions for your account, with pagination.
Query Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
limit | integer | No | Max sessions to return (default: 20, max: 100) |
starting_after | string | No | Session ID to start after (for pagination) |
agent_id | string | No | Filter by agent ID |
user_id | string | No | Filter by user ID |
Example
curl "https://api.statebase.org/v1/sessions?limit=10&agent_id=customer-support" \
-H "X-API-Key: sb_your_key"
sessions = sb.sessions.list(
limit=10,
agent_id="customer-support"
)
for session in sessions:
print(session.id, session.created_at)
const sessions = await sb.sessions.list({
limit: 10,
agentId: 'customer-support'
});
Delete Session
DELETE /v1/sessions/{session_id}
Permanently deletes a session and all associated data (state, turns, memories).
Warning: This action is irreversible.
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
session_id | string | ✅ Yes | Session ID to delete |
Example
curl -X DELETE https://api.statebase.org/v1/sessions/sess_abc123 \
-H "X-API-Key: sb_your_key"
sb.sessions.delete(session_id="sess_abc123")
await sb.sessions.delete('sess_abc123');
Rate Limits
| Tier | Requests/Minute | Burst |
|---|---|---|
| Free | 100 | 200 |
| Pro | 1,000 | 2,000 |
| Enterprise | Custom | Custom |
X-RateLimit-Limit: Max requests per minuteX-RateLimit-Remaining: Remaining requestsX-RateLimit-Reset: Unix timestamp when limit resets
Webhooks
Subscribe to session events:| Event | Description |
|---|---|
session.created | New session created |
session.updated | Session state or metadata changed |
session.deleted | Session deleted |
session.expired | Session TTL expired |
Best Practices
✅ Do This
- Use
get_context()for every turn (it’s optimized for agent prompts) - Include
reasoningin state updates (helps with debugging) - Set appropriate TTLs (don’t keep sessions forever)
- Use
user_idfor multi-tenant isolation
❌ Avoid This
- Don’t poll for updates (use webhooks instead)
- Don’t store sensitive data in state (use encrypted metadata)
- Don’t create a new session per message (reuse sessions for conversations)
Next Steps
- Turns API: Log conversation interactions
- Memory API: Store long-term knowledge
- Traces API: Audit and debugging
Need help? Join our Discord or email support@statebase.org