Overview
TheConversation 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.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.role(str): The role of the speaker (e.g., ‘User’, ‘System’, ‘Agent’)content(Union[str, dict, list]): The content of the messagemetadata(Optional[dict]): Optional metadata, stored under the message’smetadatakeycategory(Optional[str]): Optional category for the message (e.g., ‘input’, ‘output’)
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.messages(List[Dict[str, Any]]): Dicts with arolekey and usually acontentkey. Any other keys, such asname,tool_calls, ortool_call_id, are kept under the message’smetadata, so a tool exchange survives the round trip.
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.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.
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 tosave_filepath in the export_method format.
force(bool): If True, saves regardless of autosave setting
load()
Load conversation history from a file, choosing the parser by extension.filename(str): Path to a.json,.yaml, or.ymlfile
export() writes, or a {"metadata": ..., "conversation_history": ...} wrapper. A missing file logs a warning and changes nothing. Any other extension raises ValueError.
search()
Search for messages containing a keyword.keyword(str): The keyword to search for
truncate_memory_with_tokenizer()
Truncate the stored history tocontext_length tokens.
export_and_count_categories()
Export all messages with category ‘input’ and ‘output’ and count their tokens.Other Methods
Output formats
Agents and swarms turn aConversation 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
./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