Comprehensive guide to agent multi turn conversation covering architecture, implementation, testing, and operational patterns for production engineering teams.
Agent multi-turn conversation is the process by which an AI agent maintains a coherent, evolving dialogue with a user or system over multiple exchanges, preserving context, refining understanding, and adapting responses across turns. It matters when a user needs to explore a topic, complete a task, or navigate a complex system through natural language, and the agent must remember prior interactions, follow up on ambiguous inputs, and infer intent across time—without the user repeating themselves.
An agent begins a conversation by receiving an initial input, then iteratively processes user messages, updates its internal state, and emits responses. Each turn consists of a user utterance and the agent’s reply, with state preserved between turns.
The agent maintains a conversation history as a sequence of message objects. Each message has:
role: "user" or "assistant"content: the text of the messagetimestamp: ISO 8601 stringmetadata: optional structured data (e.g., intent, confidence, entities)A typical exchange:
[
{
"role": "user",
"content": "I need help planning a trip to Kyoto next April.",
"timestamp": "2025-04-05T10:12:00Z"
},
{
"role": "assistant",
"content": "Great! When will you be traveling? Do you have a preferred budget or accommodation type?",
"timestamp": "2025-04-05T10:12:30Z"
},
{
"role": "user",
"content": "I want to fly in on April 10th and leave April 20th. Budget is $1,500, and I’d like a ryokan.",
"timestamp": "2025-04-05T10:13:45Z"
}
]
The agent uses this history to infer intent, resolve references, and generate context-aware replies.
To avoid reprocessing the same information, agents must manage context efficiently. The primary mechanism is a context window, a fixed-size buffer that holds the most recent messages. The agent selects messages for processing by truncating or summarizing older entries.
When a new message arrives, the agent performs the following steps:
Example configuration in a standard YAML file used across agent systems:
agent:
conversation:
context_window:
strategy: "sliding"
max_messages: 10
max_tokens: 4096
summary_prompt: |
Summarize the following conversation:
{{conversation}}
Focus on: key decisions, user preferences, open tasks, and unresolved questions.
summary_frequency: 3 # summarize every 3 turns
A common failure: the agent forgets a user’s stated preference when a new turn arrives, because the context window was not updated in time. The agent processes the new message but fails to include the prior turn’s context in the prompt.
role: "system" message as user, causing confusion in turn tracking.An agent must persist state between turns. This state includes:
State is typically stored in a database using a table with the schema:
CREATE TABLE agent_conversation (
session_id VARCHAR(64) PRIMARY KEY,
user_id VARCHAR(64),
created_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ,
metadata JSONB,
history JSONB,
state JSONB
);
An agent queries the database on each turn to retrieve the session state:
SELECT history, state, metadata
FROM agent_conversation
WHERE session_id = 'sess_7a3b1c'
ORDER BY created_at ASC;
When the agent completes a turn, it updates the state:
UPDATE agent_conversation
SET history = jsonb_append(history, $1),
state = jsonb_set(state, '{tasks, pending}', $2),
updated_at = NOW()
WHERE session_id = 'sess_7a3b1c';
A common silent failure: the agent updates history but forgets to set updated_at, causing stale sessions and missed state transitions.
Not all conversations follow a simple user → assistant → user → assistant pattern. Some require nested turns, parallel dialogues, or asynchronous updates.
An agent may initiate a sub-conversation within the main flow. For example:
{
"role": "user",
"content": "Can we set up a calendar reminder for the Kyoto trip?",
"metadata": {
"sub_conversation_id": "sub_abc123"
}
}
The agent creates a new sub-conversation and tracks its own history. The main conversation may now include references to the sub-conversation:
{
"role": "assistant",
"content": "I’ve created a calendar event for your Kyoto trip. You can manage it in the sub-conversation.",
"metadata": {
"linked_conversation": "sub_abc123"
}
}
In systems using event-driven architectures, a user may send a message while an agent is processing a previous turn. The agent must handle concurrent turns and message batching.
The agent subscribes to an event stream (e.g., via Kafka or a WebSocket) and processes messages in order. When a message arrives, it:
session_id (from cookie, authorization header, or session_token)202 Accepted response immediatelyExample HTTP response:
HTTP/1.1 202 Accepted
Content-Type: application/json
Location: /conversations/sess_7a3b1c/turns/123
{
"message": "Turn queued for processing",
"session_id": "sess_7a3b1c",
"turn_id": 123,
"received_at": "2025-04-05T10:15:00Z"
}
The user receives a quick acknowledgment while the agent continues processing.
Agents must be configurable to handle varying loads, latency constraints, and user expectations.
agent:
conversation:
turn:
timeout_seconds: 30
retry_attempts: 3
backoff_strategy: "exponential"
max_concurrent_turns: 100
error_handling:
retryable_errors:
- "network_timeout"
- "database_timeout"
- "context_overflow"
fallback_strategy: "last_known_state"
fallback_response: "I’m currently processing your request. Please wait."
The agent uses this configuration to:
503 Service UnavailableWhen a turn fails, the agent logs the error and updates the session state with diagnostic data:
{
"error": {
"type": "context_overflow",
"message": "Context window exceeded 4096 tokens; summary needed.",
"details": {
"actual_tokens": 4210,
"required_tokens": 4096,
"summary_generated": true
},
"timestamp": "2025-04-05T10:17:30Z"
}
}
The agent may also emit a diagnostic event to a monitoring system:
{
"event_type": "conversation.turn.failed",
"session_id": "sess_7a3b1c",
"turn_id": 123,
"error": {
"code": "ctx_overflow",
"message": "Context window exceeded 4096 tokens",
"details": {
"input_tokens": 2800,
"summary_tokens": 1410,
"total": 4210
}
},
"timestamp": "2025-04-05T10:17:30Z"
}
The agent uses a prompt template that varies based on the number of turns and the current state. A minimal template might be:
{% if session.state.tasks %}
You are helping {{ user.name }} with the following tasks:
{% for task in session.state.tasks %}
- {{ task.title }} (due: {{ task.due }})
{% endfor %}
{% endif %}
Current conversation:
{{ conversation }}
User: {{ user_message }}
Assistant:
The agent evaluates this template on each turn, inserting the current state and history.
An agent may transition between conversation states, such as:
idle: waiting for a new messageplanning: gathering informationexecuting: performing actionsconfirming: validating resultsEach state may have its own prompt, behavior, and configuration. The agent updates state.current in the session:
{
"state": {
"current": "planning",
"details": {
"focus": "travel dates",
"step": 2,
"expected_next": "budget summary"
}
}
}
When the user says “Let’s finalize this plan,” the agent transitions from planning to confirming, applying a new prompt and setting up a confirmation flow.
When a user says “I’d like that,” the agent must resolve the referent. It uses coreference resolution, typically by:
The agent may ask a clarifying question:
{
"role": "assistant",
"content": "Which option do you mean? The ryokan in Gion or the one near the Fushimi Inari shrine?",
"metadata": {
"clarification": true,
"referent": "ryokan",
"candidate_options": [
"Gion ryokan",
"Fushimi Inari ryokan"
]
}
}
The user’s next message is then linked to this clarification.
max_messages, summary_frequency, and backoff_strategy are not optional—they define the behavior.This page was rewritten on 13 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy