Skip to main content

Overview

The Conversation class manages conversation history for agents, allowing for addition, deletion, and retrieval of messages. It supports saving and loading in JSON/YAML formats, per-message token counting, and trimming the rendered history to a context window. Every Agent keeps its history in one, as agent.short_memory.

Installation

Parameters

Optional[str]
default:"auto-generated"
Unique identifier for the conversation.
Optional[str]
default:"None"
Name of the conversation. When omitted, each instance gets a unique name of the form conversation-<8 hex characters>. Only an explicitly named conversation resumes from its save file.
Optional[str]
default:"None"
Added as the first message, with role "System", when a new conversation starts. Not re-added when history is restored from disk.
bool
default:"False"
Add an ISO timestamp to each message.
bool
default:"False"
Call export() after every add(), writing the history to save_filepath.
str
default:"None"
File the history is saved to. Defaults to <conversations_dir>/conversation_<name>.json (or .yaml, following export_method). An extension that does not match export_method is replaced. Setting it explicitly makes the conversation resume from that file when it exists.
str
default:"None"
Marks the conversation as one that resumes from disk. The constructor still reads save_filepath, not this path. To load a specific file, call load(path) or Conversation.load_conversation(name, load_filepath=path).
int
default:"8192"
Maximum number of tokens allowed in the conversation history. Used by truncate_memory_with_tokenizer() and dynamic_context_window.
str
default:"None"
Added after the system prompt as a message whose role is user, when a new conversation starts.
str
default:"None"
Added after rules as a message whose role is user, when a new conversation starts.
str
default:"User"
Role used for the rules and custom_rules_prompt messages.
bool
default:"False"
Stored but not read. The save format comes from export_method.
bool
default:"False"
Stored but not read. The save format comes from export_method.
bool
default:"False"
Count each message’s tokens and store the result under its token_count key.
bool
default:"False"
Attach a UUID4 message_id to every message.
str
default:"gpt-5.4"
Model name used by the tokenizer for token counting and truncation.
Optional[str]
default:"None"
Directory for the default save_filepath, and the default directory for load_conversation() and list_conversations(). When unset, ./conversations under the current working directory is used. The directory is created only when a file is written.
str
default:"json"
Format used by export() and autosave: "json" or "yaml". Any other value raises ValueError at construction.
bool
default:"True"
When True, return_history_as_string() drops text from the front of the rendered history until it fits in context_length tokens. The stored messages are not changed.
bool
default:"False"
Memoize the string returned by return_history_as_string() until the history changes, and record its token count for get_cache_stats().
bool
default:"False"
Stored but not read by Conversation.
Optional[str]
default:"None"
Path to a MEMORY.md file for persistent memory. The file is created with a header if missing. Prior interactions in it are loaded as one "System" message, and every later add() appends to it.
Optional[List[Dict[str, Any]]]
default:"None"
Chat-format messages ({"role": ..., "content": ...}) added after the system prompt and rules, through add_messages(). Agent(messages=...) uses this to seed short_memory.

Construction and resume

The constructor runs these steps in order:
1

Resume

If you passed name, save_filepath, or load_filepath, and the file at save_filepath exists, its history is loaded.
2

Seed

Only when nothing was restored: system_prompt, then rules, then custom_rules_prompt are added.
3

Persistent memory

With memory_md_path, prior MEMORY.md content is added as one "System" message.
4

Messages

messages, if given, are appended.
An unnamed conversation gets a fresh random name, so it never resumes another instance’s file. Constructing a Conversation writes nothing to disk unless memory_md_path is set, or autosave is on and a seeded message triggers a save.

Methods

add()

Add a message to the conversation history.
Parameters:
  • role (str): The role of the speaker (e.g., ‘User’, ‘System’, ‘Agent’)
  • content (Union[str, dict, list]): The content of the message
  • metadata (Optional[dict]): Optional metadata, stored under the message’s metadata key
  • category (Optional[str]): Optional category for the message (e.g., ‘input’, ‘output’)
Returns: The stored message dict. Depending on the constructor flags it also carries timestamp, message_id, category, metadata, and token_count. With autosave=True, the conversation is exported after the add.

add_messages()

Add chat-format messages in order.
Parameters:
  • messages (List[Dict[str, Any]]): Dicts with a role key and usually a content key. Any other keys, such as name, tool_calls, or tool_call_id, are kept under the message’s metadata, so a tool exchange survives the round trip.
Returns: The result of each add(), in order. Raises ValueError when an item is not a dict or has no role.

return_history_as_string()

Return the conversation history as a formatted string.
Returns: One role: content entry per message, separated by blank lines. Messages with a timestamp are prefixed with [timestamp]. With dynamic_context_window=True, the string is trimmed from the front to fit context_length tokens.

compact()

Collapse the interaction history into a single summary message, preserving the agent’s static context (system_prompt → rules → custom_rules_prompt) ahead of it. If memory_md_path is configured, the on-disk MEMORY.md is archived to <agent_folder>/archive/history_<timestamp>.md and then wiped/re-seeded so the log doesn’t keep growing across compressions.
Parameters:
  • summary (str): The compressed summary content that replaces the raw history.
  • summary_role (str): Role attached to the summary message. Defaults to "System".

export()

Save the conversation to save_filepath in the export_method format.
Parameters:
  • force (bool): If True, saves regardless of autosave setting
The file holds the bare list of message dicts. The parent directory is created if needed.

load()

Load conversation history from a file, choosing the parser by extension.
Parameters:
  • filename (str): Path to a .json, .yaml, or .yml file
Replaces the current history. Accepts the bare message list that export() writes, or a {"metadata": ..., "conversation_history": ...} wrapper. A missing file logs a warning and changes nothing. Any other extension raises ValueError. Search for messages containing a keyword.
Parameters:
  • keyword (str): The keyword to search for
Returns: List of messages containing the keyword

truncate_memory_with_tokenizer()

Truncate the stored history to context_length tokens.
Messages are kept from the start until the budget runs out. The message that crosses the limit is cut to fit, at a sentence boundary when possible, and every later message is dropped.

export_and_count_categories()

Export all messages with category ‘input’ and ‘output’ and count their tokens.
Returns: Dictionary with input_tokens, output_tokens, and total_tokens

Other Methods

list_conversations() only lists files that carry a {"metadata": {"id", "name", "created_at"}} wrapper. export() writes a bare message list, so conversations saved by this class are skipped. Use list_cached_conversations() to find them.

Output formats

Agents and swarms turn a Conversation into their return value with history_output_formatter. Each output_type maps to one method: Any other value raises ValueError. The "xml" output type has been removed.

Usage Examples

Basic Usage

Because it is named and autosaved, this conversation is written to ./conversations/conversation_my-conversation.json. Running the script again resumes that history instead of starting over.

Seed from chat messages

Export and Load

Token Management

Search and Query

Features

  • Automatic Saving: Enable autosave to persist the history after every message
  • Resume by Name: A named conversation picks up its saved history on construction
  • Token Management: Count tokens per message, trim the rendered history to the context length, or truncate the stored history on demand
  • Multiple Export Formats: Save as JSON or YAML
  • Message Search: Search through conversation history by keyword
  • Categorization: Tag messages with categories for organized tracking
  • Time Tracking: Optionally track timestamps for all messages