File size: 7,835 Bytes
330b6e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env python3
"""

Example usage of the Groq LangChain integration service.



This script demonstrates how to use the GroqClient for chat-based

programming assistance with language context switching and chat history.

"""

import os
import sys
from datetime import datetime

# Add parent directory to path for imports
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from chat_agent.services.groq_client import (
    GroqClient,
    ChatMessage,
    LanguageContext,
    create_language_context,
    GroqAuthenticationError
)


def example_basic_usage():
    """Example of basic GroqClient usage"""
    print("=== Basic GroqClient Usage Example ===\n")
    
    try:
        # Initialize client (requires GROQ_API_KEY environment variable)
        client = GroqClient()
        print("✓ GroqClient initialized successfully")
        
        # Get model information
        info = client.get_model_info()
        print(f"Model: {info['model']}")
        print(f"Max tokens: {info['max_tokens']}")
        print(f"Temperature: {info['temperature']}")
        print()
        
    except GroqAuthenticationError:
        print("❌ API key not configured. Set GROQ_API_KEY environment variable.")
        return None
    
    return client


def example_language_contexts():
    """Example of creating and using language contexts"""
    print("=== Language Context Examples ===\n")
    
    # Create contexts for different programming languages
    languages = ["python", "javascript", "java", "cpp"]
    
    for lang in languages:
        context = create_language_context(lang)
        print(f"{lang.upper()} Context:")
        print(f"  Language: {context.language}")
        print(f"  Syntax highlighting: {context.syntax_highlighting}")
        print(f"  Template preview: {context.prompt_template[:100]}...")
        print()


def example_chat_history():
    """Example of building chat history"""
    print("=== Chat History Example ===\n")
    
    # Create sample chat history
    chat_history = [
        ChatMessage(
            role="user",
            content="What is Python?",
            language="python",
            timestamp=datetime.now().isoformat()
        ),
        ChatMessage(
            role="assistant",
            content="Python is a high-level, interpreted programming language known for its simplicity and readability.",
            language="python",
            timestamp=datetime.now().isoformat()
        ),
        ChatMessage(
            role="user",
            content="How do I create a list in Python?",
            language="python",
            timestamp=datetime.now().isoformat()
        ),
        ChatMessage(
            role="assistant",
            content="You can create a list in Python using square brackets: my_list = [1, 2, 3, 'hello']",
            language="python",
            timestamp=datetime.now().isoformat()
        )
    ]
    
    print(f"Created chat history with {len(chat_history)} messages:")
    for i, msg in enumerate(chat_history, 1):
        print(f"  {i}. {msg.role}: {msg.content[:50]}...")
    print()
    
    return chat_history


def example_message_building(client, chat_history):
    """Example of building messages for API calls"""
    print("=== Message Building Example ===\n")
    
    if not client:
        print("Skipping message building (no client available)")
        return
    
    # Create language context
    python_context = create_language_context("python")
    
    # Build messages for a new prompt
    messages = client._build_messages(
        prompt="Can you explain list comprehensions?",
        chat_history=chat_history,
        language_context=python_context
    )
    
    print(f"Built {len(messages)} messages for API call:")
    for i, msg in enumerate(messages, 1):
        print(f"  {i}. {msg.role}: {msg.content[:80]}...")
    print()


def example_error_handling(client):
    """Example of error handling"""
    print("=== Error Handling Examples ===\n")
    
    if not client:
        print("Skipping error handling (no client available)")
        return
    
    # Test different error scenarios
    error_scenarios = [
        ("Rate limit error", Exception("Rate limit exceeded (429)")),
        ("Authentication error", Exception("Authentication failed (401)")),
        ("Network error", Exception("Network connection timeout")),
        ("Quota error", Exception("Quota exceeded for billing account")),
        ("Unknown error", Exception("Something unexpected happened"))
    ]
    
    for scenario_name, error in error_scenarios:
        try:
            result = client._handle_api_error(error)
            print(f"{scenario_name}: {result}")
        except Exception as e:
            print(f"{scenario_name}: Raised {type(e).__name__}: {e}")
    print()


def example_streaming_simulation():
    """Example of how streaming would work (simulated)"""
    print("=== Streaming Response Simulation ===\n")
    
    # Simulate streaming response chunks
    simulated_chunks = [
        "List comprehensions ",
        "are a concise way ",
        "to create lists in Python. ",
        "The syntax is: ",
        "[expression for item in iterable if condition]. ",
        "For example: ",
        "squares = [x**2 for x in range(10)]"
    ]
    
    print("Simulated streaming response:")
    full_response = ""
    for chunk in simulated_chunks:
        full_response += chunk
        print(f"Chunk: '{chunk}'")
    
    print(f"\nComplete response: {full_response}")
    print()


def example_language_switching():
    """Example of language context switching"""
    print("=== Language Switching Example ===\n")
    
    # Start with Python
    current_language = "python"
    python_context = create_language_context(current_language)
    print(f"Started with {current_language.upper()}")
    
    # Simulate conversation in Python
    python_history = [
        ChatMessage(role="user", content="How do I create a function in Python?"),
        ChatMessage(role="assistant", content="def my_function(): pass")
    ]
    
    # Switch to JavaScript
    current_language = "javascript"
    js_context = create_language_context(current_language)
    print(f"Switched to {current_language.upper()}")
    
    # Continue conversation in JavaScript context
    # (In real implementation, you'd maintain the history but change the context)
    js_history = python_history + [
        ChatMessage(role="user", content="Now show me the same in JavaScript"),
        ChatMessage(role="assistant", content="function myFunction() { }")
    ]
    
    print(f"Conversation now has {len(js_history)} messages with JavaScript context")
    print()


def main():
    """Main example function"""
    print("🚀 Groq LangChain Integration Service Examples\n")
    
    # Basic usage
    client = example_basic_usage()
    
    # Language contexts
    example_language_contexts()
    
    # Chat history
    chat_history = example_chat_history()
    
    # Message building
    example_message_building(client, chat_history)
    
    # Error handling
    example_error_handling(client)
    
    # Streaming simulation
    example_streaming_simulation()
    
    # Language switching
    example_language_switching()
    
    print("✅ All examples completed!")
    print("\nTo use with real API calls:")
    print("1. Set GROQ_API_KEY environment variable")
    print("2. Call client.generate_response() or client.stream_response()")
    print("3. Handle responses and errors appropriately")


if __name__ == "__main__":
    main()