# SPDX-License-Identifier: MulanPSL-2.0
"""Minimal async OpenAI-compatible client, configured by the VLM_* variables
the VLM detector also reads."""
from __future__ import annotations
import json
import logging
import os
import re
from typing import Any
import httpx
from robonix_api.llm import (
Requirements,
api_key_for,
explicit_env_set,
metrics,
resolve_from_env,
)
log = logging.getLogger(__name__)
[docs]
class SceneGraphLLMClient:
"""Chat-completions wrapper that never raises: failures return {}."""
def __init__(
self,
*,
base_url: str | None = None,
api_key: str | None = None,
model: str | None = None,
timeout: float = 30.0,
reasoning_effort: str | None = None,
) -> None:
target = None
# Constructor arguments are explicit, as is a deployment VLM_BASE_URL.
# Environment keys alone may be ones the catalog launcher forwarded.
explicit = any(
(value or "").strip() for value in (base_url, api_key, model)
) or explicit_env_set("VLM_BASE_URL")
if not explicit:
# The graph client also serves the image-relation and caption
# paths, so vision is the hard requirement.
target = resolve_from_env(Requirements(features=("vision",)))
self.requires_key = True
if target is not None:
self.base_url = target.base_url
self.api_key = api_key_for(target)
self.model = target.model
self.requires_key = target.api_key_env is not None
log.info(
"[scene-graph-llm] catalog target %s model=%s",
target.id,
target.model,
)
else:
self.base_url = (
base_url
or os.environ.get("VLM_BASE_URL")
or os.environ.get("OPENAI_BASE_URL")
or ""
).strip().rstrip("/")
self.api_key = (
api_key
or os.environ.get("VLM_API_KEY")
or os.environ.get("OPENAI_API_KEY")
or ""
).strip()
self.model = (
model
or os.environ.get("VLM_MODEL")
or os.environ.get("OPENAI_MODEL")
or "gpt-4o-mini"
).strip()
self.timeout = timeout
# Sent only when set: providers without reasoning reject the field.
if reasoning_effort is not None:
self.reasoning_effort = reasoning_effort.strip()
else:
self.reasoning_effort = os.environ.get("VLM_REASONING_EFFORT", "").strip()
if self.requires_key and not self.api_key:
log.warning(
"[scene-graph-llm] VLM_API_KEY not set; "
"relation inference will return 'unknown'"
)
@property
def available(self) -> bool:
return bool(self.base_url) and (
bool(self.api_key) or not self.requires_key
)
[docs]
async def chat_json(
self,
system_prompt: str,
user_message: str,
*,
timeout: float | None = None,
images: list[str] | None = None,
operation: str,
) -> dict[str, Any]:
"""One request expecting a JSON object reply; {} on any failure.
`images` are base64 JPEGs sent as multimodal parts of the user turn.
`operation` names the request in the LLM metrics record."""
if not self.available:
return {}
url = f"{self.base_url}/chat/completions"
headers = {"Content-Type": "application/json"}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
if images:
user_content: Any = [{"type": "text", "text": user_message}]
for img in images:
user_content.append({
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{img}"},
})
else:
user_content = user_message
body: dict[str, Any] = {
"model": self.model,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_content},
],
"temperature": 0.0,
}
if self.reasoning_effort:
body["reasoning_effort"] = self.reasoning_effort
try:
with metrics.Call("scene", operation, self.base_url, self.model) as call:
async with httpx.AsyncClient(
timeout=timeout or self.timeout
) as client:
r = await client.post(url, json=body, headers=headers)
call.finish(r)
if r.status_code >= 400:
log.warning(
"[scene-graph-llm] HTTP %d: %s",
r.status_code,
r.text[:200],
)
return {}
data = r.json()
except (httpx.HTTPError, Exception) as e: # noqa: BLE001
# The type matters: a read timeout's str() is empty.
log.warning(
"[scene-graph-llm] request failed: %s: %s",
type(e).__name__,
e,
)
return {}
try:
text = data["choices"][0]["message"]["content"]
except (KeyError, IndexError):
log.debug("[scene-graph-llm] unexpected response shape")
return {}
# Strip markdown fences if the model added them.
text = re.sub(
r"^```(?:json)?\s*|\s*```$", "", text.strip(), flags=re.MULTILINE
)
try:
obj = json.loads(text)
except json.JSONDecodeError:
log.debug("[scene-graph-llm] non-JSON response: %s", text[:200])
return {}
return obj if isinstance(obj, dict) else {}