-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm_studio_client.py
More file actions
56 lines (49 loc) · 2.37 KB
/
Copy pathllm_studio_client.py
File metadata and controls
56 lines (49 loc) · 2.37 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
import aiohttp
import asyncio
import logging
from typing import List, Dict, Any
logger = logging.getLogger(__name__)
class LMStudioMessage:
def __init__(self, content: str):
self.content = content
class LMStudioClient:
def __init__(self, model: str, base_url: str = "http://localhost:1234/v1", temperature: float = 0.7, max_tokens: int = -1):
self.model = model
self.base_url = base_url
self.temperature = temperature
self.max_tokens = max_tokens
async def ainvoke(self, messages: List[Dict[str, str]]) -> LMStudioMessage:
"""Async invoke method compatible with LangChain interface"""
try:
async with aiohttp.ClientSession() as session:
payload = {
"model": self.model,
"messages": messages,
"temperature": self.temperature,
"max_tokens": self.max_tokens,
"stream": False
}
logger.debug(f"Sending request to {self.base_url}/chat/completions with model: {self.model}")
async with session.post(
f"{self.base_url}/chat/completions",
json=payload,
headers={"Content-Type": "application/json"},
timeout=aiohttp.ClientTimeout(total=30)
) as response:
if response.status == 200:
data = await response.json()
content = data["choices"][0]["message"]["content"]
return LMStudioMessage(content)
else:
error_text = await response.text()
logger.error(f"LM Studio API error {response.status}: {error_text}")
raise Exception(f"LM Studio API error: {response.status} - {error_text}")
except aiohttp.ClientError as e:
logger.error(f"Connection error to LM Studio: {e}")
raise Exception(f"LM Studio connection error: {e}")
except asyncio.TimeoutError:
logger.error("Request to LM Studio timed out")
raise Exception("LM Studio request timeout")
def invoke(self, messages: List[Dict[str, str]]) -> LMStudioMessage:
"""Sync invoke method for compatibility"""
return asyncio.run(self.ainvoke(messages))