Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(sdk): bring TypeScript encode, score and extract options in line with the Python SDK (#704)

svonavab76f69868d81
diff --git a/packages/sie_sdk/tests/client/test_sdk_requests.py b/packages/sie_sdk/tests/client/test_sdk_requests.py
new file mode 100644
index 000000000..11ea795d7
--- /dev/null
+++ b/packages/sie_sdk/tests/client/test_sdk_requests.py
@@ -0,0 +1,306 @@
+"""The requests both clients send must match the shared request fixture.
+
+Every case of ``packages/wire-fixtures/sdk_requests.json`` is issued through
+the sync and the async client against a local HTTP server, and the request
+that reached it is compared with the fixture. The TypeScript SDK replays the
+same cases in ``sdkRequests.test.ts``, so a call one SDK serializes
+differently, or cannot express, fails here or there.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import threading
+from collections.abc import Iterator
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any
+from urllib.parse import unquote, urlsplit
+
+import msgpack
+import numpy as np
+import pytest
+from sie_sdk import SIEAsyncClient, SIEClient
+
+_FIXTURE: dict[str, Any] = json.loads((Path(__file__).parents[3] / "wire-fixtures" / "sdk_requests.json").read_text())
+_CASES: list[dict[str, Any]] = _FIXTURE["cases"]
+_MEDIA: dict[str, bytes] = {name: base64.b64decode(data) for name, data in _FIXTURE["media"].items()}
+_MEDIA_NAMES: dict[bytes, str] = {data: name for name, data in _MEDIA.items()}
+
+_SCHEMA = {
+ "type": "object",
+ "properties": {"vendor": {"type": "string"}, "total": {"type": "number"}},
+ "required": ["vendor", "total"],
+}
+_QUERY = {"text": "What is machine learning?"}
+_DOCUMENTS = [
+ {"id": "doc-1", "text": "Machine learning is a subfield of AI."},
+ {"id": "doc-2", "text": "Python is a programming language."},
+]
+_ENTITY_TEXT = {"text": "Apple was founded by Steve Jobs."}
+_STREAMS = frozenset({"stream_generate", "stream_chat_completions"})
+
+# The call each fixture case stands for: (method, positional arguments, keyword arguments).
+_CALLS: dict[str, tuple[str, tuple[Any, ...], dict[str, Any]]] = {
+ "encode_single_text": ("encode", ("BAAI/bge-m3", {"text": "hello"}), {}),
+ "encode_batch_all_params": (
+ "encode",
+ ("BAAI/bge-m3", [{"id": "a", "text": "first"}, {"id": "b", "text": "second"}]),
+ {
+ "output_types": ["dense", "sparse"],
+ "instruction": "Represent the query",
+ "output_dtype": "float16",
+ "is_query": True,
+ },
+ ),
+ "encode_profile_option": (
+ "encode",
+ ("lightonai/GTE-ModernColBERT-v1", {"text": "a long document"}),
+ {"output_types": ["multivector"], "is_query": False, "options": {"profile": "long_context"}},
+ ),
+ "encode_model_profile_id": ("encode", ("BAAI/bge-m3:sparse", {"text": "hello"}), {}),
+ "encode_image": ("encode", ("google/siglip2-base-patch16-224", {"images": [_MEDIA["png"]]}), {}),
+ "encode_pool_and_gpu": ("encode", ("BAAI/bge-m3", {"text": "hello"}), {"gpu": "eval-bench/l4"}),
+ "encode_client_defaults": ("encode", ("BAAI/bge-m3", {"text": "hello"}), {}),
+ "score_basic": ("score", ("BAAI/bge-reranker-v2-m3", _QUERY, _DOCUMENTS), {}),
+ "score_instruction_and_options": (
+ "score",
+ ("Qwen/Qwen3-Reranker-4B", _QUERY, _DOCUMENTS),
+ {"instruction": "Rank passages that answer the question", "options": {"profile": "default"}},
+ ),
+ "extract_labels": (
+ "extract",
+ ("urchade/gliner_multi-v2.1", _ENTITY_TEXT),
+ {"labels": ["person", "organization"]},
+ ),
+ "extract_threshold": (
+ "extract",
+ ("urchade/gliner_multi-v2.1", _ENTITY_TEXT),
+ {"labels": ["person", "organization"], "options": {"threshold": 0.75}},
+ ),
+ "extract_image_without_params": ("extract", ("lightonai/LightOnOCR-2-1B", {"images": [_MEDIA["png"]]}), {}),
+ "extract_output_schema_and_instruction": (
+ "extract",
+ ("fastino/GLiNER2.5-Decide", {"text": "Get me a person. This is the third time."}),
+ {
+ "output_schema": {"handoff": {"type": "noul", "instructions": "Should a person take over?"}},
+ "instruction": "Triage the support ticket.",
+ "options": {"overflow_policy": "truncate_text"},
+ },
+ ),
+ "extract_audio": (
+ "extract",
+ ("openai/whisper-large-v3-turbo", {"audio": {"data": _MEDIA["wav"], "format": "wav", "sample_rate": 16000}}),
+ {},
+ ),
+ "extract_document": ("extract", ("docling", {"document": {"data": _MEDIA["pdf"], "format": "pdf"}}), {}),
+ "generate_basic": (
+ "generate",
+ ("Qwen/Qwen3-4B-Instruct-2507", "Write a haiku about the sea."),
+ {"max_new_tokens": 64, "temperature": 0.7},
+ ),
+ "generate_all_fields": (
+ "generate",
+ ("google/gemma-4-31B-it:h100-96k-hires-thinking-budget512-no-spec", "Extract the invoice."),
+ {
+ "max_new_tokens": 256,
+ "temperature": 0,
+ "top_p": 0.9,
+ "stop": ["\n\n"],
+ "frequency_penalty": 0.5,
+ "presence_penalty": 0.25,
+ "grammar": {"json_schema": _SCHEMA, "strict": True},
+ "seed": 7,
+ "logit_bias": {"42": -1.5},
+ "routing_key": "tenant-1",
+ "prompt_cache_key": "invoice-v1",
+ "safety_identifier": "user-9",
+ "lora_adapter": "invoices",
+ "options": {"overall_timeout_s": 30},
+ },
+ ),
+ "generate_image": (
+ "generate",
+ ("Qwen/Qwen3-VL-8B-Instruct", "Describe the image."),
+ {"max_new_tokens": 32, "images": [_MEDIA["png"]]},
+ ),
+ "stream_generate": (
+ "stream_generate",
+ ("Qwen/Qwen3-4B-Instruct-2507", "Write a haiku."),
+ {"max_new_tokens": 64, "temperature": 0.7, "logprobs": True, "top_logprobs": 2},
+ ),
+ "chat_completions": (
+ "chat_completions",
+ (
+ "Qwen/Qwen3-4B-Instruct-2507",
+ [
+ {"role": "system", "content": "Answer in JSON."},
+ {"role": "user", "content": "Extract the invoice fields."},
+ ],
+ ),
+ {
+ "max_completion_tokens": 256,
+ "temperature": 0,
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {"name": "invoice", "strict": True, "schema": _SCHEMA},
+ },
+ "extra_body": {"schema_in_prompt": False},
+ },
+ ),
+ "stream_chat_completions": (
+ "stream_chat_completions",
+ ("Qwen/Qwen3-4B-Instruct-2507", [{"role": "user", "content": "Count to ten."}]),
+ {"max_completion_tokens": 64, "stream_options": {"include_usage": True}},
+ ),
+}
+
+
+def _success(path: str, accept: str, item_count: int) -> tuple[bytes, str]:
+ """A minimal success for the route, shaped by what the request asked for."""
+ if path.startswith("/v1/encode/"):
+ items = [{"dense": {"dims": 1, "values": np.zeros(1, dtype=np.float32)}} for _ in range(item_count)]
+ return _pack({"model": "m", "items": items}), "application/msgpack"
+ if path.startswith("/v1/score/"):
+ scores = [{"item_id": "doc-1", "score": 0.5, "rank": 0}]
+ return _pack({"model": "m", "scores": scores}), "application/msgpack"
+ if path.startswith("/v1/extract/"):
+ return _pack({"model": "m", "items": [{"entities": []} for _ in range(item_count)]}), "application/msgpack"
+ if accept == "text/event-stream":
+ return b"data: [DONE]\n\n", "text/event-stream"
+ if path.startswith("/v1/generate/"):
+ return json.dumps({"model": "m", "text": "ok", "finish_reason": "stop"}).encode(), "application/json"
+ chat = {"id": "chat-1", "object": "chat.completion", "model": "m", "choices": []}
+ return json.dumps(chat).encode(), "application/json"
+
+
+def _pack(body: dict[str, Any]) -> bytes:
+ # conftest patches msgpack with NumPy support, as the server's encoder has.
+ return msgpack.packb(body, use_bin_type=True)
+
+
+class _RecordingServer:
+ """Threaded HTTP server that records each request and answers with a success."""
+
+ def __init__(self) -> None:
+ self.requests: list[dict[str, Any]] = []
+ recorder = self
+
+ class _Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_POST(self) -> None:
+ raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
+ headers = {name.lower(): value for name, value in self.headers.items()}
+ if headers.get("content-type") == "application/msgpack":
+ body = msgpack.unpackb(raw, raw=False)
+ else:
+ body = json.loads(raw)
+ path = unquote(urlsplit(self.path).path)
+ recorder.requests.append({"method": self.command, "path": path, "headers": headers, "body": body})
+ item_count = len(body["items"]) if isinstance(body.get("items"), list) else 1
+ payload, content_type = _success(path, headers.get("accept", ""), item_count)
+ self.send_response(200)
+ self.send_header("Content-Type", content_type)
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, format: str, *args: Any) -> None:
+ return None
+
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ self._server.daemon_threads = True
+ self._thread = threading.Thread(target=self._server.serve_forever, args=(0.01,), daemon=True)
+ self._thread.start()
+
+ @property
+ def url(self) -> str:
+ host, port = self._server.server_address[:2]
+ return f"http://{host!s}:{port}"
+
+ def close(self) -> None:
+ self._server.shutdown()
+ self._server.server_close()
+
+
+def server() -> Iterator[_RecordingServer]:
+ recording = _RecordingServer()
+ try:
+ yield recording
+ finally:
+ recording.close()
+
+
+def _canonical(value: Any) -> Any:
+ """Fixture view of a decoded body: bytes named by media, ``None`` members dropped."""
+ if isinstance(value, bytes):
+ name = _MEDIA_NAMES.get(value)
+ return {"$bytes": base64.b64encode(value).decode()} if name is None else {"$media": name}
+ if isinstance(value, dict):
+ return {key: _canonical(member) for key, member in value.items() if member is not None}
+ if isinstance(value, (list, tuple)):
+ return [_canonical(member) for member in value]
+ return value
+
+
+def _expected_body(value: Any) -> Any:
+ """The fixture's expected body with base64 media references resolved."""
+ if isinstance(value, dict):
+ if "$media_base64" in value:
+ return _FIXTURE["media"][value["$media_base64"]]
+ return {key: _expected_body(member) for key, member in value.items() if member is not None}
+ if isinstance(value, list):
+ return [_expected_body(member) for member in value]
+ return value
+
+
+def _assert_matches_fixture(case: dict[str, Any], sent: list[dict[str, Any]]) -> None:
+ assert len(sent) == 1
+ request, expected = sent[0], case["request"]
+ assert request["method"] == expected["method"]
+ assert request["path"] == expected["path"]
+ for name in _FIXTURE["compared_headers"]:
+ assert {name: request["headers"].get(name)} == {name: expected["headers"].get(name)}
+ assert request["headers"].get("x-sie-sdk-version")
+
+ body = _canonical(request["body"])
+ for member, value in expected.get("may_send_default", {}).items():
+ if member in body:
+ assert {member: body.pop(member)} == {member: value}
+ assert body == _expected_body(expected["body"])
+
+
+def _client_kwargs(case: dict[str, Any]) -> dict[str, Any]:
+ return {"api_key": _FIXTURE["client"]["api_key"], **case.get("client", {})}
+
+
+def test_every_fixture_case_has_a_call() -> None:
+ assert sorted(_CALLS) == sorted(case["id"] for case in _CASES)
+
+
[email protected]("case", _CASES, ids=[case["id"] for case in _CASES])
+def test_sync_client_sends_the_fixture_request(server: _RecordingServer, case: dict[str, Any]) -> None:
+ method, args, kwargs = _CALLS[case["id"]]
+ client = SIEClient(server.url, **_client_kwargs(case))
+ try:
+ result = getattr(client, method)(*args, **kwargs)
+ if case["id"] in _STREAMS:
+ list(result)
+ finally:
+ client.close()
+ _assert_matches_fixture(case, server.requests)
+
+
[email protected]("case", _CASES, ids=[case["id"] for case in _CASES])
+async def test_async_client_sends_the_fixture_request(server: _RecordingServer, case: dict[str, Any]) -> None:
+ method, args, kwargs = _CALLS[case["id"]]
+ async with SIEAsyncClient(server.url, **_client_kwargs(case)) as client:
+ if case["id"] in _STREAMS:
+ async for _chunk in getattr(client, method)(*args, **kwargs):
+ pass
+ else:
+ await getattr(client, method)(*args, **kwargs)
+ _assert_matches_fixture(case, server.requests)
diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.md
index 84875bc93..29f62a3df 100644
--- a/packages/sie_ts_sdk/README.md
+++ b/packages/sie_ts_sdk/README.md
@@ -86,16 +86,76 @@ const scored = await client.score(
console.log(scored.scores[0].itemId, scored.scores[0].score);
```
+`encode` and `score` take runtime options as `adapterOptions`, which the
+Python SDK names `options`: for example
+`{ adapterOptions: { profile: "long_context" } }` selects a named model
+profile. `score` also takes an `instruction`. Each `encode` result names the
+`model` that served it.
+
+## Extraction
+
+```typescript
+import { readFile } from "node:fs/promises";
+
+// Entities for the labels you pass
+const result = await client.extract(
+ "urchade/gliner_multi-v2.1",
+ { text: "Apple was founded by Steve Jobs." },
+ { labels: ["person", "organization"] },
+);
+for (const entity of result.entities) {
+ console.log(entity.label, entity.text, entity.score);
+}
+
+// No options for models that take none: OCR, document parsing, speech to text
+const pngBytes = await readFile("page.png");
+const page = await client.extract("lightonai/LightOnOCR-2-1B", { images: [pngBytes] });
+console.log(page.entities[0]?.text); // the page as Markdown
+
+// Typed decisions: questions go in outputSchema, answers come back in data
+const decision = await client.extract(
+ "fastino/GLiNER2.5-Decide",
+ { text: "This is the third time I have explained the same missing refund." },
+ {
+ outputSchema: {
+ handoff: { type: "noul", instructions: "Should a person take over?" },
+ },
+ },
+);
+console.log(decision.data?.handoff);
+```
+
+`labels`, `outputSchema` and `instruction` are all optional. `threshold` and
+anything in `adapterOptions` are sent as runtime options (`params.options`),
+where the Python SDK's `options` keyword argument puts them.
+
+Images are bytes (`Uint8Array`, `ArrayBuffer`, `Blob`) or a base64 or `data:`
+URL string. A string is never read as a file path, unlike in the Python SDK;
+read the file and pass its bytes.
+
## Generation
Text-only `generate` and `streamGenerate` prompts are raw continuation input:
the worker preserves them without rendering a chat template or applying
`enable_thinking` / `guardian_config`. Native requests with images render one
-user turn. For chat, instruction-based structured output (`responseFormat`),
+user turn. For chat, instruction-based structured output (`response_format`),
and guard checks, use `chatCompletions` or `streamChatCompletions` with messages
so the worker applies the served template settings. Operator settings take
precedence over request template kwargs.
+```typescript
+const reply = await client.chatCompletions({
+ model: "Qwen/Qwen3-4B-Instruct-2507",
+ messages: [{ role: "user", content: "Write a haiku about the sea." }],
+ max_completion_tokens: 64,
+});
+console.log(reply.choices[0]?.message.content);
+```
+
+The chat request and response keep the wire's snake_case field names. The
+Python SDK takes the same fields as keyword arguments after `model` and
+`messages`.
+
Granite Guardian's shipped risk dimension is `harm`; requesting another
dimension in prompt text does not change it. Valid thresholded verdicts are
`Yes` (unsafe) and `No` (safe); missing or invalid verdicts fail with
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index aa3db0c86..0efc219ee 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -41,7 +41,7 @@ import {
SIEStreamError,
ServerError,
} from "./errors.js";
-import { toImageWireFormat } from "./images.js";
+import { detectImageFormat, toImageBytes } from "./images.js";
import type { ImageInput, ImageWireFormat } from "./images.js";
import {
DEFAULT_JOB_WAIT_POLL,
@@ -148,6 +148,7 @@ import type {
ScoreResult,
StatusMessage,
StreamGenerateOptions,
+ TimingInfo,
WireModelInfo,
} from "./types.js";
import { SDK_VERSION } from "./version.js";
@@ -602,11 +603,18 @@ function isImageWireFormat(image: ImageInput | ImageWireFormat): image is ImageW
return typeof image === "object" && image !== null && "data" in image;
}
+/**
+ * Wrap image bytes with the format their signature names, as the Python SDK
+ * does. Bytes with an unrecognized signature keep the historical `jpeg` label;
+ * the server reads the label as a hint and inspects the bytes itself.
+ */
async function imageForWire(image: ImageInput | ImageWireFormat): Promise<ImageWireFormat> {
if (isImageWireFormat(image)) {
return image;
}
- return toImageWireFormat(image);
+ const data = await toImageBytes(image);
+ const detected = detectImageFormat(data);
+ return { data, format: detected === "unknown" ? "jpeg" : detected };
}
function imageBytesToBase64(data: Uint8Array): string {
@@ -862,6 +870,40 @@ function requireVisibleManualRedirect(response: Response): void {
}
}
+/**
+ * `params.options` for a native primitive: the caller's runtime options with
+ * the typed fields laid over them, or `undefined` when neither is set so the
+ * member stays off the wire.
+ */
+function runtimeOptions(
+ adapterOptions: Record<string, unknown> | undefined,
+ typed: Record<string, unknown>,
+): Record<string, unknown> | undefined {
+ const set = Object.fromEntries(Object.entries(typed).filter(([, value]) => value !== undefined));
+ if (adapterOptions === undefined && Object.keys(set).length === 0) {
+ return undefined;
+ }
+ return { ...adapterOptions, ...set };
+}
+
+/** The response-level timing block, in the camelCase `TimingInfo` shape. */
+function timingFromWire(timing: unknown): TimingInfo | undefined {
+ if (typeof timing !== "object" || timing === null || Array.isArray(timing)) {
+ return undefined;
+ }
+ const wire = timing as Record<string, unknown>;
+ const ms = (key: string): number | undefined => {
+ const value = wire[key];
+ return typeof value === "number" ? value : undefined;
+ };
+ return {
+ totalMs: ms("total_ms"),
+ queueMs: ms("queue_ms"),
+ tokenizationMs: ms("tokenization_ms"),
+ inferenceMs: ms("inference_ms"),
+ };
+}
+
/** SIE-native chunk variant — see `sse.rs::build_generate_chunk_event`. */
function extractGenerateChunkError(chunk: GenerateChunk): SIEStreamError | null {
if (!chunk.error) return null;
@@ -973,8 +1015,13 @@ export class SIEClient {
`Invalid baseUrl "${url}": must be an absolute http(s) URL with a host, e.g. "http://localhost:8080".`,
);
}
- // Remove trailing slash
- this.baseUrl = url.replace(/\/$/, "");
+ // Remove trailing slashes, without a regex: `/\/+$/` backtracks
+ // quadratically on a long run of slashes that is not at the end.
+ let end = url.length;
+ while (end > 0 && url.charCodeAt(end - 1) === 0x2f) {
+ end -= 1;
+ }
+ this.baseUrl = url.slice(0, end);
// `timeoutMs` is the unit-encoded name; `timeout` is a deprecated alias
// for the same MILLISECONDS value. `timeoutMs` wins if both are set.
this.timeout = options.timeoutMs ?? options.timeout ?? DEFAULT_TIMEOUT;
@@ -1088,8 +1135,9 @@ export class SIEClient {
if (options.instruction !== undefined) {
params.instruction = options.instruction;
}
- if (options.isQuery !== undefined) {
- params.options = { is_query: options.isQuery };
+ const encodeOptions = runtimeOptions(options.adapterOptions, { is_query: options.isQuery });
+ if (encodeOptions !== undefined) {
+ params.options = encodeOptions;
}
if (options.outputDtype !== undefined) {
params.output_dtype = options.outputDtype;
@@ -1111,15 +1159,23 @@ export class SIEClient {
model,
);
- // Wire format response: {"items": [...], "timing": {...}}
+ // Wire format response: {"model": "...", "items": [...], "timing": {...}}
interface WireResponse {
+ model?: unknown;
items: unknown[];
- timing?: Record<string, unknown>;
+ timing?: unknown;
}
const data = unpackMessage<WireResponse>(new Uint8Array(await response.arrayBuffer()));
const results = parseEncodeResults(data.items);
+ // The model and the timing breakdown describe the whole response; repeat
+ // them on each result, as the Python SDK does.
+ const timing = timingFromWire(data.timing);
+ for (const result of results) {
+ if (typeof data.model === "string" && data.model) result.model = data.model;
+ if (timing !== undefined) result.timing = { ...timing };
+ }
attachRequestMetadata(results, response.headers, data);
// Guard the 1:1 input-to-output contract before any positional access
// (`results[0]` below, or index-based reassembly in callers). The queue
@@ -2022,6 +2078,12 @@ export class SIEClient {
query: queryForWire,
items: itemsForWire,
};
+ if (options.instruction !== undefined) {
+ body.instruction = options.instruction;
+ }
+ if (options.adapterOptions !== undefined) {
+ body.options = options.adapterOptions;
+ }
const waitForCapacity = options.waitForCapacity ?? this.defaultWaitForCapacity;
const { pool, gpu } = this.parseGpuParam(options.gpu);
@@ -2044,31 +2106,34 @@ export class SIEClient {
}
/**
- * Extract entities from a single item.
+ * Extract entities or structured data from a single item.
*
* @param model - Model name (e.g., "urchade/gliner_multi-v2.1")
* @param item - Item to extract from
- * @param options - Extract options with labels
- * @returns Extract result with entities
+ * @param options - Extract options: labels, output schema, instruction
+ * @returns Extract result
*/
- async extract(model: string, item: ExtractItem, options: ExtractOptions): Promise<ExtractResult>;
+ async extract(model: string, item: ExtractItem, options?: ExtractOptions): Promise<ExtractResult>;
/**
- * Extract entities from multiple items.
+ * Extract entities or structured data from multiple items.
*
* @param model - Model name (e.g., "urchade/gliner_multi-v2.1")
* @param items - Items to extract from
- * @param options - Extract options with labels
+ * @param options - Extract options: labels, output schema, instruction
* @returns Array of extract results in same order as input
*/
async extract(
model: string,
items: ExtractItem[],
- options: ExtractOptions,
+ options?: ExtractOptions,
): Promise<ExtractResult[]>;
/**
- * Extract entities from one or more items.
+ * Extract entities or structured data from one or more items.
+ *
+ * `options` may be omitted for models that take no labels, such as OCR,
+ * document parsing and speech to text.
*
* @example
* ```typescript
@@ -2089,7 +2154,7 @@ export class SIEClient {
async extract(
model: string,
items: ExtractItem | ExtractItem[],
- options: ExtractOptions,
+ options: ExtractOptions = {},
): Promise<ExtractResult | ExtractResult[]> {
const isSingleItem = !Array.isArray(items);
const itemsArray = isSingleItem ? [items] : items;
@@ -2100,17 +2165,28 @@ export class SIEClient {
items: itemsForWire,
};
- // Add params
- const params: Record<string, unknown> = {
- labels: options.labels,
- };
- if (options.threshold !== undefined) {
- params.threshold = options.threshold;
+ // Add params if any are specified
+ const params: Record<string, unknown> = {};
+ if (options.labels !== undefined) {
+ params.labels = options.labels;
}
- if (options.adapterOptions !== undefined) {
- params.options = options.adapterOptions;
+ if (options.outputSchema !== undefined) {
+ params.output_schema = options.outputSchema;
+ }
+ if (options.instruction !== undefined) {
+ params.instruction = options.instruction;
+ }
+ // `threshold` is a runtime option: the server reads it from
+ // `params.options` and ignores a `params.threshold` member.
+ const extractOptions = runtimeOptions(options.adapterOptions, {
+ threshold: options.threshold,
+ });
+ if (extractOptions !== undefined) {
+ params.options = extractOptions;
+ }
+ if (Object.keys(params).length > 0) {
+ body.params = params;
}
- body.params = params;
const waitForCapacity = options.waitForCapacity ?? this.defaultWaitForCapacity;
const { pool, gpu } = this.parseGpuParam(options.gpu);
@@ -2124,14 +2200,18 @@ export class SIEClient {
model,
);
- // Wire format response: {"items": [...]}
+ // Wire format response: {"model": "...", "items": [...]}
interface WireResponse {
+ model?: unknown;
items: unknown[];
}
const data = unpackMessage<WireResponse>(new Uint8Array(await response.arrayBuffer()));
const results = parseExtractResults(data.items);
+ if (typeof data.model === "string" && data.model) {
+ for (const result of results) result.model = data.model;
+ }
attachRequestMetadata(results, response.headers, data);
// Same positional contract as encode: `results[0]` below and index-based
// reassembly in batch callers both assume one result per input, and the
diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.ts
index 65d920137..41af2ef25 100644
--- a/packages/sie_ts_sdk/src/internal/parsing.ts
+++ b/packages/sie_ts_sdk/src/internal/parsing.ts
@@ -630,7 +630,7 @@ interface WireDetectedObject {
interface WireExtractResult {
id?: string;
- entities: WireEntity[];
+ entities?: WireEntity[];
relations?: WireRelation[];
classifications?: WireClassification[];
objects?: WireDetectedObject[];
@@ -856,7 +856,7 @@ function parseExtractItemError(data: unknown): ExtractItemError | undefined {
export function parseExtractResult(data: WireExtractResult): ExtractResult {
return {
id: data.id,
- entities: data.entities.map(parseEntity),
+ entities: (data.entities ?? []).map(parseEntity),
relations: (data.relations ?? []).map(
(r: WireRelation): Relation => ({
head: r.head,
diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.ts
index e9b84cc22..f0f2db1fb 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -199,6 +199,8 @@ export interface RequestMetadata {
* depending on what was requested via outputTypes.
*/
export interface EncodeResult {
+ /** Model identity returned by the server */
+ model?: string;
/** Item ID (echoed from request if provided) */
id?: string;
/** Dense embedding vector, shape [dims] */
@@ -555,6 +557,8 @@ export interface ExtractItemError {
* Result of extraction for a single item.
*/
export interface ExtractResult {
+ /** Model identity returned by the server */
+ model?: string;
/** Item ID (echoed from request if provided) */
id?: string;
/** List of extracted entities */
@@ -1057,6 +1061,13 @@ export interface EncodeOptions {
isQuery?: boolean;
/** Output dtype for quantization */
outputDtype?: DType;
+ /**
+ * Runtime options forwarded to the server as `params.options`: `profile` to
+ * select a named model profile, or adapter options such as `muvera`, `smve`
+ * or `normalize`. `isQuery` wins over an `is_query` entry here. This is the
+ * Python SDK's `options` keyword argument.
+ */
+ adapterOptions?: Record<string, unknown>;
/** GPU type for this request (overrides client default) */
gpu?: string;
/** Whether to wait for capacity (overrides client default) */
@@ -1067,6 +1078,14 @@ export interface EncodeOptions {
* Options for score operation.
*/
export interface ScoreOptions {
+ /** Instruction for instruction-tuned rerankers */
+ instruction?: string;
+ /**
+ * Runtime options forwarded to the server as `options`, such as `profile`
+ * to select a named model profile. This is the Python SDK's `options`
+ * keyword argument.
+ */
+ adapterOptions?: Record<string, unknown>;
/** GPU type for this request */
gpu?: string;
/** Whether to wait for capacity */
@@ -1307,7 +1326,7 @@ export type ChatFinishReason = "stop" | "length" | "tool_calls" | "content_filte
* The gateway honours: `model`, `messages`, `max_tokens` /
* `max_completion_tokens`, `temperature`, `top_p`, `top_k`, `stop`, `stream`,
* `stream_options`, `tools`, `tool_choice`, `parallel_tool_calls`,
- * `response_format`, `frequency_penalty`, `presence_penalty` (each in
+ * `response_format`, `schema_in_prompt`, `frequency_penalty`, `presence_penalty` (each in
* `[-2, 2]`), `repetition_penalty`, `n`, `best_of`, `logprobs`,
* `top_logprobs`, `logit_bias`, `seed`, `user`, `safety_identifier`,
* `lora_adapter`, `routing_key`, and `prompt_cache_key`. Unknown fields
@@ -1342,6 +1361,12 @@ export interface ChatCompletionRequest {
/** OpenAI parallel-tool-calls toggle (default `true`). */
parallel_tool_calls?: boolean;
response_format?: ResponseFormat;
+ /**
+ * SIE extension. A `json_schema` response format constrains decoding and is
+ * also shown to the model. `false` leaves the prompt as sent; the grammar
+ * still applies. Absent, the serving profile decides (default on).
+ */
+ schema_in_prompt?: boolean;
/** Accepted in the OpenAI range [-2, 2]; out-of-range values are rejected. */
frequency_penalty?: number;
presence_penalty?: number;
@@ -1585,20 +1610,30 @@ export interface GenerateChunk {
* Options for extract operation.
*/
export interface ExtractOptions {
- /** Entity labels to extract (e.g., ["person", "organization"]) */
- labels: string[];
- /** Minimum confidence threshold (0-1) */
+ /**
+ * Labels to extract or classify against (e.g., ["person", "organization"]).
+ * Omit for models that take none, such as OCR, document parsing, speech to
+ * text, and typed-decision models driven by `outputSchema`.
+ */
+ labels?: string[];
+ /** JSON schema, or a typed-decision question mapping, for structured output */
+ outputSchema?: Record<string, unknown>;
+ /** Task instruction for models trained to follow one */
+ instruction?: string;
+ /**
+ * Minimum confidence (0-1), sent as the `threshold` runtime option in
+ * `params.options`. Wins over a `threshold` entry in `adapterOptions`.
+ */
threshold?: number;
/** GPU type for this request */
gpu?: string;
/** Whether to wait for capacity */
waitForCapacity?: boolean;
/**
- * Adapter-specific runtime options forwarded to the server as
- * `params.options`. Used for adapter knobs that aren't part of the
- * core extract API — e.g. `{ overflow_policy: "error" }` for
- * gliclass token-budget control. Mirrors the Python SDK's `options`
- * keyword argument.
+ * Runtime options forwarded to the server as `params.options`: `profile`
+ * to select a named model profile, or adapter options such as
+ * `{ overflow_policy: "error" }` for gliclass token-budget control. This is
+ * the Python SDK's `options` keyword argument.
*/
adapterOptions?: Record<string, unknown>;
}
diff --git a/packages/sie_ts_sdk/tests/client.test.ts b/packages/sie_ts_sdk/tests/client.test.ts
index e8bb8d12f..e5f568ae6 100644
--- a/packages/sie_ts_sdk/tests/client.test.ts
+++ b/packages/sie_ts_sdk/tests/client.test.ts
@@ -1952,7 +1952,9 @@ describe("SIEClient.extract() - NER", () => {
expect(parsed.items?.[0]?.audio).toEqual({ data: audioBytes });
});
- it("should pass threshold option in params", async () => {
+ it("should send threshold as a runtime option in params.options", async () => {
+ // The server reads the threshold from params.options and ignores a
+ // params.threshold member, so that is where it has to go.
mockFetch.mockResolvedValueOnce(
createMsgpackResponse({
items: [{ entities: [] }],
@@ -1967,9 +1969,28 @@ describe("SIEClient.extract() - NER", () => {
const fetchCall = mockFetch.mock.calls[0];
const body = fetchCall?.[1]?.body as Uint8Array;
- const parsed = unpackMessage<{ params?: { threshold?: number } }>(body);
+ const parsed = unpackMessage<{
+ params?: { threshold?: number; options?: Record<string, unknown> };
+ }>(body);
+
+ expect(parsed.params?.options).toEqual({ threshold: 0.8 });
+ expect(parsed.params?.threshold).toBeUndefined();
+ });
+
+ it("should send no params when extract is called without options", async () => {
+ mockFetch.mockResolvedValueOnce(
+ createMsgpackResponse({
+ items: [{ entities: [] }],
+ }),
+ );
+
+ await client.extract("lightonai/LightOnOCR-2-1B", { text: "test" });
+
+ const fetchCall = mockFetch.mock.calls[0];
+ const body = fetchCall?.[1]?.body as Uint8Array;
+ const parsed = unpackMessage<Record<string, unknown>>(body);
- expect(parsed.params?.threshold).toBe(0.8);
+ expect(Object.keys(parsed)).toEqual(["items"]);
});
it("should forward adapterOptions as params.options on the wire", async () => {
diff --git a/packages/sie_ts_sdk/tests/sdkRequests.test.ts b/packages/sie_ts_sdk/tests/sdkRequests.test.ts
new file mode 100644
index 000000000..2ec089805
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/sdkRequests.test.ts
@@ -0,0 +1,480 @@
+/**
+ * The requests this SDK sends must match the shared request fixture.
+ *
+ * Every case of `packages/wire-fixtures/sdk_requests.json` is issued through
+ * the real client with `fetch` stubbed, and the request that reached the wire
+ * is compared with the fixture. The Python SDK replays the same cases in
+ * `test_sdk_requests.py`, so a call one SDK serializes differently, or cannot
+ * express, fails here or there.
+ */
+
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+import { packMessage, unpackMessage } from "../src/msgpack.js";
+import type { SIEClientOptions } from "../src/types.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+interface FixtureRequest {
+ method: string;
+ path: string;
+ headers: Record<string, string>;
+ body: unknown;
+ may_send_default?: Record<string, unknown>;
+}
+
+interface FixtureCase {
+ id: string;
+ summary: string;
+ client?: { gpu?: string; remote?: "forbid" };
+ request: FixtureRequest;
+}
+
+const fixture = JSON.parse(
+ readFileSync(
+ fileURLToPath(new URL("../../wire-fixtures/sdk_requests.json", import.meta.url)),
+ "utf8",
+ ),
+) as {
+ client: { api_key: string };
+ media: Record<string, string>;
+ compared_headers: string[];
+ cases: FixtureCase[];
+};
+
+const BASE_URL = "http://sie.test";
+
+function media(name: string): Uint8Array {
+ const encoded = fixture.media[name];
+ if (encoded === undefined) throw new Error(`fixture has no media named ${name}`);
+ return new Uint8Array(Buffer.from(encoded, "base64"));
+}
+
+const SCHEMA = {
+ type: "object",
+ properties: { vendor: { type: "string" }, total: { type: "number" } },
+ required: ["vendor", "total"],
+};
+const QUERY = { text: "What is machine learning?" };
+const DOCUMENTS = [
+ { id: "doc-1", text: "Machine learning is a subfield of AI." },
+ { id: "doc-2", text: "Python is a programming language." },
+];
+const ENTITY_TEXT = { text: "Apple was founded by Steve Jobs." };
+
+async function drain(stream: AsyncIterable<unknown>): Promise<void> {
+ for await (const _chunk of stream) {
+ // The request is what is under test; the chunks are discarded.
+ }
+}
+
+/** The call each fixture case stands for, spelled with this SDK's options. */
+const CALLS: Record<string, (client: SIEClient) => Promise<unknown>> = {
+ encode_single_text: (client) => client.encode("BAAI/bge-m3", { text: "hello" }),
+ encode_batch_all_params: (client) =>
+ client.encode(
+ "BAAI/bge-m3",
+ [
+ { id: "a", text: "first" },
+ { id: "b", text: "second" },
+ ],
+ {
+ outputTypes: ["dense", "sparse"],
+ instruction: "Represent the query",
+ outputDtype: "float16",
+ isQuery: true,
+ },
+ ),
+ encode_profile_option: (client) =>
+ client.encode(
+ "lightonai/GTE-ModernColBERT-v1",
+ { text: "a long document" },
+ {
+ outputTypes: ["multivector"],
+ isQuery: false,
+ adapterOptions: { profile: "long_context" },
+ },
+ ),
+ encode_model_profile_id: (client) => client.encode("BAAI/bge-m3:sparse", { text: "hello" }),
+ encode_image: (client) =>
+ client.encode("google/siglip2-base-patch16-224", { images: [media("png")] }),
+ encode_pool_and_gpu: (client) =>
+ client.encode("BAAI/bge-m3", { text: "hello" }, { gpu: "eval-bench/l4" }),
+ encode_client_defaults: (client) => client.encode("BAAI/bge-m3", { text: "hello" }),
+ score_basic: (client) => client.score("BAAI/bge-reranker-v2-m3", QUERY, DOCUMENTS),
+ score_instruction_and_options: (client) =>
+ client.score("Qwen/Qwen3-Reranker-4B", QUERY, DOCUMENTS, {
+ instruction: "Rank passages that answer the question",
+ adapterOptions: { profile: "default" },
+ }),
+ extract_labels: (client) =>
+ client.extract("urchade/gliner_multi-v2.1", ENTITY_TEXT, {
+ labels: ["person", "organization"],
+ }),
+ extract_threshold: (client) =>
+ client.extract("urchade/gliner_multi-v2.1", ENTITY_TEXT, {
+ labels: ["person", "organization"],
+ threshold: 0.75,
+ }),
+ extract_image_without_params: (client) =>
+ client.extract("lightonai/LightOnOCR-2-1B", { images: [media("png")] }),
+ extract_output_schema_and_instruction: (client) =>
+ client.extract(
+ "fastino/GLiNER2.5-Decide",
+ { text: "Get me a person. This is the third time." },
+ {
+ outputSchema: {
+ handoff: { type: "noul", instructions: "Should a person take over?" },
+ },
+ instruction: "Triage the support ticket.",
+ adapterOptions: { overflow_policy: "truncate_text" },
+ },
+ ),
+ extract_audio: (client) =>
+ client.extract("openai/whisper-large-v3-turbo", {
+ audio: { data: media("wav"), format: "wav", sampleRate: 16_000 },
+ }),
+ extract_document: (client) =>
+ client.extract("docling", { document: { data: media("pdf"), format: "pdf" } }),
+ generate_basic: (client) =>
+ client.generate("Qwen/Qwen3-4B-Instruct-2507", "Write a haiku about the sea.", {
+ maxNewTokens: 64,
+ temperature: 0.7,
+ }),
+ generate_all_fields: (client) =>
+ client.generate(
+ "google/gemma-4-31B-it:h100-96k-hires-thinking-budget512-no-spec",
+ "Extract the invoice.",
+ {
+ maxNewTokens: 256,
+ temperature: 0,
+ topP: 0.9,
+ stop: ["\n\n"],
+ frequencyPenalty: 0.5,
+ presencePenalty: 0.25,
+ grammar: { json_schema: SCHEMA, strict: true },
+ seed: 7,
+ logitBias: { "42": -1.5 },
+ routingKey: "tenant-1",
+ promptCacheKey: "invoice-v1",
+ safetyIdentifier: "user-9",
+ loraAdapter: "invoices",
+ adapterOptions: { overall_timeout_s: 30 },
+ },
+ ),
+ generate_image: (client) =>
+ client.generate("Qwen/Qwen3-VL-8B-Instruct", "Describe the image.", {
+ maxNewTokens: 32,
+ images: [media("png")],
+ }),
+ stream_generate: (client) =>
+ drain(
+ client.streamGenerate("Qwen/Qwen3-4B-Instruct-2507", "Write a haiku.", {
+ maxNewTokens: 64,
+ temperature: 0.7,
+ logprobs: true,
+ topLogprobs: 2,
+ }),
+ ),
+ chat_completions: (client) =>
+ client.chatCompletions({
+ model: "Qwen/Qwen3-4B-Instruct-2507",
+ messages: [
+ { role: "system", content: "Answer in JSON." },
+ { role: "user", content: "Extract the invoice fields." },
+ ],
+ max_completion_tokens: 256,
+ temperature: 0,
+ response_format: {
+ type: "json_schema",
+ json_schema: { name: "invoice", strict: true, schema: SCHEMA },
+ },
+ schema_in_prompt: false,
+ }),
+ stream_chat_completions: (client) =>
+ drain(
+ client.streamChatCompletions({
+ model: "Qwen/Qwen3-4B-Instruct-2507",
+ messages: [{ role: "user", content: "Count to ten." }],
+ max_completion_tokens: 64,
+ stream_options: { include_usage: true },
+ }),
+ ),
+};
+
+function msgpackResponse(body: unknown): Response {
+ return new Response(packMessage(body), {
+ status: 200,
+ headers: { "Content-Type": "application/msgpack" },
+ });
+}
+
+/** A minimal success for the route, shaped by what the request asked for. */
+function successFor(path: string, accept: string | undefined, itemCount: number): Response {
+ if (path.startsWith("/v1/encode/")) {
+ const items = Array.from({ length: itemCount }, () => ({
+ dense: { values: new Float32Array([0.5]) },
+ }));
+ return msgpackResponse({ model: "m", items });
+ }
+ if (path.startsWith("/v1/score/")) {
+ return msgpackResponse({ model: "m", scores: [{ item_id: "doc-1", score: 0.5, rank: 0 }] });
+ }
+ if (path.startsWith("/v1/extract/")) {
+ const items = Array.from({ length: itemCount }, () => ({ entities: [] }));
+ return msgpackResponse({ model: "m", items });
+ }
+ if (accept === "text/event-stream") {
+ return new Response("data: [DONE]\n\n", {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ });
+ }
+ const body = path.startsWith("/v1/generate/")
+ ? { model: "m", text: "ok", finish_reason: "stop" }
+ : { id: "chat-1", object: "chat.completion", model: "m", choices: [] };
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+/** Fixture view of a decoded body: bytes named by media, `null` members dropped. */
+function canonical(value: unknown): unknown {
+ if (value instanceof Uint8Array) {
+ const base64 = Buffer.from(value).toString("base64");
+ const name = Object.keys(fixture.media).find((key) => fixture.media[key] === base64);
+ return name === undefined ? { $bytes: base64 } : { $media: name };
+ }
+ if (Array.isArray(value)) return value.map(canonical);
+ if (typeof value === "object" && value !== null) {
+ const entries = Object.entries(value as Record<string, unknown>)
+ .filter(([, member]) => member !== null && member !== undefined)
+ .map(([key, member]) => [key, canonical(member)] as const)
+ .sort(([left], [right]) => left.localeCompare(right));
+ return Object.fromEntries(entries);
+ }
+ return value;
+}
+
+/** The fixture's expected body with base64 media references resolved. */
+function expectedBody(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(expectedBody);
+ if (typeof value === "object" && value !== null) {
+ const record = value as Record<string, unknown>;
+ if (typeof record.$media_base64 === "string") return fixture.media[record.$media_base64];
+ return canonical(
+ Object.fromEntries(
+ Object.entries(record).map(([key, member]) => [key, expectedBody(member)]),
+ ),
+ );
+ }
+ return value;
+}
+
+interface SentRequest {
+ method: string | undefined;
+ path: string;
+ headers: Record<string, string>;
+ body: unknown;
+}
+
+function sentRequest(): SentRequest {
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ const [url, init] = mockFetch.mock.calls[0] as [string, RequestInit];
+ const headers = Object.fromEntries(
+ Object.entries(init.headers as Record<string, string>).map(([name, value]) => [
+ name.toLowerCase(),
+ value,
+ ]),
+ );
+ const raw = init.body;
+ const body =
+ headers["content-type"] === "application/msgpack"
+ ? unpackMessage(raw as Uint8Array)
+ : JSON.parse(raw as string);
+ return {
+ method: init.method,
+ path: decodeURIComponent(new URL(url).pathname),
+ headers,
+ body: canonical(body),
+ };
+}
+
+describe("shared SDK request fixture", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ mockFetch.mockImplementation(async (url: string, init: RequestInit) => {
+ const headers = init.headers as Record<string, string>;
+ const isMsgpack = headers["Content-Type"] === "application/msgpack";
+ const decoded = isMsgpack
+ ? unpackMessage<{ items?: unknown[] }>(init.body as Uint8Array)
+ : undefined;
+ return successFor(new URL(url).pathname, headers.Accept, decoded?.items?.length ?? 1);
+ });
+ });
+
+ it("has a call for every case, and no call without a case", () => {
+ expect(Object.keys(CALLS).sort()).toEqual(fixture.cases.map((entry) => entry.id).sort());
+ });
+
+ it.each(fixture.cases.map((entry) => [entry.id, entry] as const))("%s", async (_id, entry) => {
+ const options: SIEClientOptions = { apiKey: fixture.client.api_key, ...entry.client };
+ const client = new SIEClient(BASE_URL, options);
+ const call = CALLS[entry.id];
+ if (call === undefined) throw new Error(`no call for fixture case ${entry.id}`);
+
+ await call(client);
+ await client.close();
+
+ const sent = sentRequest();
+ expect(sent.method).toBe(entry.request.method);
+ expect(sent.path).toBe(entry.request.path);
+ for (const name of fixture.compared_headers) {
+ expect({ [name]: sent.headers[name] }).toEqual({ [name]: entry.request.headers[name] });
+ }
+ expect(sent.headers["x-sie-sdk-version"]).toBeTruthy();
+
+ const body = sent.body as Record<string, unknown>;
+ for (const [member, value] of Object.entries(entry.request.may_send_default ?? {})) {
+ if (member in body) {
+ expect({ [member]: body[member] }).toEqual({ [member]: value });
+ delete body[member];
+ }
+ }
+ expect(body).toEqual(expectedBody(entry.request.body));
+ });
+});
+
+describe("encode and extract results", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it("repeats the response's model and timing on each encode result", async () => {
+ mockFetch.mockResolvedValueOnce(
+ msgpackResponse({
+ model: "BAAI/bge-m3",
+ items: [
+ { id: "a", dense: { values: new Float32Array([0.5]) } },
+ { id: "b", dense: { values: new Float32Array([0.25]) } },
+ ],
+ timing: { total_ms: 12.5, queue_ms: 1, tokenization_ms: 2, inference_ms: 9.5 },
+ }),
+ );
+ const client = new SIEClient(BASE_URL);
+
+ const results = await client.encode("BAAI/bge-m3", [{ text: "first" }, { text: "second" }]);
+
+ for (const result of results) {
+ expect(result.model).toBe("BAAI/bge-m3");
+ expect(result.timing).toEqual({
+ totalMs: 12.5,
+ queueMs: 1,
+ tokenizationMs: 2,
+ inferenceMs: 9.5,
+ });
+ }
+ });
+
+ it("leaves model and timing unset when the response carries neither", async () => {
+ mockFetch.mockResolvedValueOnce(
+ msgpackResponse({ items: [{ dense: { values: new Float32Array([0.5]) } }] }),
+ );
+ const client = new SIEClient(BASE_URL);
+
+ const result = await client.encode("BAAI/bge-m3", { text: "hello" });
+
+ expect(result.model).toBeUndefined();
+ expect(result.timing).toBeUndefined();
+ });
+
+ it("repeats the response's model on each extract result", async () => {
+ mockFetch.mockResolvedValueOnce(
+ msgpackResponse({
+ model: "urchade/gliner_multi-v2.1",
+ items: [{ entities: [] }, { entities: [] }],
+ }),
+ );
+ const client = new SIEClient(BASE_URL);
+
+ const results = await client.extract(
+ "urchade/gliner_multi-v2.1",
+ [{ text: "first" }, { text: "second" }],
+ { labels: ["person"] },
+ );
+
+ expect(results.map((result) => result.model)).toEqual([
+ "urchade/gliner_multi-v2.1",
+ "urchade/gliner_multi-v2.1",
+ ]);
+ });
+
+ it("reads an extract result without an entities member as having none", async () => {
+ mockFetch.mockResolvedValueOnce(
+ msgpackResponse({ model: "docling", items: [{ data: { text: "hello" } }] }),
+ );
+ const client = new SIEClient(BASE_URL);
+
+ const result = await client.extract("docling", { text: "hello" });
+
+ expect(result.entities).toEqual([]);
+ expect(result.data).toEqual({ text: "hello" });
+ });
+});
+
+describe("runtime options", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ mockFetch.mockImplementation(async () => msgpackResponse({ model: "m", items: [{}] }));
+ });
+
+ function sentParams(): Record<string, unknown> | undefined {
+ const [, init] = mockFetch.mock.calls[0] as [string, RequestInit];
+ return unpackMessage<{ params?: Record<string, unknown> }>(init.body as Uint8Array).params;
+ }
+
+ it("lets isQuery win over an is_query runtime option on encode", async () => {
+ const client = new SIEClient(BASE_URL);
+
+ await client.encode(
+ "BAAI/bge-m3",
+ { text: "hello" },
+ { isQuery: true, adapterOptions: { is_query: false, normalize: true } },
+ );
+
+ expect(sentParams()?.options).toEqual({ is_query: true, normalize: true });
+ });
+
+ it("lets threshold win over a threshold runtime option on extract", async () => {
+ const client = new SIEClient(BASE_URL);
+
+ await client.extract(
+ "urchade/gliner_multi-v2.1",
+ { text: "hello" },
+ { labels: ["person"], threshold: 0.75, adapterOptions: { threshold: 0.25, flat_ner: true } },
+ );
+
+ expect(sentParams()?.options).toEqual({ threshold: 0.75, flat_ner: true });
+ });
+
+ it("labels an image with an unrecognized signature as jpeg", async () => {
+ const client = new SIEClient(BASE_URL);
+ const bytes = new Uint8Array([1, 2, 3, 4, 5]);
+
+ await client.encode("google/siglip2-base-patch16-224", { images: [bytes] });
+
+ const [, init] = mockFetch.mock.calls[0] as [string, RequestInit];
+ const sent = unpackMessage<{ items: { images: unknown[] }[] }>(init.body as Uint8Array);
+ expect(sent.items[0]?.images).toEqual([{ data: bytes, format: "jpeg" }]);
+ });
+});
+
+describe("base URL", () => {
+ it("drops every trailing slash", () => {
+ expect(new SIEClient("http://localhost:8080//").getBaseUrl()).toBe("http://localhost:8080");
+ });
+});
diff --git a/packages/sie_ts_sdk/tests/typecheck/primitive-options.ts b/packages/sie_ts_sdk/tests/typecheck/primitive-options.ts
new file mode 100644
index 000000000..9222e720a
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/typecheck/primitive-options.ts
@@ -0,0 +1,58 @@
+import type { SIEClient } from "../../src/client.js";
+import type {
+ ChatCompletionRequest,
+ EncodeOptions,
+ ExtractOptions,
+ ScoreOptions,
+} from "../../src/types.js";
+
+declare const client: SIEClient;
+declare const image: Uint8Array;
+
+// Extract takes no options for models without labels (OCR, speech, documents).
+void client.extract("lightonai/LightOnOCR-2-1B", { images: [image] });
+void client.extract("lightonai/LightOnOCR-2-1B", [{ images: [image] }]);
+
+// Labels are one of several ways to say what to extract.
+const typedDecisions: ExtractOptions = {
+ outputSchema: { handoff: { type: "noul", instructions: "Should a person take over?" } },
+ instruction: "Triage the support ticket.",
+ adapterOptions: { overflow_policy: "truncate_text" },
+};
+void client.extract("fastino/GLiNER2.5-Decide", { text: "Get me a person." }, typedDecisions);
+
+const entities: ExtractOptions = { labels: ["person"], threshold: 0.75 };
+void client.extract("urchade/gliner_multi-v2.1", { text: "Tim Cook leads Apple." }, entities);
+
+// Encode and score accept the runtime options the Python SDK names `options`.
+const encodeOptions: EncodeOptions = {
+ outputTypes: ["multivector"],
+ isQuery: false,
+ adapterOptions: { profile: "long_context" },
+};
+void client.encode("lightonai/GTE-ModernColBERT-v1", { text: "a long document" }, encodeOptions);
+
+const scoreOptions: ScoreOptions = {
+ instruction: "Rank passages that answer the question",
+ adapterOptions: { profile: "default" },
+};
+void client.score("Qwen/Qwen3-Reranker-4B", { text: "query" }, [{ text: "doc" }], scoreOptions);
+
+// Results name the model that served them.
+void client.encode("BAAI/bge-m3", { text: "hello" }).then((result) => {
+ const model: string | undefined = result.model;
+ return model;
+});
+void client.extract("urchade/gliner_multi-v2.1", { text: "hello" }).then((result) => {
+ const model: string | undefined = result.model;
+ return model;
+});
+
+// The gateway's schema_in_prompt chat field is part of the request type.
+const chat: ChatCompletionRequest = {
+ model: "Qwen/Qwen3-4B-Instruct-2507",
+ messages: [{ role: "user", content: "Extract the invoice fields." }],
+ response_format: { type: "json_schema", json_schema: { name: "invoice", schema: {} } },
+ schema_in_prompt: false,
+};
+void client.chatCompletions(chat);
diff --git a/packages/wire-fixtures/README.md b/packages/wire-fixtures/README.md
index 0002c5fcc..92ba7a613 100644
--- a/packages/wire-fixtures/README.md
+++ b/packages/wire-fixtures/README.md
@@ -35,6 +35,13 @@ executable.
score, extract) and for generation, keyed by status, error code, and whether
a usable `Retry-After` is present. It also pins how a `Retry-After` value is
parsed (delay seconds or an HTTP date; a past date means retry now).
+- `sdk_requests.json` — the HTTP request each SDK sends for the same call to
+ encode, score, extract, generate and the chat route: method, path, the
+ headers that carry meaning, and the decoded body. Each case names one call;
+ each SDK spells that call with its own options and must put the same request
+ on the wire. The file states what counts as the same: paths are compared
+ percent-decoded, a `null` member equals an absent one, and a case may list
+ members an SDK is free to send at the server's default.
- `serving_disclosure.json` — remote serving: the `X-SIE-Remote: forbid`
request header a caller sends to keep a request off remote upstreams, and the
response headers that say which side served (`X-SIE-Served-By`,
@@ -74,7 +81,13 @@ fixture set. Current consumers:
server). `test_wire_contract.py` also asserts the header names, values and
patterns of `serving_disclosure.json` against the client constants and
`RequestMetadata`.
-- TypeScript SDK — `packages/sie_ts_sdk/tests/wireContract.test.ts` (asserts the
+ `packages/sie_sdk/tests/client/test_sdk_requests.py` issues every
+ `sdk_requests.json` case through the sync and the async client against a
+ local HTTP server and compares the request that arrived.
+- TypeScript SDK — `packages/sie_ts_sdk/tests/sdkRequests.test.ts` (issues every
+ `sdk_requests.json` case through the client with a stubbed `fetch` and
+ compares the request it sent; a case the SDK has no call for fails),
+ `packages/sie_ts_sdk/tests/wireContract.test.ts` (asserts the
runtime `MODEL_STATES` and `MODEL_INFO_WIRE_FIELDS` arrays — the single
sources the `ModelState` type and `WireModelInfo` interface are checked
against — match the fixtures), and
diff --git a/packages/wire-fixtures/sdk_requests.json b/packages/wire-fixtures/sdk_requests.json
new file mode 100644
index 000000000..a804466e9
--- /dev/null
+++ b/packages/wire-fixtures/sdk_requests.json
@@ -0,0 +1,457 @@
+{
+ "description": "The HTTP request each SDK sends for the same call to a native primitive or the chat route. Every SDK replays every case through its real client and compares what reached the wire. A case an SDK cannot express fails that SDK's test.",
+ "client": {
+ "api_key": "sk-sie-fixture"
+ },
+ "media": {
+ "png": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC",
+ "wav": "UklGRiwAAABXQVZFZm10IBAAAAABAAEAgD4AAAB9AAACABAAZGF0YQgAAAAAAOgDAAAY/A==",
+ "pdf": "JVBERi0xLjQKJSVFT0YK"
+ },
+ "comparison": {
+ "path": "Compared after percent-decoding: `/v1/encode/BAAI%2Fbge-m3` and `/v1/encode/BAAI/bge-m3` reach the same route.",
+ "headers": "The headers listed in `compared_headers` must equal the case's `headers`; one the case does not list must be absent. Every request also carries a non-empty `x-sie-sdk-version`.",
+ "body": "Decoded from MessagePack or JSON by content type. A `null` member equals an absent one. `{\"$media\": name}` stands for the raw bytes of `media[name]`, and `{\"$media_base64\": name}` for its base64 text.",
+ "may_send_default": "Members an SDK may send or omit. When sent, the value must equal the one listed, which is the server's default."
+ },
+ "compared_headers": [
+ "accept",
+ "authorization",
+ "content-type",
+ "x-sie-machine-profile",
+ "x-sie-pool",
+ "x-sie-remote"
+ ],
+ "cases": [
+ {
+ "id": "encode_single_text",
+ "summary": "encode one text item with no options",
+ "request": {
+ "method": "POST",
+ "path": "/v1/encode/BAAI/bge-m3",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [{ "text": "hello" }]
+ }
+ }
+ },
+ {
+ "id": "encode_batch_all_params",
+ "summary": "encode a batch with output types, instruction, output dtype and the query role",
+ "request": {
+ "method": "POST",
+ "path": "/v1/encode/BAAI/bge-m3",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [
+ { "id": "a", "text": "first" },
+ { "id": "b", "text": "second" }
+ ],
+ "params": {
+ "output_types": ["dense", "sparse"],
+ "instruction": "Represent the query",
+ "output_dtype": "float16",
+ "options": { "is_query": true }
+ }
+ }
+ }
+ },
+ {
+ "id": "encode_profile_option",
+ "summary": "encode with a named profile selected through runtime options, as a document",
+ "request": {
+ "method": "POST",
+ "path": "/v1/encode/lightonai/GTE-ModernColBERT-v1",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [{ "text": "a long document" }],
+ "params": {
+ "output_types": ["multivector"],
+ "options": { "profile": "long_context", "is_query": false }
+ }
+ }
+ }
+ },
+ {
+ "id": "encode_model_profile_id",
+ "summary": "encode addressing a profile as model:profile",
+ "request": {
+ "method": "POST",
+ "path": "/v1/encode/BAAI/bge-m3:sparse",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [{ "text": "hello" }]
+ }
+ }
+ },
+ {
+ "id": "encode_image",
+ "summary": "encode PNG bytes; the image carries the format its signature names",
+ "request": {
+ "method": "POST",
+ "path": "/v1/encode/google/siglip2-base-patch16-224",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [{ "images": [{ "data": { "$media": "png" }, "format": "png" }] }]
+ }
+ }
+ },
+ {
+ "id": "encode_pool_and_gpu",
+ "summary": "encode routed to a pool and machine profile with gpu \"eval-bench/l4\"",
+ "request": {
+ "method": "POST",
+ "path": "/v1/encode/BAAI/bge-m3",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack",
+ "x-sie-machine-profile": "l4",
+ "x-sie-pool": "eval-bench"
+ },
+ "body": {
+ "items": [{ "text": "hello" }]
+ }
+ }
+ },
+ {
+ "id": "encode_client_defaults",
+ "summary": "encode through a client built with a default gpu and remote \"forbid\"",
+ "client": { "gpu": "l4", "remote": "forbid" },
+ "request": {
+ "method": "POST",
+ "path": "/v1/encode/BAAI/bge-m3",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack",
+ "x-sie-machine-profile": "l4",
+ "x-sie-remote": "forbid"
+ },
+ "body": {
+ "items": [{ "text": "hello" }]
+ }
+ }
+ },
+ {
+ "id": "score_basic",
+ "summary": "score two documents against a query",
+ "request": {
+ "method": "POST",
+ "path": "/v1/score/BAAI/bge-reranker-v2-m3",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "query": { "text": "What is machine learning?" },
+ "items": [
+ { "id": "doc-1", "text": "Machine learning is a subfield of AI." },
+ { "id": "doc-2", "text": "Python is a programming language." }
+ ]
+ }
+ }
+ },
+ {
+ "id": "score_instruction_and_options",
+ "summary": "score with an instruction and a named profile",
+ "request": {
+ "method": "POST",
+ "path": "/v1/score/Qwen/Qwen3-Reranker-4B",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "query": { "text": "What is machine learning?" },
+ "items": [
+ { "id": "doc-1", "text": "Machine learning is a subfield of AI." },
+ { "id": "doc-2", "text": "Python is a programming language." }
+ ],
+ "instruction": "Rank passages that answer the question",
+ "options": { "profile": "default" }
+ }
+ }
+ },
+ {
+ "id": "extract_labels",
+ "summary": "extract entities for two labels",
+ "request": {
+ "method": "POST",
+ "path": "/v1/extract/urchade/gliner_multi-v2.1",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [{ "text": "Apple was founded by Steve Jobs." }],
+ "params": { "labels": ["person", "organization"] }
+ }
+ }
+ },
+ {
+ "id": "extract_threshold",
+ "summary": "extract with a confidence threshold, which is a runtime option",
+ "request": {
+ "method": "POST",
+ "path": "/v1/extract/urchade/gliner_multi-v2.1",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [{ "text": "Apple was founded by Steve Jobs." }],
+ "params": {
+ "labels": ["person", "organization"],
+ "options": { "threshold": 0.75 }
+ }
+ }
+ }
+ },
+ {
+ "id": "extract_image_without_params",
+ "summary": "extract from an image with no labels or options, as OCR does",
+ "request": {
+ "method": "POST",
+ "path": "/v1/extract/lightonai/LightOnOCR-2-1B",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [{ "images": [{ "data": { "$media": "png" }, "format": "png" }] }]
+ }
+ }
+ },
+ {
+ "id": "extract_output_schema_and_instruction",
+ "summary": "extract typed decisions with an output schema, an instruction and runtime options",
+ "request": {
+ "method": "POST",
+ "path": "/v1/extract/fastino/GLiNER2.5-Decide",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [{ "text": "Get me a person. This is the third time." }],
+ "params": {
+ "output_schema": {
+ "handoff": { "type": "noul", "instructions": "Should a person take over?" }
+ },
+ "instruction": "Triage the support ticket.",
+ "options": { "overflow_policy": "truncate_text" }
+ }
+ }
+ }
+ },
+ {
+ "id": "extract_audio",
+ "summary": "extract from encoded audio with a format and sample rate",
+ "request": {
+ "method": "POST",
+ "path": "/v1/extract/openai/whisper-large-v3-turbo",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [{ "audio": { "data": { "$media": "wav" }, "format": "wav", "sample_rate": 16000 } }]
+ }
+ }
+ },
+ {
+ "id": "extract_document",
+ "summary": "extract from a PDF document",
+ "request": {
+ "method": "POST",
+ "path": "/v1/extract/docling",
+ "headers": {
+ "accept": "application/msgpack",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/msgpack"
+ },
+ "body": {
+ "items": [{ "document": { "data": { "$media": "pdf" }, "format": "pdf" } }]
+ }
+ }
+ },
+ {
+ "id": "generate_basic",
+ "summary": "generate with a token cap and a temperature",
+ "request": {
+ "method": "POST",
+ "path": "/v1/generate/Qwen__Qwen3-4B-Instruct-2507",
+ "headers": {
+ "accept": "application/json",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/json"
+ },
+ "body": {
+ "prompt": "Write a haiku about the sea.",
+ "max_new_tokens": 64,
+ "temperature": 0.7
+ }
+ }
+ },
+ {
+ "id": "generate_all_fields",
+ "summary": "generate on a model:profile identity with every sampler, grammar and routing field",
+ "request": {
+ "method": "POST",
+ "path": "/v1/generate/google__gemma-4-31B-it:h100-96k-hires-thinking-budget512-no-spec",
+ "headers": {
+ "accept": "application/json",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/json"
+ },
+ "body": {
+ "prompt": "Extract the invoice.",
+ "max_new_tokens": 256,
+ "temperature": 0,
+ "top_p": 0.9,
+ "stop": ["\n\n"],
+ "frequency_penalty": 0.5,
+ "presence_penalty": 0.25,
+ "grammar": {
+ "json_schema": {
+ "type": "object",
+ "properties": { "vendor": { "type": "string" }, "total": { "type": "number" } },
+ "required": ["vendor", "total"]
+ },
+ "strict": true
+ },
+ "seed": 7,
+ "logit_bias": { "42": -1.5 },
+ "routing_key": "tenant-1",
+ "prompt_cache_key": "invoice-v1",
+ "safety_identifier": "user-9",
+ "lora_adapter": "invoices",
+ "options": { "overall_timeout_s": 30 }
+ }
+ }
+ },
+ {
+ "id": "generate_image",
+ "summary": "generate from a prompt and a PNG image",
+ "request": {
+ "method": "POST",
+ "path": "/v1/generate/Qwen__Qwen3-VL-8B-Instruct",
+ "headers": {
+ "accept": "application/json",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/json"
+ },
+ "body": {
+ "prompt": "Describe the image.",
+ "max_new_tokens": 32,
+ "images": [{ "data": { "$media_base64": "png" }, "format": "png" }]
+ }
+ }
+ },
+ {
+ "id": "stream_generate",
+ "summary": "stream a generation with log probabilities",
+ "request": {
+ "method": "POST",
+ "path": "/v1/generate/Qwen__Qwen3-4B-Instruct-2507",
+ "headers": {
+ "accept": "text/event-stream",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/json"
+ },
+ "body": {
+ "prompt": "Write a haiku.",
+ "max_new_tokens": 64,
+ "stream": true,
+ "temperature": 0.7,
+ "logprobs": true,
+ "top_logprobs": 2
+ }
+ }
+ },
+ {
+ "id": "chat_completions",
+ "summary": "chat completion with a json_schema response format kept out of the prompt",
+ "request": {
+ "method": "POST",
+ "path": "/v1/chat/completions",
+ "headers": {
+ "accept": "application/json",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/json"
+ },
+ "body": {
+ "model": "Qwen/Qwen3-4B-Instruct-2507",
+ "messages": [
+ { "role": "system", "content": "Answer in JSON." },
+ { "role": "user", "content": "Extract the invoice fields." }
+ ],
+ "max_completion_tokens": 256,
+ "temperature": 0,
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "invoice",
+ "strict": true,
+ "schema": {
+ "type": "object",
+ "properties": { "vendor": { "type": "string" }, "total": { "type": "number" } },
+ "required": ["vendor", "total"]
+ }
+ }
+ },
+ "schema_in_prompt": false
+ },
+ "may_send_default": { "stream": false }
+ }
+ },
+ {
+ "id": "stream_chat_completions",
+ "summary": "stream a chat completion with a final usage chunk",
+ "request": {
+ "method": "POST",
+ "path": "/v1/chat/completions",
+ "headers": {
+ "accept": "text/event-stream",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/json"
+ },
+ "body": {
+ "model": "Qwen/Qwen3-4B-Instruct-2507",
+ "messages": [{ "role": "user", "content": "Count to ten." }],
+ "stream": true,
+ "max_completion_tokens": 64,
+ "stream_options": { "include_usage": true }
+ }
+ }
+ }
+ ]
+}