-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
237 lines (188 loc) · 8.21 KB
/
main.py
File metadata and controls
237 lines (188 loc) · 8.21 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
import os
import click
import openai
import anthropic
from google import genai
from google.genai import types
from dotenv import load_dotenv
from router import choose_model
# Load environment variables from .env file
load_dotenv()
# Check if API keys are loaded
openai_key = os.getenv("OPENAI_API_KEY")
anthropic_key = os.getenv("ANTHROPIC_API_KEY")
google_key = os.getenv("GOOGLE_API_KEY")
# --- API Client Initializations ---
openai_client = openai.OpenAI(api_key=openai_key)
anthropic_client = anthropic.Anthropic(api_key=anthropic_key)
genai_client = genai.Client(api_key=google_key)
# --- Model Execution Functions ---
def execute_openai(prompt: str, conversation_history: list, model_name: str, reasoning_effort: str = None):
reasoning_msg = f"with reasoning_effort: {reasoning_effort}" if reasoning_effort is not None else "at default reasoning"
print(f"\n--- Executing with OpenAI ({model_name}) {reasoning_msg} ---\n")
try:
# Build messages with conversation history
messages = []
for msg in conversation_history:
messages.append({"role": msg["role"], "content": msg["content"]})
messages.append({"role": "user", "content": prompt})
api_params = {
"model": model_name,
"messages": messages,
"stream": True,
}
# Add reasoning parameters for o-series models (o4-mini only)
if reasoning_effort is not None:
api_params["reasoning_effort"] = reasoning_effort
response = openai_client.chat.completions.create(**api_params)
full_response = ""
for chunk in response:
content = chunk.choices[0].delta.content
if content:
print(content, end='', flush=True)
full_response += content
print()
return full_response
except Exception as e:
error_msg = f"❌ OpenAI Error: {str(e)}"
print(error_msg)
return error_msg
def execute_claude(prompt: str, conversation_history: list, model_name: str, temperature: float = None):
temp_msg = f"at temperature {temperature}" if temperature is not None else "at default temperature"
print(f"\n--- Executing with Anthropic ({model_name}) {temp_msg} ---\n")
try:
# Build messages with conversation history
messages = []
for msg in conversation_history:
messages.append({"role": msg["role"], "content": msg["content"]})
messages.append({"role": "user", "content": prompt})
api_params = {
"model": model_name,
"max_tokens": 2048,
"messages": messages,
}
if temperature is not None:
api_params["temperature"] = temperature
full_response = ""
with anthropic_client.messages.stream(**api_params) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
full_response += text
print()
return full_response
except Exception as e:
error_msg = f"❌ Anthropic Error: {str(e)}"
print(error_msg)
return error_msg
def execute_gemini(prompt: str, conversation_history: list, model_name: str, temperature: float = None, thinking_budget: int = None):
temp_msg = f"at temperature {temperature}" if temperature is not None else "at default temperature"
thinking_msg = f"with thinking_budget: {thinking_budget}" if thinking_budget is not None else ""
print(f"\n--- Executing with Google ({model_name}) {temp_msg} {thinking_msg}---\n")
try:
# Build conversation history for Gemini
contents = []
for msg in conversation_history:
contents.append(f"{msg['role']}: {msg['content']}")
contents.append(f"user: {prompt}")
# Combine all conversation into a single prompt
full_conversation = "\n".join(contents)
# Set up generation config
config_params = {}
if temperature is not None:
config_params["temperature"] = temperature
# Set up thinking config if thinking_budget is specified
thinking_config = None
if thinking_budget is not None:
thinking_config = types.ThinkingConfig(thinking_budget=thinking_budget)
# Create generation config
config = types.GenerateContentConfig(
**config_params,
thinking_config=thinking_config
) if config_params or thinking_config else None
# Generate content using the new API
response = genai_client.models.generate_content(
model=model_name,
contents=full_conversation,
config=config
)
print(response.text, end="", flush=True)
print()
return response.text
except Exception as e:
error_msg = f"❌ Google Error: {str(e)}"
print(error_msg)
return error_msg
# --- Main CLI Command ---
@click.command()
def main():
"""AI router that selects the best model for your task."""
print("AI Model Router")
print("'quit' to end the conversation.")
print("'clear' to clear conversation history.\n")
# Initialize conversation history
conversation_history = []
while True:
# Get user input interactively
prompt = input("User: ")
# Check for exit commands
if prompt.lower() in ['quit']:
print("Ending conversation...")
break
# Check for clear command
if prompt.lower() == 'clear':
conversation_history = []
print("History cleared")
continue
# Skip empty inputs
if not prompt.strip():
continue
# 1. Let the router AI choose the best model provider and get its instruction
router_result = choose_model(prompt)
model_info = router_result["model_info"]
instruction = router_result["instruction"]
# Combine the instruction with the user's prompt
full_prompt = f"{instruction}\n\nUser: {prompt}"
# 2. A simple 'factory' to call the correct execution function with the full prompt
ai_response = ""
# Execute based on provider
if model_info["provider"] == "openai":
# OpenAI o4-mini only supports reasoning_effort, not temperature
params = {
"prompt": full_prompt,
"conversation_history": conversation_history,
"model_name": model_info["model"],
}
if "reasoning_effort" in model_info:
params["reasoning_effort"] = model_info["reasoning_effort"]
ai_response = execute_openai(**params)
elif model_info["provider"] == "claude":
# Claude supports temperature
params = {
"prompt": full_prompt,
"conversation_history": conversation_history,
"model_name": model_info["model"],
}
if "temperature" in model_info:
params["temperature"] = model_info["temperature"]
ai_response = execute_claude(**params)
elif model_info["provider"] == "gemini":
# Gemini supports both temperature and thinking_budget
params = {
"prompt": full_prompt,
"conversation_history": conversation_history,
"model_name": model_info["model"],
}
if "temperature" in model_info:
params["temperature"] = model_info["temperature"]
if "thinking_budget" in model_info:
params["thinking_budget"] = model_info["thinking_budget"]
ai_response = execute_gemini(**params)
else:
print(f"Error: Unknown model provider '{model_info['provider']}'.")
# Add the current exchange to conversation history
conversation_history.append({"role": "user", "content": prompt})
if ai_response:
conversation_history.append({"role": "assistant", "content": ai_response})
print() # Add a blank line for better readability
if __name__ == "__main__":
main()