Files
CyberGril/src/cybergril/providers/embedding/openai_compat.py
T
mobai 1012d8bb79 chore: project foundation
Contracts (the shared language):
- percept / state / context / utterance / render / audio / capabilities
- Capability model instead of vendor schemas (see below)

Providers (capability-based abstraction):
- LLM + Embedding: OpenAI-compatible shape IS the standard, adopted directly
- ASR: internal contract is an event stream (partial -> final), because
  /v1/audio/transcriptions has no partial and dialogue needs it for
  endpointing. OpenAI adapter degrades to supports_partial=False.
- TTS: internal contract carries tags/emotion/style, because
  /v1/audio/speech has no paralinguistics and [laughter]/[breath] are
  the core of feeling alive. Unsupported providers are stripped AND
  reported via Degradation -- silent degradation is forbidden.
- Avatar: no de-facto standard, custom RenderCmd protocol driven by State.

Core:
- mood: dynamical system, slow variables, negativity bias (grudge),
  numbing after prolonged negativity
- bazi: four pillars -> numeric vector; 'ming' is data, not prose
- projection: phi, system event -> in-world statement; uncovered events
  are counted as projection gaps

Storage:
- SQLite schema, three memory layers, dyad ledger
- accessibility floor 0.03 (not 0): forgettable but still there

Config split:
- models.yaml is the ONLY place model versions live
- character.yaml holds world rules / emotion params, no version numbers

58 tests pass; ruff clean.
2026-10-19 20:08:52 +08:00

74 lines
2.3 KiB
Python

"""OpenAI 兼容的 embedding 适配器。
覆盖 OpenAI / Qwen / vLLM / Ollama / 以及任何实现了 /v1/embeddings 的服务。
"""
from __future__ import annotations
import httpx
from ...contracts import Capabilities, HealthStatus, Modality
from ..base import ProviderError
from .base import EmbeddingProvider
class OpenAICompatEmbedding(EmbeddingProvider):
name = "openai_compat"
def __init__(
self,
*,
base_url: str,
model: str,
api_key: str | None = None,
dim: int = 1024,
timeout: float = 30.0,
) -> None:
self.model = model
self._dim = dim
headers = {"Content-Type": "application/json"}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
self._client = httpx.AsyncClient(
base_url=base_url.rstrip("/"),
timeout=httpx.Timeout(timeout, connect=10.0),
headers=headers,
)
@property
def capabilities(self) -> Capabilities:
return Capabilities(modality=Modality.VECTOR, extra={"dim": self._dim})
async def health(self) -> HealthStatus:
try:
r = await self._client.get("/models", timeout=5.0)
return HealthStatus(ok=r.status_code < 500, detail=str(r.status_code))
except httpx.HTTPError as exc:
return HealthStatus(ok=False, detail=f"{type(exc).__name__}: {exc}")
async def embed(self, texts: list[str]) -> list[list[float]]:
if not texts:
return []
try:
r = await self._client.post(
"/embeddings", json={"model": self.model, "input": texts}
)
except httpx.HTTPError as exc:
raise ProviderError(f"embedding 请求失败: {exc}") from exc
if r.status_code >= 400:
raise ProviderError(f"embedding HTTP {r.status_code}: {r.text[:300]}")
data = r.json().get("data", [])
# 按 index 排序,防止服务端乱序
data = sorted(data, key=lambda d: d.get("index", 0))
vectors = [d["embedding"] for d in data]
if len(vectors) != len(texts):
raise ProviderError(
f"embedding 数量不匹配: 请求 {len(texts)},返回 {len(vectors)}"
)
return vectors
async def aclose(self) -> None:
await self._client.aclose()