๐ณ 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)¶
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.
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¶
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:
- Agent runs tasks 1-3.
- Agent encounters a high-cost decision โ Pauses Thread.
- Human reviews the thread state in the Console.
- Human hits Resume โ Agent continues from Task 4 with all previous state intact.
This makes your agents not just "smart", but reliable enterprise employees. ๐ค๐