> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.world/llms.txt
> Use this file to discover all available pages before exploring further.

# Conversation

> A class to manage conversation history with in-memory storage, supporting multiple export formats and automatic token management

## 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, automatic token counting, and dynamic context window management.

## Installation

```bash theme={null}
pip install -U swarms
```

## Parameters

<ParamField path="id" type="str" default="auto-generated">
  Unique identifier for the conversation.
</ParamField>

<ParamField path="name" type="str" default="conversation-test">
  Name of the conversation.
</ParamField>

<ParamField path="system_prompt" type="Optional[str]" default="None">
  The system prompt for the conversation.
</ParamField>

<ParamField path="time_enabled" type="bool" default="False">
  Enable ISO timestamps on each message.
</ParamField>

<ParamField path="autosave" type="bool" default="False">
  Enable automatic saving of conversation history.
</ParamField>

<ParamField path="save_filepath" type="str" default="None">
  File path for saving the conversation history.
</ParamField>

<ParamField path="load_filepath" type="str" default="None">
  File path to load conversation history from on initialization.
</ParamField>

<ParamField path="context_length" type="int" default="8192">
  Maximum number of tokens allowed in the conversation history. Used by token-based truncation and dynamic context windowing.
</ParamField>

<ParamField path="rules" type="str" default="None">
  Rules injected into the conversation to govern participant behavior.
</ParamField>

<ParamField path="custom_rules_prompt" type="str" default="None">
  Custom prompt prepended alongside `rules`.
</ParamField>

<ParamField path="user" type="str" default="User">
  The user identifier used as the role for user messages.
</ParamField>

<ParamField path="save_as_yaml_on" type="bool" default="False">
  When `True`, persisted history is written as YAML.
</ParamField>

<ParamField path="save_as_json_bool" type="bool" default="False">
  When `True`, persisted history is written as JSON.
</ParamField>

<ParamField path="token_count" type="bool" default="False">
  Enable per-message token counting.
</ParamField>

<ParamField path="message_id_on" type="bool" default="False">
  Attach a unique ID to every message.
</ParamField>

<ParamField path="tokenizer_model_name" type="str" default="gpt-5.4">
  Model name used by the tokenizer for token counting and truncation.
</ParamField>

<ParamField path="conversations_dir" type="Optional[str]" default="None">
  Directory used to persist and load named conversations.
</ParamField>

<ParamField path="export_method" type="str" default="json">
  Export format used by `export()`: `"json"` or `"yaml"`.
</ParamField>

<ParamField path="dynamic_context_window" type="bool" default="True">
  Enable dynamic context window management (grow/shrink the kept history based on token usage).
</ParamField>

<ParamField path="cache_enabled" type="bool" default="False">
  Enable token-count caching for repeated history reads.
</ParamField>

<ParamField path="output_metadata" type="bool" default="False">
  Include per-message metadata in formatted output.
</ParamField>

<ParamField path="memory_md_path" type="Optional[str]" default="None">
  Path to the `MEMORY.md` file used for persistent-memory reads/writes.
</ParamField>

## Methods

### add()

Add a message to the conversation history.

```python theme={null}
def add(
    self,
    role: str,
    content: Union[str, dict, list, Any],
    metadata: Optional[dict] = None,
    category: Optional[str] = None,
)
```

**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 for the message
* `category` (Optional\[str]): Optional category for the message (e.g., 'input', 'output')

### return\_history\_as\_string()

Return the conversation history as a formatted string.

```python theme={null}
def return_history_as_string(self) -> str:
```

**Returns:** String representation of the conversation history

### 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.

```python theme={null}
def compact(
    self,
    summary: str,
    summary_role: str = "System",
) -> None
```

**Parameters:**

* `summary` (str): The compressed summary content that replaces the raw history.
* `summary_role` (str): Role attached to the summary message. Defaults to `"System"`.

```python theme={null}
conv.compact(
    summary="User asked about X. Assistant explained X.",
    summary_role="System",
)
```

### export()

Export the conversation to a file based on the export method.

```python theme={null}
def export(self, force: bool = True)
```

**Parameters:**

* `force` (bool): If True, saves regardless of autosave setting

### load()

Load conversation history from a file (auto-detects format).

```python theme={null}
def load(self, filename: str)
```

**Parameters:**

* `filename` (str): Path to the file to load from

### search()

Search for messages containing a keyword.

```python theme={null}
def search(self, keyword: str) -> list
```

**Parameters:**

* `keyword` (str): The keyword to search for

**Returns:** List of messages containing the keyword

### truncate\_memory\_with\_tokenizer()

Truncate conversation history based on token count using tokenizer.

```python theme={null}
def truncate_memory_with_tokenizer(self)
```

### export\_and\_count\_categories()

Export all messages with category 'input' and 'output' and count their tokens.

```python theme={null}
def export_and_count_categories(self) -> Dict[str, int]
```

**Returns:** Dictionary with input\_tokens, output\_tokens, and total\_tokens

### Other Methods

| Method                                                                                 | Description                                                                                                                |
| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `query(index)`                                                                         | Return the message dict at `index`, or `None` if out of range                                                              |
| `delete(index)`                                                                        | Remove the message at `index`                                                                                              |
| `update(index, role, content)`                                                         | Replace the role/content of the message at `index`                                                                         |
| `add_multiple(roles, contents)` / `add_multiple_messages(roles, contents)`             | Add several messages concurrently (thread pool)                                                                            |
| `batch_add(messages)`                                                                  | Add a list of `{"role": ..., "content": ...}` dicts                                                                        |
| `get_str()`                                                                            | Alias for `return_history_as_string()`                                                                                     |
| `get_cache_stats()`                                                                    | Returns `{hits, misses, cached_tokens, hit_rate}` for the history-string cache (only meaningful when `cache_enabled=True`) |
| `get_last_message_as_string()`                                                         | Returns the last message formatted as `"role: content"`                                                                    |
| `get_final_message()` / `get_final_message_content()`                                  | Returns the last message dict / just its content                                                                           |
| `return_messages_as_list()` / `return_messages_as_dictionary()`                        | Formatted views of the full history                                                                                        |
| `return_all_except_first()` / `return_all_except_first_string()`                       | History excluding the first (system) message                                                                               |
| `to_dict()` / `to_json()` / `to_yaml()` / `to_list()`                                  | Serialize the conversation (config + history)                                                                              |
| `count_messages_by_role()`                                                             | Dict of message counts keyed by role                                                                                       |
| `clear()`                                                                              | Empty the conversation history                                                                                             |
| `clear_memory()`                                                                       | Reset in-memory conversation state                                                                                         |
| `Conversation.load_conversation(name, conversations_dir=None, load_filepath=None)`     | Classmethod: load a previously saved conversation by name or explicit file path                                            |
| `Conversation.list_conversations(...)` / `Conversation.list_cached_conversations(...)` | Classmethods to enumerate saved/cached conversations                                                                       |

## Usage Examples

### Basic Usage

```python theme={null}
from swarms.structs import Conversation

# Create a conversation
conversation = Conversation(
    name="my-conversation",
    system_prompt="You are a helpful assistant.",
    time_enabled=True,
    autosave=True,
    token_count=True,
    context_length=8192
)

# Add messages
conversation.add("user", "Hello, how are you?")
conversation.add("assistant", "I am doing well, thanks.")
conversation.add("user", "What is the weather in Tokyo?")

# Get conversation as string
print(conversation.return_history_as_string())
```

### Export and Load

```python theme={null}
# Export to JSON
conversation.export_method = "json"
conversation.export()

# Load from file
conversation = Conversation.load_conversation(
    name="my-conversation",
    load_filepath="conversation_my-conversation.json"
)
```

### Token Management

```python theme={null}
# Enable token counting and context management
conversation = Conversation(
    token_count=True,
    context_length=4096,
    dynamic_context_window=True
)

# Add messages with categories for tracking
conversation.add("user", "My input", category="input")
conversation.add("assistant", "My response", category="output")

# Count tokens by category
tokens = conversation.export_and_count_categories()
print(f"Input tokens: {tokens['input_tokens']}")
print(f"Output tokens: {tokens['output_tokens']}")
print(f"Total tokens: {tokens['total_tokens']}")
```

### Search and Query

```python theme={null}
# Search for messages
results = conversation.search("weather")

# Get last message
last_message = conversation.get_last_message_as_string()

# Get specific message by index
message = conversation.query(0)
```

## Features

* **Automatic Saving**: Enable autosave to automatically persist conversation history
* **Token Management**: Track token counts and automatically truncate based on context length
* **Multiple Export Formats**: Save as JSON or YAML
* **Dynamic Context Window**: Automatically manage conversation length to fit context limits
* **Message Search**: Search through conversation history by keyword
* **Categorization**: Tag messages with categories for organized tracking
* **Time Tracking**: Optionally track timestamps for all messages
