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, automatic token counting, and dynamic context window management.
Installation
Attributes
Unique identifier for the conversation
Name of the conversation
The system prompt for the conversation
Flag to enable time tracking for messages
Flag to enable automatic saving of conversation history
File path for saving the conversation history
Maximum number of tokens allowed in the conversation history
The user identifier for messages
Flag to enable token counting for messages
Export format: “json” or “yaml”
Enable dynamic context window management
Enable conversation caching
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 for the messagecategory(Optional[str]): Optional category for the message (e.g., ‘input’, ‘output’)
return_history_as_string()
Return the conversation history as a formatted string.export()
Export the conversation to a file based on the export method.force(bool): If True, saves regardless of autosave setting
load()
Load conversation history from a file (auto-detects format).filename(str): Path to the file to load from
search()
Search for messages containing a keyword.keyword(str): The keyword to search for
truncate_memory_with_tokenizer()
Truncate conversation history based on token count using tokenizer.export_and_count_categories()
Export all messages with category ‘input’ and ‘output’ and count their tokens.Usage Examples
Basic Usage
Export and Load
Token Management
Search and Query
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