|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +"""Shared core for OpenAI-dialect backend handlers. |
| 3 | +
|
| 4 | +vLLM, llama.cpp, LM Studio and Ollama all speak the OpenAI `/v1/*` HTTP dialect, so |
| 5 | +the request/response plumbing is identical — only the default port and the engine |
| 6 | +label in error messages differ. This module hosts that shared plumbing so the |
| 7 | +per-engine modules (`openai_compat`, `vllm`, `llamacpp`) stay thin and a new engine |
| 8 | +is one factory call, not a copy of the whole handler. |
| 9 | +
|
| 10 | +Port of iicp-adapter `backends/{base,vllm,llamacpp,openai_compat}.py` into the SDK's |
| 11 | +handler-factory style (tracker iicp.network#340; parity Block B). |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import logging |
| 17 | +from collections.abc import Awaitable, Callable |
| 18 | +from typing import Any |
| 19 | + |
| 20 | +import httpx |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | +TaskHandler = Callable[[dict[str, Any]], Awaitable[dict[str, Any]]] |
| 25 | + |
| 26 | +# Maps IICP intent URN → OpenAI-compatible HTTP path. |
| 27 | +INTENT_TO_PATH: dict[str, str] = { |
| 28 | + "urn:iicp:intent:llm:chat:v1": "/chat/completions", |
| 29 | + "urn:iicp:intent:llm:completion:v1": "/completions", |
| 30 | + "urn:iicp:intent:llm:embedding:v1": "/embeddings", |
| 31 | +} |
| 32 | + |
| 33 | + |
| 34 | +def build_openai_dialect_handler( |
| 35 | + *, |
| 36 | + engine: str, |
| 37 | + base_url: str, |
| 38 | + model: str | None, |
| 39 | + api_key: str, |
| 40 | + timeout_s: float, |
| 41 | +) -> TaskHandler: |
| 42 | + """Build a TaskHandler that proxies CALLs to an OpenAI-dialect server. |
| 43 | +
|
| 44 | + `engine` is the label used in error messages (e.g. "vllm"). All engines share |
| 45 | + this body; the per-engine modules differ only in their default `base_url`. |
| 46 | + """ |
| 47 | + base = base_url.rstrip("/") |
| 48 | + headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} |
| 49 | + |
| 50 | + async def handler(task: dict[str, Any]) -> dict[str, Any]: |
| 51 | + intent = str(task.get("intent", "")) |
| 52 | + payload = task.get("payload") or {} |
| 53 | + if not isinstance(payload, dict): |
| 54 | + return { |
| 55 | + "error_code": 400, |
| 56 | + "error_message": ( |
| 57 | + f"{engine}: task.payload must be a dict, got {type(payload).__name__}" |
| 58 | + ), |
| 59 | + } |
| 60 | + |
| 61 | + path = INTENT_TO_PATH.get(intent) |
| 62 | + if path is None: |
| 63 | + return { |
| 64 | + "error_code": 400, |
| 65 | + "error_message": ( |
| 66 | + f"{engine}: unsupported intent {intent!r}; " |
| 67 | + f"supported: {sorted(INTENT_TO_PATH.keys())}" |
| 68 | + ), |
| 69 | + } |
| 70 | + |
| 71 | + # Merge model: explicit task payload field wins; factory default fills in. |
| 72 | + body = dict(payload) |
| 73 | + body.setdefault("model", model) |
| 74 | + if not body.get("model"): |
| 75 | + return { |
| 76 | + "error_code": 400, |
| 77 | + "error_message": ( |
| 78 | + f"{engine}: no model — either pass `model=...` to the backend " |
| 79 | + "factory or include `model` in the task payload" |
| 80 | + ), |
| 81 | + } |
| 82 | + |
| 83 | + try: |
| 84 | + async with httpx.AsyncClient(timeout=timeout_s, headers=headers) as client: |
| 85 | + r = await client.post(f"{base}{path}", json=body) |
| 86 | + except httpx.TimeoutException: |
| 87 | + return {"error_code": 408, "error_message": f"{engine}: backend timed out"} |
| 88 | + except httpx.HTTPError as exc: |
| 89 | + return { |
| 90 | + "error_code": 502, |
| 91 | + "error_message": f"{engine}: HTTP transport error: {exc}", |
| 92 | + } |
| 93 | + |
| 94 | + if r.status_code >= 400: |
| 95 | + # Surface the upstream error verbatim — operators usually need the |
| 96 | + # original message (rate-limit, model-not-loaded, etc.) |
| 97 | + return { |
| 98 | + "error_code": r.status_code, |
| 99 | + "error_message": f"{engine}: upstream {r.status_code}: {r.text[:512]}", |
| 100 | + } |
| 101 | + |
| 102 | + try: |
| 103 | + data = r.json() |
| 104 | + except ValueError as exc: |
| 105 | + return { |
| 106 | + "error_code": 502, |
| 107 | + "error_message": f"{engine}: upstream returned non-JSON: {exc}", |
| 108 | + } |
| 109 | + |
| 110 | + return {"result": data} |
| 111 | + |
| 112 | + return handler |
0 commit comments