modelsaar 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- modelsaar/__init__.py +13 -0
- modelsaar/adapters/__init__.py +27 -0
- modelsaar/adapters/base.py +274 -0
- modelsaar/adapters/ollama.py +317 -0
- modelsaar/adapters/openai_compat.py +296 -0
- modelsaar/catalogue/__init__.py +72 -0
- modelsaar/catalogue/starter.yaml +435 -0
- modelsaar/cli.py +880 -0
- modelsaar/clientconfig/__init__.py +364 -0
- modelsaar/config.py +631 -0
- modelsaar/doctor.py +233 -0
- modelsaar/evaluation/__init__.py +1 -0
- modelsaar/evaluation/fixtures/tasks.jsonl +47 -0
- modelsaar/evaluation/harness.py +768 -0
- modelsaar/evaluation/judge.py +173 -0
- modelsaar/evaluation/sandbox.py +341 -0
- modelsaar/evaluation/scoring.py +233 -0
- modelsaar/learning.py +227 -0
- modelsaar/lifecycle.py +208 -0
- modelsaar/pipelines.py +439 -0
- modelsaar/probes.py +526 -0
- modelsaar/protocol/__init__.py +1 -0
- modelsaar/protocol/anthropic.py +401 -0
- modelsaar/protocol/decisions.py +229 -0
- modelsaar/protocol/openai.py +322 -0
- modelsaar/protocol/responses.py +560 -0
- modelsaar/protocol/sse.py +181 -0
- modelsaar/registry.py +229 -0
- modelsaar/responses_store.py +117 -0
- modelsaar/routing/__init__.py +1 -0
- modelsaar/routing/admission.py +359 -0
- modelsaar/routing/affinity.py +131 -0
- modelsaar/routing/cascade.py +53 -0
- modelsaar/routing/classifier.py +298 -0
- modelsaar/routing/decision.py +85 -0
- modelsaar/routing/eligibility.py +158 -0
- modelsaar/routing/requirements.py +290 -0
- modelsaar/routing/router.py +1026 -0
- modelsaar/routing/scoring.py +179 -0
- modelsaar/routing/tokens.py +114 -0
- modelsaar/runtime.py +82 -0
- modelsaar/security.py +63 -0
- modelsaar/server.py +1546 -0
- modelsaar/static/status.html +95 -0
- modelsaar/store.py +208 -0
- modelsaar/testing/__init__.py +1 -0
- modelsaar/testing/fakebackend.py +661 -0
- modelsaar-0.2.0.dist-info/METADATA +285 -0
- modelsaar-0.2.0.dist-info/RECORD +54 -0
- modelsaar-0.2.0.dist-info/WHEEL +5 -0
- modelsaar-0.2.0.dist-info/entry_points.txt +2 -0
- modelsaar-0.2.0.dist-info/licenses/LICENSE +202 -0
- modelsaar-0.2.0.dist-info/licenses/NOTICE +18 -0
- modelsaar-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
"""A controllable fake inference backend that speaks Ollama's native metadata
|
|
2
|
+
API and the OpenAI-compatible chat/embeddings API.
|
|
3
|
+
|
|
4
|
+
It is used by the contract/fault-injection test suite and by ``modelsaar demo``
|
|
5
|
+
(clearly labelled SIMULATED). Behaviours are deterministic and can be changed
|
|
6
|
+
per model at runtime:
|
|
7
|
+
|
|
8
|
+
ok | error_500 | fail_mid_stream | truncate_stream | slow | stall | hang | bad_json | unsupported_tools
|
|
9
|
+
|
|
10
|
+
Responses are synthetic: a model "answers" by echoing structural facts, calls
|
|
11
|
+
a tool when one is offered, emits schema-conformant JSON when asked, and
|
|
12
|
+
reports "red" for the embedded 1x1 probe image if it has the vision capability.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import asyncio
|
|
18
|
+
import json
|
|
19
|
+
import re
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
from collections.abc import AsyncIterator
|
|
23
|
+
from dataclasses import dataclass, field
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
import uvicorn
|
|
27
|
+
from starlette.applications import Starlette
|
|
28
|
+
from starlette.requests import Request
|
|
29
|
+
from starlette.responses import JSONResponse, Response, StreamingResponse
|
|
30
|
+
from starlette.routing import Route
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class FakeModel:
|
|
35
|
+
name: str
|
|
36
|
+
capabilities: list[str] = field(default_factory=lambda: ["completion"])
|
|
37
|
+
context_length: int = 8192
|
|
38
|
+
family: str = "fake"
|
|
39
|
+
parameter_size: str = "1.0B"
|
|
40
|
+
quantization: str = "Q4_K_M"
|
|
41
|
+
size_bytes: int = 700_000_000
|
|
42
|
+
behaviour: str = "ok"
|
|
43
|
+
# Simulated per-token delay in seconds (for latency/perf tests).
|
|
44
|
+
token_delay_s: float = 0.0
|
|
45
|
+
remote: bool = False
|
|
46
|
+
loaded: bool = False
|
|
47
|
+
# Simulated "skill": which tasks this model answers correctly in the eval harness.
|
|
48
|
+
good_at: list[str] = field(default_factory=list)
|
|
49
|
+
json_schema_ok: bool = True
|
|
50
|
+
embedding_dimensions: int = 8
|
|
51
|
+
normalize_embeddings: bool = True
|
|
52
|
+
template: str = "{{ .Prompt }}"
|
|
53
|
+
# Simulated thinking model: spends this many output tokens on reasoning before answering.
|
|
54
|
+
thinking_tokens: int = 0
|
|
55
|
+
# Simulated decision model (capability "decision", served at /v1/systemone): the option it picks for a
|
|
56
|
+
# ``choice`` question when that option exists in the criteria (otherwise the first option), and the
|
|
57
|
+
# probability it assigns to it (the rest is spread evenly over the other options).
|
|
58
|
+
decides: str = ""
|
|
59
|
+
decision_probability: float = 0.9
|
|
60
|
+
# Simulated backend that refuses ``reasoning_content`` on assistant messages in the history (HTTP 400),
|
|
61
|
+
# the way a strict OpenAI-compatible layer would; used by the continuation-probe tests.
|
|
62
|
+
reject_reasoning_history: bool = False
|
|
63
|
+
# Whether the Modelfile sets num_ctx (reported by /api/show). False = the runtime's server default
|
|
64
|
+
# applies, which Ollama does not expose for an unloaded model.
|
|
65
|
+
modelfile_num_ctx: bool = True
|
|
66
|
+
# Simulated LLM judge that always answers PASS or FAIL regardless of the answer ("" = look at the answer).
|
|
67
|
+
judge_always: str = ""
|
|
68
|
+
# Simulated ballot for POST /v1/vote ("" = the first option; "OUT-OF-SET" = an answer outside the choices).
|
|
69
|
+
votes: str = ""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _expected_json(text: str) -> dict[str, Any]:
|
|
73
|
+
em = re.search(r"[\w.]+@[\w.]+", text)
|
|
74
|
+
am = re.search(r"\b(\d{2})\b", text)
|
|
75
|
+
return {"name": "Person", "email": em.group(0).rstrip(".;") if em else "", "age": int(am.group(1)) if am else 0}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
_GOLD = {
|
|
79
|
+
"math": lambda t: "391" if "17 * 23" in t else "72" if "180 km" in t else "6" if "3x + 7" in t else "55" if "first 10" in t else "50" if "perimeter 30" in t else "144" if "12 × 12" in t else "yes",
|
|
80
|
+
"translation": lambda t: "La bibliothèque ouvre à neuf heures demain." if "library" in t else "¿Dónde está la estación de tren más cercana?" if "train station" in t else "The train is twenty minutes late.",
|
|
81
|
+
"rag": lambda t: "2019" if "repainted" in t.split("Question:")[-1] else "410 metres" if "long" in t.split("Question:")[-1] else "harbour blue",
|
|
82
|
+
"decision": lambda t: "negative" if "sentiment" in t else "account" if "password" in t else "sports",
|
|
83
|
+
"summarization": lambda t: "LINE 0: THE QUICK BROWN FOX" if "uppercase" in t else "The council approved a six-month bicycle lane trial with a parking review.",
|
|
84
|
+
"conversation": lambda t: "pineapple" if "pineapple" in t else "They weigh the same - both are one kilogram." if "feathers" in t else "La fotosíntesis es el proceso por el que las plantas usan la luz del sol para producir energía." if "fotosíntesis" in t else "Here is a friendly answer.",
|
|
85
|
+
"coding": lambda t: _gold_code(t),
|
|
86
|
+
"document_vision": lambda t: "red",
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _gold_code(t: str) -> str:
|
|
91
|
+
if "is_palindrome" in t:
|
|
92
|
+
return "```python\nimport re\ndef is_palindrome(s):\n s = re.sub(r'[^a-z0-9]', '', s.lower())\n return s == s[::-1]\n```"
|
|
93
|
+
if "fizzbuzz" in t:
|
|
94
|
+
return "```python\ndef fizzbuzz(n):\n return ['FizzBuzz' if i%15==0 else 'Fizz' if i%3==0 else 'Buzz' if i%5==0 else str(i) for i in range(1,n+1)]\n```"
|
|
95
|
+
if "word_freq" in t:
|
|
96
|
+
return "```python\ndef word_freq(text):\n d={}\n for w in text.split():\n w=w.strip('.,!?').lower()\n d[w]=d.get(w,0)+1\n return d\n```"
|
|
97
|
+
if "def mean" in t:
|
|
98
|
+
return "```python\ndef mean(xs):\n return sum(xs) / len(xs)\n```"
|
|
99
|
+
if "rle" in t:
|
|
100
|
+
return "```python\ndef rle(s):\n out=''\n i=0\n while i<len(s):\n j=i\n while j<len(s) and s[j]==s[i]: j+=1\n out+=s[i]+str(j-i); i=j\n return out\n```"
|
|
101
|
+
return "It matches three digits, a hyphen, then four digits (undefined is not a function is a JavaScript error)."
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _gold_tool_args(fn: dict[str, Any], text: str) -> dict[str, Any]:
|
|
105
|
+
"""Arguments a competent agent would pass for the eval fixtures: every required parameter
|
|
106
|
+
of the offered tool is filled with a task-appropriate value (the strict ``tool_call`` scorer
|
|
107
|
+
rejects calls that lack required arguments or the expected substrings)."""
|
|
108
|
+
low = text.lower()
|
|
109
|
+
required = list(((fn.get("parameters") or {}).get("required")) or [])
|
|
110
|
+
args: dict[str, Any] = {}
|
|
111
|
+
for key in required:
|
|
112
|
+
if key == "command":
|
|
113
|
+
args[key] = "pytest -q" if "pytest" in low else "git status" if "git" in low else "ls"
|
|
114
|
+
elif key == "path":
|
|
115
|
+
args[key] = "README.md" if "readme" in low else "pyproject.toml" if "pyproject" in low else "."
|
|
116
|
+
else:
|
|
117
|
+
args[key] = "x"
|
|
118
|
+
return args
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _expected_text(task: str, text: str, ok: bool, name: str) -> str:
|
|
122
|
+
if not ok:
|
|
123
|
+
return f"I am not sure about that. ({name})"
|
|
124
|
+
fn = _GOLD.get(task)
|
|
125
|
+
return fn(text) if fn else f"Answer from {name}."
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class FakeBackend:
|
|
129
|
+
def __init__(self, models: list[FakeModel], version: str = "0.0.0-fake", flavor: str = "ollama") -> None:
|
|
130
|
+
self.models: dict[str, FakeModel] = {m.name: m for m in models}
|
|
131
|
+
self.version = version
|
|
132
|
+
# "ollama" (default; also answers the generic OpenAI-compatible paths), "vllm" (/v1/models carries
|
|
133
|
+
# max_model_len, /tokenize accepts messages) or "llamacpp" (/props, /apply-template, /tokenize {content}).
|
|
134
|
+
self.flavor = flavor
|
|
135
|
+
# Served context reported by /api/ps for loaded models (None = the model's context_length).
|
|
136
|
+
self.ps_context: dict[str, int] = {}
|
|
137
|
+
self.layout_boxes: list[dict[str, Any]] | None = None # scripted layout result (None = the service fails)
|
|
138
|
+
self.layout_raw: bytes | None = None # a raw answer body (e.g. one carrying NaN), served as is
|
|
139
|
+
self.layout_requests: list[dict[str, Any]] = []
|
|
140
|
+
self.embedding_requests: list[dict[str, Any]] = [] # metadata only (model, form, kinds)
|
|
141
|
+
self.lifecycle_requests: list[dict[str, Any]] = [] # load/unload calls (metadata only)
|
|
142
|
+
self.active = 0
|
|
143
|
+
self.max_active = 0
|
|
144
|
+
self.requests: list[dict[str, Any]] = [] # metadata only (model, stream, has_tools)
|
|
145
|
+
self.tokenize_requests: list[dict[str, Any]] = [] # metadata only (model, chars)
|
|
146
|
+
self._lock = threading.Lock()
|
|
147
|
+
self.app = self._build()
|
|
148
|
+
self._server: uvicorn.Server | None = None
|
|
149
|
+
self._thread: threading.Thread | None = None
|
|
150
|
+
self.port: int = 0
|
|
151
|
+
|
|
152
|
+
# ---------------------------------------------------------------- #
|
|
153
|
+
def _build(self) -> Starlette:
|
|
154
|
+
return Starlette(
|
|
155
|
+
routes=[
|
|
156
|
+
Route("/api/version", self.api_version, methods=["GET"]),
|
|
157
|
+
Route("/api/tags", self.api_tags, methods=["GET"]),
|
|
158
|
+
Route("/api/show", self.api_show, methods=["POST"]),
|
|
159
|
+
Route("/api/ps", self.api_ps, methods=["GET"]),
|
|
160
|
+
Route("/v1/models", self.v1_models, methods=["GET"]),
|
|
161
|
+
Route("/models", self.v1_models, methods=["GET"]),
|
|
162
|
+
Route("/v1/chat/completions", self.v1_chat, methods=["POST"]),
|
|
163
|
+
Route("/chat/completions", self.v1_chat, methods=["POST"]),
|
|
164
|
+
Route("/v1/embeddings", self.v1_embeddings, methods=["POST"]),
|
|
165
|
+
Route("/embeddings", self.v1_embeddings, methods=["POST"]),
|
|
166
|
+
Route("/tokenize", self.tokenize, methods=["POST"]),
|
|
167
|
+
Route("/props", self.props, methods=["GET"]),
|
|
168
|
+
Route("/layout-analysis", self.layout, methods=["POST"]),
|
|
169
|
+
Route("/object-detection", self.layout, methods=["POST"]),
|
|
170
|
+
Route("/api/generate", self.api_generate, methods=["POST"]),
|
|
171
|
+
Route("/running", self.swap_running, methods=["GET"]),
|
|
172
|
+
Route("/api/models/unload/{model:path}", self.swap_unload, methods=["POST"]),
|
|
173
|
+
Route("/apply-template", self.apply_template, methods=["POST"]),
|
|
174
|
+
Route("/v1/systemone", self.v1_systemone, methods=["POST"]),
|
|
175
|
+
]
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
async def api_version(self, request: Request) -> Response:
|
|
179
|
+
return JSONResponse({"version": self.version})
|
|
180
|
+
|
|
181
|
+
async def api_tags(self, request: Request) -> Response:
|
|
182
|
+
out = []
|
|
183
|
+
for m in self.models.values():
|
|
184
|
+
d: dict[str, Any] = {
|
|
185
|
+
"name": m.name,
|
|
186
|
+
"model": m.name,
|
|
187
|
+
"size": m.size_bytes,
|
|
188
|
+
"digest": f"sha256:{abs(hash((m.name, m.template, m.quantization))) % (10**12):012d}",
|
|
189
|
+
"details": {
|
|
190
|
+
"family": m.family,
|
|
191
|
+
"parameter_size": m.parameter_size,
|
|
192
|
+
"quantization_level": m.quantization,
|
|
193
|
+
},
|
|
194
|
+
}
|
|
195
|
+
if m.remote:
|
|
196
|
+
d["remote_model"] = m.name
|
|
197
|
+
d["remote_host"] = "https://ollama.com"
|
|
198
|
+
out.append(d)
|
|
199
|
+
return JSONResponse({"models": out})
|
|
200
|
+
|
|
201
|
+
async def api_show(self, request: Request) -> Response:
|
|
202
|
+
body = await request.json()
|
|
203
|
+
m = self.models.get(body.get("model") or body.get("name"))
|
|
204
|
+
if not m:
|
|
205
|
+
return JSONResponse({"error": "model not found"}, status_code=404)
|
|
206
|
+
return JSONResponse(
|
|
207
|
+
{
|
|
208
|
+
"capabilities": m.capabilities,
|
|
209
|
+
"details": {"family": m.family, "parameter_size": m.parameter_size, "quantization_level": m.quantization},
|
|
210
|
+
"model_info": {
|
|
211
|
+
"general.architecture": m.family,
|
|
212
|
+
f"{m.family}.context_length": m.context_length,
|
|
213
|
+
f"{m.family}.embedding_length": m.embedding_dimensions,
|
|
214
|
+
},
|
|
215
|
+
"template": m.template,
|
|
216
|
+
"parameters": f"num_ctx {m.context_length}" if m.modelfile_num_ctx else "temperature 0.7",
|
|
217
|
+
"license": "fake-licence",
|
|
218
|
+
}
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
async def api_ps(self, request: Request) -> Response:
|
|
222
|
+
return JSONResponse(
|
|
223
|
+
{
|
|
224
|
+
"models": [
|
|
225
|
+
{"name": m.name, "model": m.name, "size": m.size_bytes, "size_vram": m.size_bytes, "context_length": self.ps_context.get(m.name, m.context_length)}
|
|
226
|
+
for m in self.models.values()
|
|
227
|
+
if m.loaded
|
|
228
|
+
]
|
|
229
|
+
}
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
async def v1_models(self, request: Request) -> Response:
|
|
233
|
+
extra = (lambda m: {"max_model_len": m.context_length}) if self.flavor == "vllm" else (lambda m: {})
|
|
234
|
+
return JSONResponse({"object": "list", "data": [{"id": m.name, "object": "model", **extra(m)} for m in self.models.values()]})
|
|
235
|
+
|
|
236
|
+
async def api_generate(self, request: Request) -> Response:
|
|
237
|
+
"""Ollama's prompt-less generate: load (optionally with keep_alive) or unload (keep_alive 0)."""
|
|
238
|
+
body = await request.json()
|
|
239
|
+
m = self.models.get(body.get("model"))
|
|
240
|
+
if not m:
|
|
241
|
+
return JSONResponse({"error": "model not found"}, status_code=404)
|
|
242
|
+
self.lifecycle_requests.append({"model": m.name, "keep_alive": body.get("keep_alive"), "has_prompt": bool(body.get("prompt"))})
|
|
243
|
+
if m.behaviour == "error_500":
|
|
244
|
+
return JSONResponse({"error": "simulated load failure"}, status_code=500)
|
|
245
|
+
if m.behaviour == "slow":
|
|
246
|
+
await asyncio.sleep(0.6)
|
|
247
|
+
if body.get("keep_alive") == 0:
|
|
248
|
+
m.loaded = False
|
|
249
|
+
return JSONResponse({"model": m.name, "done": True, "done_reason": "unload"})
|
|
250
|
+
m.loaded = True
|
|
251
|
+
return JSONResponse({"model": m.name, "done": True, "done_reason": "load"})
|
|
252
|
+
|
|
253
|
+
async def swap_running(self, request: Request) -> Response:
|
|
254
|
+
if self.flavor != "llamaswap":
|
|
255
|
+
return JSONResponse({"error": "not found"}, status_code=404)
|
|
256
|
+
return JSONResponse({"running": [{"model": m.name, "state": "ready"} for m in self.models.values() if m.loaded]})
|
|
257
|
+
|
|
258
|
+
async def swap_unload(self, request: Request) -> Response:
|
|
259
|
+
if self.flavor != "llamaswap":
|
|
260
|
+
return JSONResponse({"error": "not found"}, status_code=404)
|
|
261
|
+
m = self.models.get(request.path_params["model"])
|
|
262
|
+
if not m:
|
|
263
|
+
return JSONResponse({"error": "model not found"}, status_code=404)
|
|
264
|
+
self.lifecycle_requests.append({"model": m.name, "keep_alive": 0, "via": "llama-swap"})
|
|
265
|
+
m.loaded = False
|
|
266
|
+
return JSONResponse({"msg": "ok"})
|
|
267
|
+
|
|
268
|
+
async def layout(self, request: Request) -> Response:
|
|
269
|
+
"""A layout-detection service in the two answer shapes the gateway understands (scripted boxes)."""
|
|
270
|
+
body = await request.json()
|
|
271
|
+
self.layout_requests.append({"path": request.url.path, "fields": sorted(body), "bytes": len(str(body.get("image", "")))})
|
|
272
|
+
if self.layout_raw is not None:
|
|
273
|
+
return Response(self.layout_raw, media_type="application/json")
|
|
274
|
+
if self.layout_boxes is None:
|
|
275
|
+
return JSONResponse({"errorCode": 500, "errorMsg": "no model"}, status_code=500)
|
|
276
|
+
if request.url.path == "/object-detection":
|
|
277
|
+
# PaddleX's documented answer for a served detection pipeline (POST /object-detection).
|
|
278
|
+
objs = [{"bbox": b["coordinate"], "categoryName": b["label"], "categoryId": b.get("cls_id", 0), "score": b.get("score", 0.9)} for b in self.layout_boxes]
|
|
279
|
+
return JSONResponse({"logId": "fake", "errorCode": 0, "errorMsg": "Success", "result": {"detectedObjects": objs, "image": None}})
|
|
280
|
+
return JSONResponse({"res": {"boxes": self.layout_boxes}})
|
|
281
|
+
|
|
282
|
+
async def props(self, request: Request) -> Response:
|
|
283
|
+
if self.flavor != "llamacpp":
|
|
284
|
+
return JSONResponse({"error": "not found"}, status_code=404)
|
|
285
|
+
first = next(iter(self.models.values()))
|
|
286
|
+
return JSONResponse({"default_generation_settings": {"n_ctx": first.context_length}, "total_slots": 1, "model_alias": first.name})
|
|
287
|
+
|
|
288
|
+
async def apply_template(self, request: Request) -> Response:
|
|
289
|
+
if self.flavor != "llamacpp":
|
|
290
|
+
return JSONResponse({"error": "not found"}, status_code=404)
|
|
291
|
+
body = await request.json()
|
|
292
|
+
prompt = "".join(f"<|im_start|>{m.get('role')}\n{m.get('content') if isinstance(m.get('content'), str) else json.dumps(m.get('content'))}<|im_end|>\n" for m in body.get("messages") or [])
|
|
293
|
+
if body.get("tools"):
|
|
294
|
+
prompt = json.dumps(body["tools"]) + prompt
|
|
295
|
+
return JSONResponse({"prompt": prompt + "<|im_start|>assistant\n"})
|
|
296
|
+
|
|
297
|
+
# ---------------------------------------------------------------- #
|
|
298
|
+
def _answer(self, m: FakeModel, body: dict[str, Any]) -> dict[str, Any]:
|
|
299
|
+
"""Return {'content': str} or {'tool_calls': [...]}."""
|
|
300
|
+
msgs = body.get("messages") or []
|
|
301
|
+
last = msgs[-1] if msgs else {}
|
|
302
|
+
text = ""
|
|
303
|
+
has_image = False
|
|
304
|
+
if isinstance(last.get("content"), str):
|
|
305
|
+
text = last["content"]
|
|
306
|
+
elif isinstance(last.get("content"), list):
|
|
307
|
+
for p in last["content"]:
|
|
308
|
+
if p.get("type") == "text":
|
|
309
|
+
text += p.get("text", "")
|
|
310
|
+
if p.get("type") == "image_url":
|
|
311
|
+
has_image = True
|
|
312
|
+
tools = body.get("tools") or []
|
|
313
|
+
if "Reply with exactly one line: VERDICT: PASS or VERDICT: FAIL" in text:
|
|
314
|
+
# Simulated judge: passes an answer unless it carries the simulation's own failure markers.
|
|
315
|
+
if m.behaviour == "bad_score":
|
|
316
|
+
return {"content": "This answer seems reasonable to me overall."}
|
|
317
|
+
answer = text.split("### Answer", 1)[-1].split("### Your verdict", 1)[0]
|
|
318
|
+
bad = any(k in answer for k in ("WRONG", "I am not sure", "cannot")) or not answer.strip()
|
|
319
|
+
if m.judge_always:
|
|
320
|
+
bad = m.judge_always == "FAIL"
|
|
321
|
+
return {"content": f"<think>\n</think>\nVERDICT: {'FAIL' if bad else 'PASS'}"}
|
|
322
|
+
if "guardian" in m.name:
|
|
323
|
+
# Simulated judge: answers in the <score> format; "flags" when the judged message (the one before
|
|
324
|
+
# the guardian block) contains a marker phrase. behaviour "bad_score" breaks the format.
|
|
325
|
+
judged = str(msgs[-2].get("content")) if len(msgs) >= 2 else ""
|
|
326
|
+
if m.behaviour == "bad_score":
|
|
327
|
+
return {"content": "I think this is probably fine."}
|
|
328
|
+
hit = "ignore previous instructions" in judged.lower() and "jailbreak" in text.lower() or "MARKER-" in judged and judged.split("MARKER-")[1].split()[0].lower() in text.lower()
|
|
329
|
+
pre = "<think>\nchecked\n</think>\n" if "<think>" in text and "<no-think>" not in text else "<think>\n</think>\n"
|
|
330
|
+
return {"content": f"{pre}<score>{'yes' if hit else 'no'}</score>"}
|
|
331
|
+
if m.name.startswith("glm-ocr"):
|
|
332
|
+
if not has_image:
|
|
333
|
+
return {"content": ""}
|
|
334
|
+
if text.startswith("Table Recognition:"):
|
|
335
|
+
return {"content": "| item | total |\n|---|---|\n| widget | 42.00 |"}
|
|
336
|
+
if text.startswith("Formula Recognition:"):
|
|
337
|
+
return {"content": "$$E = mc^2$$"}
|
|
338
|
+
if text.startswith("Text Recognition:"):
|
|
339
|
+
return {"content": "INVOICE 2026-001\nTotal: 42.00 — ünïcødé ✓"}
|
|
340
|
+
return {"content": json.dumps({"instruction_seen": text[:40]})}
|
|
341
|
+
if last.get("role") == "tool":
|
|
342
|
+
n = len(str(last.get("content") or "").splitlines())
|
|
343
|
+
return {"content": f"Tool result received ({last.get('tool_call_id')}). There are {n} entries. Final answer from {m.name}."}
|
|
344
|
+
# Eval harness marker (simulation artefact): a model answers "correctly" when the task is in good_at.
|
|
345
|
+
mk = re.search(r"<!-- eval:(\w+) -->", text)
|
|
346
|
+
if mk:
|
|
347
|
+
task = mk.group(1)
|
|
348
|
+
ok = task in m.good_at
|
|
349
|
+
if tools and "tools" in m.capabilities:
|
|
350
|
+
if ok:
|
|
351
|
+
fn = tools[0].get("function", {})
|
|
352
|
+
return {"tool_calls": [{"id": f"call_{m.name.replace(':', '_')}_0", "type": "function", "function": {"name": fn.get("name", "fn"), "arguments": json.dumps(_gold_tool_args(fn, text))}}]}
|
|
353
|
+
return {"content": f"I would list the files but I cannot. ({m.name})"}
|
|
354
|
+
rf = body.get("response_format") or {}
|
|
355
|
+
if rf.get("type") == "json_schema":
|
|
356
|
+
return {"content": json.dumps({"name": "X", "email": "x@example.org", "age": 1}) if not ok else json.dumps(_expected_json(text))}
|
|
357
|
+
return {"content": _expected_text(task, text, ok, m.name)}
|
|
358
|
+
if tools and "tools" in m.capabilities and m.behaviour != "unsupported_tools":
|
|
359
|
+
calls = []
|
|
360
|
+
want_all = "both" in text.lower() or "one turn" in text.lower()
|
|
361
|
+
for i, t in enumerate(tools[: 2 if want_all else 1]):
|
|
362
|
+
fn = t.get("function", {})
|
|
363
|
+
calls.append(
|
|
364
|
+
{
|
|
365
|
+
"id": f"call_{m.name.replace(':', '_')}_{i}",
|
|
366
|
+
"type": "function",
|
|
367
|
+
"function": {"name": fn.get("name", "fn"), "arguments": json.dumps({"city": "Paris"})},
|
|
368
|
+
}
|
|
369
|
+
)
|
|
370
|
+
return {"tool_calls": calls}
|
|
371
|
+
rf = body.get("response_format") or {}
|
|
372
|
+
if rf.get("type") == "json_schema" and (rf.get("json_schema") or {}).get("name") == "ballot" and m.json_schema_ok:
|
|
373
|
+
enum = rf["json_schema"]["schema"]["properties"]["choice"]["enum"]
|
|
374
|
+
return {"content": json.dumps({"choice": m.votes if m.votes in enum or m.votes == "OUT-OF-SET" else enum[0]})}
|
|
375
|
+
if rf.get("type") == "json_schema":
|
|
376
|
+
if m.json_schema_ok:
|
|
377
|
+
return {"content": json.dumps({"city": "Paris", "population_millions": 2.1})}
|
|
378
|
+
return {"content": "Paris has about 2.1 million people."}
|
|
379
|
+
if rf.get("type") == "json_object":
|
|
380
|
+
return {"content": json.dumps({"answer": 42})}
|
|
381
|
+
if has_image:
|
|
382
|
+
return {"content": "red" if "vision" in m.capabilities else "I cannot see images."}
|
|
383
|
+
if "count from 1 to 5" in text.lower():
|
|
384
|
+
return {"content": "1 2 3 4 5"}
|
|
385
|
+
if "single word: ready" in text.lower():
|
|
386
|
+
return {"content": "ready"}
|
|
387
|
+
# Eval harness: a model answers "correctly" when the task is in its good_at list.
|
|
388
|
+
task = (body.get("metadata") or {}).get("eval_task") if isinstance(body.get("metadata"), dict) else None
|
|
389
|
+
if task:
|
|
390
|
+
ok = task in m.good_at
|
|
391
|
+
return {"content": f"[{'CORRECT' if ok else 'WRONG'}] answer from {m.name} for {task}"}
|
|
392
|
+
return {"content": f"Hello from {m.name}: you said {text[:60]!r} — ünïcødé ✓"}
|
|
393
|
+
|
|
394
|
+
async def v1_chat(self, request: Request) -> Response:
|
|
395
|
+
body = await request.json()
|
|
396
|
+
name = body.get("model")
|
|
397
|
+
m = self.models.get(name)
|
|
398
|
+
with self._lock:
|
|
399
|
+
self.requests.append({"model": name, "stream": bool(body.get("stream")), "has_tools": bool(body.get("tools")), "fields": sorted(body.keys())})
|
|
400
|
+
if not m:
|
|
401
|
+
return JSONResponse({"error": {"message": f"model '{name}' not found", "type": "not_found"}}, status_code=404)
|
|
402
|
+
if m.behaviour == "error_500":
|
|
403
|
+
return JSONResponse({"error": {"message": "simulated internal error", "type": "server_error"}}, status_code=500)
|
|
404
|
+
if m.behaviour == "hang":
|
|
405
|
+
await asyncio.sleep(3600)
|
|
406
|
+
if m.reject_reasoning_history and any(
|
|
407
|
+
isinstance(x, dict) and x.get("role") == "assistant" and x.get("reasoning_content") is not None for x in body.get("messages") or []
|
|
408
|
+
):
|
|
409
|
+
return JSONResponse(
|
|
410
|
+
{"error": {"message": "unknown field 'reasoning_content' in messages[].", "type": "invalid_request_error"}}, status_code=400
|
|
411
|
+
)
|
|
412
|
+
if "video" not in m.capabilities and any(
|
|
413
|
+
isinstance(p, dict) and p.get("type") == "video_url"
|
|
414
|
+
for x in body.get("messages") or [] if isinstance(x, dict) and isinstance(x.get("content"), list)
|
|
415
|
+
for p in x["content"]
|
|
416
|
+
):
|
|
417
|
+
return JSONResponse({"error": {"message": "this model does not support video input", "type": "invalid_request_error"}}, status_code=400)
|
|
418
|
+
if "audio" not in m.capabilities and any(
|
|
419
|
+
isinstance(p, dict) and p.get("type") == "input_audio"
|
|
420
|
+
for x in body.get("messages") or [] if isinstance(x, dict) and isinstance(x.get("content"), list)
|
|
421
|
+
for p in x["content"]
|
|
422
|
+
):
|
|
423
|
+
return JSONResponse({"error": {"message": "this model does not support audio input", "type": "invalid_request_error"}}, status_code=400)
|
|
424
|
+
with self._lock:
|
|
425
|
+
self.active += 1
|
|
426
|
+
self.max_active = max(self.max_active, self.active)
|
|
427
|
+
if self.flavor == "llamaswap":
|
|
428
|
+
m.loaded = True # llama-swap starts the model's upstream server on its first request
|
|
429
|
+
try:
|
|
430
|
+
if m.behaviour == "slow":
|
|
431
|
+
await asyncio.sleep(1.0)
|
|
432
|
+
if m.behaviour == "stall":
|
|
433
|
+
await asyncio.sleep(1.5) # longer than a test gateway's request timeout, short enough to finish
|
|
434
|
+
ans = self._answer(m, body)
|
|
435
|
+
rid = f"chatcmpl-fake-{int(time.time()*1000)}"
|
|
436
|
+
budget = body.get("max_tokens") or 4096
|
|
437
|
+
if m.thinking_tokens and not body.get("stream") and budget <= m.thinking_tokens:
|
|
438
|
+
return JSONResponse(
|
|
439
|
+
{
|
|
440
|
+
"id": rid, "object": "chat.completion", "created": int(time.time()), "model": name,
|
|
441
|
+
"choices": [{"index": 0, "message": {"role": "assistant", "content": "", "reasoning_content": "thinking..."}, "finish_reason": "length"}],
|
|
442
|
+
"usage": {"prompt_tokens": 10, "completion_tokens": budget, "total_tokens": 10 + budget},
|
|
443
|
+
}
|
|
444
|
+
)
|
|
445
|
+
if m.behaviour == "bad_json":
|
|
446
|
+
# A reverse proxy's HTML page served with 200, for both streaming and non-streaming.
|
|
447
|
+
return Response(b"<html>not json</html>", status_code=200, media_type="text/html")
|
|
448
|
+
if not body.get("stream"):
|
|
449
|
+
msg: dict[str, Any] = {"role": "assistant", "content": ans.get("content")}
|
|
450
|
+
finish = "stop"
|
|
451
|
+
if ans.get("tool_calls"):
|
|
452
|
+
msg["tool_calls"] = ans["tool_calls"]
|
|
453
|
+
msg["content"] = None
|
|
454
|
+
finish = "tool_calls"
|
|
455
|
+
return JSONResponse(
|
|
456
|
+
{
|
|
457
|
+
"id": rid,
|
|
458
|
+
"object": "chat.completion",
|
|
459
|
+
"created": int(time.time()),
|
|
460
|
+
"model": name,
|
|
461
|
+
"choices": [{"index": 0, "message": msg, "finish_reason": finish}],
|
|
462
|
+
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
|
463
|
+
}
|
|
464
|
+
)
|
|
465
|
+
return StreamingResponse(self._stream(m, name, rid, ans, body), media_type="text/event-stream")
|
|
466
|
+
finally:
|
|
467
|
+
with self._lock:
|
|
468
|
+
self.active -= 1
|
|
469
|
+
|
|
470
|
+
async def _stream(self, m: FakeModel, name: str, rid: str, ans: dict[str, Any], body: dict[str, Any]) -> AsyncIterator[bytes]:
|
|
471
|
+
with self._lock:
|
|
472
|
+
self.active += 1
|
|
473
|
+
self.max_active = max(self.max_active, self.active)
|
|
474
|
+
try:
|
|
475
|
+
def frame(delta: dict[str, Any], finish: str | None = None, usage: Any = None) -> bytes:
|
|
476
|
+
obj: dict[str, Any] = {
|
|
477
|
+
"id": rid,
|
|
478
|
+
"object": "chat.completion.chunk",
|
|
479
|
+
"created": int(time.time()),
|
|
480
|
+
"model": name,
|
|
481
|
+
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
|
|
482
|
+
}
|
|
483
|
+
if usage is not None:
|
|
484
|
+
obj["usage"] = usage
|
|
485
|
+
return b"data: " + json.dumps(obj, ensure_ascii=False).encode("utf-8") + b"\n\n"
|
|
486
|
+
|
|
487
|
+
yield frame({"role": "assistant", "content": ""})
|
|
488
|
+
if m.thinking_tokens:
|
|
489
|
+
budget = body.get("max_tokens") or 4096
|
|
490
|
+
for _ in range(3):
|
|
491
|
+
yield frame({"reasoning_content": "hmm "})
|
|
492
|
+
if budget <= m.thinking_tokens:
|
|
493
|
+
yield frame({}, finish="length")
|
|
494
|
+
if (body.get("stream_options") or {}).get("include_usage"):
|
|
495
|
+
yield frame({}, usage={"prompt_tokens": 10, "completion_tokens": budget, "total_tokens": 10 + budget})
|
|
496
|
+
yield b"data: [DONE]\n\n"
|
|
497
|
+
return
|
|
498
|
+
if m.behaviour == "truncate_stream":
|
|
499
|
+
yield frame({"content": "half"})
|
|
500
|
+
return # ends cleanly without finish_reason or [DONE]
|
|
501
|
+
if ans.get("tool_calls"):
|
|
502
|
+
# Indexed, interleaved tool-call deltas: id+name first, then argument fragments.
|
|
503
|
+
calls = ans["tool_calls"]
|
|
504
|
+
for i, c in enumerate(calls):
|
|
505
|
+
yield frame({"tool_calls": [{"index": i, "id": c["id"], "type": "function", "function": {"name": c["function"]["name"], "arguments": ""}}]})
|
|
506
|
+
args = [c["function"]["arguments"] for c in calls]
|
|
507
|
+
pos = 0
|
|
508
|
+
while any(pos < len(a) for a in args):
|
|
509
|
+
for i, a in enumerate(args):
|
|
510
|
+
if pos < len(a):
|
|
511
|
+
yield frame({"tool_calls": [{"index": i, "function": {"arguments": a[pos : pos + 4]}}]})
|
|
512
|
+
pos += 4
|
|
513
|
+
if m.behaviour == "fail_mid_stream":
|
|
514
|
+
raise RuntimeError("simulated backend crash during tool streaming")
|
|
515
|
+
yield frame({}, finish="tool_calls")
|
|
516
|
+
else:
|
|
517
|
+
content = ans.get("content") or ""
|
|
518
|
+
words = content.split(" ")
|
|
519
|
+
for i, w in enumerate(words):
|
|
520
|
+
piece = w + (" " if i < len(words) - 1 else "")
|
|
521
|
+
if m.behaviour == "fail_mid_stream" and i == max(1, len(words) // 2):
|
|
522
|
+
raise RuntimeError("simulated backend crash mid-stream")
|
|
523
|
+
if m.token_delay_s:
|
|
524
|
+
await asyncio.sleep(m.token_delay_s)
|
|
525
|
+
# Split the frame bytes into two partial writes to exercise partial-frame parsing,
|
|
526
|
+
# deliberately cutting inside multi-byte UTF-8 sequences when present.
|
|
527
|
+
data = frame({"content": piece})
|
|
528
|
+
cut = len(data) // 2
|
|
529
|
+
yield data[:cut]
|
|
530
|
+
await asyncio.sleep(0)
|
|
531
|
+
yield data[cut:]
|
|
532
|
+
yield frame({}, finish="stop")
|
|
533
|
+
if (body.get("stream_options") or {}).get("include_usage"):
|
|
534
|
+
yield frame({}, usage={"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15})
|
|
535
|
+
yield b"data: [DONE]\n\n"
|
|
536
|
+
finally:
|
|
537
|
+
with self._lock:
|
|
538
|
+
self.active -= 1
|
|
539
|
+
|
|
540
|
+
async def tokenize(self, request: Request) -> Response:
|
|
541
|
+
"""vLLM-style /tokenize: here 1 token per 4 characters (deterministic fake tokenizer)."""
|
|
542
|
+
body = await request.json()
|
|
543
|
+
if self.flavor == "llamacpp":
|
|
544
|
+
text = str(body.get("content", ""))
|
|
545
|
+
self.tokenize_requests.append({"model": None, "chars": len(text), "mode": "content"})
|
|
546
|
+
return JSONResponse({"tokens": list(range(len(text) // 4))})
|
|
547
|
+
if self.flavor == "vllm" and isinstance(body.get("messages"), list):
|
|
548
|
+
text = json.dumps(body["messages"]) + json.dumps(body.get("tools") or "")
|
|
549
|
+
n = len(text) // 4 + 4 * len(body["messages"])
|
|
550
|
+
self.tokenize_requests.append({"model": body.get("model"), "chars": len(text), "mode": "chat"})
|
|
551
|
+
return JSONResponse({"count": n, "max_model_len": 32768, "tokens": list(range(n))})
|
|
552
|
+
n = len(str(body.get("prompt", ""))) // 4
|
|
553
|
+
# Metadata only: which model and how much text reached this backend's tokenizer.
|
|
554
|
+
self.tokenize_requests.append({"model": body.get("model"), "chars": len(str(body.get("prompt", "")))})
|
|
555
|
+
return JSONResponse({"count": n, "max_model_len": 32768, "tokens": list(range(n))})
|
|
556
|
+
|
|
557
|
+
async def v1_systemone(self, request: Request) -> Response:
|
|
558
|
+
"""Ollama's System One decision endpoint as documented (docs.ollama.com/api/systemone): one JSON
|
|
559
|
+
answer per named question; errors are ``{"error": str}`` with 400 (invalid request or a model that
|
|
560
|
+
is not a decision model), 404 (model not found) or 500."""
|
|
561
|
+
body = await request.json()
|
|
562
|
+
name = body.get("model")
|
|
563
|
+
m = self.models.get(name) if isinstance(name, str) else None
|
|
564
|
+
with self._lock:
|
|
565
|
+
self.requests.append({"model": name, "path": "/v1/systemone", "fields": sorted(body.keys()), "questions": sorted((body.get("questions") or {}).keys()) if isinstance(body.get("questions"), dict) else None})
|
|
566
|
+
if not m:
|
|
567
|
+
return JSONResponse({"error": f"model '{name}' not found"}, status_code=404)
|
|
568
|
+
if "decision" not in m.capabilities:
|
|
569
|
+
return JSONResponse({"error": f"model '{name}' does not support system one requests"}, status_code=400)
|
|
570
|
+
if m.behaviour == "error_500":
|
|
571
|
+
return JSONResponse({"error": "simulated scoring failure"}, status_code=500)
|
|
572
|
+
if m.behaviour == "hang":
|
|
573
|
+
await asyncio.sleep(3600)
|
|
574
|
+
state, questions = body.get("state"), body.get("questions")
|
|
575
|
+
if not isinstance(state, (str, dict, list)) or (isinstance(state, str) and not state.strip()):
|
|
576
|
+
return JSONResponse({"error": "state must be a non-empty string, object or array"}, status_code=400)
|
|
577
|
+
if not isinstance(questions, dict) or not 1 <= len(questions) <= 64:
|
|
578
|
+
return JSONResponse({"error": "questions must name 1 to 64 questions"}, status_code=400)
|
|
579
|
+
if body.get("images") and "vision" not in m.capabilities:
|
|
580
|
+
return JSONResponse({"error": f"model '{name}' does not support images"}, status_code=400)
|
|
581
|
+
if m.behaviour == "bad_json":
|
|
582
|
+
return Response("<html>proxy error</html>", status_code=200, media_type="text/html")
|
|
583
|
+
answers: dict[str, Any] = {}
|
|
584
|
+
for qname, q in questions.items():
|
|
585
|
+
if not isinstance(q, dict) or q.get("type") not in ("choice", "noul", "score"):
|
|
586
|
+
return JSONResponse({"error": f"question '{qname}': unsupported type"}, status_code=400)
|
|
587
|
+
if q["type"] == "choice":
|
|
588
|
+
crit = q.get("criteria")
|
|
589
|
+
if not isinstance(crit, dict) or not 2 <= len(crit) <= 255:
|
|
590
|
+
return JSONResponse({"error": f"question '{qname}': choice needs 2 to 255 criteria"}, status_code=400)
|
|
591
|
+
options = list(crit)
|
|
592
|
+
pick = m.decides if m.decides in crit else options[0]
|
|
593
|
+
p = min(max(m.decision_probability, 0.0), 1.0)
|
|
594
|
+
rest = (1.0 - p) / max(len(options) - 1, 1)
|
|
595
|
+
probs = {o: round(p if o == pick else rest, 4) for o in options}
|
|
596
|
+
if m.behaviour == "malformed_decision":
|
|
597
|
+
probs = {o: 2.0 for o in options} # probabilities out of range: the gateway must reject it
|
|
598
|
+
answers[qname] = {"type": "choice", "choice": pick, "probabilities": probs, "confidence": round(p, 4)}
|
|
599
|
+
elif q["type"] == "noul":
|
|
600
|
+
answers[qname] = {"type": "noul", "noul": 0.5}
|
|
601
|
+
else:
|
|
602
|
+
crit = q.get("criteria") or []
|
|
603
|
+
answers[qname] = {
|
|
604
|
+
"type": "score", "score": 0.0, "legend": {str(i): c for i, c in enumerate(crit)},
|
|
605
|
+
"probabilities": {str(i): (1.0 if i == 0 else 0.0) for i in range(len(crit))}, "confidence": 1.0,
|
|
606
|
+
}
|
|
607
|
+
return JSONResponse({"model": name, "answers": answers, "usage": {"input_tokens": 100, "output_tokens": 1}})
|
|
608
|
+
|
|
609
|
+
async def v1_embeddings(self, request: Request) -> Response:
|
|
610
|
+
body = await request.json()
|
|
611
|
+
m = self.models.get(body.get("model"))
|
|
612
|
+
if not m or "embedding" not in m.capabilities:
|
|
613
|
+
return JSONResponse({"error": {"message": "not an embedding model", "type": "invalid_request_error"}}, status_code=400)
|
|
614
|
+
inputs = body.get("input")
|
|
615
|
+
if isinstance(body.get("messages"), list):
|
|
616
|
+
# vLLM's chat-style embeddings request: one prompt (possibly with media parts) -> one vector.
|
|
617
|
+
if self.flavor != "vllm":
|
|
618
|
+
return JSONResponse({"error": {"message": "messages are not accepted by this embeddings endpoint", "type": "invalid_request_error"}}, status_code=400)
|
|
619
|
+
parts = body["messages"][-1].get("content")
|
|
620
|
+
kinds = [p.get("type") for p in parts] if isinstance(parts, list) else ["text"]
|
|
621
|
+
if "image_url" in kinds and "vision" not in m.capabilities:
|
|
622
|
+
return JSONResponse({"error": {"message": "model has no vision encoder", "type": "invalid_request_error"}}, status_code=400)
|
|
623
|
+
self.embedding_requests.append({"model": m.name, "form": "messages", "kinds": kinds})
|
|
624
|
+
inputs = [json.dumps(parts, sort_keys=True)]
|
|
625
|
+
elif inputs is not None:
|
|
626
|
+
self.embedding_requests.append({"model": m.name, "form": "input", "n": 1 if isinstance(inputs, str) else len(inputs)})
|
|
627
|
+
if isinstance(inputs, str):
|
|
628
|
+
inputs = [inputs]
|
|
629
|
+
data = []
|
|
630
|
+
for i, text in enumerate(inputs or []):
|
|
631
|
+
vec = [((hash((m.name, str(text), j)) % 1000) / 1000.0 + 0.001) for j in range(m.embedding_dimensions)]
|
|
632
|
+
if m.normalize_embeddings:
|
|
633
|
+
norm = sum(v * v for v in vec) ** 0.5
|
|
634
|
+
vec = [v / norm for v in vec]
|
|
635
|
+
data.append({"object": "embedding", "index": i, "embedding": vec})
|
|
636
|
+
return JSONResponse({"object": "list", "data": data, "model": m.name, "usage": {"prompt_tokens": 3, "total_tokens": 3}})
|
|
637
|
+
|
|
638
|
+
# ---------------------------------------------------------------- #
|
|
639
|
+
def start(self, host: str = "127.0.0.1", port: int = 0) -> str:
|
|
640
|
+
import socket
|
|
641
|
+
|
|
642
|
+
if port == 0:
|
|
643
|
+
s = socket.socket()
|
|
644
|
+
s.bind((host, 0))
|
|
645
|
+
port = s.getsockname()[1]
|
|
646
|
+
s.close()
|
|
647
|
+
self.port = port
|
|
648
|
+
config = uvicorn.Config(self.app, host=host, port=port, log_level="error", lifespan="off")
|
|
649
|
+
self._server = uvicorn.Server(config)
|
|
650
|
+
self._thread = threading.Thread(target=self._server.run, daemon=True)
|
|
651
|
+
self._thread.start()
|
|
652
|
+
deadline = time.time() + 10
|
|
653
|
+
while not self._server.started and time.time() < deadline:
|
|
654
|
+
time.sleep(0.02)
|
|
655
|
+
return f"http://{host}:{port}"
|
|
656
|
+
|
|
657
|
+
def stop(self) -> None:
|
|
658
|
+
if self._server:
|
|
659
|
+
self._server.should_exit = True
|
|
660
|
+
if self._thread:
|
|
661
|
+
self._thread.join(timeout=5)
|