Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(sdk): pass a target language to recommend (#611)
Shai Shmuel47cf60918ac3
diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex ac471f452..bb6f4d20a 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -509,6 +509,18 @@ def raise_if_estimate_unroutable(response: _HttpResponse) -> None:)+def build_recommend_body(task: str, target_language: str | None) -> dict[str, str]:+ """The ``POST /v1/recommend`` body.++ ``target_language`` is sent only when the caller passes one, so a call+ without it sends exactly the body it always did and gets the same answer.+ """+ body = {"task": task}+ if target_language is not None:+ body["target_language"] = target_language+ return body++# Resource-exhausted retry settings (server-side OOM recovery exhausted).# Default backoff sequence: 5 -> 10 -> 20 s (capped at 30s). Three attempts# is enough to cover the typical eviction + retry window without makingdiff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex b880732e4..4ceb43c3f 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -127,6 +127,7 @@ from ._shared import (base_url_accepts_origin_credentials,build_chat_body,build_estimate_envelope,+ build_recommend_body,build_responses_body,cached_prompt_tokens_from_usage,check_version_skew,@@ -1659,6 +1660,7 @@ class SIEAsyncClient:self,task: str,*,+ target_language: str | None = None,# Same rationale as `estimate`: this is the per-call HTTP budget, not a# caller-supplied cancellation budget.timeout: float | None = None, # noqa: ASYNC109@@ -1668,7 +1670,7 @@ class SIEAsyncClient:try:response = await self._post(RECOMMEND_PATH,- json_data={"task": task},+ json_data=build_recommend_body(task, target_language),headers={"Accept": JSON_CONTENT_TYPE,"Content-Type": JSON_CONTENT_TYPE,diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 61554efae..f31e36827 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -136,6 +136,7 @@ from ._shared import (base_url_accepts_origin_credentials,build_chat_body,build_estimate_envelope,+ build_recommend_body,build_responses_body,cached_prompt_tokens_from_usage,check_version_skew,@@ -1756,7 +1757,13 @@ class SIEClient:return cast("CostEstimate", response.json())- def recommend(self, task: str, *, timeout: float | None = None) -> Recommendation:+ def recommend(+ self,+ task: str,+ *,+ target_language: str | None = None,+ timeout: float | None = None,+ ) -> Recommendation:"""Ask which model to use for a task family (``POST /v1/recommend``).Read-only and non-billable: no dispatch, no reservation, no credits.@@ -1775,6 +1782,13 @@ class SIEClient:Args:task: A catalog task family id, e.g. ``"rerank"``. A 404 namesevery id this release recommends for.+ target_language: Optional exact locale code of the language you+ want output in, e.g. ``"ja_JP"``. When the release compared+ the family's choices for that language, ``best`` is that+ language's winner and the answer adds ``target_language`` and+ ``language_evidence_ref``. Any other value, including another+ spelling such as ``"ja-JP"``, returns the answer you would get+ without it. Omit it for the language-independent answer.timeout: Per-call timeout override in seconds.Returns:@@ -1785,8 +1799,9 @@ class SIEClient:200 with its evidence and no picks.Raises:- RequestError: 400 for an empty or malformed ``task``; 404 when the- task family is unknown to this release.+ RequestError: 400 for an empty or malformed ``task`` or a+ non-string ``target_language``; 404 when the task family is+ unknown to this release.SIEConnectionError: If unable to connect to the server.ServerError: For other 5xx responses.@@ -1796,6 +1811,9 @@ class SIEClient:'rerank-best'>>> pick["basis"]'ranked'+ >>> pick = client.recommend("translation", target_language="ja_JP")+ >>> pick["target_language"]+ 'ja_JP'"""# Same reason every other public method opens with this: without it the# call inherits the previous call's retry/revision state on this thread.@@ -1803,7 +1821,7 @@ class SIEClient:try:response = self._client.post(RECOMMEND_PATH,- json={"task": task},+ json=build_recommend_body(task, target_language),headers={"Accept": JSON_CONTENT_TYPE,"Content-Type": JSON_CONTENT_TYPE,diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex d5b99fd1c..431f3d8e6 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -1499,6 +1499,14 @@ class Recommendation(TypedDict, total=False):shared_benchmarks: list[str]fast: RecommendedChoicebest: RecommendedChoice+ target_language: str+ """The language ``best`` was chosen for.++ Present only when the request's ``target_language`` decided ``best``. When+ it is absent, ``best`` is the language-independent pick.+ """+ language_evidence_ref: str+ """The per-language comparison behind that choice; present with ``target_language``."""class CostEstimate(TypedDict):diff --git a/packages/sie_sdk/tests/client/test_recommend.py b/packages/sie_sdk/tests/client/test_recommend.pyindex 2aaba066f..f2ca90e03 100644--- a/packages/sie_sdk/tests/client/test_recommend.py+++ b/packages/sie_sdk/tests/client/test_recommend.py@@ -69,6 +69,26 @@ NO_EVIDENCE: dict[str, Any] = {},}+# `best` chosen for one target language: the answer names the language and the+# per-language comparison behind the pick, next to the usual fields.+TRANSLATION_JA: dict[str, Any] = {+ "task": "translation",+ "label": "Translation",+ "basis": "curated",+ "shared_benchmarks": [],+ "best": {+ "intent": "fast",+ "model": "tencent/Hy-MT2-1.8B",+ "runtime_id": "tencent/Hy-MT2-1.8B",+ "profile": "default",+ "alias": None,+ "available": True,+ "evidence_guarded": False,+ },+ "target_language": "ja_JP",+ "language_evidence_ref": "quality-evidence/translation-by-language.json",+}+UNKNOWN_TASK = {"detail": {"code": "TASK_NOT_FOUND",@@ -137,6 +157,32 @@ class TestSyncRecommend:assert "best" not in answerclient.close()+ def test_sends_target_language_and_returns_the_language_pick(self) -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post = MagicMock(return_value=_resp(200, TRANSLATION_JA))+ client = SIEClient("http://localhost:8080")++ answer = client.recommend("translation", target_language="ja_JP")++ assert answer == TRANSLATION_JA+ kwargs = mock_client.return_value.post.call_args[1]+ assert kwargs["json"] == {"task": "translation", "target_language": "ja_JP"}+ assert answer["target_language"] == "ja_JP"+ assert answer["language_evidence_ref"] == "quality-evidence/translation-by-language.json"+ client.close()++ def test_omitted_target_language_is_not_sent(self) -> None:+ """Without a language the SDK sends the body it sent before the parameter existed."""+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post = MagicMock(return_value=_resp(200, RANKED))+ client = SIEClient("http://localhost:8080")++ client.recommend("rerank", target_language=None)++ kwargs = mock_client.return_value.post.call_args[1]+ assert kwargs["json"] == {"task": "rerank"}+ client.close()+def test_unknown_task_raises_request_error(self) -> None:with patch("sie_sdk.client.sync.httpx.Client") as mock_client:mock_client.return_value.post = MagicMock(return_value=_resp(404, UNKNOWN_TASK))@@ -178,6 +224,21 @@ class TestAsyncRecommend:assert client._post.await_args[1]["json_data"] == {"task": "rerank"}await client.close()+ @pytest.mark.asyncio+ async def test_sends_target_language_like_the_sync_twin(self) -> None:+ with patch("sie_sdk.client.async_.aiohttp.ClientSession"):+ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(return_value=_aio(200, TRANSLATION_JA)) # type: ignore[method-assign]++ answer = await client.recommend("translation", target_language="ja_JP")++ assert answer == TRANSLATION_JA+ assert client._post.await_args[1]["json_data"] == {+ "task": "translation",+ "target_language": "ja_JP",+ }+ await client.close()+@pytest.mark.asyncioasync def test_unknown_task_raises_request_error(self) -> None:with patch("sie_sdk.client.async_.aiohttp.ClientSession"):diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.tsindex 216288cc4..d2515d772 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -68,7 +68,9 @@ import {} from "./internal/constants.js";import {ESTIMATE_PATH,+ RECOMMEND_PATH,buildEstimateEnvelope,+ buildRecommendBody,getErrorCode,getErrorParam,getRetryAfter,@@ -137,6 +139,8 @@ import type {ModelInfo,PoolInfo,PoolSpec,+ RecommendOptions,+ Recommendation,RequestMetadata,SIEClientOptions,File as SIEFile,@@ -1267,6 +1271,52 @@ export class SIEClient {);}+ /**+ * Ask which model to use for a task family (`POST /v1/recommend`).+ *+ * Read-only and non-billable: no dispatch, no reservation, no credits. The+ * managed gateway answers from evidence compiled into the release it is+ * running, so the recommendation and the `/v1/catalog` entry it names can+ * never disagree.+ *+ * The answer always states its `basis`. `ranked` means two or more of the+ * family's choices were measured on the same benchmark, so the ordering+ * rests on a comparison somebody ran. `curated` means evidence exists but no+ * two choices share a benchmark, so the pick is the catalog's judgement.+ * `no_evidence` means the family cites nothing. Read it before trusting a+ * pick.+ *+ * @param task - A catalog task family id, e.g. `"rerank"`. A 404 names every+ * id this release recommends for.+ * @param options.targetLanguage - Optional exact locale code of the language+ * you want output in, e.g. `"ja_JP"`. When the release compared the+ * family's choices for that language, `best` is that language's winner and+ * the answer adds `target_language` and `language_evidence_ref`. Any other+ * value, including another spelling such as `"ja-JP"`, returns the answer+ * you would get without it.+ * @param options.timeout - Per-call timeout override in milliseconds.+ * @returns The family's `fast` and/or `best` picks, each with its alias,+ * evidence refs, and `evidence_guarded`. Both are optional: a pick names+ * only a model this release can serve.+ * @throws {RequestError} 400 for an empty or malformed `task` or a+ * non-string `targetLanguage`; 404 when the task family is unknown to this+ * release.+ *+ * @example+ * ```typescript+ * const pick = await client.recommend("translation", { targetLanguage: "ja_JP" });+ * console.log(pick.best?.runtime_id, pick.target_language);+ * ```+ */+ async recommend(task: string, options: RecommendOptions = {}): Promise<Recommendation> {+ return this.jsonRequest<Recommendation>(+ RECOMMEND_PATH,+ "POST",+ buildRecommendBody(task, options.targetLanguage),+ options.timeout ?? this.timeout,+ );+ }+/*** List available models.*diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.tsindex 4e9f66cea..45cbf73f4 100644--- a/packages/sie_ts_sdk/src/index.ts+++ b/packages/sie_ts_sdk/src/index.ts@@ -162,6 +162,10 @@ export type {AppliedRate,RateIdentity,CostEstimate,+ // Model recommendation (client.recommend)+ RecommendOptions,+ RecommendedChoice,+ Recommendation,} from "./types.js";// Utility functionsdiff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.tsindex 2b5357b46..e81e3460d 100644--- a/packages/sie_ts_sdk/src/internal/parsing.ts+++ b/packages/sie_ts_sdk/src/internal/parsing.ts@@ -239,6 +239,23 @@ export async function throwIfInputTooLong(response: Response, model?: string): P/** The one exact path of the cost-estimate dry run (#2435). */export const ESTIMATE_PATH = "/v1/estimate";+/** The one exact path of the model recommendation read. */+export const RECOMMEND_PATH = "/v1/recommend";++/**+ * The `POST /v1/recommend` body.+ *+ * `target_language` is sent only when the caller passes one, so a call without+ * it carries the task alone and gets the language-independent answer.+ */+export function buildRecommendBody(+ task: string,+ targetLanguage?: string,+): { task: string; target_language?: string } {+ if (targetLanguage == null) return { task };+ return { task, target_language: targetLanguage };+}+/*** Error codes the gateway answers when it cannot PRICE a request.*diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex 96fc376c7..45c45dbbd 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -1666,6 +1666,86 @@ export interface CostEstimate {minimum_billed_units?: Record<string, number> | null;}+// ---------------------------------------------------------------------------+// Model recommendation (`POST /v1/recommend`)+// ---------------------------------------------------------------------------++/** Options for `SIEClient.recommend`. */+export interface RecommendOptions {+ /**+ * Exact locale code of the language you want output in, e.g. `"ja_JP"`.+ *+ * When the release compared the family's choices for that language, `best`+ * is that language's winner and the answer adds `target_language` and+ * `language_evidence_ref`. Any other value, including another spelling such+ * as `"ja-JP"`, returns the answer you would get without it. Omit it for the+ * language-independent answer.+ */+ targetLanguage?: string;+ /** Per-call timeout override in milliseconds. */+ timeout?: number;+}++/**+ * One tier's pick for a task family, with the evidence behind it.+ *+ * Wire-shaped (snake_case) like {@link CostEstimate}: the gateway's answer,+ * returned verbatim.+ */+export interface RecommendedChoice {+ /** `fast`, `smart`, or `single`. */+ intent: string;+ model: string;+ /** The string to send as `model`, including any `:profile` suffix. */+ runtime_id: string;+ profile: string;+ /** The short name to send instead of the runtime id, when one is seeded. */+ alias?: string | null;+ available?: boolean;+ quality_ref?: string | null;+ performance_ref?: string | null;+ measurement_status?: string | null;+ /**+ * Whether a committed target floor guards the cited number.+ *+ * A cited measurement with no floor is a real number that nothing protects+ * from silently regressing. `false` does not mean unmeasured; it means+ * unguarded.+ */+ evidence_guarded?: boolean;+}++/** The answer for one task family (`POST /v1/recommend`). */+export interface Recommendation {+ task: string;+ label: string;+ /**+ * `ranked` | `curated` | `no_evidence`.+ *+ * `ranked` means two or more choices were measured on the same benchmark.+ * `curated` means evidence exists but no two choices share one, so the order+ * is the catalog's judgement rather than a measurement. `no_evidence` means+ * the family cites no measurements at all.+ */+ basis: string;+ shared_benchmarks: string[];+ /** The lowest-latency pick, when the family has a serveable one. */+ fast?: RecommendedChoice;+ /**+ * The highest-quality pick, or the sole pick of a single-choice family.+ * Absent when this release can serve neither.+ */+ best?: RecommendedChoice;+ /**+ * The language `best` was chosen for. Present only when the request's+ * `targetLanguage` decided `best`; when absent, `best` is the+ * language-independent pick.+ */+ target_language?: string;+ /** The per-language comparison behind that choice; present with `target_language`. */+ language_evidence_ref?: string;+}+/*** Helper to convert typed arrays to regular number array.* Useful for JSON serialization or working with libraries that expect number[].diff --git a/packages/sie_ts_sdk/tests/recommend.test.ts b/packages/sie_ts_sdk/tests/recommend.test.tsnew file mode 100644index 000000000..e103d21ef--- /dev/null+++ b/packages/sie_ts_sdk/tests/recommend.test.ts@@ -0,0 +1,156 @@+/**+ * Tests for the model recommendation read (`POST /v1/recommend`).+ *+ * The SDK's job here is narrow: send the task (and the target language, when+ * the caller gives one), return the gateway's answer unchanged, and map+ * failures onto the same typed errors every other method uses. `basis` and+ * `evidence_guarded` are what let a caller decide whether to trust a pick, so+ * the answer must reach the caller with every field intact.+ */++import { beforeEach, describe, expect, it, vi } from "vitest";+import { SIEClient } from "../src/client.js";+import { RequestError, ServerError } from "../src/errors.js";+import { RECOMMEND_PATH, buildRecommendBody } from "../src/internal/parsing.js";+import type { Recommendation } from "../src/types.js";++const mockFetch = vi.fn();+vi.stubGlobal("fetch", mockFetch);++const RANKED: Recommendation = {+ task: "rerank",+ label: "Rerank",+ basis: "ranked",+ shared_benchmarks: ["mteb__AskUbuntuDupQuestions"],+ fast: {+ intent: "fast",+ model: "Qwen/Qwen3-Reranker-0.6B",+ runtime_id: "Qwen/Qwen3-Reranker-0.6B",+ profile: "default",+ alias: "rerank-fast",+ available: true,+ quality_ref: "quality-evidence/rerank-fast.json",+ performance_ref: null,+ measurement_status: "verified",+ evidence_guarded: true,+ },+ best: {+ intent: "smart",+ model: "Qwen/Qwen3-Reranker-4B",+ runtime_id: "Qwen/Qwen3-Reranker-4B",+ profile: "default",+ alias: "rerank-best",+ available: true,+ quality_ref: "quality-evidence/rerank-best.json",+ performance_ref: null,+ measurement_status: "verified",+ evidence_guarded: false,+ },+};++// `best` chosen for one target language: the answer names the language and the+// per-language comparison behind the pick, next to the usual fields.+const TRANSLATION_JA: Recommendation = {+ task: "translation",+ label: "Translation",+ basis: "curated",+ shared_benchmarks: [],+ best: {+ intent: "fast",+ model: "tencent/Hy-MT2-1.8B",+ runtime_id: "tencent/Hy-MT2-1.8B",+ profile: "default",+ alias: null,+ available: true,+ evidence_guarded: false,+ },+ target_language: "ja_JP",+ language_evidence_ref: "quality-evidence/translation-by-language.json",+};++function jsonResponse(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++function sentBody(): Record<string, unknown> {+ const init = mockFetch.mock.calls[0][1] as RequestInit;+ return JSON.parse(init.body as string);+}++describe("recommend body", () => {+ it("carries only the task when no language is given", () => {+ expect(buildRecommendBody("rerank")).toEqual({ task: "rerank" });+ expect(Object.keys(buildRecommendBody("rerank", undefined))).toEqual(["task"]);+ });++ it("adds target_language when one is given", () => {+ expect(buildRecommendBody("translation", "ja_JP")).toEqual({+ task: "translation",+ target_language: "ja_JP",+ });+ });+});++describe("client.recommend", () => {+ beforeEach(() => {+ mockFetch.mockClear();+ });++ it("posts the task to /v1/recommend and returns the answer verbatim", async () => {+ mockFetch.mockResolvedValueOnce(jsonResponse(200, RANKED));+ const client = new SIEClient("http://localhost:8080");++ const answer = await client.recommend("rerank");++ expect(answer).toEqual(RANKED);+ expect(answer.basis).toBe("ranked");+ expect(answer.best?.evidence_guarded).toBe(false);+ expect(answer.fast?.evidence_guarded).toBe(true);+ expect(mockFetch.mock.calls[0][0]).toBe(`http://localhost:8080${RECOMMEND_PATH}`);+ expect((mockFetch.mock.calls[0][1] as RequestInit).method).toBe("POST");+ expect(sentBody()).toEqual({ task: "rerank" });+ });++ it("sends targetLanguage as target_language and returns the language pick", async () => {+ mockFetch.mockResolvedValueOnce(jsonResponse(200, TRANSLATION_JA));+ const client = new SIEClient("http://localhost:8080");++ const answer = await client.recommend("translation", { targetLanguage: "ja_JP" });++ expect(sentBody()).toEqual({ task: "translation", target_language: "ja_JP" });+ expect(answer).toEqual(TRANSLATION_JA);+ expect(answer.best?.model).toBe("tencent/Hy-MT2-1.8B");+ expect(answer.target_language).toBe("ja_JP");+ expect(answer.language_evidence_ref).toBe("quality-evidence/translation-by-language.json");+ });++ it("raises RequestError for an unknown task", async () => {+ mockFetch.mockResolvedValueOnce(+ jsonResponse(404, {+ detail: {+ code: "TASK_NOT_FOUND",+ message: 'unknown task "embeddings"; this release recommends for: rerank, translation',+ },+ }),+ );+ const client = new SIEClient("http://localhost:8080");++ const error = await client.recommend("embeddings").catch((caught: unknown) => caught);++ expect(error).toBeInstanceOf(RequestError);+ expect((error as RequestError).statusCode).toBe(404);+ expect((error as RequestError).code).toBe("TASK_NOT_FOUND");+ });++ it("raises ServerError for a 5xx", async () => {+ mockFetch.mockResolvedValueOnce(+ jsonResponse(503, { detail: { code: "UNAVAILABLE", message: "down" } }),+ );+ const client = new SIEClient("http://localhost:8080");++ await expect(client.recommend("rerank")).rejects.toBeInstanceOf(ServerError);+ });+});