OpenAI Adapter¶
Adapter for parsing ChatGPT conversation exports.
Overview¶
The OpenAIAdapter implements the ConversationProvider protocol for OpenAI (ChatGPT) conversation exports. It provides stateless, streaming-based parsing with O(1) memory usage.
API Reference¶
OpenAIAdapter
¶
Adapter for streaming OpenAI conversation exports.
This adapter uses ijson to stream-parse OpenAI ChatGPT export files with O(1) memory complexity. Conversations are yielded one at a time, enabling processing of arbitrarily large export files on modest hardware.
Memory Model
- Streaming parser state: ~10-50MB (ijson buffer)
- Per-conversation overhead: ~5MB (metadata + message tree)
- Total working set: <100MB regardless of file size
Error Handling Strategy
- FileNotFoundError: Raised for missing files (fail-fast)
- ParseError: Raised for invalid JSON syntax (fail-fast)
- ValidationError: Raised for schema violations (fail-fast during streaming)
- Malformed conversations: Logged and skipped (graceful degradation)
Example
from pathlib import Path
from echomine.adapters import OpenAIAdapter
adapter = OpenAIAdapter()
# Stream all conversations (lazy iteration)
for conversation in adapter.stream_conversations(Path("export.json")):
print(f"{conversation.title}: {conversation.message_count} messages")
# Process first N conversations only (memory-efficient)
conversations = []
for i, conv in enumerate(adapter.stream_conversations(Path("export.json"))):
conversations.append(conv)
if i >= 9: # First 10 conversations
break
Requirements
- FR-003: O(1) memory streaming implementation
- FR-018: Extract conversation metadata (id, title, timestamps)
- FR-122: Use ijson for incremental JSON parsing
- FR-281-285: Skip malformed entries with warning logs
- SC-001: Memory usage <1GB for large exports
stream_conversations
¶
stream_conversations(
file_path: Path,
*,
progress_callback: ProgressCallback | None = None,
on_skip: OnSkipCallback | None = None,
) -> Iterator[Conversation]
Stream conversations from OpenAI export file with O(1) memory.
This method uses ijson to incrementally parse the export file, yielding Conversation objects one at a time. The entire file is NEVER loaded into memory - only the current conversation being parsed.
Streaming Behavior
- Returns iterator (lazy evaluation)
- Conversations yielded in file order
- Parser state bounded by ijson buffer (~50MB)
- No buffering between conversations
Error Handling
- Invalid JSON: Raises ParseError immediately
- Missing file: Raises FileNotFoundError
- Schema violations: Raises ValidationError (Pydantic)
- Empty array: Succeeds, yields zero conversations
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to OpenAI export JSON file |
required |
progress_callback
|
ProgressCallback | None
|
Optional callback invoked every 100 conversations (FR-069) |
None
|
on_skip
|
OnSkipCallback | None
|
Optional callback invoked when malformed entries skipped (FR-107) |
None
|
Yields:
| Type | Description |
|---|---|
Conversation
|
Conversation objects parsed from export |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist |
ParseError
|
If JSON is malformed (syntax errors) |
ValidationError
|
If conversation data violates schema |
Example
# Basic usage
adapter = OpenAIAdapter()
for conv in adapter.stream_conversations(Path("export.json")):
print(f"Conversation: {conv.title}")
# Handle errors
try:
conversations = list(adapter.stream_conversations(path))
except ParseError as e:
print(f"Invalid export format: {e}")
except ValidationError as e:
print(f"Schema violation: {e}")
Memory Complexity: O(1) for file size, O(N) for single conversation Time Complexity: O(M) where M = total conversations in file
Source code in src/echomine/adapters/openai.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | |
search
¶
search(
file_path: Path,
query: SearchQuery,
*,
progress_callback: ProgressCallback | None = None,
on_skip: OnSkipCallback | None = None,
) -> Iterator[SearchResult[Conversation]]
Search conversations with BM25 relevance ranking.
Algorithm: 1. Stream all conversations (O(1) memory per conversation) 2. Apply title filter if specified (metadata-only, fast) 3. Apply date range filter if specified 4. Build corpus and calculate BM25 scores 5. Rank by relevance (descending) 6. Apply limit if specified 7. Yield SearchResult objects one at a time
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to OpenAI export file |
required |
query
|
SearchQuery
|
SearchQuery with keywords, title_filter, limit |
required |
progress_callback
|
ProgressCallback | None
|
Optional callback invoked per conversation processed |
None
|
on_skip
|
OnSkipCallback | None
|
Optional callback for malformed entries |
None
|
Yields:
| Type | Description |
|---|---|
SearchResult[Conversation]
|
SearchResult[Conversation] with ranked results and scores |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist |
ParseError
|
If JSON is malformed |
Performance
- Memory: O(N) where N = matching conversations
- Time: O(M) where M = total conversations in file
- Early termination: Not implemented (stream all for BM25)
Example
Source code in src/echomine/adapters/openai.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | |
get_conversation_by_id
¶
Retrieve specific conversation by UUID (FR-155, FR-217, FR-356).
Uses streaming search for memory efficiency - O(N) time, O(1) memory. For large files with frequent ID lookups, consider building an index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to OpenAI export JSON file |
required |
conversation_id
|
str
|
UUID of conversation to retrieve |
required |
Returns:
| Type | Description |
|---|---|
Conversation | None
|
Conversation object if found, None otherwise (FR-155) |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist |
ParseError
|
If JSON is malformed |
Example
Performance
- Time: O(N) where N = conversations in file (streaming search)
- Memory: O(1) for file size, O(M) for single conversation
- Early termination: Returns immediately when match found
Source code in src/echomine/adapters/openai.py
get_message_by_id
¶
get_message_by_id(
file_path: Path, message_id: str, *, conversation_id: str | None = None
) -> tuple[Message, Conversation] | None
Retrieve specific message by UUID with parent conversation context.
Searches for a message by ID, optionally scoped to a specific conversation for performance optimization. Returns both the message and its parent conversation to provide full context.
Uses streaming search for memory efficiency - O(1) memory usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
Path
|
Path to OpenAI export JSON file |
required |
message_id
|
str
|
UUID of message to retrieve |
required |
conversation_id
|
str | None
|
Optional conversation UUID to scope search (performance hint) |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Message, Conversation] | None
|
Tuple of (Message, Conversation) if found, None otherwise. |
tuple[Message, Conversation] | None
|
The Conversation is the parent containing the message. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist |
ParseError
|
If JSON is malformed |
Example
adapter = OpenAIAdapter()
# Search with conversation hint (faster)
result = adapter.get_message_by_id(
Path("export.json"),
"msg-123",
conversation_id="conv-456"
)
# Search all conversations (slower)
result = adapter.get_message_by_id(
Path("export.json"),
"msg-123"
)
if result:
message, conversation = result
print(f"Message: {message.content}")
print(f"From conversation: {conversation.title}")
else:
print("Message not found")
Performance
- With conversation_id:
- Time: O(N) where N = conversations until match
- Memory: O(1) for file size, O(M) for single conversation
- Without conversation_id:
- Time: O(N*M) where N = conversations, M = messages per conversation
- Memory: O(1) for file size, O(M) for single conversation
- Early termination: Returns immediately when match found
Design Notes
Returns tuple instead of just Message to provide conversation context (title, timestamps, other messages) which is valuable for CLI display and analysis workflows.
Source code in src/echomine/adapters/openai.py
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 | |
Usage Examples¶
Basic Setup¶
from echomine import OpenAIAdapter
from pathlib import Path
# Create adapter (stateless, reusable)
adapter = OpenAIAdapter()
export_file = Path("conversations.json")
Stream All Conversations¶
Memory-efficient iteration over all conversations:
# Stream conversations (O(1) memory usage)
for conversation in adapter.stream_conversations(export_file):
print(f"[{conversation.created_at.date()}] {conversation.title}")
print(f" Messages: {len(conversation.messages)}")
print(f" ID: {conversation.id}")
Search with Keywords¶
Full-text search with BM25 ranking:
from echomine.models import SearchQuery
# Create search query
query = SearchQuery(
keywords=["algorithm", "leetcode"],
limit=10
)
# Execute search
for result in adapter.search(export_file, query):
print(f"[{result.score:.2f}] {result.conversation.title}")
Get Conversation by ID¶
Retrieve a specific conversation:
# Get specific conversation
conversation = adapter.get_conversation_by_id(export_file, "conv-abc123")
if conversation:
print(f"Found: {conversation.title}")
print(f"Messages: {len(conversation.messages)}")
else:
print("Conversation not found")
Progress Reporting¶
Track progress for long-running operations:
def progress_callback(count: int) -> None:
"""Called periodically during processing."""
if count % 100 == 0:
print(f"Processed {count:,} conversations...")
# Stream with progress reporting
for conversation in adapter.stream_conversations(
export_file,
progress_callback=progress_callback
):
process(conversation)
Graceful Degradation¶
Handle malformed entries gracefully:
skipped_entries = []
def handle_skipped(conversation_id: str, reason: str) -> None:
"""Called when malformed entry is skipped."""
skipped_entries.append({
"id": conversation_id,
"reason": reason,
})
# Stream with skip handler
for conversation in adapter.stream_conversations(
export_file,
on_skip=handle_skipped
):
process(conversation)
if skipped_entries:
print(f"Skipped {len(skipped_entries)} malformed conversations")
Methods¶
stream_conversations()¶
Stream all conversations from export file.
Signature:
def stream_conversations(
self,
file_path: Path,
*,
progress_callback: Optional[Callable[[int], None]] = None,
on_skip: Optional[Callable[[str, str], None]] = None,
) -> Iterator[Conversation]:
...
Parameters:
file_path: Path to OpenAI export JSON fileprogress_callback: Optional callback invoked periodically with conversation counton_skip: Optional callback invoked when malformed entry is skipped
Returns:
Iterator yielding Conversation objects.
Raises:
FileNotFoundError: If file does not existPermissionError: If file cannot be readParseError: If export format is invalidSchemaVersionError: If export schema version is unsupported
Memory Usage: O(1) - constant memory regardless of file size.
search()¶
Search conversations with BM25 ranking and filtering.
Signature:
def search(
self,
file_path: Path,
query: SearchQuery,
*,
progress_callback: Optional[Callable[[int], None]] = None,
on_skip: Optional[Callable[[str, str], None]] = None,
) -> Iterator[SearchResult[Conversation]]:
...
Parameters:
file_path: Path to OpenAI export JSON filequery: Search parameters (keywords, filters, limit)progress_callback: Optional callback for progress reportingon_skip: Optional callback for skipped entries
Returns:
Iterator yielding SearchResult[Conversation] objects, sorted by relevance score (descending).
Raises:
Same as stream_conversations().
Performance:
- Title-only search: <5 seconds for 10K conversations (metadata-only)
- Keyword search: <30 seconds for 1.6GB files (full-text with BM25)
get_conversation_by_id()¶
Retrieve a specific conversation by ID.
Signature:
def get_conversation_by_id(
self,
file_path: Path,
conversation_id: str,
) -> Optional[Conversation]:
...
Parameters:
file_path: Path to OpenAI export JSON fileconversation_id: ID of conversation to retrieve
Returns:
Conversation if found, None otherwise.
Raises:
Same as stream_conversations().
Performance: Early termination - stops searching after finding conversation.
Adapter Pattern¶
Stateless Design¶
OpenAIAdapter has no __init__ parameters and maintains no internal state:
# ✅ CORRECT: Reusable adapter
adapter = OpenAIAdapter()
for file in export_files:
for conv in adapter.stream_conversations(file):
process(conv)
Benefits:
- Thread-safe (no shared state)
- Reusable across multiple files
- Simple, predictable behavior
Protocol Implementation¶
Implements ConversationProvider protocol:
from echomine.protocols import ConversationProvider
# Type-safe adapter usage
def process_export(
adapter: ConversationProvider, # Works with ANY adapter
file_path: Path
) -> None:
for conv in adapter.stream_conversations(file_path):
print(conv.title)
# OpenAIAdapter implements protocol
process_export(OpenAIAdapter(), Path("export.json"))
OpenAI-Specific Behavior¶
Export Format¶
Expects OpenAI ChatGPT export JSON format:
[
{
"id": "conv-uuid",
"title": "Conversation Title",
"create_time": 1704974400.0,
"update_time": 1704974500.0,
"mapping": {
"msg-uuid-1": {
"id": "msg-uuid-1",
"message": {
"id": "msg-uuid-1",
"author": {"role": "user"},
"content": {"content_type": "text", "parts": ["Hello"]},
"create_time": 1704974410.0
},
"parent": null,
"children": ["msg-uuid-2"]
}
}
}
]
Metadata Mapping¶
Provider-specific fields stored in conversation.metadata:
openai_model: Model used (e.g., "gpt-4")openai_conversation_template_id: Template IDopenai_plugin_ids: List of plugin IDs usedopenai_moderation_results: Moderation results (if any)
Example:
conversation = adapter.get_conversation_by_id(file_path, "conv-123")
model = conversation.metadata.get("openai_model", "unknown")
print(f"Model: {model}")
Role Normalization¶
OpenAI roles are already normalized (no mapping needed):
- "user" → "user"
- "assistant" → "assistant"
- "system" → "system"
Error Handling¶
Exceptions¶
from echomine import (
ParseError, # Malformed JSON/structure
ValidationError, # Invalid data
SchemaVersionError, # Unsupported version
)
try:
for conv in adapter.stream_conversations(file_path):
process(conv)
except ParseError as e:
print(f"Export file corrupted: {e}")
except SchemaVersionError as e:
print(f"Unsupported export version: {e}")
except FileNotFoundError:
print(f"File not found: {file_path}")
Graceful Degradation¶
Malformed conversations are skipped with warnings logged:
# Skipped entries logged as WARNING
# Processing continues for valid entries
for conv in adapter.stream_conversations(file_path):
# Only valid conversations yielded
process(conv)
Concurrency¶
Thread Safety¶
- Adapter instances: Thread-safe (stateless)
- Iterators: NOT thread-safe (each thread needs its own)
from threading import Thread
adapter = OpenAIAdapter() # SAFE: Share adapter
def worker(thread_id):
# SAFE: Each thread creates its own iterator
for conv in adapter.stream_conversations(file_path):
process(conv, thread_id)
threads = [Thread(target=worker, args=(i,)) for i in range(4)]
Multi-Process Safety¶
Multiple processes can read the same file concurrently:
from multiprocessing import Process
def worker(process_id):
adapter = OpenAIAdapter() # Each process has its own adapter
for conv in adapter.stream_conversations(file_path):
process(conv, process_id)
processes = [Process(target=worker, args=(i,)) for i in range(4)]
Performance¶
Memory Efficiency¶
- O(1) memory usage: Constant memory regardless of file size
- Streaming: Uses ijson for incremental parsing
- No buffering: Yields conversations as they're parsed
Speed¶
- 10K conversations: <5 seconds for listing (metadata-only)
- 1.6GB file: <30 seconds for keyword search
- Early termination:
get_conversation_by_idstops after finding match
Related¶
- ConversationProvider Protocol: Protocol definition
- Conversation Model: Result type
- SearchQuery: Search parameters