Skip to content

๐Ÿณ Cookbook: Building Stateful Agents with Memory

Autonomous agents need more than just one-shot prompts; they need to remember past interactions, user preferences, and intermediate task results. This guide covers the Traylinx Memory & Thread Architecture.

๐Ÿง  Memory Architecture

Traylinx uses a dual-layer memory system: 1. STM (Short-Term Memory): Fast, volatile storage (Redis) for active conversation context. 2. LTM (Long-Term Memory): Persistent storage (Postgres/Vector DB) for knowledge and historical threads.


๐Ÿงต Phase 1: Using Threads

A Thread is a conversation container. Every message in a thread is preserved and provided to the agent as context automatically.

1. Creating a Thread (CLI)

poetry run agentic thread "Let's plan a vacation" --namespace="user-123"

2. Programmatic Thread Management

from app.services.thread_manager import ThreadManager
from app.models.thread import Task

tm = ThreadManager()

# Create a new thread
thread = await tm.create(
    goal="Design a luxury watch",
    namespace="designer-tools",
    tasks=[Task(id="draft", agent="executor", input="Create a 3D sketch")]
)

print(f"Thread ID: {thread.id}")

๐Ÿ—๏ธ Phase 2: Memory Isolation (Namespaces)

Namespaces allow you to build Multi-Tenant agents. Data in tenant-A is cryptographically and logically isolated from tenant-B.

Setting a Namespace

# All memory operations are scoped by namespace
await thread_manager.get_active_thread(namespace="client-acme-prod")

๐Ÿ’พ Phase 3: Persistent STM (Redis)

To enable persistent memory between agent restarts, configure Redis in your .env.

# .env
REDIS_URL=redis://localhost:6379/0

If Redis is not configured, the template falls back to an In-Memory Dictionary, which is lost when the agent stops.


๐Ÿ“š Phase 4: Long-Term Memory (LTM)

For production, you should connect a database to store every conversation forever.

1. Configure Postgres

# .env
DATABASE_URL=postgresql://user:pass@localhost:5432/traylinx

2. Retrieving Context

The specialized agents in the template automatically query the database for "Relevant Past Context" using semantic similarity before answering a new prompt.


๐Ÿ’ก Pro Tip: Pause & Resume

The AsyncExecutor in the template supports pausing a thread. This is perfect for "Human-in-the-Loop" workflows:

  1. Agent runs tasks 1-3.
  2. Agent encounters a high-cost decision โ†’ Pauses Thread.
  3. Human reviews the thread state in the Console.
  4. Human hits Resume โ†’ Agent continues from Task 4 with all previous state intact.
# Check status of all persistent threads
agentic list-threads

This makes your agents not just "smart", but reliable enterprise employees. ๐Ÿค–๐Ÿ“ˆ