class Exchange
A dataclass representing a single exchange (input-response pair) in a conversation, storing metadata about the interaction including timing, tokens, and file information.
/tf/active/vicechatdev/e-ink-llm/session_manager.py
17 - 27
simple
Purpose
The Exchange class serves as a structured data container for capturing all relevant information about a single conversational exchange. It tracks the input source, response content, performance metrics (processing time, token usage), and maintains conversation ordering through sequence numbers. This class is typically used in conversation management systems to persist and retrieve interaction history, enabling features like conversation replay, analytics, and audit trails.
Source Code
class Exchange:
"""Represents a single exchange in a conversation"""
exchange_id: str
sequence_number: int
input_file: str
input_type: str
response_text: str
processing_time: float
tokens_used: int
created_at: str
metadata: Dict[str, Any]
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
exchange_id: Unique identifier for this exchange, typically a UUID string. Used to reference and retrieve specific exchanges from storage.
sequence_number: Integer representing the order of this exchange within a conversation. Starts from 0 or 1 and increments with each new exchange.
input_file: Path or filename of the input file that was processed in this exchange. Can be a relative or absolute path string.
input_type: String indicating the type/format of the input (e.g., 'text', 'image', 'audio', 'pdf'). Used to determine how the input should be processed or displayed.
response_text: The actual text response generated or received during this exchange. Contains the main output content.
processing_time: Float value representing the time taken to process this exchange in seconds. Used for performance monitoring and optimization.
tokens_used: Integer count of tokens consumed during this exchange. Important for tracking API usage and costs in LLM applications.
created_at: ISO 8601 formatted timestamp string indicating when this exchange was created (e.g., '2024-01-15T10:30:00Z').
metadata: Dictionary containing additional arbitrary key-value pairs for storing extra information about the exchange (e.g., model name, temperature, user info).
Return Value
As a dataclass, instantiation returns an Exchange object with all specified attributes. The class automatically generates __init__, __repr__, __eq__, and other methods. When used with asdict() from dataclasses module, it returns a dictionary representation of the exchange suitable for JSON serialization or database storage.
Class Interface
Methods
__init__(exchange_id: str, sequence_number: int, input_file: str, input_type: str, response_text: str, processing_time: float, tokens_used: int, created_at: str, metadata: Dict[str, Any]) -> None
Purpose: Automatically generated constructor that initializes an Exchange instance with all required attributes
Parameters:
exchange_id: Unique identifier string for the exchangesequence_number: Integer position in conversation sequenceinput_file: Path to input fileinput_type: Type of input contentresponse_text: Generated response contentprocessing_time: Time taken in secondstokens_used: Token count for the exchangecreated_at: ISO timestamp of creationmetadata: Additional key-value metadata
Returns: None (initializes the instance)
__repr__() -> str
Purpose: Automatically generated method that returns a string representation of the Exchange instance showing all attributes
Returns: String representation in format 'Exchange(exchange_id=..., sequence_number=..., ...)'
__eq__(other: object) -> bool
Purpose: Automatically generated method that compares two Exchange instances for equality based on all attributes
Parameters:
other: Another object to compare with
Returns: True if all attributes are equal, False otherwise
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
exchange_id |
str | Unique identifier for this exchange | instance |
sequence_number |
int | Order position of this exchange in the conversation | instance |
input_file |
str | Path or filename of the input file processed | instance |
input_type |
str | Type/format of the input (e.g., 'text', 'image') | instance |
response_text |
str | The actual response content generated | instance |
processing_time |
float | Time taken to process this exchange in seconds | instance |
tokens_used |
int | Number of tokens consumed in this exchange | instance |
created_at |
str | ISO 8601 timestamp of when the exchange was created | instance |
metadata |
Dict[str, Any] | Dictionary of additional metadata about the exchange | instance |
Dependencies
dataclasses
Required Imports
from dataclasses import dataclass
from typing import Dict, Any
Usage Example
from dataclasses import dataclass, asdict
from typing import Dict, Any
from datetime import datetime
import uuid
@dataclass
class Exchange:
exchange_id: str
sequence_number: int
input_file: str
input_type: str
response_text: str
processing_time: float
tokens_used: int
created_at: str
metadata: Dict[str, Any]
# Create a new exchange
exchange = Exchange(
exchange_id=str(uuid.uuid4()),
sequence_number=1,
input_file='user_query.txt',
input_type='text',
response_text='This is the AI response',
processing_time=1.23,
tokens_used=150,
created_at=datetime.now().isoformat(),
metadata={'model': 'gpt-4', 'temperature': 0.7}
)
# Access attributes
print(exchange.exchange_id)
print(exchange.response_text)
# Convert to dictionary for serialization
exchange_dict = asdict(exchange)
print(exchange_dict)
Best Practices
- Always generate unique exchange_id values using uuid.uuid4() to avoid collisions
- Use ISO 8601 format for created_at timestamps (datetime.now().isoformat()) for consistent parsing
- Increment sequence_number sequentially within a conversation to maintain proper ordering
- Store only serializable data in the metadata dictionary (strings, numbers, lists, dicts) to enable JSON conversion
- Use asdict() from dataclasses module to convert Exchange instances to dictionaries for database storage or API responses
- Consider making Exchange frozen (frozen=True in @dataclass decorator) if immutability is desired
- Validate input_type against a predefined set of allowed types to maintain data consistency
- Store processing_time with sufficient precision (float) for accurate performance analysis
- Keep response_text as the primary content field; use metadata for supplementary information
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class ConversationTurn 72.4% similar
-
class ConversationState 72.0% similar
-
class ConversationReference 71.4% similar
-
class ConversationContext 64.9% similar
-
class ChatMessage 61.1% similar