scratch_chat / examples /groq_client_example.py
WebashalarForML's picture
Upload 178 files
330b6e4 verified
#!/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()