Files
ecs-relay-service/patch-source/a8137fe7e675b0a9/hainuo-relay/relay/hainuo1065.py
T

108 lines
5.5 KiB
Python

"""Adapter for the native API actually found in installer 1.065.
Loopback only, independent API key, no platform secrets, no redirects or retries.
The included native launcher offers only text inference with no tools.
"""
import hashlib
import json
import re
from pathlib import Path
from urllib.parse import urlsplit
import httpx
class NativeAPIError(RuntimeError):
"""Contains a sanitized status only, never response body or credentials."""
def read_native_config(path):
path = Path(path)
data = json.loads(path.read_text(encoding="utf-8-sig"))
url = data.get("url", "")
parts = urlsplit(url)
if (parts.scheme != "http" or parts.hostname != "127.0.0.1" or not parts.port
or parts.username or parts.password or parts.query or parts.fragment
or parts.path not in {"", "/"}):
raise ValueError("native API must be a fixed IPv4 loopback HTTP base URL")
if not isinstance(data.get("api_key"), str) or len(data["api_key"]) < 32:
raise ValueError("native API requires a dedicated key of at least 32 characters")
if data.get("mode") not in {"text-only", "profile-tools"}:
raise ValueError("unsupported native API mode")
data["url"] = url.rstrip("/")
return data
class Hainuo1065Agent:
def __init__(self, config_path, transport=None):
self.config = read_native_config(config_path)
self.http = httpx.AsyncClient(base_url=self.config["url"], timeout=120,
follow_redirects=False, trust_env=False, transport=transport)
self.headers = {"Authorization": "Bearer " + self.config["api_key"]}
async def _json(self, method, path, **kwargs):
try:
async with self.http.stream(method, path, headers={**self.headers, **kwargs.pop("headers", {})}, **kwargs) as response:
if response.status_code != 200:
raise NativeAPIError(f"native API HTTP {response.status_code}")
body = bytearray()
async for chunk in response.aiter_bytes():
body.extend(chunk)
if len(body) > 262144:
raise NativeAPIError("native API response exceeds limit")
data = json.loads(body)
if not isinstance(data, dict):
raise NativeAPIError("native API response is not an object")
return data
except (httpx.HTTPError, ValueError):
raise NativeAPIError("native API connection/JSON failure") from None
async def probe(self):
health = await self._json("GET", "/health")
if health.get("platform") != "hermes-agent" or health.get("status") != "ok":
raise NativeAPIError("endpoint is not the native Hermes API")
capabilities = await self._json("GET", "/v1/capabilities")
policy = capabilities.get("hainuo_relay_policy", {})
# A stock unrestricted API endpoint is deliberately not sufficient.
expected_mode = self.config["mode"]
expected_tools = "profile" if expected_mode == "profile-tools" else "disabled"
if policy != {"mode": expected_mode, "tools": expected_tools, "contract": "hainuo-1065-v1"}:
raise NativeAPIError("native API policy missing; start the supplied restricted launcher")
models = await self._json("GET", "/v1/models")
model = self.config.get("model")
available = models.get("data")
if not isinstance(available, list) or not available or not all(isinstance(x, dict) and isinstance(x.get("id"), str) for x in available):
raise NativeAPIError("native model list invalid")
if model and model not in {x["id"] for x in available}:
raise NativeAPIError("configured model alias unavailable")
self.model = model or available[0]["id"]
return {"status": "ready", "platform": "hermes-agent", "model": self.model,
"mode": expected_mode, "version": health.get("version", "unknown")}
async def execute(self, text, owner, turn):
try:
# Recheck the actual local service before each inference, including reconnects.
await self.probe()
digest = hashlib.sha256((owner + "\0" + turn).encode()).hexdigest()
data = await self._json("POST", "/v1/chat/completions",
headers={"Idempotency-Key": "hn-" + digest},
json={"model": self.model, "stream": False,
"messages": [{"role": "user", "content": text}]})
choices = data.get("choices")
if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
raise NativeAPIError("native completion choices missing")
choice = choices[0]
message = choice.get("message", {})
if (choice.get("finish_reason") != "stop" or message.get("tool_calls")
or not isinstance(message.get("content"), str)
or data.get("hermes", {}).get("failed")
or data.get("hermes", {}).get("partial")):
raise NativeAPIError("native completion incomplete or unexpected tool call")
return message["content"][:16000]
except NativeAPIError as error:
# Safe generated error strings only; never echo upstream model/API errors.
return "海诺原生接口未完成请求:" + str(error) + "。未自动重试。"
async def close(self):
await self.http.aclose()