broadfield-dev commited on
Commit
900f476
·
verified ·
1 Parent(s): c8d60ec

Create model_logic.py

Browse files
Files changed (1) hide show
  1. model_logic.py +437 -0
model_logic.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # model_handler.py
2
+ import os
3
+ import requests
4
+ import json
5
+ import logging
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables from .env file
9
+ load_dotenv()
10
+
11
+ logging.basicConfig(
12
+ level=logging.INFO,
13
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
14
+ )
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Maps provider name (uppercase) to environment variable name for API key
18
+ API_KEYS_ENV_VARS = {
19
+ "HUGGINGFACE": 'HF_TOKEN', # Note: HF_TOKEN is often used for general HF auth
20
+ "GROQ": 'GROQ_API_KEY',
21
+ "OPENROUTER": 'OPENROUTER_API_KEY',
22
+ "TOGETHERAI": 'TOGETHERAI_API_KEY',
23
+ "COHERE": 'COHERE_API_KEY',
24
+ "XAI": 'XAI_API_KEY',
25
+ "OPENAI": 'OPENAI_API_KEY',
26
+ "GOOGLE": 'GOOGLE_API_KEY', # Or GOOGLE_GEMINI_API_KEY etc.
27
+ }
28
+
29
+ API_URLS = {
30
+ "HUGGINGFACE": 'https://api-inference.huggingface.co/models/',
31
+ "GROQ": 'https://api.groq.com/openai/v1/chat/completions',
32
+ "OPENROUTER": 'https://openrouter.ai/api/v1/chat/completions',
33
+ "TOGETHERAI": 'https://api.together.ai/v1/chat/completions',
34
+ "COHERE": 'https://api.cohere.ai/v1/chat', # v1 is common for chat, was v2 in ai-learn
35
+ "XAI": 'https://api.x.ai/v1/chat/completions',
36
+ "OPENAI": 'https://api.openai.com/v1/chat/completions',
37
+ "GOOGLE": 'https://generativelanguage.googleapis.com/v1beta/models/',
38
+ }
39
+
40
+ #MODELS_BY_PROVIDER = json.load(open("./models.json"))
41
+ MODELS_BY_PROVIDER = {
42
+ "groq": {
43
+ "default": "llama3-8b-8192",
44
+ "models": {
45
+ "Llama 3 8B (Groq)": "llama3-8b-8192",
46
+ }
47
+ }
48
+ }
49
+
50
+ def _get_api_key(provider: str, ui_api_key_override: str = None) -> str | None:
51
+ """
52
+ Retrieves API key for a given provider.
53
+ Priority: UI Override > Environment Variable from API_KEYS_ENV_VARS > Specific (e.g. HF_TOKEN for HuggingFace).
54
+ """
55
+ provider_upper = provider.upper()
56
+ if ui_api_key_override and ui_api_key_override.strip():
57
+ logger.debug(f"Using UI-provided API key for {provider_upper}.")
58
+ return ui_api_key_override.strip()
59
+
60
+ env_var_name = API_KEYS_ENV_VARS.get(provider_upper)
61
+ if env_var_name:
62
+ env_key = os.getenv(env_var_name)
63
+ if env_key and env_key.strip():
64
+ logger.debug(f"Using API key from env var '{env_var_name}' for {provider_upper}.")
65
+ return env_key.strip()
66
+
67
+ # Specific fallback for HuggingFace if HF_TOKEN is set and API_KEYS_ENV_VARS['HUGGINGFACE'] wasn't specific enough
68
+ if provider_upper == 'HUGGINGFACE':
69
+ hf_token_fallback = os.getenv("HF_TOKEN")
70
+ if hf_token_fallback and hf_token_fallback.strip():
71
+ logger.debug("Using HF_TOKEN as fallback for HuggingFace provider.")
72
+ return hf_token_fallback.strip()
73
+
74
+ logger.warning(f"API Key not found for provider '{provider_upper}'. Checked UI override and environment variable '{env_var_name or 'N/A'}'.")
75
+ return None
76
+
77
+ def get_available_providers() -> list[str]:
78
+ """Returns a sorted list of available provider names (e.g., 'groq', 'openai')."""
79
+ return sorted(list(MODELS_BY_PROVIDER.keys()))
80
+
81
+ def get_model_display_names_for_provider(provider: str) -> list[str]:
82
+ """Returns a sorted list of model display names for a given provider."""
83
+ return sorted(list(MODELS_BY_PROVIDER.get(provider.lower(), {}).get("models", {}).keys()))
84
+
85
+ def get_default_model_display_name_for_provider(provider: str) -> str | None:
86
+ """Gets the default model's display name for a provider."""
87
+ provider_data = MODELS_BY_PROVIDER.get(provider.lower(), {})
88
+ models_dict = provider_data.get("models", {})
89
+ default_model_id = provider_data.get("default")
90
+
91
+ if default_model_id and models_dict:
92
+ for display_name, model_id_val in models_dict.items():
93
+ if model_id_val == default_model_id:
94
+ return display_name
95
+
96
+ # Fallback to the first model in the sorted list if default not found or not set
97
+ if models_dict:
98
+ sorted_display_names = sorted(list(models_dict.keys()))
99
+ if sorted_display_names:
100
+ return sorted_display_names[0]
101
+ return None
102
+
103
+ def get_model_id_from_display_name(provider: str, display_name: str) -> str | None:
104
+ """Gets the actual model ID from its display name for a given provider."""
105
+ models = MODELS_BY_PROVIDER.get(provider.lower(), {}).get("models", {})
106
+ return models.get(display_name)
107
+
108
+
109
+ def call_model_stream(provider: str, model_display_name: str, messages: list[dict], api_key_override: str = None, temperature: float = 0.7, max_tokens: int = None) -> iter:
110
+ """
111
+ Calls the specified model via its provider and streams the response.
112
+ Handles provider-specific request formatting and error handling.
113
+ Yields chunks of the response text or an error string.
114
+ """
115
+ provider_lower = provider.lower()
116
+ api_key = _get_api_key(provider_lower, api_key_override)
117
+ base_url = API_URLS.get(provider.upper())
118
+ model_id = get_model_id_from_display_name(provider_lower, model_display_name)
119
+
120
+ if not api_key:
121
+ env_var_name = API_KEYS_ENV_VARS.get(provider.upper(), 'N/A')
122
+ yield f"Error: API Key not found for {provider}. Please set it in the UI or env var '{env_var_name}'."
123
+ return
124
+ if not base_url:
125
+ yield f"Error: Unknown provider '{provider}' or missing API URL configuration."
126
+ return
127
+ if not model_id:
128
+ yield f"Error: Model ID not found for '{model_display_name}' under provider '{provider}'. Check configuration."
129
+ return
130
+
131
+ headers = {}
132
+ payload = {}
133
+ request_url = base_url
134
+
135
+ logger.info(f"Streaming from {provider}/{model_display_name} (ID: {model_id})...")
136
+
137
+ # --- Standard OpenAI-compatible providers ---
138
+ if provider_lower in ["groq", "openrouter", "togetherai", "openai", "xai"]:
139
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
140
+ payload = {"model": model_id, "messages": messages, "stream": True, "temperature": temperature}
141
+ if max_tokens: payload["max_tokens"] = max_tokens
142
+
143
+ if provider_lower == "openrouter":
144
+ headers["HTTP-Referer"] = os.getenv("OPENROUTER_REFERRER") or "http://localhost/gradio" # Example Referer
145
+ headers["X-Title"] = os.getenv("OPENROUTER_X_TITLE") or "Gradio AI Researcher" # Example Title
146
+
147
+ try:
148
+ response = requests.post(request_url, headers=headers, json=payload, stream=True, timeout=180)
149
+ response.raise_for_status()
150
+
151
+ # More robust SSE parsing
152
+ buffer = ""
153
+ for chunk in response.iter_content(chunk_size=None): # Process raw bytes
154
+ buffer += chunk.decode('utf-8', errors='replace')
155
+ while '\n\n' in buffer:
156
+ event_str, buffer = buffer.split('\n\n', 1)
157
+ if not event_str.strip(): continue
158
+
159
+ content_chunk = ""
160
+ for line in event_str.splitlines():
161
+ if line.startswith('data: '):
162
+ data_json = line[len('data: '):].strip()
163
+ if data_json == '[DONE]':
164
+ return # Stream finished
165
+ try:
166
+ data = json.loads(data_json)
167
+ if data.get("choices") and len(data["choices"]) > 0:
168
+ delta = data["choices"][0].get("delta", {})
169
+ if delta and delta.get("content"):
170
+ content_chunk += delta["content"]
171
+ except json.JSONDecodeError:
172
+ logger.warning(f"Failed to decode JSON from stream line: {data_json}")
173
+ if content_chunk:
174
+ yield content_chunk
175
+ # Process any remaining buffer content (less common with '\n\n' delimiter)
176
+ if buffer.strip():
177
+ logger.debug(f"Remaining buffer after OpenAI-like stream: {buffer}")
178
+
179
+
180
+ except requests.exceptions.HTTPError as e:
181
+ err_msg = f"API HTTP Error ({e.response.status_code}): {e.response.text[:500]}"
182
+ logger.error(f"{err_msg} for {provider}/{model_id}", exc_info=False)
183
+ yield f"Error: {err_msg}"
184
+ except requests.exceptions.RequestException as e:
185
+ logger.error(f"API Request Error for {provider}/{model_id}: {e}", exc_info=False)
186
+ yield f"Error: Could not connect to {provider} ({e})"
187
+ except Exception as e:
188
+ logger.exception(f"Unexpected error during {provider} stream:")
189
+ yield f"Error: An unexpected error occurred: {e}"
190
+ return
191
+
192
+ # --- Google Gemini ---
193
+ elif provider_lower == "google":
194
+ system_instruction = None
195
+ filtered_messages = []
196
+ for msg in messages:
197
+ if msg["role"] == "system": system_instruction = {"parts": [{"text": msg["content"]}]}
198
+ else:
199
+ role = "model" if msg["role"] == "assistant" else msg["role"]
200
+ filtered_messages.append({"role": role, "parts": [{"text": msg["content"]}]})
201
+
202
+ payload = {
203
+ "contents": filtered_messages,
204
+ "safetySettings": [ # Example: more permissive settings
205
+ {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
206
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
207
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
208
+ {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
209
+ ],
210
+ "generationConfig": {"temperature": temperature}
211
+ }
212
+ if max_tokens: payload["generationConfig"]["maxOutputTokens"] = max_tokens
213
+ if system_instruction: payload["system_instruction"] = system_instruction
214
+
215
+ request_url = f"{base_url}{model_id}:streamGenerateContent?key={api_key}" # API key in query param
216
+ headers = {"Content-Type": "application/json"}
217
+
218
+ try:
219
+ response = requests.post(request_url, headers=headers, json=payload, stream=True, timeout=180)
220
+ response.raise_for_status()
221
+
222
+ # Google's stream is a bit different, often newline-delimited JSON arrays/objects
223
+ buffer = ""
224
+ for chunk in response.iter_content(chunk_size=None):
225
+ buffer += chunk.decode('utf-8', errors='replace')
226
+ # Google might send chunks that are not complete JSON objects, or multiple objects
227
+ # A common pattern is [ {obj1} , {obj2} ] where chunks split mid-array or mid-object.
228
+ # This parsing needs to be robust. A simple split by '\n' might not always work if JSON is pretty-printed.
229
+ # The previous code's `json.loads(f"[{decoded_line}]")` was an attempt to handle this.
230
+ # For now, let's assume newline delimited for simplicity, but this is a known tricky part.
231
+
232
+ while '\n' in buffer:
233
+ line, buffer = buffer.split('\n', 1)
234
+ line = line.strip()
235
+ if not line: continue
236
+ if line.startswith(','): line = line[1:] # Handle leading commas if splitting an array
237
+
238
+ try:
239
+ # Remove "data: " prefix if present (less common for Gemini direct API but good practice)
240
+ if line.startswith('data: '): line = line[len('data: '):]
241
+
242
+ # Gemini often streams an array of objects, or just one object.
243
+ # Try to parse as a single object first. If fails, try as array.
244
+ parsed_data = None
245
+ try:
246
+ parsed_data = json.loads(line)
247
+ except json.JSONDecodeError:
248
+ # If it's part of an array, it might be missing brackets.
249
+ # This heuristic is fragile. A proper SSE parser or stateful JSON parser is better.
250
+ if line.startswith('{') and line.endswith('}'): # Looks like a complete object
251
+ pass # already tried json.loads
252
+ # Try to wrap with [] if it seems like a list content without brackets
253
+ elif line.startswith('{') or line.endswith('}'):
254
+ try:
255
+ temp_parsed_list = json.loads(f"[{line}]")
256
+ if temp_parsed_list and isinstance(temp_parsed_list, list):
257
+ parsed_data = temp_parsed_list[0] # take first if it becomes a list
258
+ except json.JSONDecodeError:
259
+ logger.warning(f"Google: Still can't parse line even with array wrap: {line}")
260
+
261
+ if parsed_data:
262
+ data_to_process = [parsed_data] if isinstance(parsed_data, dict) else parsed_data # Ensure list
263
+ for event_data in data_to_process:
264
+ if not isinstance(event_data, dict): continue
265
+ if event_data.get("candidates"):
266
+ for candidate in event_data["candidates"]:
267
+ if candidate.get("content", {}).get("parts"):
268
+ for part in candidate["content"]["parts"]:
269
+ if part.get("text"):
270
+ yield part["text"]
271
+ except json.JSONDecodeError:
272
+ logger.warning(f"Google: JSONDecodeError for line: {line}")
273
+ except Exception as e_google_proc:
274
+ logger.error(f"Google: Error processing stream data: {e_google_proc}, Line: {line}")
275
+
276
+ except requests.exceptions.HTTPError as e:
277
+ err_msg = f"Google API HTTP Error ({e.response.status_code}): {e.response.text[:500]}"
278
+ logger.error(err_msg, exc_info=False)
279
+ yield f"Error: {err_msg}"
280
+ except Exception as e:
281
+ logger.exception(f"Unexpected error during Google stream:")
282
+ yield f"Error: An unexpected error occurred with Google API: {e}"
283
+ return
284
+
285
+ # --- Cohere ---
286
+ elif provider_lower == "cohere":
287
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json", "Accept": "application/json"}
288
+
289
+ # Cohere message format
290
+ chat_history_cohere = []
291
+ preamble_cohere = None
292
+ user_message_cohere = ""
293
+
294
+ temp_messages = list(messages) # Work with a copy
295
+ if temp_messages and temp_messages[0]["role"] == "system":
296
+ preamble_cohere = temp_messages.pop(0)["content"]
297
+
298
+ if temp_messages:
299
+ user_message_cohere = temp_messages.pop()["content"] # Last message is the current user query
300
+ for msg in temp_messages: # Remaining are history
301
+ role = "USER" if msg["role"] == "user" else "CHATBOT"
302
+ chat_history_cohere.append({"role": role, "message": msg["content"]})
303
+
304
+ if not user_message_cohere:
305
+ yield "Error: User message is empty for Cohere."
306
+ return
307
+
308
+ payload = {
309
+ "model": model_id,
310
+ "message": user_message_cohere,
311
+ "stream": True,
312
+ "temperature": temperature
313
+ }
314
+ if max_tokens: payload["max_tokens"] = max_tokens # Cohere uses max_tokens
315
+ if chat_history_cohere: payload["chat_history"] = chat_history_cohere
316
+ if preamble_cohere: payload["preamble"] = preamble_cohere
317
+
318
+ try:
319
+ response = requests.post(base_url, headers=headers, json=payload, stream=True, timeout=180)
320
+ response.raise_for_status()
321
+
322
+ # Cohere SSE format is event: type\ndata: {json}\n\n
323
+ buffer = ""
324
+ for chunk_bytes in response.iter_content(chunk_size=None):
325
+ buffer += chunk_bytes.decode('utf-8', errors='replace')
326
+ while '\n\n' in buffer:
327
+ event_str, buffer = buffer.split('\n\n', 1)
328
+ if not event_str.strip(): continue
329
+
330
+ event_type = None
331
+ data_json_str = None
332
+ for line in event_str.splitlines():
333
+ if line.startswith("event:"): event_type = line[len("event:"):].strip()
334
+ elif line.startswith("data:"): data_json_str = line[len("data:"):].strip()
335
+
336
+ if data_json_str:
337
+ try:
338
+ data = json.loads(data_json_str)
339
+ if event_type == "text-generation" and "text" in data:
340
+ yield data["text"]
341
+ elif event_type == "stream-end":
342
+ logger.debug(f"Cohere stream ended. Finish reason: {data.get('finish_reason')}")
343
+ return
344
+ except json.JSONDecodeError:
345
+ logger.warning(f"Cohere: Failed to decode JSON: {data_json_str}")
346
+ if buffer.strip():
347
+ logger.debug(f"Cohere: Remaining buffer: {buffer.strip()}")
348
+
349
+
350
+ except requests.exceptions.HTTPError as e:
351
+ err_msg = f"Cohere API HTTP Error ({e.response.status_code}): {e.response.text[:500]}"
352
+ logger.error(err_msg, exc_info=False)
353
+ yield f"Error: {err_msg}"
354
+ except Exception as e:
355
+ logger.exception(f"Unexpected error during Cohere stream:")
356
+ yield f"Error: An unexpected error occurred with Cohere API: {e}"
357
+ return
358
+
359
+ # --- HuggingFace Inference API (Basic TGI support) ---
360
+ # This is very basic and might not work for all models or complex scenarios.
361
+ # Assumes model is deployed with Text Generation Inference (TGI) and supports streaming.
362
+ elif provider_lower == "huggingface":
363
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
364
+ # Construct prompt string for TGI (often needs specific formatting)
365
+ # This is a generic attempt, specific models might need <|user|>, <|assistant|> etc.
366
+ prompt_parts = []
367
+ for msg in messages:
368
+ role_prefix = ""
369
+ if msg['role'] == 'system': role_prefix = "System: " # Or might be ignored/handled differently
370
+ elif msg['role'] == 'user': role_prefix = "User: "
371
+ elif msg['role'] == 'assistant': role_prefix = "Assistant: "
372
+ prompt_parts.append(f"{role_prefix}{msg['content']}")
373
+
374
+ # TGI typically expects a final "Assistant: " to start generating from
375
+ tgi_prompt = "\n".join(prompt_parts) + "\nAssistant: "
376
+
377
+ payload = {
378
+ "inputs": tgi_prompt,
379
+ "parameters": {
380
+ "temperature": temperature if temperature > 0 else 0.01, # TGI needs temp > 0 for sampling
381
+ "max_new_tokens": max_tokens or 1024, # Default TGI max_new_tokens
382
+ "return_full_text": False, # We only want generated part
383
+ "do_sample": True if temperature > 0 else False,
384
+ },
385
+ "stream": True
386
+ }
387
+ request_url = f"{base_url}{model_id}" # Model ID is part of URL path for HF
388
+
389
+ try:
390
+ response = requests.post(request_url, headers=headers, json=payload, stream=True, timeout=180)
391
+ response.raise_for_status()
392
+
393
+ # TGI SSE stream: data: {"token": {"id": ..., "text": "...", "logprob": ..., "special": ...}}
394
+ # Or sometimes just data: "text_chunk" for simpler models/configs
395
+ buffer = ""
396
+ for chunk_bytes in response.iter_content(chunk_size=None):
397
+ buffer += chunk_bytes.decode('utf-8', errors='replace')
398
+ while '\n' in buffer: # TGI often uses single newline
399
+ line, buffer = buffer.split('\n', 1)
400
+ line = line.strip()
401
+ if not line: continue
402
+
403
+ if line.startswith('data:'):
404
+ data_json_str = line[len('data:'):].strip()
405
+ try:
406
+ data = json.loads(data_json_str)
407
+ if "token" in data and "text" in data["token"]:
408
+ yield data["token"]["text"]
409
+ elif "generated_text" in data and data.get("details") is None: # Sometimes a final non-streaming like object might appear
410
+ # This case is tricky, if it's the *only* thing then it's not really streaming
411
+ pass # For now, ignore if it's not a token object
412
+ # Some TGI might send raw text if not fully SSE compliant for stream
413
+ # elif isinstance(data, str): yield data
414
+
415
+ except json.JSONDecodeError:
416
+ # If it's not JSON, it might be a raw string (less common for TGI stream=True)
417
+ # For safety, only yield if it's a clear text string
418
+ if not data_json_str.startswith('{') and not data_json_str.startswith('['):
419
+ yield data_json_str
420
+ else:
421
+ logger.warning(f"HF: Failed to decode JSON and not raw string: {data_json_str}")
422
+ if buffer.strip():
423
+ logger.debug(f"HF: Remaining buffer: {buffer.strip()}")
424
+
425
+
426
+ except requests.exceptions.HTTPError as e:
427
+ err_msg = f"HF API HTTP Error ({e.response.status_code}): {e.response.text[:500]}"
428
+ logger.error(err_msg, exc_info=False)
429
+ yield f"Error: {err_msg}"
430
+ except Exception as e:
431
+ logger.exception(f"Unexpected error during HF stream:")
432
+ yield f"Error: An unexpected error occurred with HF API: {e}"
433
+ return
434
+
435
+ else:
436
+ yield f"Error: Provider '{provider}' is not configured for streaming in this handler."
437
+ return