Spaces:
Sleeping
Sleeping
File size: 11,999 Bytes
40ee6b4 |
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 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 299 300 301 302 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 |
"""
LM Studio local LLM client adapter.
Implements the LLMClient protocol for LM Studio's OpenAI-compatible API.
Designed for running local models with configurable endpoint.
"""
import json
import logging
from collections.abc import AsyncIterator
from typing import Any
import httpx
from .base import BaseLLMClient, LLMResponse
from .exceptions import (
LLMClientError,
LLMConnectionError,
LLMResponseParseError,
LLMServerError,
LLMStreamError,
LLMTimeoutError,
)
logger = logging.getLogger(__name__)
class LMStudioClient(BaseLLMClient):
"""
LM Studio local server client.
LM Studio provides an OpenAI-compatible API for running local models.
This client is optimized for local deployment with:
- No authentication required (local)
- Configurable base URL
- No circuit breaker (local server expected to be stable)
- Longer timeouts for large models
"""
PROVIDER_NAME = "lmstudio"
DEFAULT_BASE_URL = "http://localhost:1234/v1"
DEFAULT_MODEL = "local-model" # LM Studio uses the loaded model
def __init__(
self,
api_key: str | None = None, # Not required for local
model: str | None = None,
base_url: str | None = None,
timeout: float = 300.0, # Long timeout for local inference
max_retries: int = 2, # Fewer retries for local
# Rate limiting
rate_limit_per_minute: int | None = None,
):
"""
Initialize LM Studio client.
Args:
api_key: Not required for local server (ignored)
model: Model identifier (often ignored by LM Studio, uses loaded model)
base_url: Local server URL (default: http://localhost:1234/v1)
timeout: Request timeout in seconds (default longer for local models)
max_retries: Max retry attempts (fewer for local)
rate_limit_per_minute: Rate limit for requests per minute (None to disable)
"""
import os
# Allow overriding via environment variable
base_url = base_url or os.environ.get("LMSTUDIO_BASE_URL", self.DEFAULT_BASE_URL)
super().__init__(
api_key=api_key or "not-required", # Placeholder
model=model or self.DEFAULT_MODEL,
base_url=base_url,
timeout=timeout,
max_retries=max_retries,
rate_limit_per_minute=rate_limit_per_minute,
)
self._client: httpx.AsyncClient | None = None
async def _get_client(self) -> httpx.AsyncClient:
"""Get or create the HTTP client."""
if self._client is None or self._client.is_closed:
headers = {"Content-Type": "application/json"}
# Add auth header if provided (some local servers may require it)
if self.api_key and self.api_key != "not-required":
headers["Authorization"] = f"Bearer {self.api_key}"
self._client = httpx.AsyncClient(
base_url=self.base_url,
headers=headers,
timeout=httpx.Timeout(self.timeout),
)
return self._client
async def check_health(self) -> bool:
"""
Check if LM Studio server is running.
Returns:
True if server is accessible, False otherwise
"""
try:
client = await self._get_client()
response = await client.get("/models")
return response.status_code == 200
except Exception:
return False
async def list_models(self) -> list[dict]:
"""
List available models on the LM Studio server.
Returns:
List of model information dicts
"""
try:
client = await self._get_client()
response = await client.get("/models")
if response.status_code == 200:
data = response.json()
return data.get("data", [])
return []
except Exception as e:
logger.warning(f"Failed to list models: {e}")
return []
def _handle_error_response(self, response: httpx.Response) -> None:
"""Handle error responses from LM Studio server."""
status_code = response.status_code
try:
error_data = response.json()
error_message = error_data.get("error", {}).get("message", response.text)
except Exception:
error_message = response.text
if status_code >= 500:
raise LLMServerError(self.PROVIDER_NAME, status_code, error_message)
else:
raise LLMClientError(error_message, self.PROVIDER_NAME, status_code=status_code)
async def generate(
self,
*,
messages: list[dict] | None = None,
prompt: str | None = None,
temperature: float = 0.7,
max_tokens: int | None = None,
tools: list[dict] | None = None,
stream: bool = False,
stop: list[str] | None = None,
**kwargs: Any,
) -> LLMResponse | AsyncIterator[str]:
"""
Generate a response from LM Studio local model.
Args:
messages: Chat messages in OpenAI format
prompt: Simple string prompt
temperature: Sampling temperature
max_tokens: Maximum tokens to generate
tools: Tool definitions (limited support in local models)
stream: If True, returns AsyncIterator
stop: Stop sequences
**kwargs: Additional parameters
Returns:
LLMResponse or AsyncIterator[str] for streaming
"""
# Apply rate limiting before proceeding
await self._apply_rate_limit()
if stream:
return self._generate_stream(
messages=messages,
prompt=prompt,
temperature=temperature,
max_tokens=max_tokens,
tools=tools,
stop=stop,
**kwargs,
)
else:
return await self._generate_non_stream(
messages=messages,
prompt=prompt,
temperature=temperature,
max_tokens=max_tokens,
tools=tools,
stop=stop,
**kwargs,
)
async def _generate_non_stream(
self,
*,
messages: list[dict] | None = None,
prompt: str | None = None,
temperature: float = 0.7,
max_tokens: int | None = None,
tools: list[dict] | None = None,
stop: list[str] | None = None,
**kwargs: Any,
) -> LLMResponse:
"""Non-streaming generation."""
client = await self._get_client()
# Build request payload (OpenAI-compatible)
payload = {
"model": self.model,
"messages": self._build_messages(messages, prompt),
"temperature": temperature,
}
if max_tokens is not None:
payload["max_tokens"] = max_tokens
if stop:
payload["stop"] = stop
# Note: most local models don't support tools well
if tools:
logger.warning("Tool calling may not be fully supported by local models")
payload["tools"] = tools
# Add additional kwargs (e.g., top_p, repeat_penalty)
for key in ["top_p", "top_k", "repeat_penalty", "presence_penalty", "frequency_penalty"]:
if key in kwargs:
payload[key] = kwargs[key]
# Retry logic for local server
last_error = None
for attempt in range(self.max_retries):
try:
response = await client.post("/chat/completions", json=payload)
if response.status_code != 200:
self._handle_error_response(response)
# Parse response
try:
data = response.json()
choice = data["choices"][0]
message = choice["message"]
usage = data.get("usage", {})
finish_reason = choice.get("finish_reason", "stop")
llm_response = LLMResponse(
text=message.get("content", ""),
usage=usage,
model=data.get("model", self.model),
raw_response=data,
finish_reason=finish_reason,
)
self._update_stats(llm_response)
return llm_response
except (KeyError, json.JSONDecodeError) as e:
raise LLMResponseParseError(self.PROVIDER_NAME, response.text) from e
except httpx.TimeoutException:
last_error = LLMTimeoutError(self.PROVIDER_NAME, self.timeout)
logger.warning(f"Attempt {attempt + 1} timed out, retrying...")
except httpx.ConnectError:
last_error = LLMConnectionError(self.PROVIDER_NAME, self.base_url)
logger.warning(f"Attempt {attempt + 1} connection failed, retrying...")
except LLMClientError:
raise # Don't retry client errors
# All retries exhausted
if last_error:
raise last_error
raise LLMConnectionError(self.PROVIDER_NAME, self.base_url)
async def _generate_stream(
self,
*,
messages: list[dict] | None = None,
prompt: str | None = None,
temperature: float = 0.7,
max_tokens: int | None = None,
tools: list[dict] | None = None, # noqa: ARG002
stop: list[str] | None = None,
**kwargs: Any,
) -> AsyncIterator[str]:
"""Streaming generation."""
client = await self._get_client()
# Build request payload
payload = {
"model": self.model,
"messages": self._build_messages(messages, prompt),
"temperature": temperature,
"stream": True,
}
if max_tokens is not None:
payload["max_tokens"] = max_tokens
if stop:
payload["stop"] = stop
for key in ["top_p", "top_k", "repeat_penalty"]:
if key in kwargs:
payload[key] = kwargs[key]
async def stream_generator():
try:
async with client.stream("POST", "/chat/completions", json=payload) as response:
if response.status_code != 200:
await response.aread()
self._handle_error_response(response)
async for line in response.aiter_lines():
if line.startswith("data: "):
data_str = line[6:]
if data_str.strip() == "[DONE]":
break
try:
data = json.loads(data_str)
delta = data["choices"][0].get("delta", {})
content = delta.get("content", "")
if content:
yield content
except (json.JSONDecodeError, KeyError):
continue
except httpx.TimeoutException:
raise LLMTimeoutError(self.PROVIDER_NAME, self.timeout)
except httpx.ConnectError:
raise LLMConnectionError(self.PROVIDER_NAME, self.base_url)
except Exception as e:
if isinstance(e, LLMClientError):
raise
raise LLMStreamError(self.PROVIDER_NAME, str(e)) from e
return stream_generator()
async def close(self) -> None:
"""Close the HTTP client."""
if self._client and not self._client.is_closed:
await self._client.aclose()
self._client = None
|