Chat History ExampleΒΆ

This example demonstrates how to use ChatHistory for conversation management.

  1#!/usr/bin/env python
  2"""
  340 Chat History - Advanced Conversation Management
  4
  5Learn how to use ChatHistory for sophisticated conversation tracking.
  6This includes history formatting, searching, and merging.
  7
  8Level: Expert Topic
  9"""
 10
 11from config_loader import get_chat_config, parse_args
 12
 13from lexilux import Chat, ChatHistory, ChatHistoryFormatter, Conversation
 14
 15
 16def main():
 17    """Demonstrate ChatHistory features."""
 18    args = parse_args()
 19    try:
 20        config = get_chat_config(config_path=args.config)
 21    except (FileNotFoundError, KeyError) as e:
 22        print(f"Configuration error: {e}")
 23        print("\nUsing placeholder values. Please configure test_endpoints.json")
 24        config = {
 25            "base_url": "https://api.example.com/v1",
 26            "api_key": "your-api-key",
 27            "model": "gpt-4",
 28        }
 29
 30    chat = Chat(**config)
 31
 32    # Example 1: Building conversation history
 33    print("=" * 50)
 34    print("Example 1: Building Conversation History")
 35    print("=" * 50)
 36
 37    # Create a conversation
 38    conv = Conversation()
 39
 40    # Add messages
 41    result = conv.chat(chat, "Hello, I'm learning Python.")
 42    print("You: Hello, I'm learning Python.")
 43    print(f"AI: {result.text}\n")
 44
 45    result = conv.chat(chat, "What are the key features?")
 46    print("You: What are the key features?")
 47    print(f"AI: {result.text}\n")
 48
 49    # Get the history
 50    history = conv.to_history()
 51    print(f"History has {len(history)} messages")
 52    print(f"Total tokens: {history.usage.total_tokens}\n")
 53
 54    # Example 2: ChatHistory from messages
 55    print("=" * 50)
 56    print("Example 2: Creating ChatHistory")
 57    print("=" * 50)
 58
 59    messages = [
 60        {"role": "user", "content": "What is Python?"},
 61        {"role": "assistant", "content": "Python is a programming language."},
 62        {"role": "user", "content": "Why is it popular?"},
 63    ]
 64
 65    history = ChatHistory.from_messages(messages)
 66
 67    print("ChatHistory created from messages:")
 68    print(f"  Messages: {len(history.messages)}")
 69    print(f"  Total tokens: {history.usage.total_tokens}\n")
 70
 71    # Example 3: Formatting history
 72    print("=" * 50)
 73    print("Example 3: Formatting Conversation")
 74    print("=" * 50)
 75
 76    # Get a longer conversation
 77    conv = Conversation()
 78    conv.chat(chat, "Tell me about Python lists")
 79    conv.chat(chat, "How do I append to a list?")
 80    conv.chat(chat, "What about list comprehensions?")
 81
 82    history = conv.to_history()
 83
 84    # Format as markdown
 85    formatter = ChatHistoryFormatter()
 86    markdown = formatter.format_markdown(history)
 87
 88    print("Markdown format:")
 89    print(markdown)
 90    print()
 91
 92    # Example 4: Saving and loading history
 93    print("=" * 50)
 94    print("Example 4: Save and Load History")
 95    print("=" * 50)
 96
 97    # Save to JSON
 98    json_data = history.to_json()
 99    print(f"History saved as JSON ({len(json_data)} characters)\n")
100
101    # Load from JSON
102    loaded_history = ChatHistory.from_json(json_data)
103    print(f"History loaded: {len(loaded_history.messages)} messages\n")
104
105    # Example 5: Searching history
106    print("=" * 50)
107    print("Example 5: Search in History")
108    print("=" * 50)
109
110    from lexilux import search_content
111
112    # Search for keywords
113    results = search_content(history, "list")
114
115    print(f"Messages containing 'list': {len(results)}")
116    for msg in results:
117        print(f"  [{msg.role}]: {msg.content[:60]}...")
118    print()
119
120    # Example 6: Filter by role
121    print("=" * 50)
122    print("Example 6: Filter by Role")
123    print("=" * 50)
124
125    from lexilux import filter_by_role
126
127    user_messages = filter_by_role(history, "user")
128    print(f"User messages: {len(user_messages)}")
129    for msg in user_messages:
130        print(f"  - {msg.content[:60]}...")
131    print()
132
133    # Example 7: Merge histories
134    print("=" * 50)
135    print("Example 7: Merge Multiple Histories")
136    print("=" * 50)
137
138    from lexilux import merge_histories
139
140    history1 = ChatHistory.from_messages(
141        [
142            {"role": "user", "content": "Hi"},
143            {"role": "assistant", "content": "Hello!"},
144        ]
145    )
146
147    history2 = ChatHistory.from_messages(
148        [
149            {"role": "user", "content": "How are you?"},
150            {"role": "assistant", "content": "I'm doing well!"},
151        ]
152    )
153
154    merged = merge_histories(history1, history2)
155
156    print(f"Merged history has {len(merged.messages)} messages:")
157    for msg in merged.messages:
158        print(f"  [{msg.role}]: {msg.content}")
159
160    # Example 8: Statistics
161    print("\n" + "=" * 50)
162    print("Example 8: Conversation Statistics")
163    print("=" * 50)
164
165    from lexilux import get_statistics
166
167    stats = get_statistics(history)
168
169    print(f"Total messages: {stats['message_count']}")
170    print(f"User messages: {stats['user_message_count']}")
171    print(f"Assistant messages: {stats['assistant_message_count']}")
172    print(f"Total tokens: {stats['total_tokens']}")
173    print(f"Average tokens per message: {stats['avg_tokens_per_message']:.1f}")
174
175
176if __name__ == "__main__":
177    main()