Spaces:
Running
Running
File size: 6,370 Bytes
f9ad313 d4ecac6 f9ad313 d4ecac6 f9ad313 d4ecac6 f9ad313 d4ecac6 f9ad313 d4ecac6 f9ad313 d4ecac6 f9ad313 d4ecac6 f9ad313 d4ecac6 f9ad313 d4ecac6 f9ad313 |
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 |
"""
LLM Client - Unified interface for Groq, OpenAI, and local models.
Groq is the DEFAULT provider (free tier available).
"""
import logging
from abc import ABC, abstractmethod
from typing import List, Dict, Optional
logger = logging.getLogger(__name__)
from dataclasses import dataclass
@dataclass
class LLMResponse:
content: str
input_tokens: int = 0
output_tokens: int = 0
total_tokens: int = 0
class LLMClient(ABC):
"""Abstract base class for LLM clients."""
@abstractmethod
def chat(self, messages: List[Dict[str, str]]) -> LLMResponse:
pass
@abstractmethod
def is_available(self) -> bool:
pass
class GroqClient(LLMClient):
"""
Groq API client - FREE and FAST inference.
Available models:
- llama-3.3-70b-versatile (recommended)
- llama-3.1-8b-instant (faster)
- mixtral-8x7b-32768
- gemma2-9b-it
"""
AVAILABLE_MODELS = [
"llama-3.3-70b-versatile",
"llama-3.1-70b-versatile",
"llama-3.1-8b-instant",
"llama3-70b-8192",
"llama3-8b-8192",
"mixtral-8x7b-32768",
"gemma2-9b-it"
]
def __init__(
self,
api_key: str,
model: str = "llama-3.3-70b-versatile",
temperature: float = 0.1,
max_tokens: int = 1024
):
self.api_key = api_key
self.model = model
self.temperature = temperature
self.max_tokens = max_tokens
self._client = None
@property
def client(self):
if self._client is None:
from groq import Groq
self._client = Groq(api_key=self.api_key)
return self._client
def chat(self, messages: List[Dict[str, str]]) -> LLMResponse:
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=self.temperature,
max_tokens=self.max_tokens
)
usage = response.usage
return LLMResponse(
content=response.choices[0].message.content,
input_tokens=usage.prompt_tokens if usage else 0,
output_tokens=usage.completion_tokens if usage else 0,
total_tokens=usage.total_tokens if usage else 0
)
def is_available(self) -> bool:
try:
# Simple test call
self.client.models.list()
return True
except Exception as e:
logger.warning(f"Groq availability check failed: {e}")
return False
class OpenAIClient(LLMClient):
"""OpenAI API client (paid)."""
def __init__(
self,
api_key: str,
model: str = "gpt-4o-mini",
temperature: float = 0.1,
max_tokens: int = 1024
):
self.api_key = api_key
self.model = model
self.temperature = temperature
self.max_tokens = max_tokens
self._client = None
@property
def client(self):
if self._client is None:
from openai import OpenAI
self._client = OpenAI(api_key=self.api_key)
return self._client
def chat(self, messages: List[Dict[str, str]]) -> LLMResponse:
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=self.temperature,
max_tokens=self.max_tokens
)
usage = response.usage
return LLMResponse(
content=response.choices[0].message.content,
input_tokens=usage.prompt_tokens if usage else 0,
output_tokens=usage.completion_tokens if usage else 0,
total_tokens=usage.total_tokens if usage else 0
)
def is_available(self) -> bool:
try:
self.client.models.list()
return True
except Exception:
return False
class LocalLLaMAClient(LLMClient):
"""Local LLaMA/Phi model client via transformers."""
def __init__(
self,
model_name: str = "microsoft/Phi-3-mini-4k-instruct",
temperature: float = 0.1,
max_tokens: int = 1024
):
self.model_name = model_name
self.temperature = temperature
self.max_tokens = max_tokens
self._pipeline = None
@property
def pipeline(self):
if self._pipeline is None:
from transformers import pipeline
logger.info(f"Loading local model: {self.model_name}")
self._pipeline = pipeline(
"text-generation",
model=self.model_name,
torch_dtype="auto",
device_map="auto"
)
return self._pipeline
def chat(self, messages: List[Dict[str, str]]) -> LLMResponse:
output = self.pipeline(
messages,
max_new_tokens=self.max_tokens,
temperature=self.temperature,
do_sample=True
)
generated_text = output[0]["generated_text"][-1]["content"]
# Approximate tokens for local (or use tokenizer if available)
return LLMResponse(
content=generated_text,
input_tokens=0, # Local pipeline generic usually doesn't give this easily without more access
output_tokens=0,
total_tokens=0
)
def is_available(self) -> bool:
try:
_ = self.pipeline
return True
except Exception:
return False
def create_llm_client(provider: str = "groq", **kwargs) -> LLMClient:
"""
Factory function to create LLM client.
Args:
provider: "groq" (default, free), "openai", or "local"
**kwargs: Provider-specific arguments
Returns:
Configured LLMClient instance
"""
if provider == "groq":
return GroqClient(**kwargs)
elif provider == "openai":
return OpenAIClient(**kwargs)
elif provider == "local":
return LocalLLaMAClient(**kwargs)
else:
raise ValueError(f"Unknown provider: {provider}. Use 'groq', 'openai', or 'local'")
|