-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_groq.py
More file actions
237 lines (183 loc) · 7.5 KB
/
demo_groq.py
File metadata and controls
237 lines (183 loc) · 7.5 KB
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
"""
Demo script for OneHourBook with Groq API integration.
Shows model switching capabilities.
"""
import asyncio
import sys
import os
from pathlib import Path
# Load environment variables
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass # Silently continue if dotenv not available
# Add src to path
sys.path.append(str(Path(__file__).parent / "src"))
def print_header():
"""Print demo header."""
print("=" * 80)
print("🤖 ONEHOURBOOK WITH GROQ API")
print(" ChronosReader & 14-Agent Swarm")
print(" Multiple Model Support")
print("=" * 80)
print()
def show_available_models():
"""Show available Groq models."""
print("🔧 AVAILABLE GROQ MODELS:")
print("-" * 40)
models = [
("llama-3.3-70b-versatile", "🦙 Llama 3.3 70B", "Best for complex reasoning & analysis"),
("llama-3.1-70b-versatile", "🦙 Llama 3.1 70B", "Great balance of speed & capability"),
("llama-3.1-8b-instant", "⚡ Llama 3.1 8B", "Fastest option for simple tasks"),
("mixtral-8x7b-32768", "🎭 Mixtral 8x7B", "Excellent for creative writing"),
("gemma2-9b-it", "💎 Gemma2 9B", "Efficient for basic processing"),
("gemma-7b-it", "💎 Gemma 7B", "Lightweight option")
]
for model_id, name, description in models:
print(f" {name:20} | {model_id:25} | {description}")
print()
def simulate_model_switching():
"""Simulate switching between models for different tasks."""
print("🔄 MODEL SWITCHING DEMONSTRATION:")
print("-" * 40)
tasks = [
("📚 Book Intake", "llama-3.3-70b-versatile", "Complex metadata resolution"),
("🧠 Context Analysis", "llama-3.1-70b-versatile", "Author background research"),
("⚡ Chapter Processing", "llama-3.1-8b-instant", "Fast parallel processing"),
("💎 Quote Extraction", "mixtral-8x7b-32768", "Creative quote selection"),
("🔍 Fact Checking", "llama-3.3-70b-versatile", "Rigorous validation"),
("📄 Export Generation", "gemma2-9b-it", "Template formatting")
]
print("Task | Model Used | Reasoning")
print("-" * 70)
for task, model, reasoning in tasks:
print(f"{task:20} | {model:23} | {reasoning}")
print()
def show_usage_examples():
"""Show usage examples with different models."""
print("📋 USAGE EXAMPLES:")
print("-" * 40)
examples = [
"# Default (Llama 3.3 70B for best quality)",
'python src/main.py --book-title "Thinking, Fast and Slow" --author "Daniel Kahneman"',
"",
"# Fast processing with Llama 8B",
'python src/main.py --book-title "Atomic Habits" --author "James Clear" \\',
' --model "llama-3.1-8b-instant"',
"",
"# Creative analysis with Mixtral",
'python src/main.py --book-title "The Great Gatsby" --author "F. Scott Fitzgerald" \\',
' --model "mixtral-8x7b-32768" --public-domain',
"",
"# User text with custom model",
'python src/main.py --book-title "Your Book" --author "Your Author" \\',
' --user-text book.txt --model "llama-3.1-70b-versatile"'
]
for example in examples:
print(example)
print()
def check_environment():
"""Check if Groq API key is configured."""
print("🔐 ENVIRONMENT CHECK:")
print("-" * 40)
groq_key = os.getenv("GROQ_API_KEY")
if groq_key:
# Mask the key for security
masked_key = groq_key[:8] + "..." + groq_key[-4:] if len(groq_key) > 12 else "***"
print(f"✅ GROQ_API_KEY found: {masked_key}")
print(" Ready for real book processing!")
else:
print("❌ GROQ_API_KEY not found")
print(" Set your API key:")
print(" export GROQ_API_KEY=your_key_here")
print(" Or add to .env file")
print()
async def test_groq_connection():
"""Test connection to Groq API."""
groq_key = os.getenv("GROQ_API_KEY")
if not groq_key:
print("⏭️ Skipping connection test (no API key)")
return
print("🔌 TESTING GROQ CONNECTION:")
print("-" * 40)
try:
from frameworks.groq_client import GroqClient
client = GroqClient(model="llama-3.1-8b-instant")
print("⏳ Testing connection with Llama 3.1 8B...")
response = await client.complete(
prompt="Hello! Please respond with exactly 5 words.",
max_tokens=20,
temperature=0.1
)
content = response["choices"][0]["message"]["content"]
print(f"✅ Connection successful!")
print(f" Response: {content}")
# Test model switching
print("\n⏳ Testing model switch to Llama 3.3 70B...")
client.set_model("llama-3.3-70b-versatile")
response2 = await client.complete(
prompt="What is the capital of France? One word only.",
max_tokens=10,
temperature=0.1
)
content2 = response2["choices"][0]["message"]["content"]
print(f"✅ Model switching successful!")
print(f" Response: {content2}")
await client.close()
except Exception as e:
print(f"❌ Connection failed: {e}")
print(" Check your API key and internet connection")
print()
def show_configuration():
"""Show current configuration."""
print("⚙️ SYSTEM CONFIGURATION:")
print("-" * 40)
try:
from utils.io import load_config
config = load_config("configs/settings.yaml")
llm_config = config.get("llm", {})
print(f"Provider: {llm_config.get('provider', 'groq')}")
print(f"Default Model: {llm_config.get('model', 'llama-3.3-70b-versatile')}")
print(f"Max Tokens: {llm_config.get('max_tokens', 4096)}")
print(f"Temperature: {llm_config.get('temperature', 0.1)}")
print(f"Rate Limit: {llm_config.get('rate_limit_requests_per_minute', 30)} req/min")
except Exception as e:
print(f"Could not load config: {e}")
print()
def main():
"""Run the demo."""
try:
print_header()
print("📖 DEMONSTRATION: The Art of War by Sun Tzu")
print("🔓 STATUS: Public Domain (Ancient text)")
print("⏱️ TARGET: 230 WPM → 13,800 words (58-60 minutes)")
print()
show_available_models()
simulate_model_switching()
show_configuration()
check_environment()
# Test connection if API key is available
print("🧪 RUNNING CONNECTION TEST...")
print("-" * 40)
asyncio.run(test_groq_connection())
show_usage_examples()
print("🎯 DEMO COMPLETE!")
print("-" * 40)
print("✅ Groq API integration configured")
print("✅ Multiple model support enabled")
print("✅ Model switching capabilities demonstrated")
print("✅ Ready for real book processing!")
print()
print("To process a real book:")
print('python src/main.py --book-title "Your Book" --author "Author Name"')
return 0
except KeyboardInterrupt:
print("\n⏹️ Demo interrupted by user")
return 130
except Exception as e:
print(f"\n❌ Demo failed: {e}")
return 1
if __name__ == "__main__":
exit_code = main()
sys.exit(exit_code)