Thread & Messages Management
Learn how to manage stateful conversations and agent messages
Thread & Messages Management
xpander.ai’s state management system enables agents to maintain continuity across multiple interactions and effectively manage messages. This guide explains how to implement stateful agents that remember previous conversations and maintain context over time.
Thread Concepts
Threads in xpander.ai are the foundation of persistent conversations. A thread represents:
- A sequence of messages between the user and agent(s)
- The conversation context that persists across multiple executions
- An identifiable object that can be retrieved for future interactions
Understanding Agent Messages
Agent messages, which are stored within threads, consists of:
- Message History: Sequential record of all messages in the conversation
- Context Information: Additional data that informs the agent’s understanding
- Tool Call Results: Results from previous tool executions
- System Instructions: Core guidelines defining the agent’s behavior
The messages system ensures that agents maintain a coherent context throughout interactions.
Creating and Using Threads
When you create a new task for an agent, you can either:
- Start a new conversation thread (default behavior)
- Continue an existing thread by providing a
thread_id
Retrieving and Storing Thread IDs
After an execution completes, you can retrieve the thread ID for future use:
Working with Message History
You can directly access and modify the agent’s messages within a thread:
Searching and Analyzing Messages
You can analyze the agent’s messages to make decisions:
Agent Execution Loop with Thread Management
Here’s a simple implementation showing how to build an agent that can maintain conversation state:
Important Note About Message Initialization
When you call add_task()
, the system automatically:
- Creates a new thread with the system prompt
- Initializes the agent’s messages with necessary messages
- Makes the execution input available as
agent.execution.input_message
Do not use agent.memory.init_messages()
- it’s deprecated and should be replaced with agent.add_task()
, which handles message initialization automatically and supports thread continuity through the optional thread_id
parameter.