Skip to main content
Acontext provides a flexible message storage system that supports multiple LLM providers (OpenAI, Anthropic). You can store messages then retrieve them later for analysis, debugging, or continuing conversations.

Prerequisites

Before storing messages, you need:
  • A running Acontext server (run locally)
  • An Acontext API key (default is sk-ac-your-root-api-bearer-token)
Messages are stored within sessions. Create a session first, then send messages to it.

Sending messages

Create a session first

Before sending messages, create a session to store them:
from acontext import AcontextClient

client = AcontextClient(
    api_key="sk-ac-your-root-api-bearer-token",
    base_url="http://localhost:8029/api/v1"
)
client.ping()
# Create a session
session = client.sessions.create()
print(f"Session created: {session.id}")

Send a single message

Send messages in OpenAI or Anthropic format:
  • OpenAI Format
  • Anthropic Format
from acontext import AcontextClient

client = AcontextClient(
    api_key="sk-ac-your-root-api-bearer-token",
    base_url="http://localhost:8029/api/v1"
)
session = client.sessions.create()

# Send a message in OpenAI format
message = client.sessions.send_message(
    session_id=session.id,
    blob={
        "role": "user",
        "content": "What is the capital of France?"
    },
    format="openai"
)

print(f"Message sent: {message.id}")

Send multiple messages

You can send multiple messages sequentially to build a conversation:
from acontext import AcontextClient

client = AcontextClient(
    api_key="sk-ac-your-root-api-bearer-token",
    base_url="http://localhost:8029/api/v1"
)
session = client.sessions.create()

# Send multiple messages to build a conversation
messages_to_send = [
    {"role": "user", "content": "Hello! Can you help me with Python?"},
    {"role": "assistant", "content": "Of course! I'd be happy to help with Python. What would you like to know?"},
    {"role": "user", "content": "How do I read a JSON file?"},
    {"role": "assistant", "content": "You can use the json module: import json; with open('file.json') as f: data = json.load(f)"}
]

for msg in messages_to_send:
    message = client.sessions.send_message(
        session_id=session.id,
        blob=msg,
        format="openai"
    )
    print(f"Sent message: {message.id}")

print(f"Total messages sent: {len(messages_to_send)}")
Each message receives a unique ID upon creation. You can use these IDs to reference specific messages later.

Retrieving messages

Get all messages from a session

Retrieve messages from a session with pagination support:
from acontext import AcontextClient

client = AcontextClient(
    api_key="sk-ac-your-root-api-bearer-token",
    base_url="http://localhost:8029/api/v1"
)

# Get messages from a session
result = client.sessions.get_messages(
    session_id="session_uuid",
    limit=50,
    format="openai",
    time_desc=True  # Most recent first
)

print(f"Retrieved {len(result.items)} messages")
for msg in result.items:
    print(f"- {msg.role}: {msg.content[:50]}...")

# Handle pagination if there are more messages
if result.next_cursor:
    next_page = client.sessions.get_messages(
        session_id="session_uuid",
        cursor=result.next_cursor,
        limit=50
    )

Message format compatibility

Acontext supports two message formats for maximum compatibility:

OpenAI Format

Compatible with OpenAI’s Chat Completion API format. Use for GPT-3.5, GPT-4, and similar models.

Anthropic Format

Compatible with Anthropic’s Messages API format. Use for Claude models.
You can send messages in one format and retrieve them in another. Acontext automatically handles format conversion.

Complete workflow example

Here’s a complete example showing how to store and retrieve a conversation:
from acontext import AcontextClient

# Initialize client
client = AcontextClient(
    api_key="sk-ac-your-root-api-bearer-token",
    base_url="http://localhost:8029/api/v1"
)

try:
    # 1. Create a session
    session = client.sessions.create()
    
    # 2. Send multiple messages
    conversation = [
        {"role": "user", "content": "I'm having trouble logging in"},
        {"role": "assistant", "content": "I can help with that. What error are you seeing?"},
        {"role": "user", "content": "It says 'Invalid credentials'"},
        {"role": "assistant", "content": "Try resetting your password using the forgot password link."}
    ]
    
    for msg in conversation:
        client.sessions.send_message(
            session_id=session.id,
            blob=msg,
            format="openai"
        )
    
    print(f"Stored {len(conversation)} messages in session {session.id}")
    
    # 3. Retrieve messages later
    result = client.sessions.get_messages(
        session_id=session.id,
        format="openai",
        time_desc=False  # Chronological order
    )
    
    print(f"\nRetrieved conversation ({len(result.items)} messages):")
    for msg in result.items:
        print(f"{msg.role}: {msg.content}")
        
finally:
    client.close()

Pagination and limits

When retrieving large message histories, use pagination to efficiently process results:
1

Set an appropriate limit

Start with a reasonable page size (e.g., 50-100 messages) based on your use case.
result = client.sessions.get_messages(session_id="session_uuid", limit=50)
2

Check for more pages

Look for the next_cursor field in the response to determine if more messages exist.
if result.next_cursor:
    print("More messages available")
3

Fetch subsequent pages

Use the cursor to retrieve the next page of results.
next_page = client.sessions.get_messages(
    session_id="session_uuid",
    cursor=result.next_cursor,
    limit=50
)
The maximum limit per request is typically 100 messages. Check your plan’s specific limits in the dashboard.

Managing sessions

Delete a session

When you’re done with a conversation or workflow, you can delete the session to clean up storage:
from acontext import AcontextClient

client = AcontextClient(
    api_key="sk-ac-your-root-api-bearer-token",
    base_url="http://localhost:8029/api/v1"
)

# Delete a session when you're done with it
session_id = "session_uuid"
client.sessions.delete(session_id)

print(f"Session {session_id} deleted successfully")
Deleting a session permanently removes all associated messages. This action cannot be undone.

List and clean up old sessions

You can list sessions and delete the ones you no longer need:
from acontext import AcontextClient

client = AcontextClient(
    api_key="sk-ac-your-root-api-bearer-token",
    base_url="http://localhost:8029/api/v1"
)

# List all sessions
sessions = client.sessions.list(limit=100, time_desc=True)

print(f"Found {len(sessions.items)} sessions")

# Delete old sessions (example: delete all except the most recent 10)
for session in sessions.items[10:]:
    client.sessions.delete(session.id)
    print(f"Deleted session {session.id}")

Best practices

  • Use sessions to group related messages (e.g., one conversation, one task)
  • Create a new session for each distinct conversation or workflow
  • Use OpenAI format if you’re working with OpenAI models or want broad compatibility
  • Use Anthropic format if you’re primarily using Claude models
  • You can convert between formats when retrieving messages
  • Set appropriate page sizes (50-100 messages typically works well)
  • Cache results when possible to reduce API calls
  • Use time_desc=True to get most recent messages first
  • Process pages asynchronously for better performance with large histories

Next steps