Conversation ExampleΒΆ

Multi-turn conversation example:

 1#!/usr/bin/env python
 2"""
 311 Multi-turn Conversation - Chat That Remembers
 4
 5Learn how to have multi-turn conversations where the AI remembers context.
 6You can pass message history to maintain conversation state.
 7
 8Level: Core Feature
 9"""
10
11from config_loader import get_chat_config, parse_args
12
13from lexilux import Chat
14
15
16def main():
17    """Demonstrate multi-turn conversations."""
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: Manual conversation history
33    print("=" * 50)
34    print("Example 1: Manual Conversation History")
35    print("=" * 50)
36
37    # Start with a user message
38    messages = [{"role": "user", "content": "My favorite color is blue."}]
39    result = chat(messages)
40    print(f"AI: {result.text}")
41
42    # Add AI response to history and ask a follow-up
43    messages.append({"role": "assistant", "content": result.text})
44    messages.append({"role": "user", "content": "What's my favorite color?"})
45    result = chat(messages)
46    print(f"AI: {result.text}\n")
47
48    # Example 2: Building a simple chat loop
49    print("=" * 50)
50    print("Example 2: Simple Chat Loop")
51    print("=" * 50)
52    print("Type 'quit' to exit\n")
53
54    conversation_history = []
55    system_message = "You are a friendly and helpful assistant."
56
57    while True:
58        user_input = input("You: ")
59
60        if user_input.lower() in ("quit", "exit", "q"):
61            print("Goodbye!")
62            break
63
64        # Build messages with history
65        messages = [{"role": "system", "content": system_message}]
66        messages.extend(conversation_history)
67        messages.append({"role": "user", "content": user_input})
68
69        # Get response
70        result = chat(messages)
71        print(f"AI: {result.text}")
72
73        # Add to history
74        conversation_history.append({"role": "user", "content": user_input})
75        conversation_history.append({"role": "assistant", "content": result.text})
76
77        # Keep history manageable (last 10 messages)
78        if len(conversation_history) > 10:
79            conversation_history = conversation_history[-10:]
80
81
82if __name__ == "__main__":
83    main()