| """OpenAI-compatible HTTP client for a vLLM server. |
| |
| The wire format uses the standard OpenAI ``/v1/chat/completions`` schema. |
| Frames are sent inline as base64 ``data:`` URLs. |
| """ |
| from __future__ import annotations |
|
|
| import json |
| import time |
| from typing import Any, Optional |
|
|
| import requests |
|
|
|
|
| class VLLMClient: |
| """OpenAI-compatible client backed by a vLLM server.""" |
|
|
| def __init__( |
| self, |
| base_url: str, |
| model_name: str, |
| api_key: str = "EMPTY", |
| max_tokens: int = 2048, |
| temperature: float = 0.0, |
| top_p: Optional[float] = None, |
| request_interval: float = 0.0, |
| max_retries: int = 3, |
| retry_base_delay: float = 2.0, |
| request_timeout: int = 300, |
| ) -> None: |
| base_url = (base_url or "").rstrip("/") |
| if not base_url.endswith("/v1"): |
| base_url = f"{base_url}/v1" |
| self.base_url = base_url |
| self.model_name = model_name |
| self.max_tokens = int(max_tokens) |
| self.temperature = float(temperature) |
| self.top_p = top_p |
| self.request_interval = float(request_interval) |
| self.max_retries = int(max_retries) |
| self.retry_base_delay = float(retry_base_delay) |
| self.request_timeout = int(request_timeout) |
| self.headers = { |
| "Content-Type": "application/json", |
| "Authorization": f"Bearer {api_key or 'EMPTY'}", |
| } |
|
|
| |
| |
| |
|
|
| def infer_text_only( |
| self, |
| user_text: str, |
| system_text: Optional[str] = None, |
| ) -> str: |
| messages = self._build_messages( |
| user_content=[{"type": "text", "text": user_text}], |
| system_text=system_text, |
| ) |
| return self._infer(messages) |
|
|
| def infer_with_frames( |
| self, |
| user_text: str, |
| frame_b64_list: list[str], |
| system_text: Optional[str] = None, |
| ) -> str: |
| content_parts: list[dict[str, Any]] = [] |
| for frame_b64 in frame_b64_list: |
| content_parts.append( |
| { |
| "type": "image_url", |
| "image_url": {"url": f"data:image/jpeg;base64,{frame_b64}"}, |
| } |
| ) |
| content_parts.append({"type": "text", "text": user_text}) |
| messages = self._build_messages( |
| user_content=content_parts, system_text=system_text |
| ) |
| return self._infer(messages) |
|
|
| |
| |
| |
|
|
| @staticmethod |
| def _build_messages( |
| user_content: list[dict[str, Any]], |
| system_text: Optional[str], |
| ) -> list[dict[str, Any]]: |
| messages: list[dict[str, Any]] = [] |
| if system_text and system_text.strip(): |
| messages.append( |
| { |
| "role": "system", |
| "content": [{"type": "text", "text": system_text}], |
| } |
| ) |
| messages.append({"role": "user", "content": user_content}) |
| return messages |
|
|
| def _infer(self, messages: list[dict[str, Any]]) -> str: |
| url = f"{self.base_url}/chat/completions" |
| payload: dict[str, Any] = { |
| "model": self.model_name, |
| "messages": messages, |
| "max_tokens": self.max_tokens, |
| "temperature": self.temperature, |
| } |
| if self.top_p is not None: |
| payload["top_p"] = self.top_p |
|
|
| resp = self._post_with_retry(url, payload) |
| data = resp.json() |
| if data.get("error"): |
| raise RuntimeError(f"vLLM API error: {data['error']}") |
|
|
| choices = data.get("choices", []) |
| if not choices: |
| raise RuntimeError( |
| "vLLM API returned no choices: " |
| f"{json.dumps(data, ensure_ascii=False)[:500]}" |
| ) |
|
|
| content = choices[0].get("message", {}).get("content", "") |
| if isinstance(content, str) and content.strip(): |
| return content |
| if isinstance(content, list): |
| text_parts = [ |
| part.get("text", "") |
| for part in content |
| if isinstance(part, dict) |
| ] |
| text = "\n".join(p for p in text_parts if p) |
| if text.strip(): |
| return text |
|
|
| raise RuntimeError( |
| "No text found in vLLM response: " |
| f"{json.dumps(data, ensure_ascii=False)[:500]}" |
| ) |
|
|
| def _post_with_retry( |
| self, url: str, payload: dict[str, Any] |
| ) -> requests.Response: |
| last_exc: Optional[Exception] = None |
| for attempt in range(self.max_retries): |
| try: |
| resp = requests.post( |
| url, |
| headers=self.headers, |
| json=payload, |
| timeout=self.request_timeout, |
| ) |
| resp.raise_for_status() |
| return resp |
| except Exception as exc: |
| last_exc = exc |
| if attempt < self.max_retries - 1: |
| delay = self.retry_base_delay * (2 ** attempt) |
| print( |
| f" [vllm retry] attempt {attempt + 1}/" |
| f"{self.max_retries} failed: {exc}; sleep {delay:.1f}s" |
| ) |
| time.sleep(delay) |
| raise RuntimeError( |
| f"vLLM request failed after {self.max_retries} attempts: {last_exc}" |
| ) |
|
|