2026-11-10 23:56:50 +08:00
|
|
|
|
"""Reuse the existing Qwen3.8 FP8 endpoint for text reasoning and vision.
|
|
|
|
|
|
|
|
|
|
|
|
Only QWEN_API_BASE, QWEN_MODEL and QWEN_API_KEY are read for service
|
|
|
|
|
|
configuration. No weights are downloaded and no service is launched here.
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
import base64
|
|
|
|
|
|
from io import BytesIO
|
|
|
|
|
|
import json
|
|
|
|
|
|
import os
|
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
import re
|
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
from urllib.parse import urlsplit
|
|
|
|
|
|
|
|
|
|
|
|
from PIL import Image, UnidentifiedImageError
|
|
|
|
|
|
import requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
DEFAULT_BASE_URL = "http://192.168.28.10:14081/v1"
|
|
|
|
|
|
DEFAULT_MODEL = "Qwen/Qwen3.8-27B-FP8"
|
|
|
|
|
|
DEFAULT_STRUCTURE_PROMPT = (
|
|
|
|
|
|
"请只根据图片中可见内容输出一个JSON对象,不要Markdown或解释。"
|
|
|
|
|
|
'字段为:"subjects"(主体描述字符串数组)、"scene"(场景描述字符串)、'
|
|
|
|
|
|
'"ocr"(画面中实际可见文字的字符串数组,无文字则为空数组)。'
|
|
|
|
|
|
"看不清的内容请标为不确定,不要臆测;不要求坐标。"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class QwenClientError(RuntimeError):
|
|
|
|
|
|
"""An HTTP or response-shape failure when calling the existing service."""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, message: str, *, raw_response: Any = None):
|
|
|
|
|
|
super().__init__(message)
|
|
|
|
|
|
self.raw_response = raw_response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class QwenClient:
|
|
|
|
|
|
"""Small synchronous client; image reads are confined to workspace_root.
|
|
|
|
|
|
|
|
|
|
|
|
Callers must serialize requests through their global task queue. The
|
|
|
|
|
|
returned dictionary keeps raw_response for auditing and separates SGLang's
|
|
|
|
|
|
reasoning_content from its final content. A visual result's structured
|
|
|
|
|
|
field is None when the final answer is not a JSON object or array.
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
|
self,
|
|
|
|
|
|
base_url: str | None = None,
|
|
|
|
|
|
model: str | None = None,
|
|
|
|
|
|
api_key: str | None = None,
|
|
|
|
|
|
workspace_root: str | Path = "/workspace",
|
|
|
|
|
|
enable_thinking: bool = False,
|
2026-11-14 14:07:26 +08:00
|
|
|
|
timeout: float = 1800,
|
2026-11-10 23:56:50 +08:00
|
|
|
|
max_tokens: int = 2048,
|
|
|
|
|
|
):
|
|
|
|
|
|
self.base_url = (base_url or os.environ.get("QWEN_API_BASE") or DEFAULT_BASE_URL).rstrip("/")
|
|
|
|
|
|
parsed = urlsplit(self.base_url)
|
|
|
|
|
|
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
|
|
|
|
raise ValueError("Qwen base_url must be an absolute HTTP(S) URL")
|
|
|
|
|
|
if parsed.username is not None or parsed.password is not None or parsed.query or parsed.fragment:
|
|
|
|
|
|
raise ValueError("Qwen base_url must not contain credentials, query or fragment")
|
|
|
|
|
|
if timeout <= 0 or max_tokens <= 0:
|
|
|
|
|
|
raise ValueError("timeout and max_tokens must be positive")
|
|
|
|
|
|
self.model = model or os.environ.get("QWEN_MODEL") or DEFAULT_MODEL
|
|
|
|
|
|
self.api_key = os.environ.get("QWEN_API_KEY") if api_key is None else api_key
|
|
|
|
|
|
self.workspace_root = Path(workspace_root).resolve()
|
|
|
|
|
|
self.enable_thinking = bool(enable_thinking)
|
|
|
|
|
|
self.timeout = timeout
|
|
|
|
|
|
self.max_tokens = max_tokens
|
|
|
|
|
|
self._session = requests.Session()
|
|
|
|
|
|
# Prevent unrelated proxy or .netrc credentials from changing this
|
|
|
|
|
|
# explicitly configured internal service connection.
|
|
|
|
|
|
self._session.trust_env = False
|
|
|
|
|
|
|
|
|
|
|
|
def solve_math(self, question: str) -> dict[str, Any]:
|
|
|
|
|
|
"""Submit a text reasoning request; this is not a formal proof checker."""
|
|
|
|
|
|
if not isinstance(question, str) or not question.strip():
|
|
|
|
|
|
raise ValueError("question must be a non-empty string")
|
|
|
|
|
|
return self._chat([
|
|
|
|
|
|
{"role": "system", "content": "请准确回答数学问题,注意公式与单位;无法确定时请说明。"},
|
|
|
|
|
|
{"role": "user", "content": question},
|
|
|
|
|
|
])
|
|
|
|
|
|
|
|
|
|
|
|
def describe_image(self, image_path: str | Path, prompt: str | None = None) -> dict[str, Any]:
|
|
|
|
|
|
"""Send a workspace image as a data URI and retain the actual answer."""
|
|
|
|
|
|
if prompt is not None and (not isinstance(prompt, str) or not prompt.strip()):
|
|
|
|
|
|
raise ValueError("prompt must be a non-empty string")
|
|
|
|
|
|
path = Path(image_path)
|
|
|
|
|
|
if not path.is_absolute():
|
|
|
|
|
|
path = self.workspace_root / path
|
|
|
|
|
|
path = path.resolve()
|
|
|
|
|
|
if not path.is_relative_to(self.workspace_root):
|
|
|
|
|
|
raise ValueError("image_path must stay within workspace_root")
|
|
|
|
|
|
if not path.is_file():
|
|
|
|
|
|
raise ValueError("image_path must name an existing workspace file")
|
|
|
|
|
|
image_bytes = path.read_bytes()
|
|
|
|
|
|
try:
|
|
|
|
|
|
with Image.open(BytesIO(image_bytes)) as image:
|
|
|
|
|
|
image_format = image.format
|
|
|
|
|
|
image.verify()
|
|
|
|
|
|
except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
|
|
|
|
|
|
raise ValueError("image_path must contain a valid image") from exc
|
|
|
|
|
|
mime_type = {"PNG": "image/png", "JPEG": "image/jpeg", "WEBP": "image/webp"}.get(image_format)
|
|
|
|
|
|
if mime_type is None:
|
|
|
|
|
|
raise ValueError("supported image formats are PNG, JPEG and WebP")
|
|
|
|
|
|
data_uri = f"data:{mime_type};base64,{base64.b64encode(image_bytes).decode('ascii')}"
|
|
|
|
|
|
result = self._chat([{
|
|
|
|
|
|
"role": "user",
|
|
|
|
|
|
"content": [
|
|
|
|
|
|
{"type": "image_url", "image_url": {"url": data_uri}},
|
|
|
|
|
|
{"type": "text", "text": prompt or DEFAULT_STRUCTURE_PROMPT},
|
|
|
|
|
|
],
|
|
|
|
|
|
}])
|
|
|
|
|
|
result["structured"] = _parse_structured(result["content"])
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def _chat(self, messages: list[dict[str, Any]]) -> dict[str, Any]:
|
|
|
|
|
|
payload = {
|
|
|
|
|
|
"model": self.model,
|
|
|
|
|
|
"messages": messages,
|
|
|
|
|
|
"stream": False,
|
|
|
|
|
|
"temperature": 0.0,
|
|
|
|
|
|
"max_tokens": self.max_tokens,
|
|
|
|
|
|
"chat_template_kwargs": {"enable_thinking": self.enable_thinking},
|
|
|
|
|
|
}
|
|
|
|
|
|
headers = {"Content-Type": "application/json"}
|
|
|
|
|
|
if self.api_key:
|
|
|
|
|
|
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
|
|
|
|
try:
|
|
|
|
|
|
response = self._session.post(
|
|
|
|
|
|
self.base_url + "/chat/completions", json=payload,
|
|
|
|
|
|
headers=headers, timeout=self.timeout,
|
|
|
|
|
|
)
|
|
|
|
|
|
except requests.RequestException as exc:
|
|
|
|
|
|
raise QwenClientError(f"Qwen request failed: {type(exc).__name__}") from exc
|
|
|
|
|
|
try:
|
|
|
|
|
|
raw_response = response.json()
|
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
|
raise QwenClientError(f"Qwen returned non-JSON HTTP {response.status_code}") from exc
|
|
|
|
|
|
if not response.ok:
|
|
|
|
|
|
raise QwenClientError(f"Qwen returned HTTP {response.status_code}", raw_response=raw_response)
|
|
|
|
|
|
return _normalize_response(raw_response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _text_content(content: Any) -> str:
|
|
|
|
|
|
if content is None:
|
|
|
|
|
|
return ""
|
|
|
|
|
|
if isinstance(content, str):
|
|
|
|
|
|
return content
|
|
|
|
|
|
if isinstance(content, list):
|
|
|
|
|
|
if not all(isinstance(part, dict) and isinstance(part.get("text"), str) for part in content):
|
|
|
|
|
|
raise ValueError("unsupported assistant content blocks")
|
|
|
|
|
|
return "".join(part["text"] for part in content)
|
|
|
|
|
|
raise ValueError("unsupported assistant content")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _normalize_response(raw_response: Any) -> dict[str, Any]:
|
|
|
|
|
|
try:
|
|
|
|
|
|
choice = raw_response["choices"][0]
|
|
|
|
|
|
message = choice["message"]
|
|
|
|
|
|
content = _text_content(message.get("content"))
|
|
|
|
|
|
reasoning_content = message.get("reasoning_content") or message.get("reasoning")
|
|
|
|
|
|
inline_thinking = re.fullmatch(r"\s*<think>(.*?)</think>\s*(.*)", content, flags=re.DOTALL)
|
|
|
|
|
|
if inline_thinking:
|
|
|
|
|
|
reasoning_content = reasoning_content or inline_thinking.group(1).strip()
|
|
|
|
|
|
content = inline_thinking.group(2)
|
|
|
|
|
|
return {
|
|
|
|
|
|
"content": content,
|
|
|
|
|
|
"reasoning_content": reasoning_content,
|
|
|
|
|
|
"finish_reason": choice.get("finish_reason"),
|
|
|
|
|
|
"usage": raw_response.get("usage") or {},
|
|
|
|
|
|
"raw_response": raw_response,
|
|
|
|
|
|
}
|
|
|
|
|
|
except (KeyError, IndexError, TypeError, AttributeError, ValueError) as exc:
|
|
|
|
|
|
raise QwenClientError("Qwen response has no valid chat completion", raw_response=raw_response) from exc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _parse_structured(content: str) -> dict[str, Any] | list[Any] | None:
|
|
|
|
|
|
candidate = content.strip()
|
|
|
|
|
|
fenced = re.fullmatch(r"```(?:json)?\s*(.*?)\s*```", candidate, flags=re.DOTALL | re.IGNORECASE)
|
|
|
|
|
|
if fenced:
|
|
|
|
|
|
candidate = fenced.group(1)
|
|
|
|
|
|
try:
|
|
|
|
|
|
parsed = json.loads(candidate)
|
|
|
|
|
|
except ValueError:
|
|
|
|
|
|
return None
|
|
|
|
|
|
return parsed if isinstance(parsed, (dict, list)) else None
|