Spaces:
Running
Running
Update llm_engine.py
Browse files- llm_engine.py +488 -473
llm_engine.py
CHANGED
|
@@ -1,474 +1,489 @@
|
|
| 1 |
-
# llmEngine.py
|
| 2 |
-
# IMPROVED: Multi-provider LLM engine with CACHING to prevent reloading
|
| 3 |
-
# This version fixes the critical issue where LocalLLM was reloading on every call
|
| 4 |
-
# Features:
|
| 5 |
-
# - Provider caching (models stay in memory)
|
| 6 |
-
# - Unified OpenAI-style chat() API
|
| 7 |
-
# - Providers: OpenAI, Anthropic, HuggingFace, Nebius, SambaNova, Local (transformers)
|
| 8 |
-
# - Automatic fallback to local model on errors
|
| 9 |
-
# - JSON-based credit tracking
|
| 10 |
-
|
| 11 |
-
import
|
| 12 |
-
import
|
| 13 |
-
import
|
| 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 |
-
class
|
| 63 |
-
def
|
| 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 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
print(f"[LocalLLM]
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
self.
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
print(
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
main()
|
|
|
|
| 1 |
+
# llmEngine.py
|
| 2 |
+
# IMPROVED: Multi-provider LLM engine with CACHING to prevent reloading
|
| 3 |
+
# This version fixes the critical issue where LocalLLM was reloading on every call
|
| 4 |
+
# Features:
|
| 5 |
+
# - Provider caching (models stay in memory)
|
| 6 |
+
# - Unified OpenAI-style chat() API
|
| 7 |
+
# - Providers: OpenAI, Anthropic, HuggingFace, Nebius, SambaNova, Local (transformers)
|
| 8 |
+
# - Automatic fallback to local model on errors
|
| 9 |
+
# - JSON-based credit tracking
|
| 10 |
+
|
| 11 |
+
from dotenv import load_dotenv
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import traceback
|
| 15 |
+
from typing import List, Dict, Optional
|
| 16 |
+
|
| 17 |
+
load_dotenv()
|
| 18 |
+
hf_token = os.getenv('HUGGINGFACE_TOKEN')
|
| 19 |
+
if hf_token:
|
| 20 |
+
from huggingface_hub import login
|
| 21 |
+
try:
|
| 22 |
+
login(token=hf_token)
|
| 23 |
+
# logger.info("[HF] Logged in")
|
| 24 |
+
except Exception as e:
|
| 25 |
+
# logger.warning(f"[HF] Login failed: {e}")
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
###########################################################
|
| 29 |
+
# SIMPLE JSON CREDIT STORE
|
| 30 |
+
###########################################################
|
| 31 |
+
CREDITS_DB_PATH = "credits.json"
|
| 32 |
+
|
| 33 |
+
DEFAULT_CREDITS = {
|
| 34 |
+
"openai": 25,
|
| 35 |
+
"anthropic": 25000,
|
| 36 |
+
"huggingface": 25,
|
| 37 |
+
"nebius": 50,
|
| 38 |
+
"modal": 250,
|
| 39 |
+
"blaxel": 250,
|
| 40 |
+
"elevenlabs": 44,
|
| 41 |
+
"sambanova": 25,
|
| 42 |
+
"local": 9999999
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_credits():
|
| 47 |
+
if not os.path.exists(CREDITS_DB_PATH):
|
| 48 |
+
with open(CREDITS_DB_PATH, "w") as f:
|
| 49 |
+
json.dump(DEFAULT_CREDITS, f)
|
| 50 |
+
return DEFAULT_CREDITS.copy()
|
| 51 |
+
with open(CREDITS_DB_PATH, "r") as f:
|
| 52 |
+
return json.load(f)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def save_credits(data):
|
| 56 |
+
with open(CREDITS_DB_PATH, "w") as f:
|
| 57 |
+
json.dump(data, f, indent=2)
|
| 58 |
+
|
| 59 |
+
###########################################################
|
| 60 |
+
# BASE PROVIDER INTERFACE
|
| 61 |
+
###########################################################
|
| 62 |
+
class BaseProvider:
|
| 63 |
+
def chat(self, model: str, messages: List[Dict], **kwargs) -> str:
|
| 64 |
+
raise NotImplementedError
|
| 65 |
+
|
| 66 |
+
###########################################################
|
| 67 |
+
# PROVIDER: OPENAI
|
| 68 |
+
###########################################################
|
| 69 |
+
try:
|
| 70 |
+
from openai import OpenAI
|
| 71 |
+
except Exception:
|
| 72 |
+
OpenAI = None
|
| 73 |
+
|
| 74 |
+
class OpenAIProvider(BaseProvider):
|
| 75 |
+
def __init__(self):
|
| 76 |
+
if OpenAI is None:
|
| 77 |
+
raise RuntimeError("openai library not installed or not importable")
|
| 78 |
+
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY", ""))
|
| 79 |
+
|
| 80 |
+
def chat(self, model, messages, **kwargs):
|
| 81 |
+
try:
|
| 82 |
+
from openai.types.chat import (
|
| 83 |
+
ChatCompletionUserMessageParam,
|
| 84 |
+
ChatCompletionAssistantMessageParam,
|
| 85 |
+
ChatCompletionSystemMessageParam,
|
| 86 |
+
)
|
| 87 |
+
except Exception:
|
| 88 |
+
ChatCompletionUserMessageParam = dict
|
| 89 |
+
ChatCompletionAssistantMessageParam = dict
|
| 90 |
+
ChatCompletionSystemMessageParam = dict
|
| 91 |
+
|
| 92 |
+
if not isinstance(messages, list) or not all(isinstance(m, dict) for m in messages):
|
| 93 |
+
raise TypeError("messages must be a list of dicts with 'role' and 'content'")
|
| 94 |
+
|
| 95 |
+
safe_messages = []
|
| 96 |
+
for m in messages:
|
| 97 |
+
role = str(m.get("role", "user"))
|
| 98 |
+
content = str(m.get("content", ""))
|
| 99 |
+
if role == "user":
|
| 100 |
+
safe_messages.append(ChatCompletionUserMessageParam(role="user", content=content))
|
| 101 |
+
elif role == "assistant":
|
| 102 |
+
safe_messages.append(ChatCompletionAssistantMessageParam(role="assistant", content=content))
|
| 103 |
+
elif role == "system":
|
| 104 |
+
safe_messages.append(ChatCompletionSystemMessageParam(role="system", content=content))
|
| 105 |
+
else:
|
| 106 |
+
safe_messages.append({"role": role, "content": content})
|
| 107 |
+
|
| 108 |
+
response = self.client.chat.completions.create(model=model, messages=safe_messages)
|
| 109 |
+
try:
|
| 110 |
+
return response.choices[0].message.content
|
| 111 |
+
except Exception:
|
| 112 |
+
return str(response)
|
| 113 |
+
|
| 114 |
+
###########################################################
|
| 115 |
+
# PROVIDER: ANTHROPIC
|
| 116 |
+
###########################################################
|
| 117 |
+
try:
|
| 118 |
+
from anthropic import Anthropic
|
| 119 |
+
except Exception:
|
| 120 |
+
Anthropic = None
|
| 121 |
+
|
| 122 |
+
class AnthropicProvider(BaseProvider):
|
| 123 |
+
def __init__(self):
|
| 124 |
+
if Anthropic is None:
|
| 125 |
+
raise RuntimeError("anthropic library not installed or not importable")
|
| 126 |
+
self.client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY", ""))
|
| 127 |
+
|
| 128 |
+
def chat(self, model, messages, **kwargs):
|
| 129 |
+
if not isinstance(messages, list) or not all(isinstance(m, dict) for m in messages):
|
| 130 |
+
raise TypeError("messages must be a list of dicts with 'role' and 'content'")
|
| 131 |
+
|
| 132 |
+
user_text = "\n".join([m.get("content", "") for m in messages if m.get("role") == "user"])
|
| 133 |
+
reply = self.client.messages.create(
|
| 134 |
+
model=model,
|
| 135 |
+
max_tokens=300,
|
| 136 |
+
messages=[{"role": "user", "content": user_text}]
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
if hasattr(reply, "content"):
|
| 140 |
+
content = reply.content
|
| 141 |
+
if isinstance(content, list) and content and len(content) > 0:
|
| 142 |
+
block = content[0]
|
| 143 |
+
if hasattr(block, "text"):
|
| 144 |
+
return getattr(block, "text", str(block))
|
| 145 |
+
elif isinstance(block, dict) and "text" in block:
|
| 146 |
+
return block["text"]
|
| 147 |
+
else:
|
| 148 |
+
return str(block)
|
| 149 |
+
elif isinstance(content, str):
|
| 150 |
+
return content
|
| 151 |
+
|
| 152 |
+
if isinstance(reply, dict) and "completion" in reply:
|
| 153 |
+
return reply["completion"]
|
| 154 |
+
return str(reply)
|
| 155 |
+
|
| 156 |
+
###########################################################
|
| 157 |
+
# PROVIDER: HUGGINGFACE INFERENCE API
|
| 158 |
+
###########################################################
|
| 159 |
+
import requests
|
| 160 |
+
|
| 161 |
+
class HuggingFaceProvider(BaseProvider):
|
| 162 |
+
def __init__(self):
|
| 163 |
+
self.key = os.getenv("HF_API_KEY", "")
|
| 164 |
+
|
| 165 |
+
def chat(self, model, messages, **kwargs):
|
| 166 |
+
if not messages:
|
| 167 |
+
raise ValueError("messages is empty")
|
| 168 |
+
text = messages[-1].get("content", "")
|
| 169 |
+
r = requests.post(
|
| 170 |
+
f"https://api-inference.huggingface.co/models/{model}",
|
| 171 |
+
headers={"Authorization": f"Bearer {self.key}"} if self.key else {},
|
| 172 |
+
json={"inputs": text},
|
| 173 |
+
timeout=60
|
| 174 |
+
)
|
| 175 |
+
r.raise_for_status()
|
| 176 |
+
out = r.json()
|
| 177 |
+
if isinstance(out, list) and out and isinstance(out[0], dict):
|
| 178 |
+
return out[0].get("generated_text") or str(out[0])
|
| 179 |
+
return str(out)
|
| 180 |
+
|
| 181 |
+
###########################################################
|
| 182 |
+
# PROVIDER: NEBIUS (OpenAI-compatible)
|
| 183 |
+
###########################################################
|
| 184 |
+
class NebiusProvider(BaseProvider):
|
| 185 |
+
def __init__(self):
|
| 186 |
+
if OpenAI is None:
|
| 187 |
+
raise RuntimeError("openai library not installed; Nebius wrapper expects OpenAI-compatible client")
|
| 188 |
+
self.client = OpenAI(
|
| 189 |
+
api_key=os.getenv("NEBIUS_API_KEY", ""),
|
| 190 |
+
base_url=os.getenv("NEBIUS_BASE_URL", "https://api.studio.nebius.ai/v1")
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
def chat(self, model, messages, **kwargs):
|
| 194 |
+
try:
|
| 195 |
+
from openai.types.chat import (
|
| 196 |
+
ChatCompletionUserMessageParam,
|
| 197 |
+
ChatCompletionAssistantMessageParam,
|
| 198 |
+
ChatCompletionSystemMessageParam,
|
| 199 |
+
)
|
| 200 |
+
except Exception:
|
| 201 |
+
ChatCompletionUserMessageParam = dict
|
| 202 |
+
ChatCompletionAssistantMessageParam = dict
|
| 203 |
+
ChatCompletionSystemMessageParam = dict
|
| 204 |
+
|
| 205 |
+
safe_messages = []
|
| 206 |
+
for m in messages:
|
| 207 |
+
role = str(m.get("role", "user"))
|
| 208 |
+
content = str(m.get("content", ""))
|
| 209 |
+
if role == "user":
|
| 210 |
+
safe_messages.append(ChatCompletionUserMessageParam(role="user", content=content))
|
| 211 |
+
elif role == "assistant":
|
| 212 |
+
safe_messages.append(ChatCompletionAssistantMessageParam(role="assistant", content=content))
|
| 213 |
+
elif role == "system":
|
| 214 |
+
safe_messages.append(ChatCompletionSystemMessageParam(role="system", content=content))
|
| 215 |
+
else:
|
| 216 |
+
safe_messages.append({"role": role, "content": content})
|
| 217 |
+
|
| 218 |
+
r = self.client.chat.completions.create(model=model, messages=safe_messages)
|
| 219 |
+
try:
|
| 220 |
+
return r.choices[0].message.content
|
| 221 |
+
except Exception:
|
| 222 |
+
return str(r)
|
| 223 |
+
|
| 224 |
+
###########################################################
|
| 225 |
+
# PROVIDER: SAMBANOVA (OpenAI-compatible)
|
| 226 |
+
###########################################################
|
| 227 |
+
class SambaNovaProvider(BaseProvider):
|
| 228 |
+
def __init__(self):
|
| 229 |
+
if OpenAI is None:
|
| 230 |
+
raise RuntimeError("openai library not installed; SambaNova wrapper expects OpenAI-compatible client")
|
| 231 |
+
self.client = OpenAI(
|
| 232 |
+
api_key=os.getenv("SAMBANOVA_API_KEY", ""),
|
| 233 |
+
base_url=os.getenv("SAMBANOVA_BASE_URL", "https://api.sambanova.ai/v1")
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def chat(self, model, messages, **kwargs):
|
| 237 |
+
try:
|
| 238 |
+
from openai.types.chat import (
|
| 239 |
+
ChatCompletionUserMessageParam,
|
| 240 |
+
ChatCompletionAssistantMessageParam,
|
| 241 |
+
ChatCompletionSystemMessageParam,
|
| 242 |
+
)
|
| 243 |
+
except Exception:
|
| 244 |
+
ChatCompletionUserMessageParam = dict
|
| 245 |
+
ChatCompletionAssistantMessageParam = dict
|
| 246 |
+
ChatCompletionSystemMessageParam = dict
|
| 247 |
+
|
| 248 |
+
safe_messages = []
|
| 249 |
+
for m in messages:
|
| 250 |
+
role = str(m.get("role", "user"))
|
| 251 |
+
content = str(m.get("content", ""))
|
| 252 |
+
if role == "user":
|
| 253 |
+
safe_messages.append(ChatCompletionUserMessageParam(role="user", content=content))
|
| 254 |
+
elif role == "assistant":
|
| 255 |
+
safe_messages.append(ChatCompletionAssistantMessageParam(role="assistant", content=content))
|
| 256 |
+
elif role == "system":
|
| 257 |
+
safe_messages.append(ChatCompletionSystemMessageParam(role="system", content=content))
|
| 258 |
+
else:
|
| 259 |
+
safe_messages.append({"role": role, "content": content})
|
| 260 |
+
|
| 261 |
+
r = self.client.chat.completions.create(model=model, messages=safe_messages)
|
| 262 |
+
try:
|
| 263 |
+
return r.choices[0].message.content
|
| 264 |
+
except Exception:
|
| 265 |
+
return str(r)
|
| 266 |
+
|
| 267 |
+
###########################################################
|
| 268 |
+
# PROVIDER: LOCAL TRANSFORMERS (CACHED)
|
| 269 |
+
###########################################################
|
| 270 |
+
try:
|
| 271 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 272 |
+
import torch
|
| 273 |
+
TRANSFORMERS_AVAILABLE = True
|
| 274 |
+
except Exception:
|
| 275 |
+
TRANSFORMERS_AVAILABLE = False
|
| 276 |
+
|
| 277 |
+
class LocalLLMProvider(BaseProvider):
|
| 278 |
+
"""
|
| 279 |
+
Local LLM provider with caching - MODEL LOADS ONCE
|
| 280 |
+
"""
|
| 281 |
+
def __init__(self, model_name: str = "meta-llama/Llama-3.2-3B-Instruct"):
|
| 282 |
+
print(f"[LocalLLM] Initializing with model: {model_name}")
|
| 283 |
+
self.model_name = os.getenv("LOCAL_MODEL", model_name)
|
| 284 |
+
self.model = None
|
| 285 |
+
self.tokenizer = None
|
| 286 |
+
self.device = None
|
| 287 |
+
self._initialize_model()
|
| 288 |
+
|
| 289 |
+
def _initialize_model(self):
|
| 290 |
+
"""Initialize model ONCE - this is called only during __init__"""
|
| 291 |
+
try:
|
| 292 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 293 |
+
import torch
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
print(f"[LocalLLM] Loading model {self.model_name}...")
|
| 299 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 300 |
+
print(f"[LocalLLM] Using device: {self.device}")
|
| 301 |
+
|
| 302 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
|
| 303 |
+
if self.tokenizer.pad_token is None:
|
| 304 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 305 |
+
|
| 306 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 307 |
+
self.model_name,
|
| 308 |
+
device_map="auto" if self.device == "cuda" else None,
|
| 309 |
+
torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
|
| 310 |
+
trust_remote_code=True
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
print(f"[LocalLLM] ✅ Model loaded successfully!")
|
| 314 |
+
|
| 315 |
+
except Exception as e:
|
| 316 |
+
print(f"[LocalLLM] ❌ Failed to load model: {e}")
|
| 317 |
+
self.model = None
|
| 318 |
+
traceback.print_exc()
|
| 319 |
+
|
| 320 |
+
def chat(self, model, messages, **kwargs):
|
| 321 |
+
"""
|
| 322 |
+
Generate response - MODEL ALREADY LOADED
|
| 323 |
+
"""
|
| 324 |
+
if self.model is None or self.tokenizer is None:
|
| 325 |
+
return "Error: Model or tokenizer not loaded."
|
| 326 |
+
|
| 327 |
+
# Extract text from messages
|
| 328 |
+
text = messages[-1]["content"] if isinstance(messages[-1], dict) and "content" in messages[-1] else str(messages[-1])
|
| 329 |
+
|
| 330 |
+
max_tokens = kwargs.get("max_tokens", 128)
|
| 331 |
+
temperature = kwargs.get("temperature", 0.7)
|
| 332 |
+
|
| 333 |
+
import torch
|
| 334 |
+
|
| 335 |
+
# Tokenize
|
| 336 |
+
inputs = self.tokenizer(
|
| 337 |
+
text,
|
| 338 |
+
return_tensors="pt",
|
| 339 |
+
padding=True,
|
| 340 |
+
truncation=True,
|
| 341 |
+
max_length=2048
|
| 342 |
+
).to(self.device)
|
| 343 |
+
|
| 344 |
+
# Generate (model is already loaded, just inference)
|
| 345 |
+
with torch.no_grad():
|
| 346 |
+
outputs = self.model.generate(
|
| 347 |
+
**inputs,
|
| 348 |
+
max_new_tokens=max_tokens,
|
| 349 |
+
temperature=temperature,
|
| 350 |
+
top_p=0.9,
|
| 351 |
+
do_sample=temperature > 0,
|
| 352 |
+
pad_token_id=self.tokenizer.eos_token_id if self.tokenizer and hasattr(self.tokenizer, 'eos_token_id') else None,
|
| 353 |
+
eos_token_id=self.tokenizer.eos_token_id if self.tokenizer and hasattr(self.tokenizer, 'eos_token_id') else None
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
# Decode
|
| 357 |
+
response = self.tokenizer.decode(
|
| 358 |
+
outputs[0][inputs['input_ids'].shape[1]:],
|
| 359 |
+
skip_special_tokens=True
|
| 360 |
+
).strip() if self.tokenizer else "Error: Tokenizer not loaded."
|
| 361 |
+
|
| 362 |
+
return response
|
| 363 |
+
|
| 364 |
+
###########################################################
|
| 365 |
+
# PROVIDER CACHE - CRITICAL FIX
|
| 366 |
+
###########################################################
|
| 367 |
+
class ProviderCache:
|
| 368 |
+
"""
|
| 369 |
+
Cache provider instances to avoid reloading models
|
| 370 |
+
This is the KEY fix - providers are created ONCE and reused
|
| 371 |
+
"""
|
| 372 |
+
_cache = {}
|
| 373 |
+
|
| 374 |
+
@classmethod
|
| 375 |
+
def get_provider(cls, provider_name: str) -> BaseProvider:
|
| 376 |
+
"""Get or create cached provider instance"""
|
| 377 |
+
if provider_name not in cls._cache:
|
| 378 |
+
print(f"[ProviderCache] Creating new instance of {provider_name}")
|
| 379 |
+
provider_class = ProviderFactory.providers[provider_name]
|
| 380 |
+
cls._cache[provider_name] = provider_class()
|
| 381 |
+
else:
|
| 382 |
+
print(f"[ProviderCache] Using cached instance of {provider_name}")
|
| 383 |
+
return cls._cache[provider_name]
|
| 384 |
+
|
| 385 |
+
@classmethod
|
| 386 |
+
def clear_cache(cls):
|
| 387 |
+
"""Clear all cached providers (useful for debugging)"""
|
| 388 |
+
cls._cache.clear()
|
| 389 |
+
print("[ProviderCache] Cache cleared")
|
| 390 |
+
|
| 391 |
+
###########################################################
|
| 392 |
+
# PROVIDER FACTORY (IMPROVED WITH CACHING)
|
| 393 |
+
###########################################################
|
| 394 |
+
class ProviderFactory:
|
| 395 |
+
providers = {
|
| 396 |
+
"openai": OpenAIProvider,
|
| 397 |
+
"anthropic": AnthropicProvider,
|
| 398 |
+
"huggingface": HuggingFaceProvider,
|
| 399 |
+
"nebius": NebiusProvider,
|
| 400 |
+
"sambanova": SambaNovaProvider,
|
| 401 |
+
"local": LocalLLMProvider,
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
@staticmethod
|
| 405 |
+
def get(provider_name: str) -> BaseProvider:
|
| 406 |
+
"""
|
| 407 |
+
Get provider instance - NOW USES CACHING
|
| 408 |
+
This prevents reloading the model on every call
|
| 409 |
+
"""
|
| 410 |
+
provider_name = provider_name.lower()
|
| 411 |
+
if provider_name not in ProviderFactory.providers:
|
| 412 |
+
raise ValueError(f"Unknown provider: {provider_name}")
|
| 413 |
+
|
| 414 |
+
# USE CACHE instead of creating new instance every time
|
| 415 |
+
return ProviderCache.get_provider(provider_name)
|
| 416 |
+
|
| 417 |
+
###########################################################
|
| 418 |
+
# MAIN ENGINE WITH FALLBACK + OPENAI-STYLE API
|
| 419 |
+
###########################################################
|
| 420 |
+
class LLMEngine:
|
| 421 |
+
def __init__(self):
|
| 422 |
+
self.credits = load_credits()
|
| 423 |
+
|
| 424 |
+
def deduct(self, provider, amount):
|
| 425 |
+
if provider not in self.credits:
|
| 426 |
+
self.credits[provider] = 0
|
| 427 |
+
self.credits[provider] = max(0, self.credits[provider] - amount)
|
| 428 |
+
save_credits(self.credits)
|
| 429 |
+
|
| 430 |
+
def chat(self, provider: str, model: str, messages: List[Dict], fallback: bool = True, **kwargs):
|
| 431 |
+
"""
|
| 432 |
+
Main chat method - providers are now cached
|
| 433 |
+
"""
|
| 434 |
+
try:
|
| 435 |
+
p = ProviderFactory.get(provider) # This now returns cached instance
|
| 436 |
+
result = p.chat(model=model, messages=messages, **kwargs)
|
| 437 |
+
try:
|
| 438 |
+
self.deduct(provider, 0.001)
|
| 439 |
+
except Exception:
|
| 440 |
+
pass
|
| 441 |
+
return result
|
| 442 |
+
except Exception as exc:
|
| 443 |
+
print(f"⚠ Provider '{provider}' failed → fallback activated: {exc}")
|
| 444 |
+
traceback.print_exc()
|
| 445 |
+
if fallback:
|
| 446 |
+
try:
|
| 447 |
+
lp = ProviderFactory.get("local") # Gets cached local provider
|
| 448 |
+
return lp.chat(model="local", messages=messages, **kwargs)
|
| 449 |
+
except Exception as le:
|
| 450 |
+
print("Fallback to local provider failed:", le)
|
| 451 |
+
traceback.print_exc()
|
| 452 |
+
raise
|
| 453 |
+
raise
|
| 454 |
+
|
| 455 |
+
###########################################################
|
| 456 |
+
# EXAMPLES + SIMPLE TESTS
|
| 457 |
+
###########################################################
|
| 458 |
+
def main():
|
| 459 |
+
engine = LLMEngine()
|
| 460 |
+
|
| 461 |
+
print("=== Testing Provider Caching ===")
|
| 462 |
+
print("\nFirst call (should load model):")
|
| 463 |
+
result1 = engine.chat(
|
| 464 |
+
provider="local",
|
| 465 |
+
model="meta-llama/Llama-3.2-3B-Instruct",
|
| 466 |
+
messages=[{"role": "user", "content": "Say hello"}]
|
| 467 |
+
)
|
| 468 |
+
print(f"Response: {result1[:100]}")
|
| 469 |
+
|
| 470 |
+
print("\nSecond call (should use cached model - NO RELOAD):")
|
| 471 |
+
result2 = engine.chat(
|
| 472 |
+
provider="local",
|
| 473 |
+
model="meta-llama/Llama-3.2-3B-Instruct",
|
| 474 |
+
messages=[{"role": "user", "content": "Say goodbye"}]
|
| 475 |
+
)
|
| 476 |
+
print(f"Response: {result2[:100]}")
|
| 477 |
+
|
| 478 |
+
print("\n✅ If you didn't see 'Loading model' twice, caching works!")
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
if __name__ == "__main__":
|
| 482 |
+
import argparse
|
| 483 |
+
parser = argparse.ArgumentParser()
|
| 484 |
+
parser.add_argument("--test", action="store_true", help="run examples and simple tests")
|
| 485 |
+
args = parser.parse_args()
|
| 486 |
+
if args.test:
|
| 487 |
+
main()
|
| 488 |
+
else:
|
| 489 |
main()
|