Skip to content

armgit / sie

Public Imported from GitHub
0

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

12.7 KB
Raw Blame

@superlinked/sie-sdk

Official TypeScript SDK for SIE (Search Inference Engine). Async-only, built on native fetch, works in Node.js (>= 22) and the browser.

Installation

npm install @superlinked/sie-sdk

Creating a client

import { SIEClient } from "@superlinked/sie-sdk";

// SIE Serverless (https://api.superlinked.com). Server-side only, see below.
const client = new SIEClient(); // reads SIE_API_KEY

// Local server
const local = new SIEClient("http://localhost:8080");

// Another SIE gateway: pass its URL and your API key
// (sent as a Bearer token). Server-side code only — see below.
const managed = new SIEClient("https://your-gateway.example.com", {
  apiKey: "YOUR_API_KEY",
});

The client takes its base URL from baseUrl, then SIE_BASE_URL (in Node.js), then SIE Serverless when an API key is available (apiKey, or SIE_API_KEY when apiKey is omitted), so new SIEClient(undefined, { apiKey }) also targets SIE Serverless. With none of these it throws a TypeError; it does not assume a local server. Keys issued for the EU region use https://eu.api.superlinked.com; set SIE_BASE_URL to it. Set SIE_BASE_URL alongside a key for your own gateway too, or new SIEClient() sends that key to SIE Serverless.

An omitted apiKey selects SIE_API_KEY only for a base URL with the same origin as SIE_BASE_URL, or as SIE Serverless while SIE_BASE_URL is unset; a client for any other URL, such as http://localhost:8080, does not pick it up. An explicit value always wins; apiKey: "" sends no credential and does not select SIE Serverless. The connections namespace reuses the client's key on requests to an explicitly configured controlPlaneUrl, so a client whose controlPlaneUrl is on another origin must pass apiKey explicitly rather than rely on SIE_API_KEY.

Warning: only pass apiKey in server-side code. Shipping it in a browser bundle exposes the bearer key to anyone who loads the page. For browser apps, route requests through a backend proxy that holds the key.

Cold-start continuations: non-streaming requests through a managed gateway may receive a bounded Modal result continuation. Consuming it safely requires a server-side Fetch runtime (Node.js >= 22) that exposes the status and Location of a redirect: "manual" response. Browser Fetch exposes an opaque redirect instead, so the SDK fails closed; route these browser calls through a backend proxy as well.

Encoding

// Single item — result.dense is a Float32Array
const result = await client.encode("BAAI/bge-m3", { text: "Hello world" });
console.log(result.dense?.length); // 1024

// Batch — results come back in input order
const results = await client.encode("BAAI/bge-m3", [
  { text: "First document" },
  { text: "Second document" },
]);

Scoring (reranking)

const scored = await client.score(
  "BAAI/bge-reranker-v2-m3",
  { text: "What is machine learning?" },
  [
    { id: "doc-1", text: "Machine learning is a subfield of AI." },
    { id: "doc-2", text: "Python is a programming language." },
  ],
);
// Sorted by relevance (rank 0 = most relevant)
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

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 (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.

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.

responses and streamResponses take the OpenAI Responses shape and keep no state: send the whole conversation in input every turn, including earlier output items and the function_call_output or custom_tool_call_output items that answer tool calls. Both take instructions, function and custom tools, tool_choice, reasoning (effort), text (format), and base64 data: input_image parts. streamResponses yields typed events and throws SIEStreamError on response.failed:

for await (const event of client.streamResponses({
  model: "Qwen/Qwen3-4B-Instruct-2507",
  instructions: "Answer in English.",
  input: "Write a haiku about the sea.",
})) {
  if (event.type === "response.output_text.delta") process.stdout.write(event.delta);
}

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 invalid_guard_verdict. Never interpret an error or empty output as safe. Reasoning remains private. A budget exhausted during reasoning returns an empty answer whose finish reason is "length"; a model that stops without usable output fails with empty_model_output.

// Aggregated result
const gen = await client.generate(
  "Qwen/Qwen3-4B-Instruct-2507",
  "Write a haiku about the sea.",
  { maxNewTokens: 64, temperature: 0.7 },
);
console.log(gen.text, gen.finishReason, gen.usage);

// Streaming (SSE) — chunks as they arrive (Node.js example;
// process.stdout is not available in the browser)
for await (const chunk of client.streamGenerate(
  "Qwen/Qwen3-4B-Instruct-2507",
  "Write a haiku about the sea.",
  { maxNewTokens: 64 },
)) {
  process.stdout.write(chunk.text_delta);
  if (chunk.done && chunk.ttft_ms !== undefined) {
    console.log(`\nTTFT: ${chunk.ttft_ms}ms`);
  }
}

Error handling

All errors extend SIEError and are exported from the package root. Server-reported errors carry .code and .statusCode, plus .requestId (the gateway x-sie-request-id) when the gateway included one in the response — check it before using it. RequestError, ServerError, ProvisioningError, ModelLoadingError and LoraLoadingError also carry .request, the request metadata of the error response when it carried any: for example servedBy, fallbackReason and fallbackError on a local refusal that answers a failed remote attempt. When a retry budget runs out, it describes the last refusal.

import {
  ModelLoadingError,
  RequestError,
  ResourceExhaustedError,
  ServerError,
  SIEStreamError,
} from "@superlinked/sie-sdk";

try {
  const res = await client.encode("BAAI/bge-m3", { text: "Hello" });
} catch (error) {
  if (error instanceof RequestError) {
    console.error(`Bad request (${error.code}):`, error.message);
  } else if (error instanceof ServerError) {
    const correlation = error.requestId ? ` [request ${error.requestId}]` : "";
    console.error(`Server error (${error.code})${correlation}:`, error.message);
  }
}

Retry semantics for transient 503 codes:

  • PROVISIONING — the cluster is scaling capacity from zero. Retried automatically while waitForCapacity: true (the default); with waitForCapacity: false it throws ProvisioningError immediately.
  • MODEL_LOADING — the worker is cold-loading the model. The SDK retries automatically until provisionTimeout (default 900000 ms), then throws ModelLoadingError.
  • LORA_LOADING — the requested LoRA adapter is still loading. Retried a bounded number of times, then throws LoraLoadingError.
  • RESOURCE_EXHAUSTED — server-side GPU OOM. Retried with bounded exponential backoff; throws ResourceExhaustedError (a ServerError subclass) when retries run out.

Admission rejections happen before any work is dispatched, so every inference call retries them within provisionTimeout, honouring Retry-After (delay seconds or an HTTP date; estimate() throws them without retrying): 429 RATE_LIMIT, 503 QUEUE_FULL, 503 BILLING_CAPACITY_UNAVAILABLE, the gateway's queue backpressure, a 503 QUEUE_UNAVAILABLE that carries Retry-After, and a 503 KEY_STATE_UNAVAILABLE that carries Retry-After. Either code without Retry-After is terminal. On SIE Cloud, 429 RATE_LIMIT means the API key or its account has reached its limit on requests in flight or per second, 503 BILLING_CAPACITY_UNAVAILABLE means the gateway could not reserve billing capacity for the request in time, and 503 KEY_STATE_UNAVAILABLE means the gateway has not yet decided whether the API key is valid, as on the first request with a key created moments ago. None of them means the credit balance ran out, and none is billed. packages/wire-fixtures/retry_classification.json lists how each response is classified; the TypeScript and Python SDKs both test against it.

SIE Cloud answers 403 when it will not serve a request through SIE Relay, its partner capacity. The SDK throws RelayUnavailableError, a RequestError subclass that carries the server's message, and never retries it. Branch on .code:

  • THIRD_PARTY_SERVING_DISABLED — serving through SIE Relay is disabled.
  • THIRD_PARTY_RUNTIME_UNLISTED — the SIE Relay runtime that would serve the model is not listed.
  • THIRD_PARTY_REGION_UNAVAILABLE — SIE Relay cannot serve the model in the API key's region. .keyRegion and .deploymentRegion name the regions when the response includes them.

Each attempt waits up to timeoutMs (default 150000 ms, longer than the gateway's default 120 s request deadline) for a response. A timed-out request is never retried, because the server may still be processing it. generate, chatCompletions and responses accept a per-call timeoutMs; set it to at least the model profile's overall_timeout_s for long generations. Connection failures are classified by their cause: refused, unreachable or reset connections are retried under waitForCapacity, while DNS name, TLS and certificate failures fail immediately.

When a batch response carries fewer items than were sent, encode and extract throw IncompleteBatchError. Its results holds the items that did come back (match them by id), and missingIds names the dropped items when every submitted item carried an id.

Streaming calls throw SIEStreamError for mid-stream error chunks — the HTTP connection was healthy but the worker or gateway emitted an error envelope partway through. Branch on error.code (for example empty_model_output, a terminal generation that produced no visible text, or MODEL_OUTPUT_PARSE_ERROR, a strict grammar whose finished output did not conform) and, when error.requestId is present, use it to correlate with gateway logs. For a validated RESOURCE_EXHAUSTED terminal, error.retryAfter carries the operator hint in milliseconds; its presence does not make retrying generation safe after output has already arrived.

License

Apache 2.0