Skip to content

armgit / sie

Public Imported from GitHub
0

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

feat(sdk): cover tools, streaming and reasoning effort in the responses helpers (#1015)

Krisztian Gajdar45bdd5cfa571
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index fc2959388..295b218fe 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -231,6 +231,24 @@ answer = client.chat_completions(
print(answer["choices"][0]["message"]["content"])
```
+`responses` and `stream_responses` 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. `stream_responses` yields typed events and raises
+`ServerError` on `response.failed`:
+
+```python
+for event in client.stream_responses(
+ "Qwen/Qwen3-4B-Instruct-2507",
+ "Write a haiku about the sea.",
+ instructions="Answer in English.",
+):
+ if event["type"] == "response.output_text.delta":
+ print(event["delta"], end="")
+```
+
Requests that constrain decoding with a grammar (`response_format` with a
`json_schema` or `json_object` type, the Responses `text.format`, or a native
`grammar`) default to greedy decoding: temperature, `presence_penalty`, and
diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.py
index 17409871b..5ce5d08ca 100644
--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py
+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py
@@ -1894,27 +1894,50 @@ def build_responses_body(
model: str,
input: str | Sequence[Mapping[str, Any]],
*,
+ stream: bool = False,
+ instructions: str | None = None,
max_output_tokens: int | None = None,
temperature: float | None = None,
top_p: float | None = None,
seed: int | None = None,
+ tools: Sequence[Mapping[str, Any]] | None = None,
+ tool_choice: str | Mapping[str, Any] | None = None,
+ parallel_tool_calls: bool | None = None,
+ reasoning: Mapping[str, Any] | None = None,
+ text: Mapping[str, Any] | None = None,
+ metadata: Mapping[str, str] | None = None,
+ prompt_cache_key: str | None = None,
+ user: str | None = None,
+ safety_identifier: str | None = None,
) -> dict[str, Any]:
- """Assemble the strict, non-streaming ``/v1/responses`` request body.
+ """Assemble the strict ``/v1/responses`` request body.
- The gateway's Responses MVP is stateless, text-only, and non-streaming.
- Keeping this builder typed to the complete public OpenAPI allow-list
- prevents SDK callers from accidentally relying on wider parser behavior or
- OpenAI fields that the gateway contract does not expose.
+ The gateway serves Responses statelessly: the full conversation travels
+ in ``input`` and nothing is stored. Keeping this builder typed to the
+ accepted field set prevents SDK callers from relying on OpenAI fields the
+ gateway refuses (stored responses, background mode, hosted tools).
"""
body: dict[str, Any] = {
"model": model,
"input": input if isinstance(input, str) else list(input),
}
+ if stream:
+ body["stream"] = True
optional: dict[str, Any] = {
+ "instructions": instructions,
"max_output_tokens": max_output_tokens,
"temperature": temperature,
"top_p": top_p,
"seed": seed,
+ "tools": list(tools) if tools is not None else None,
+ "tool_choice": tool_choice,
+ "parallel_tool_calls": parallel_tool_calls,
+ "reasoning": reasoning,
+ "text": text,
+ "metadata": metadata,
+ "prompt_cache_key": prompt_cache_key,
+ "user": user,
+ "safety_identifier": safety_identifier,
}
body.update({key: value for key, value in optional.items() if value is not None})
return body
@@ -1938,12 +1961,18 @@ def sse_chunk_error(chunk: dict[str, Any]) -> tuple[str, str, str | None, int |
Both the chat and SIE-native generate surfaces put the error object at the
top level of the chunk (see ``send_error_chunk`` in
- ``packages/sie_gateway/src/handlers/sse.rs``). The additive retry hint is
- trusted only for ``RESOURCE_EXHAUSTED`` and only in the engine config's
- integer ``1..=60`` domain; booleans are integers in Python, so exclude
- them explicitly.
+ ``packages/sie_gateway/src/handlers/sse.rs``); a Responses
+ ``response.failed`` event carries it as ``response.error``. The additive
+ retry hint is trusted only for ``RESOURCE_EXHAUSTED`` and only in the
+ engine config's integer ``1..=60`` domain; booleans are integers in
+ Python, so exclude them explicitly.
"""
err = chunk.get("error")
+ if chunk.get("type") == "response.failed":
+ response = chunk.get("response")
+ err = response.get("error") if isinstance(response, dict) else None
+ if not isinstance(err, dict):
+ err = {}
if isinstance(err, dict):
code = str(err.get("code") or "error")
param = err.get("param")
diff --git a/packages/sie_sdk/src/sie_sdk/client/_sse.py b/packages/sie_sdk/src/sie_sdk/client/_sse.py
index cc7a51b6a..c489108e2 100644
--- a/packages/sie_sdk/src/sie_sdk/client/_sse.py
+++ b/packages/sie_sdk/src/sie_sdk/client/_sse.py
@@ -9,8 +9,10 @@ payload out of each line and honour the ``[DONE]`` terminator.
Scope mirrors the gateway (``packages/sie_gateway/src/handlers/sse.rs``):
the SIE gateway emits one single-line ``data: <json>`` event per chunk plus
the literal ``data: [DONE]`` terminator. Blank separator lines and ``:``
-keep-alive comments are skipped; ``event:`` / ``id:`` / ``retry:`` fields and
-multi-line ``data:`` continuations are not produced and are not handled here.
+keep-alive comments are skipped. Responses events also carry an ``event:``
+line, which is skipped because the payload repeats it as ``type``; ``id:`` /
+``retry:`` fields and multi-line ``data:`` continuations are not produced
+and are not handled here.
"""
from __future__ import annotations
@@ -23,20 +25,24 @@ if TYPE_CHECKING:
from collections.abc import AsyncIterable, AsyncIterator, Iterable, Iterator
_SSE_DONE = "[DONE]"
+SSE_MAX_LINE_BYTES = 8 * 1024 * 1024
+_RESPONSES_TERMINAL_EVENTS = frozenset({"response.completed", "response.incomplete"})
class SSECompletion:
"""Distinguish transport EOF from a completed generation.
- A gateway ``[DONE]`` marker ends either surface. Without that marker,
+ A gateway ``[DONE]`` marker ends every surface. Without that marker,
native generation must have emitted ``done: true``; chat must have
- finished every requested choice. Usage-only chat events do not complete
- a stream and do not erase an earlier finish event.
+ finished every requested choice; Responses must have emitted
+ ``response.completed`` or ``response.incomplete``. Usage-only chat events
+ do not complete a stream and do not erase an earlier finish event.
"""
- def __init__(self, *, chat_choices: int | None = None) -> None:
+ def __init__(self, *, chat_choices: int | None = None, responses: bool = False) -> None:
self.done = False
self._native_terminal = False
+ self._responses = responses
self._chat_choices = chat_choices
if chat_choices is not None and (type(chat_choices) is not int or chat_choices <= 0):
# The gateway still validates the unchanged request. A malformed
@@ -47,6 +53,10 @@ class SSECompletion:
def observe(self, chunk: Any) -> None:
if not isinstance(chunk, dict):
return
+ if self._responses:
+ if chunk.get("type") in _RESPONSES_TERMINAL_EVENTS:
+ self._native_terminal = True
+ return
if self._chat_choices is None:
if chunk.get("done") is True:
self._native_terminal = True
diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.py
index 18fa7cbd1..0efc327c9 100644
--- a/packages/sie_sdk/src/sie_sdk/client/async_.py
+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py
@@ -35,13 +35,14 @@ import json
import logging
import time
import warnings
-from collections.abc import AsyncIterator, Mapping, Sequence
+from collections.abc import AsyncGenerator, AsyncIterator, Mapping, Sequence
from inspect import signature
from pathlib import Path
from typing import IO, Any, Literal, Self, cast, overload
from urllib.parse import quote, urlencode
import aiohttp
+from aiohttp.http_exceptions import LineTooLong
from sie_sdk._msgpack import packb as pack_msgpack
from sie_sdk.audio import convert_item_audio
@@ -97,8 +98,13 @@ from sie_sdk.types import (
PoolSpec,
Recommendation,
RequestMetadata,
- ResponseInputMessage,
+ ResponseInputItem,
+ ResponseReasoning,
ResponseResult,
+ ResponseStreamEvent,
+ ResponseTextConfig,
+ ResponseTool,
+ ResponseToolChoice,
ScoreResult,
StatusMessage,
SystemOneResult,
@@ -185,7 +191,7 @@ from ._shared import (
validate_generate_request_body,
websocket_matches_base_url_origin,
)
-from ._sse import SSECompletion, aiter_sse_payloads
+from ._sse import SSE_MAX_LINE_BYTES, SSECompletion, aiter_sse_payloads
from .errors import (
JobFailedError,
LoraLoadingError,
@@ -400,9 +406,18 @@ async def _aiter_text_lines(content: aiohttp.StreamReader) -> AsyncIterator[str]
aiohttp async-iterates ``content`` as byte chunks split on newline
boundaries (each includes the trailing newline). We decode UTF-8 and strip
the line ending so the SSE parser sees the same per-line shape as httpx's
- ``iter_lines``.
+ ``iter_lines``. A line longer than aiohttp accepts raises
+ :class:`RequestError` instead of aiohttp's own error.
"""
- async for raw in content:
+ lines = aiter(content)
+ while True:
+ try:
+ raw = await anext(lines)
+ except StopAsyncIteration:
+ return
+ except (LineTooLong, ValueError) as e:
+ msg = f"SSE event line exceeds the {SSE_MAX_LINE_BYTES}-byte limit"
+ raise RequestError(msg) from e
yield raw.decode("utf-8").rstrip("\r\n")
@@ -2523,12 +2538,22 @@ class SIEAsyncClient:
async def responses(
self,
model: str,
- input: str | Sequence[ResponseInputMessage],
+ input: str | Sequence[ResponseInputItem],
*,
+ instructions: str | None = None,
max_output_tokens: int | None = None,
temperature: float | None = None,
top_p: float | None = None,
seed: int | None = None,
+ tools: Sequence[ResponseTool] | None = None,
+ tool_choice: ResponseToolChoice | None = None,
+ parallel_tool_calls: bool | None = None,
+ reasoning: ResponseReasoning | None = None,
+ text: ResponseTextConfig | None = None,
+ metadata: dict[str, str] | None = None,
+ prompt_cache_key: str | None = None,
+ user: str | None = None,
+ safety_identifier: str | None = None,
gpu: str | None = None,
wait_for_capacity: bool = True,
provision_timeout_s: float | None = None,
@@ -2537,8 +2562,9 @@ class SIEAsyncClient:
) -> ResponseResult:
"""Async counterpart of :meth:`SIEClient.responses`.
- The gateway's Responses MVP is stateless, text-only, and
- non-streaming. Retry behavior matches the sync method: only explicit
+ The gateway serves Responses statelessly: send the whole conversation
+ in ``input`` every turn. For streaming use :meth:`stream_responses`.
+ Retry behavior matches the sync method: only explicit
pre-execution capacity signals, pre-dispatch admission rejections and
connect-before-send failures are retried; mid-flight failures, read
timeouts and post-publish 504 responses are terminal because
@@ -2550,10 +2576,20 @@ class SIEAsyncClient:
build_responses_body(
model,
input,
+ instructions=instructions,
max_output_tokens=max_output_tokens,
temperature=temperature,
top_p=top_p,
seed=seed,
+ tools=tools,
+ tool_choice=tool_choice,
+ parallel_tool_calls=parallel_tool_calls,
+ reasoning=reasoning,
+ text=text,
+ metadata=metadata,
+ prompt_cache_key=prompt_cache_key,
+ user=user,
+ safety_identifier=safety_identifier,
)
).encode("utf-8")
headers: dict[str, str] = {"content-type": JSON_CONTENT_TYPE, "accept": JSON_CONTENT_TYPE}
@@ -2629,6 +2665,75 @@ class SIEAsyncClient:
attach_request_metadata([data], response.headers, data)
return cast("ResponseResult", data)
+ async def stream_responses(
+ self,
+ model: str,
+ input: str | Sequence[ResponseInputItem],
+ *,
+ instructions: str | None = None,
+ max_output_tokens: int | None = None,
+ temperature: float | None = None,
+ top_p: float | None = None,
+ seed: int | None = None,
+ tools: Sequence[ResponseTool] | None = None,
+ tool_choice: ResponseToolChoice | None = None,
+ parallel_tool_calls: bool | None = None,
+ reasoning: ResponseReasoning | None = None,
+ text: ResponseTextConfig | None = None,
+ metadata: dict[str, str] | None = None,
+ prompt_cache_key: str | None = None,
+ user: str | None = None,
+ safety_identifier: str | None = None,
+ gpu: str | None = None,
+ wait_for_capacity: bool = True,
+ provision_timeout_s: float | None = None,
+ max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,
+ ) -> AsyncIterator[ResponseStreamEvent]:
+ """Streaming OpenAI-compatible Responses result.
+
+ Async counterpart of :meth:`SIEClient.stream_responses`. Yields
+ :class:`ResponseStreamEvent` events; raises :class:`ServerError` on a
+ ``response.failed`` or error event. Breaking out of the iterator early
+ closes the stream so the worker stops generating.
+ """
+ pool_name, resolved_gpu = await self._resolve_pool_and_gpu(gpu)
+ body = json.dumps(
+ build_responses_body(
+ model,
+ input,
+ stream=True,
+ instructions=instructions,
+ max_output_tokens=max_output_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ seed=seed,
+ tools=tools,
+ tool_choice=tool_choice,
+ parallel_tool_calls=parallel_tool_calls,
+ reasoning=reasoning,
+ text=text,
+ metadata=metadata,
+ prompt_cache_key=prompt_cache_key,
+ user=user,
+ safety_identifier=safety_identifier,
+ )
+ ).encode("utf-8")
+ headers = sse_headers(resolved_gpu, pool_name)
+ async with contextlib.aclosing(
+ self._stream_sse_chunks(
+ "/v1/responses",
+ body,
+ headers,
+ model=model,
+ resolved_gpu=resolved_gpu,
+ wait_for_capacity=wait_for_capacity,
+ provision_timeout_s=provision_timeout_s,
+ max_oom_retries=max_oom_retries,
+ )
+ ) as events:
+ async for event in events:
+ yield event
+
async def chat_completions(
self,
model: str,
@@ -2863,17 +2968,20 @@ class SIEAsyncClient:
)
).encode("utf-8")
headers = sse_headers(resolved_gpu, pool_name)
- async for chunk in self._stream_sse_chunks(
- "/v1/chat/completions",
- body,
- headers,
- model=model,
- resolved_gpu=resolved_gpu,
- wait_for_capacity=wait_for_capacity,
- provision_timeout_s=provision_timeout_s,
- max_oom_retries=max_oom_retries,
- ):
- yield chunk
+ async with contextlib.aclosing(
+ self._stream_sse_chunks(
+ "/v1/chat/completions",
+ body,
+ headers,
+ model=model,
+ resolved_gpu=resolved_gpu,
+ wait_for_capacity=wait_for_capacity,
+ provision_timeout_s=provision_timeout_s,
+ max_oom_retries=max_oom_retries,
+ )
+ ) as chunks:
+ async for chunk in chunks:
+ yield chunk
async def stream_generate(
self,
@@ -2947,17 +3055,20 @@ class SIEAsyncClient:
req.update(prompt=prompt, max_new_tokens=max_new_tokens, stream=True)
body = json.dumps(req).encode("utf-8")
headers = sse_headers(resolved_gpu, pool_name)
- async for chunk in self._stream_sse_chunks(
- f"/v1/generate/{safe_model}",
- body,
- headers,
- model=model,
- resolved_gpu=resolved_gpu,
- wait_for_capacity=wait_for_capacity,
- provision_timeout_s=provision_timeout_s,
- max_oom_retries=max_oom_retries,
- ):
- yield chunk
+ async with contextlib.aclosing(
+ self._stream_sse_chunks(
+ f"/v1/generate/{safe_model}",
+ body,
+ headers,
+ model=model,
+ resolved_gpu=resolved_gpu,
+ wait_for_capacity=wait_for_capacity,
+ provision_timeout_s=provision_timeout_s,
+ max_oom_retries=max_oom_retries,
+ )
+ ) as chunks:
+ async for chunk in chunks:
+ yield chunk
async def _stream_sse_chunks(
self,
@@ -2970,10 +3081,11 @@ class SIEAsyncClient:
wait_for_capacity: bool,
provision_timeout_s: float | None,
max_oom_retries: int,
- ) -> AsyncIterator[Any]:
+ ) -> AsyncGenerator[Any, None]:
"""Open an aiohttp SSE stream (with pre-stream provisioning retry) and yield chunks.
- Shared by :meth:`stream_chat_completions` and :meth:`stream_generate`.
+ Shared by :meth:`stream_chat_completions`, :meth:`stream_responses`
+ and :meth:`stream_generate`.
Pre-execution capacity errors are retried when they arrive either as
an HTTP 503 or as the first SSE event. Once a chunk has been yielded a
failure is terminal (non-idempotent). The ``async with`` keeps the
@@ -3018,6 +3130,8 @@ class SIEAsyncClient:
sock_connect=min(self._connect_timeout, attempt_timeout_cap(remaining)),
sock_read=self._timeout,
),
+ # aiohttp refuses a line longer than twice ``read_bufsize``.
+ read_bufsize=SSE_MAX_LINE_BYTES // 2,
allow_redirects=False,
) as raw,
):
@@ -3042,7 +3156,7 @@ class SIEAsyncClient:
chat_choices = json.loads(body).get("n")
if chat_choices is None:
chat_choices = 1
- completion = SSECompletion(chat_choices=chat_choices)
+ completion = SSECompletion(chat_choices=chat_choices, responses=url == "/v1/responses")
async for payload in aiter_sse_payloads(_aiter_text_lines(raw.content), completion=completion):
try:
chunk = json.loads(payload)
diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.py
index 6f94197d4..8a3d93ccc 100644
--- a/packages/sie_sdk/src/sie_sdk/client/sync.py
+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py
@@ -105,8 +105,13 @@ from sie_sdk.types import (
PoolSpec,
Recommendation,
RequestMetadata,
- ResponseInputMessage,
+ ResponseInputItem,
+ ResponseReasoning,
ResponseResult,
+ ResponseStreamEvent,
+ ResponseTextConfig,
+ ResponseTool,
+ ResponseToolChoice,
ScoreResult,
StatusMessage,
SystemOneResult,
@@ -2891,12 +2896,22 @@ class SIEClient:
def responses(
self,
model: str,
- input: str | Sequence[ResponseInputMessage],
+ input: str | Sequence[ResponseInputItem],
*,
+ instructions: str | None = None,
max_output_tokens: int | None = None,
temperature: float | None = None,
top_p: float | None = None,
seed: int | None = None,
+ tools: Sequence[ResponseTool] | None = None,
+ tool_choice: ResponseToolChoice | None = None,
+ parallel_tool_calls: bool | None = None,
+ reasoning: ResponseReasoning | None = None,
+ text: ResponseTextConfig | None = None,
+ metadata: dict[str, str] | None = None,
+ prompt_cache_key: str | None = None,
+ user: str | None = None,
+ safety_identifier: str | None = None,
gpu: str | None = None,
wait_for_capacity: bool = True,
provision_timeout_s: float | None = None,
@@ -2905,11 +2920,11 @@ class SIEClient:
) -> ResponseResult:
"""Create one non-streaming OpenAI-compatible Responses result.
- The gateway's Responses MVP is stateless and text-only. ``input`` may
- be a raw prompt or a sequence of role/content messages; content-part
- arrays accept text parts only. Streaming, tools, stateful threading,
- reasoning, metadata, instructions, and multimodal parts are not
- supported by this surface.
+ The gateway serves Responses statelessly as a translation onto chat
+ completions: send the whole conversation in ``input`` every turn,
+ including earlier ``output`` items and the tool results that answer
+ them. Stored responses, background mode and hosted tools are not
+ supported. For streaming use :meth:`stream_responses`.
Generation is non-idempotent. Only explicit pre-execution 503
PROVISIONING / MODEL_LOADING / RESOURCE_EXHAUSTED responses,
@@ -2920,11 +2935,27 @@ class SIEClient:
Args:
model: Model name to use for generation.
- input: Raw prompt string or typed role/content messages.
+ input: Raw prompt string or typed input items: messages (text and,
+ on user messages, base64 ``data:`` image parts), function and
+ custom tool calls, and their outputs.
+ instructions: Optional system text placed before any leading
+ system or developer messages.
max_output_tokens: Optional hard cap on output tokens.
temperature: Optional sampling temperature override.
top_p: Optional nucleus sampling cutoff override.
seed: Optional signed 64-bit per-request sampling seed.
+ tools: Optional function and custom tool definitions.
+ tool_choice: Optional ``"auto"``, ``"none"``, ``"required"``, or a
+ named declared tool.
+ parallel_tool_calls: Optional parallel tool calls toggle.
+ reasoning: Optional reasoning configuration; ``effort`` is checked
+ against the model's advertised reasoning efforts.
+ text: Optional output configuration; ``format`` selects text,
+ JSON object, or JSON Schema output.
+ metadata: Optional string key/value metadata.
+ prompt_cache_key: Optional prompt cache affinity key.
+ user: Optional end-user identifier.
+ safety_identifier: Optional opaque privacy-preserving safety id.
gpu: Target GPU type or pool spec; see :meth:`encode`.
wait_for_capacity: Auto-retry ``503 PROVISIONING`` responses
under ``provision_timeout_s``. Worker-side model loading and
@@ -2953,10 +2984,20 @@ class SIEClient:
build_responses_body(
model,
input,
+ instructions=instructions,
max_output_tokens=max_output_tokens,
temperature=temperature,
top_p=top_p,
seed=seed,
+ tools=tools,
+ tool_choice=tool_choice,
+ parallel_tool_calls=parallel_tool_calls,
+ reasoning=reasoning,
+ text=text,
+ metadata=metadata,
+ prompt_cache_key=prompt_cache_key,
+ user=user,
+ safety_identifier=safety_identifier,
)
).encode("utf-8")
headers: dict[str, str] = {"content-type": JSON_CONTENT_TYPE, "accept": JSON_CONTENT_TYPE}
@@ -3026,6 +3067,78 @@ class SIEClient:
attach_request_metadata([data], response.headers, data)
return cast("ResponseResult", data)
+ def stream_responses(
+ self,
+ model: str,
+ input: str | Sequence[ResponseInputItem],
+ *,
+ instructions: str | None = None,
+ max_output_tokens: int | None = None,
+ temperature: float | None = None,
+ top_p: float | None = None,
+ seed: int | None = None,
+ tools: Sequence[ResponseTool] | None = None,
+ tool_choice: ResponseToolChoice | None = None,
+ parallel_tool_calls: bool | None = None,
+ reasoning: ResponseReasoning | None = None,
+ text: ResponseTextConfig | None = None,
+ metadata: dict[str, str] | None = None,
+ prompt_cache_key: str | None = None,
+ user: str | None = None,
+ safety_identifier: str | None = None,
+ gpu: str | None = None,
+ wait_for_capacity: bool = True,
+ provision_timeout_s: float | None = None,
+ max_oom_retries: int = RESOURCE_EXHAUSTED_MAX_RETRIES,
+ ) -> Iterator[ResponseStreamEvent]:
+ """Streaming OpenAI-compatible Responses result.
+
+ Takes the request fields of :meth:`responses` and yields
+ :class:`ResponseStreamEvent` events in ``sequence_number`` order:
+ ``response.created`` and ``response.in_progress``, then output item,
+ content part, text delta and tool call argument events, and finally
+ ``response.completed`` or ``response.incomplete`` carrying the whole
+ result with ``usage``. A ``response.failed`` event or an error event
+ raises :class:`ServerError` with the failure code instead of being
+ yielded, and :class:`SIEConnectionError` is raised if the stream ends
+ before a terminal event. Breaking out of the iterator early closes the
+ stream so the worker stops generating. Capacity retries before the
+ first event match :meth:`stream_chat_completions`.
+ """
+ pool_name, resolved_gpu = self._resolve_pool_and_gpu(gpu)
+ body = json.dumps(
+ build_responses_body(
+ model,
+ input,
+ stream=True,
+ instructions=instructions,
+ max_output_tokens=max_output_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ seed=seed,
+ tools=tools,
+ tool_choice=tool_choice,
+ parallel_tool_calls=parallel_tool_calls,
+ reasoning=reasoning,
+ text=text,
+ metadata=metadata,
+ prompt_cache_key=prompt_cache_key,
+ user=user,
+ safety_identifier=safety_identifier,
+ )
+ ).encode("utf-8")
+ headers = sse_headers(resolved_gpu, pool_name)
+ yield from self._stream_sse_chunks(
+ "/v1/responses",
+ body,
+ headers,
+ model=model,
+ resolved_gpu=resolved_gpu,
+ wait_for_capacity=wait_for_capacity,
+ provision_timeout_s=provision_timeout_s,
+ max_oom_retries=max_oom_retries,
+ )
+
def chat_completions(
self,
model: str,
@@ -3377,7 +3490,8 @@ class SIEClient:
) -> Iterator[Any]:
"""Open an SSE stream (with pre-stream provisioning retry) and yield chunks.
- Shared by :meth:`stream_chat_completions` and :meth:`stream_generate`.
+ Shared by :meth:`stream_chat_completions`, :meth:`stream_responses`
+ and :meth:`stream_generate`.
Pre-execution capacity errors are retried when they arrive either as
an HTTP 503 or as the first SSE event. Once a chunk has been yielded a
failure is terminal (non-idempotent). Yielding inside the ``with``
@@ -3426,7 +3540,7 @@ class SIEClient:
chat_choices = json.loads(body).get("n")
if chat_choices is None:
chat_choices = 1
- completion = SSECompletion(chat_choices=chat_choices)
+ completion = SSECompletion(chat_choices=chat_choices, responses=url == "/v1/responses")
for payload in iter_sse_payloads(response.iter_lines(), completion=completion):
try:
chunk = json.loads(payload)
diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.py
index df845fac8..6ba47831b 100644
--- a/packages/sie_sdk/src/sie_sdk/types.py
+++ b/packages/sie_sdk/src/sie_sdk/types.py
@@ -989,24 +989,80 @@ class ChatCompletionChunk(TypedDict, total=False):
class ResponseInputContentPart(TypedDict):
- """One text-only content part accepted by the Responses MVP."""
+ """One text content part of a Responses input message or tool output."""
- type: Literal["text", "input_text"]
+ type: Literal["text", "input_text", "output_text"]
text: str
+class ResponseInputImagePart(TypedDict):
+ """One image content part of a user message or tool output.
+
+ ``image_url`` is a base64 ``data:`` URI; remote URLs and file ids are
+ rejected. ``detail`` is accepted and ignored.
+ """
+
+ type: Literal["input_image"]
+ image_url: str
+ detail: NotRequired[Literal["auto", "low", "high"]]
+
+
ResponseInputRole = Literal["system", "user", "assistant", "developer"]
+ResponseItemStatus = Literal["in_progress", "completed", "incomplete"]
+
class ResponseInputMessage(TypedDict):
- """One stateless text message accepted by the Responses MVP."""
+ """One message of a stateless Responses conversation.
+
+ ``input_image`` parts are accepted on user messages only.
+ """
role: ResponseInputRole
- content: str | list[ResponseInputContentPart]
+ content: str | list[ResponseInputContentPart | ResponseInputImagePart]
+ type: NotRequired[Literal["message"]]
+
+
+class ResponseFunctionCall(TypedDict):
+ """A function tool call, returned as an output item and replayed as an input item."""
+
+ type: Literal["function_call"]
+ call_id: str
+ name: str
+ arguments: str
+ id: NotRequired[str]
+ status: NotRequired[ResponseItemStatus]
+
+
+class ResponseCustomToolCall(TypedDict):
+ """A custom tool call, returned as an output item and replayed as an input item."""
+
+ type: Literal["custom_tool_call"]
+ call_id: str
+ name: str
+ input: str
+ id: NotRequired[str]
+ status: NotRequired[ResponseItemStatus]
+
+
+class ResponseFunctionCallOutput(TypedDict):
+ """The result of a function tool call, sent back as an input item."""
+
+ type: Literal["function_call_output"]
+ call_id: str
+ output: str | list[ResponseInputContentPart | ResponseInputImagePart]
+
+
+class ResponseCustomToolCallOutput(TypedDict):
+ """The result of a custom tool call, sent back as an input item."""
+
+ type: Literal["custom_tool_call_output"]
+ call_id: str
+ output: str | list[ResponseInputContentPart | ResponseInputImagePart]
class ResponseOutputText(TypedDict):
- """One text content part returned by the Responses MVP."""
+ """One text content part of a Responses output message."""
type: Literal["output_text"]
text: str
@@ -1014,37 +1070,273 @@ class ResponseOutputText(TypedDict):
class ResponseOutputMessage(TypedDict):
- """One completed assistant message returned by the Responses MVP."""
+ """One assistant message output item; may also be replayed as an input item."""
type: Literal["message"]
id: str
role: Literal["assistant"]
- status: Literal["completed"]
+ status: ResponseItemStatus
content: list[ResponseOutputText]
+ResponseOutputItem = ResponseOutputMessage | ResponseFunctionCall | ResponseCustomToolCall
+"""One item of :attr:`ResponseResult.output`."""
+
+ResponseInputItem = (
+ ResponseInputMessage
+ | ResponseOutputMessage
+ | ResponseFunctionCall
+ | ResponseFunctionCallOutput
+ | ResponseCustomToolCall
+ | ResponseCustomToolCallOutput
+)
+"""One item of a Responses ``input`` array."""
+
+
+class ResponseFunctionTool(TypedDict):
+ """A function tool the model may call.
+
+ ``strict`` may be omitted or ``False``; strict function schemas are
+ rejected.
+ """
+
+ type: Literal["function"]
+ name: str
+ description: NotRequired[str]
+ parameters: NotRequired[dict[str, Any]]
+ strict: NotRequired[Literal[False]]
+
+
+class ResponseCustomTool(TypedDict):
+ """A custom tool whose call carries one free-text ``input``.
+
+ ``format`` is accepted and not enforced.
+ """
+
+ type: Literal["custom"]
+ name: str
+ description: NotRequired[str]
+ format: NotRequired[dict[str, Any]]
+
+
+ResponseTool = ResponseFunctionTool | ResponseCustomTool
+"""A tool definition accepted by ``tools``."""
+
+
+class ResponseNamedToolChoice(TypedDict):
+ """Force a call to one declared function or custom tool."""
+
+ type: Literal["function", "custom"]
+ name: str
+
+
+ResponseToolChoice = Literal["auto", "none", "required"] | ResponseNamedToolChoice
+"""A ``tool_choice`` value."""
+
+
+class ResponseReasoning(TypedDict, total=False):
+ """Reasoning configuration.
+
+ ``effort`` is forwarded as the chat ``reasoning_effort`` and checked
+ against the model's advertised values (:class:`ModelReasoning`).
+ """
+
+ effort: str | None
+
+
+class ResponseTextFormatText(TypedDict):
+ """Plain text output (the default)."""
+
+ type: Literal["text"]
+
+
+class ResponseTextFormatJsonObject(TypedDict):
+ """Output constrained to a JSON object."""
+
+ type: Literal["json_object"]
+
+
+class ResponseTextFormatJsonSchema(TypedDict):
+ """Output constrained to a JSON Schema."""
+
+ type: Literal["json_schema"]
+ name: str
+ schema: dict[str, Any]
+ strict: NotRequired[bool]
+ description: NotRequired[str]
+
+
+ResponseTextFormat = ResponseTextFormatText | ResponseTextFormatJsonObject | ResponseTextFormatJsonSchema
+"""Structured-output format of ``text.format``."""
+
+
+class ResponseTextConfig(TypedDict, total=False):
+ """Text output configuration."""
+
+ format: ResponseTextFormat
+
+
+class ResponseOutputTokensDetails(TypedDict):
+ """Breakdown of a response's output tokens."""
+
+ reasoning_tokens: int
+
+
class ResponseUsage(TypedDict):
- """Token usage returned by the Responses MVP."""
+ """Token usage of a Responses result."""
input_tokens: int
output_tokens: int
total_tokens: int
input_tokens_details: NotRequired[PromptTokensDetails]
+ output_tokens_details: NotRequired[ResponseOutputTokensDetails]
+
+
+class ResponseIncompleteDetails(TypedDict):
+ """Why a response ended with ``status: "incomplete"``."""
+
+ reason: Literal["max_output_tokens", "content_filter"]
+
+
+class ResponseError(TypedDict):
+ """Why a streamed response ended with ``status: "failed"``."""
+
+ code: str
+ message: str
class ResponseResult(TypedDict, total=False):
- """Non-streaming result from :meth:`SIEClient.responses`."""
+ """A Responses result.
+
+ Returned by :meth:`SIEClient.responses` and carried by the lifecycle
+ events of :meth:`SIEClient.stream_responses`, where ``status`` is
+ ``"in_progress"``, ``output`` is empty and ``usage`` is ``None`` until
+ the terminal event.
+ """
id: str
object: Literal["response"]
created_at: int
model: str
- status: Literal["completed"]
- output: list[ResponseOutputMessage]
- usage: ResponseUsage
+ status: Literal["in_progress", "completed", "incomplete", "failed"]
+ incomplete_details: ResponseIncompleteDetails | None
+ error: ResponseError | None
+ store: bool
+ parallel_tool_calls: bool
+ tool_choice: ResponseToolChoice
+ output: list[ResponseOutputItem]
+ usage: ResponseUsage | None
request: RequestMetadata
+class ResponseLifecycleEvent(TypedDict):
+ """A stream event carrying the whole response object.
+
+ ``response.completed`` and ``response.incomplete`` end the stream with
+ the final result.
+ """
+
+ type: Literal["response.created", "response.in_progress", "response.completed", "response.incomplete"]
+ sequence_number: int
+ response: ResponseResult
+
+
+class ResponseOutputItemEvent(TypedDict):
+ """An output item opened (``added``) or finished (``done``)."""
+
+ type: Literal["response.output_item.added", "response.output_item.done"]
+ sequence_number: int
+ output_index: int
+ item: ResponseOutputItem
+
+
+class ResponseContentPartEvent(TypedDict):
+ """A message content part opened (``added``) or finished (``done``)."""
+
+ type: Literal["response.content_part.added", "response.content_part.done"]
+ sequence_number: int
+ item_id: str
+ output_index: int
+ content_index: int
+ part: ResponseOutputText
+
+
+class ResponseOutputTextDeltaEvent(TypedDict):
+ """Incremental message text."""
+
+ type: Literal["response.output_text.delta"]
+ sequence_number: int
+ item_id: str
+ output_index: int
+ content_index: int
+ delta: str
+
+
+class ResponseOutputTextDoneEvent(TypedDict):
+ """The complete message text."""
+
+ type: Literal["response.output_text.done"]
+ sequence_number: int
+ item_id: str
+ output_index: int
+ content_index: int
+ text: str
+
+
+class ResponseFunctionCallArgumentsDeltaEvent(TypedDict):
+ """Incremental function call arguments."""
+
+ type: Literal["response.function_call_arguments.delta"]
+ sequence_number: int
+ item_id: str
+ output_index: int
+ delta: str
+
+
+class ResponseFunctionCallArgumentsDoneEvent(TypedDict):
+ """The complete function call arguments."""
+
+ type: Literal["response.function_call_arguments.done"]
+ sequence_number: int
+ item_id: str
+ output_index: int
+ arguments: str
+
+
+class ResponseCustomToolCallInputDeltaEvent(TypedDict):
+ """The decoded custom tool call input, emitted once when the call ends."""
+
+ type: Literal["response.custom_tool_call_input.delta"]
+ sequence_number: int
+ item_id: str
+ output_index: int
+ delta: str
+
+
+class ResponseCustomToolCallInputDoneEvent(TypedDict):
+ """The complete custom tool call input."""
+
+ type: Literal["response.custom_tool_call_input.done"]
+ sequence_number: int
+ item_id: str
+ output_index: int
+ input: str
+
+
+ResponseStreamEvent = (
+ ResponseLifecycleEvent
+ | ResponseOutputItemEvent
+ | ResponseContentPartEvent
+ | ResponseOutputTextDeltaEvent
+ | ResponseOutputTextDoneEvent
+ | ResponseFunctionCallArgumentsDeltaEvent
+ | ResponseFunctionCallArgumentsDoneEvent
+ | ResponseCustomToolCallInputDeltaEvent
+ | ResponseCustomToolCallInputDoneEvent
+)
+"""One event yielded by :meth:`SIEClient.stream_responses`."""
+
+
class NumericalAdmissionObservation(TypedDict):
"""Local execution identities that current evidence covers for a model's remote profile."""
diff --git a/packages/sie_sdk/tests/client/test_chat_async.py b/packages/sie_sdk/tests/client/test_chat_async.py
index 4d8ee0034..43d4774a6 100644
--- a/packages/sie_sdk/tests/client/test_chat_async.py
+++ b/packages/sie_sdk/tests/client/test_chat_async.py
@@ -34,6 +34,7 @@ class _FakeRaw:
self._body = {} if body is None else body
# ``content`` async-iterates byte lines, mirroring aiohttp.StreamReader.
self.content = self._aiter_bytes()
+ self.exited = False
async def _aiter_bytes(self):
for b in self._line_bytes:
@@ -43,6 +44,7 @@ class _FakeRaw:
return self
async def __aexit__(self, *exc: object) -> bool:
+ self.exited = True
return False
async def read(self) -> bytes:
@@ -462,6 +464,24 @@ async def test_async_stream_capacity_after_output_preserves_hint_without_retry(
await client.close()
[email protected]("surface", ["chat", "native"])
+async def test_async_stream_aclose_releases_the_stream(surface: str) -> None:
+ first = (
+ _chat_chunk("Hi") if surface == "chat" else {"request_id": "req-1", "seq": 0, "text_delta": "Hi", "done": False}
+ )
+ raw = _FakeRaw(status=200, line_bytes=_sse_bytes(first, first))
+ client = SIEAsyncClient("http://localhost:8080")
+ _patch_session(client, post_returns=raw)
+ stream = _stream_surface(client, surface)
+
+ await anext(stream)
+ await stream.aclose()
+
+ assert raw.exited
+ await client.close()
+
+
@pytest.mark.asyncio
async def test_async_stream_chat_error_chunk_surfaces_request_id() -> None:
"""#3136: async mirror — a chat-shape stream error must surface the
diff --git a/packages/sie_sdk/tests/client/test_responses.py b/packages/sie_sdk/tests/client/test_responses.py
index 3ee243677..e7655ed99 100644
--- a/packages/sie_sdk/tests/client/test_responses.py
+++ b/packages/sie_sdk/tests/client/test_responses.py
@@ -1,8 +1,12 @@
-"""Tests for the typed, non-streaming Responses SDK surface."""
+"""Tests for the typed Responses SDK surface (buffered and streaming)."""
from __future__ import annotations
+import inspect
import json
+import threading
+from collections.abc import Iterator
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Self, get_args, get_type_hints
from unittest.mock import AsyncMock, MagicMock, patch
@@ -11,7 +15,7 @@ import httpx
import pytest
from sie_sdk import SIEAsyncClient, SIEClient
from sie_sdk.client.errors import ProvisioningError, RequestError, ServerError, SIEConnectionError
-from sie_sdk.types import ResponseInputContentPart, ResponseInputMessage
+from sie_sdk.types import ResponseInputContentPart, ResponseInputItem, ResponseInputMessage, ResponseTool
def _payload() -> dict[str, Any]:
@@ -52,7 +56,7 @@ def test_responses_input_types_match_public_openapi() -> None:
part_types = get_args(get_type_hints(ResponseInputContentPart)["type"])
roles = get_args(get_type_hints(ResponseInputMessage)["role"])
- assert set(part_types) == {"text", "input_text"}
+ assert set(part_types) == {"text", "input_text", "output_text"}
assert set(roles) == {"system", "user", "assistant", "developer"}
@@ -239,6 +243,429 @@ def test_responses_does_not_retry_midflight_transport_failure() -> None:
client.close()
+_IMAGE = "data:image/png;base64,iVBORw0KGgo="
+
+_TOOLS: list[ResponseTool] = [
+ {
+ "type": "function",
+ "name": "get_weather",
+ "description": "Look up the weather",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}},
+ "strict": False,
+ },
+ {"type": "custom", "name": "run_python", "description": "Run code", "format": {"type": "text"}},
+]
+
+_INPUT: list[ResponseInputItem] = [
+ {"role": "developer", "content": "Be brief."},
+ {
+ "role": "user",
+ "content": [
+ {"type": "input_text", "text": "What is this?"},
+ {"type": "input_image", "image_url": _IMAGE, "detail": "low"},
+ ],
+ },
+ {"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": '{"city":"Paris"}'},
+ {"type": "function_call_output", "call_id": "call_1", "output": "sunny"},
+ {"type": "custom_tool_call", "call_id": "call_2", "name": "run_python", "input": "print(1)"},
+ {
+ "type": "custom_tool_call_output",
+ "call_id": "call_2",
+ "output": [{"type": "input_text", "text": "1"}, {"type": "input_image", "image_url": _IMAGE}],
+ },
+]
+
+_TYPED_FIELDS: dict[str, Any] = {
+ "instructions": "You are a helpful assistant.",
+ "tools": _TOOLS,
+ "tool_choice": {"type": "custom", "name": "run_python"},
+ "parallel_tool_calls": False,
+ "reasoning": {"effort": "low"},
+ "text": {"format": {"type": "json_schema", "name": "answer", "schema": {"type": "object"}, "strict": True}},
+ "metadata": {"tenant": "t-1"},
+ "prompt_cache_key": "cache-1",
+ "user": "user-1",
+ "safety_identifier": "safety-1",
+}
+
+_ABSENT_PARAMETERS = {"store", "previous_response_id", "conversation", "background", "stream", "extra_body"}
+
+
[email protected]("method", ["responses", "stream_responses"])
[email protected]("client_cls", [SIEClient, SIEAsyncClient])
+def test_responses_signatures_cover_typed_fields_and_omit_refused_fields(
+ client_cls: type[SIEClient | SIEAsyncClient], method: str
+) -> None:
+ parameters = inspect.signature(getattr(client_cls, method)).parameters
+
+ assert set(_TYPED_FIELDS) <= set(parameters)
+ assert {"max_output_tokens", "temperature", "top_p", "seed"} <= set(parameters)
+ assert not _ABSENT_PARAMETERS & set(parameters)
+
+
+def test_responses_sends_every_typed_field() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:
+ client_cls.return_value.post.return_value = _sync_response(200, _payload())
+ client = SIEClient("http://localhost:8080")
+
+ client.responses("m", _INPUT, max_output_tokens=64, **_TYPED_FIELDS)
+
+ sent = json.loads(client_cls.return_value.post.call_args.kwargs["content"])
+ assert sent == {"model": "m", "input": _INPUT, "max_output_tokens": 64, **_TYPED_FIELDS}
+ client.close()
+
+
+ ("field", "value"),
+ [
+ ("tool_choice", "required"),
+ ("tool_choice", {"type": "function", "name": "get_weather"}),
+ ("reasoning", {"effort": None}),
+ ("text", {"format": {"type": "json_object"}}),
+ ("text", {"format": {"type": "text"}}),
+ ],
+)
+def test_responses_forwards_field_values_unchanged(field: str, value: Any) -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:
+ client_cls.return_value.post.return_value = _sync_response(200, _payload())
+ client = SIEClient("http://localhost:8080")
+
+ client.responses("m", "Hi", **{field: value})
+
+ sent = json.loads(client_cls.return_value.post.call_args.kwargs["content"])
+ assert sent == {"model": "m", "input": "Hi", field: value}
+ client.close()
+
+
+class _FakeStream:
+ def __init__(
+ self,
+ *,
+ status_code: int = 200,
+ lines: list[str] | None = None,
+ headers: dict[str, str] | None = None,
+ json_body: dict[str, Any] | None = None,
+ ) -> None:
+ self.status_code = status_code
+ self._lines = lines or []
+ self.headers = headers or {"content-type": "text/event-stream"}
+ self._json = json_body or {}
+ self.content = json.dumps(self._json).encode()
+
+ def __enter__(self) -> Self:
+ return self
+
+ def __exit__(self, *exc: object) -> bool:
+ return False
+
+ def iter_lines(self) -> Iterator[str]:
+ yield from self._lines
+
+ def read(self) -> bytes:
+ return self.content
+
+ def json(self) -> dict[str, Any]:
+ return self._json
+
+
+def _sse(*events: dict[str, Any]) -> list[str]:
+ lines: list[str] = []
+ for sequence_number, event in enumerate(events):
+ if "type" in event:
+ lines.append(f"event: {event['type']}")
+ lines.append(f"data: {json.dumps({**event, 'sequence_number': sequence_number})}")
+ lines.append("")
+ return lines
+
+
+def _response(status: str, output: list[dict[str, Any]] | None = None, **fields: Any) -> dict[str, Any]:
+ terminal = status != "in_progress"
+ return {
+ "id": "resp-req-1",
+ "object": "response",
+ "created_at": 0,
+ "model": "m",
+ "status": status,
+ "incomplete_details": None,
+ "error": None,
+ "store": False,
+ "parallel_tool_calls": True,
+ "tool_choice": "auto",
+ "output": output or [],
+ "usage": (
+ {
+ "input_tokens": 3,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens": 2,
+ "output_tokens_details": {"reasoning_tokens": 0},
+ "total_tokens": 5,
+ }
+ if terminal
+ else None
+ ),
+ **fields,
+ }
+
+
+def _lifecycle(kind: str, response: dict[str, Any]) -> dict[str, Any]:
+ return {"type": f"response.{kind}", "response": response}
+
+
+def _opening() -> list[dict[str, Any]]:
+ return [_lifecycle("created", _response("in_progress")), _lifecycle("in_progress", _response("in_progress"))]
+
+
+def _message(text: str, status: str) -> dict[str, Any]:
+ content = [] if status == "in_progress" else [{"type": "output_text", "text": text, "annotations": []}]
+ return {"type": "message", "id": "msg-req-1", "role": "assistant", "status": status, "content": content}
+
+
+def _text_events(*deltas: str) -> list[dict[str, Any]]:
+ text = "".join(deltas)
+ part = {"type": "output_text", "text": text, "annotations": []}
+ location = {"item_id": "msg-req-1", "output_index": 0, "content_index": 0}
+ return [
+ {"type": "response.output_item.added", "output_index": 0, "item": _message("", "in_progress")},
+ {"type": "response.content_part.added", **location, "part": {**part, "text": ""}},
+ *({"type": "response.output_text.delta", **location, "delta": delta} for delta in deltas),
+ {"type": "response.output_text.done", **location, "text": text},
+ {"type": "response.content_part.done", **location, "part": part},
+ {"type": "response.output_item.done", "output_index": 0, "item": _message(text, "completed")},
+ ]
+
+
+def _function_call(status: str, arguments: str) -> dict[str, Any]:
+ return {
+ "type": "function_call",
+ "id": "fc-req-1-0",
+ "call_id": "call_1",
+ "name": "get_weather",
+ "arguments": arguments,
+ "status": status,
+ }
+
+
+def _function_call_events() -> list[dict[str, Any]]:
+ location = {"item_id": "fc-req-1-0", "output_index": 0}
+ return [
+ {"type": "response.output_item.added", "output_index": 0, "item": _function_call("in_progress", "")},
+ {"type": "response.function_call_arguments.delta", **location, "delta": '{"city":'},
+ {"type": "response.function_call_arguments.delta", **location, "delta": '"Paris"}'},
+ {"type": "response.function_call_arguments.done", **location, "arguments": '{"city":"Paris"}'},
+ {
+ "type": "response.output_item.done",
+ "output_index": 0,
+ "item": _function_call("completed", '{"city":"Paris"}'),
+ },
+ ]
+
+
+def _custom_tool_call(status: str, tool_input: str) -> dict[str, Any]:
+ return {
+ "type": "custom_tool_call",
+ "id": "ctc-req-1-0",
+ "call_id": "call_2",
+ "name": "run_python",
+ "input": tool_input,
+ "status": status,
+ }
+
+
+def _custom_tool_call_events() -> list[dict[str, Any]]:
+ location = {"item_id": "ctc-req-1-0", "output_index": 0}
+ return [
+ {"type": "response.output_item.added", "output_index": 0, "item": _custom_tool_call("in_progress", "")},
+ {"type": "response.custom_tool_call_input.delta", **location, "delta": "print(1)"},
+ {"type": "response.custom_tool_call_input.done", **location, "input": "print(1)"},
+ {"type": "response.output_item.done", "output_index": 0, "item": _custom_tool_call("completed", "print(1)")},
+ ]
+
+
+def _failed(code: str, message: str) -> dict[str, Any]:
+ return _lifecycle("failed", _response("failed", error={"code": code, "message": message}))
+
+
+def _stream_cases() -> list[Any]:
+ text = [
+ *_opening(),
+ *_text_events("Hel", "lo"),
+ _lifecycle("completed", _response("completed", [_message("Hello", "completed")])),
+ ]
+ function_call = [
+ *_opening(),
+ *_function_call_events(),
+ _lifecycle("completed", _response("completed", [_function_call("completed", '{"city":"Paris"}')])),
+ ]
+ custom_tool_call = [
+ *_opening(),
+ *_custom_tool_call_events(),
+ _lifecycle("completed", _response("completed", [_custom_tool_call("completed", "print(1)")])),
+ ]
+ incomplete = [
+ *_opening(),
+ *_text_events("Hel"),
+ _lifecycle(
+ "incomplete",
+ _response(
+ "incomplete",
+ [_message("Hel", "completed")],
+ incomplete_details={"reason": "max_output_tokens"},
+ ),
+ ),
+ ]
+ return [
+ pytest.param(text, "response.completed", id="text"),
+ pytest.param(function_call, "response.completed", id="function_call"),
+ pytest.param(custom_tool_call, "response.completed", id="custom_tool_call"),
+ pytest.param(incomplete, "response.incomplete", id="incomplete"),
+ ]
+
+
[email protected](("events", "terminal"), _stream_cases())
+def test_stream_responses_yields_typed_events_until_terminal(events: list[dict[str, Any]], terminal: str) -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:
+ client_cls.return_value.stream.return_value = _FakeStream(lines=_sse(*events))
+ client = SIEClient("http://localhost:8080")
+
+ out = list(client.stream_responses("m", "Hi", tools=_TOOLS, max_output_tokens=8))
+
+ assert [event["type"] for event in out] == [event["type"] for event in events]
+ assert [event["sequence_number"] for event in out] == list(range(len(events)))
+ assert out[-1]["type"] == terminal
+ assert out == [{**event, "sequence_number": i} for i, event in enumerate(events)]
+ call = client_cls.return_value.stream.call_args
+ assert call.args == ("POST", "/v1/responses")
+ assert json.loads(call.kwargs["content"]) == {
+ "model": "m",
+ "input": "Hi",
+ "stream": True,
+ "max_output_tokens": 8,
+ "tools": _TOOLS,
+ }
+ assert call.kwargs["headers"]["accept"] == "text/event-stream"
+ client.close()
+
+
+def test_stream_responses_sends_every_typed_field() -> None:
+ events = [*_opening(), _lifecycle("completed", _response("completed"))]
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:
+ client_cls.return_value.stream.return_value = _FakeStream(lines=_sse(*events))
+ client = SIEClient("http://localhost:8080")
+
+ list(client.stream_responses("m", _INPUT, seed=5, **_TYPED_FIELDS))
+
+ sent = json.loads(client_cls.return_value.stream.call_args.kwargs["content"])
+ assert sent == {"model": "m", "input": _INPUT, "stream": True, "seed": 5, **_TYPED_FIELDS}
+ client.close()
+
+
+def test_stream_responses_raises_failed_event_as_server_error() -> None:
+ events = [*_opening(), *_text_events("Hel"), _failed("inference_error", "boom")]
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls, patch("sie_sdk.client.sync.time.sleep") as sleep:
+ client_cls.return_value.stream.return_value = _FakeStream(lines=_sse(*events))
+ client = SIEClient("http://localhost:8080")
+ seen: list[str] = []
+
+ with pytest.raises(ServerError, match="boom") as exc_info:
+ seen.extend(event["type"] for event in client.stream_responses("m", "Hi"))
+
+ assert exc_info.value.code == "inference_error"
+ assert seen == [event["type"] for event in events[:-1]]
+ assert client_cls.return_value.stream.call_count == 1
+ sleep.assert_not_called()
+ client.close()
+
+
+def test_stream_responses_raises_failed_event_without_error_object() -> None:
+ failed = _lifecycle("failed", _response("failed"))
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:
+ client_cls.return_value.stream.return_value = _FakeStream(lines=_sse(*_opening(), failed))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(ServerError) as exc_info:
+ list(client.stream_responses("m", "Hi"))
+
+ assert exc_info.value.code == "error"
+ client.close()
+
+
+def test_stream_responses_raises_error_frame_after_output() -> None:
+ error_frame = {"error": {"code": "MODEL_LOADING", "message": "loading"}}
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:
+ client_cls.return_value.stream.return_value = _FakeStream(lines=_sse(*_opening(), error_frame))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(ServerError, match="loading"):
+ list(client.stream_responses("m", "Hi"))
+
+ assert client_cls.return_value.stream.call_count == 1
+ assert client.last_retry_count == 0
+ client.close()
+
+
+def test_stream_responses_requires_a_terminal_event() -> None:
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:
+ client_cls.return_value.stream.return_value = _FakeStream(lines=_sse(*_opening(), *_text_events("Hel")))
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(SIEConnectionError, match="before generation completed"):
+ list(client.stream_responses("m", "Hi"))
+
+ client.close()
+
+
+def test_stream_responses_retries_503_provisioning_before_the_first_event() -> None:
+ provisioning = _FakeStream(
+ status_code=503,
+ headers={"Retry-After": "0.01", "content-type": "application/json"},
+ json_body={"error": {"code": "PROVISIONING", "message": "warming"}},
+ )
+ events = [*_opening(), _lifecycle("completed", _response("completed"))]
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls, patch("sie_sdk.client.sync.time.sleep"):
+ client_cls.return_value.stream.side_effect = [provisioning, _FakeStream(lines=_sse(*events))]
+ client = SIEClient("http://localhost:8080")
+
+ out = list(client.stream_responses("m", "Hi", provision_timeout_s=5.0))
+
+ assert out[-1]["type"] == "response.completed"
+ assert client_cls.return_value.stream.call_count == 2
+ assert client.last_retry_count == 1
+ client.close()
+
+
+def test_stream_responses_retries_first_sse_capacity_error_frame() -> None:
+ loading = _FakeStream(lines=_sse({"error": {"code": "MODEL_LOADING", "message": "loading"}}))
+ events = [*_opening(), _lifecycle("completed", _response("completed"))]
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls, patch("sie_sdk.client.sync.time.sleep"):
+ client_cls.return_value.stream.side_effect = [loading, _FakeStream(lines=_sse(*events))]
+ client = SIEClient("http://localhost:8080")
+
+ out = list(client.stream_responses("m", "Hi", provision_timeout_s=5.0))
+
+ assert [event["type"] for event in out] == [event["type"] for event in events]
+ assert client_cls.return_value.stream.call_count == 2
+ assert client.last_retry_count == 1
+ client.close()
+
+
+def test_stream_responses_surfaces_provisioning_without_retry_when_waiting_is_disabled() -> None:
+ provisioning = _FakeStream(
+ status_code=503,
+ headers={"Retry-After": "0.01", "content-type": "application/json"},
+ json_body={"error": {"code": "PROVISIONING", "message": "warming"}},
+ )
+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls, patch("sie_sdk.client.sync.time.sleep") as sleep:
+ client_cls.return_value.stream.return_value = provisioning
+ client = SIEClient("http://localhost:8080")
+
+ with pytest.raises(ProvisioningError):
+ list(client.stream_responses("m", "Hi", wait_for_capacity=False))
+
+ assert client_cls.return_value.stream.call_count == 1
+ sleep.assert_not_called()
+ client.close()
+
+
class _AsyncRaw:
def __init__(
self,
@@ -246,15 +673,24 @@ class _AsyncRaw:
body: dict[str, Any],
*,
headers: dict[str, str] | None = None,
+ lines: list[str] | None = None,
) -> None:
self.status = status
self._body = body
self.headers = headers or {}
+ self._lines = lines or []
+ self.content = self._aiter_bytes()
+ self.exited = False
+
+ async def _aiter_bytes(self):
+ for line in self._lines:
+ yield f"{line}\n".encode()
async def __aenter__(self) -> Self:
return self
async def __aexit__(self, *exc: object) -> bool:
+ self.exited = True
return False
async def read(self) -> bytes:
@@ -394,3 +830,190 @@ async def test_async_responses_consumes_modal_continuation_without_reposting() -
assert session.post.call_count == 1
assert session.get.call_args.args[0] == "/v1/responses?__modal_attempt_token=opaque"
await client.close()
+
+
+async def test_async_responses_sends_every_typed_field() -> None:
+ client = SIEAsyncClient("http://localhost:8080")
+ session = _patch_async_session(client, post_returns=_AsyncRaw(200, _payload()))
+
+ await client.responses("m", _INPUT, max_output_tokens=64, **_TYPED_FIELDS)
+
+ sent = json.loads(session.post.call_args.kwargs["data"])
+ assert sent == {"model": "m", "input": _INPUT, "max_output_tokens": 64, **_TYPED_FIELDS}
+ await client.close()
+
+
[email protected](("events", "terminal"), _stream_cases())
+async def test_async_stream_responses_yields_typed_events_until_terminal(
+ events: list[dict[str, Any]], terminal: str
+) -> None:
+ client = SIEAsyncClient("http://localhost:8080")
+ session = _patch_async_session(client, post_returns=_AsyncRaw(200, {}, lines=_sse(*events)))
+
+ out = [event async for event in client.stream_responses("m", _INPUT, **_TYPED_FIELDS)]
+
+ assert out == [{**event, "sequence_number": i} for i, event in enumerate(events)]
+ assert out[-1]["type"] == terminal
+ call = session.post.call_args
+ assert call.args[0] == "/v1/responses"
+ assert json.loads(call.kwargs["data"]) == {"model": "m", "input": _INPUT, "stream": True, **_TYPED_FIELDS}
+ assert call.kwargs["headers"]["accept"] == "text/event-stream"
+ await client.close()
+
+
+async def test_async_stream_responses_raises_failed_event_as_server_error() -> None:
+ events = [*_opening(), *_text_events("Hel"), _failed("inference_error", "boom")]
+ client = SIEAsyncClient("http://localhost:8080")
+ session = _patch_async_session(client, post_returns=_AsyncRaw(200, {}, lines=_sse(*events)))
+ seen: list[str] = []
+
+ with pytest.raises(ServerError, match="boom") as exc_info:
+ async for event in client.stream_responses("m", "Hi"):
+ seen.append(event["type"])
+
+ assert exc_info.value.code == "inference_error"
+ assert seen == [event["type"] for event in events[:-1]]
+ assert session.post.call_count == 1
+ await client.close()
+
+
+async def test_async_stream_responses_requires_a_terminal_event() -> None:
+ client = SIEAsyncClient("http://localhost:8080")
+ _patch_async_session(client, post_returns=_AsyncRaw(200, {}, lines=_sse(*_opening())))
+
+ with pytest.raises(SIEConnectionError, match="before generation completed"):
+ _ = [event async for event in client.stream_responses("m", "Hi")]
+
+ await client.close()
+
+
+ "first_attempt",
+ [
+ pytest.param(
+ _AsyncRaw(503, {"error": {"code": "PROVISIONING", "message": "warming"}}, headers={"Retry-After": "0.01"}),
+ id="http-503",
+ ),
+ pytest.param(
+ _AsyncRaw(200, {}, lines=_sse({"error": {"code": "MODEL_LOADING", "message": "loading"}})),
+ id="first-sse-error",
+ ),
+ ],
+)
+async def test_async_stream_responses_retries_capacity_before_the_first_event(first_attempt: _AsyncRaw) -> None:
+ events = [*_opening(), _lifecycle("completed", _response("completed"))]
+ client = SIEAsyncClient("http://localhost:8080")
+ session = _patch_async_session(
+ client,
+ post_side_effect=[first_attempt, _AsyncRaw(200, {}, lines=_sse(*events))],
+ )
+
+ with patch("sie_sdk.client.async_.asyncio.sleep", new=AsyncMock()):
+ out = [event async for event in client.stream_responses("m", "Hi", provision_timeout_s=5)]
+
+ assert [event["type"] for event in out] == [event["type"] for event in events]
+ assert session.post.call_count == 2
+ assert client.last_retry_count == 1
+ await client.close()
+
+
+async def test_async_stream_responses_aclose_releases_the_stream() -> None:
+ raw = _AsyncRaw(200, {}, lines=_sse(*_opening(), _lifecycle("completed", _response("completed"))))
+ client = SIEAsyncClient("http://localhost:8080")
+ _patch_async_session(client, post_returns=raw)
+ stream = client.stream_responses("m", "Hi")
+
+ first = await anext(stream)
+ await stream.aclose()
+
+ assert first["type"] == "response.created"
+ assert raw.exited
+ await client.close()
+
+
+class _SSEServer:
+ def __init__(self, body: bytes) -> None:
+ class _Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_POST(self) -> None:
+ self.rfile.read(int(self.headers.get("Content-Length") or 0))
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ try:
+ self.wfile.write(body)
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+ 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 _sse_body(*events: dict[str, Any]) -> bytes:
+ return "\n".join(_sse(*events)).encode() + b"\n"
+
+
+def _long_text_events(text: str) -> list[dict[str, Any]]:
+ return [
+ *_opening(),
+ *_text_events(text),
+ _lifecycle("completed", _response("completed", [_message(text, "completed")])),
+ ]
+
+
+def test_stream_responses_accepts_event_lines_longer_than_the_default_read_buffer() -> None:
+ text = "x" * (1 << 20)
+ server = _SSEServer(_sse_body(*_long_text_events(text)))
+ try:
+ with SIEClient(server.url) as client:
+ events = list(client.stream_responses("m", "Hi"))
+ finally:
+ server.close()
+
+ assert events == [{**event, "sequence_number": i} for i, event in enumerate(_long_text_events(text))]
+
+
+async def test_async_stream_responses_accepts_event_lines_longer_than_the_default_read_buffer() -> None:
+ text = "x" * (1 << 20)
+ server = _SSEServer(_sse_body(*_long_text_events(text)))
+ try:
+ async with SIEAsyncClient(server.url) as client:
+ events = [event async for event in client.stream_responses("m", "Hi")]
+ finally:
+ server.close()
+
+ assert events == [{**event, "sequence_number": i} for i, event in enumerate(_long_text_events(text))]
+
+
+async def test_async_stream_responses_reports_an_oversized_event_line_as_request_error() -> None:
+ server = _SSEServer(_sse_body(*_long_text_events("x" * (9 << 20))))
+ try:
+ async with SIEAsyncClient(server.url) as client:
+ with pytest.raises(RequestError, match="SSE event line exceeds"):
+ _ = [event async for event in client.stream_responses("m", "Hi")]
+ finally:
+ server.close()
diff --git a/packages/sie_sdk/tests/client/test_sdk_requests.py b/packages/sie_sdk/tests/client/test_sdk_requests.py
index 276e03de2..972bcd90d 100644
--- a/packages/sie_sdk/tests/client/test_sdk_requests.py
+++ b/packages/sie_sdk/tests/client/test_sdk_requests.py
@@ -39,7 +39,13 @@ _DOCUMENTS = [
{"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"})
+_STREAMS = frozenset({"stream_generate", "stream_chat_completions", "stream_responses"})
+_WEATHER_TOOL = {
+ "type": "function",
+ "name": "get_weather",
+ "description": "Look up the current weather in a city.",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
+}
# The call each fixture case stands for: (method, positional arguments, keyword arguments).
_CALLS: dict[str, tuple[str, tuple[Any, ...], dict[str, Any]]] = {
@@ -154,6 +160,55 @@ _CALLS: dict[str, tuple[str, tuple[Any, ...], dict[str, Any]]] = {
("Qwen/Qwen3-4B-Instruct-2507", [{"role": "user", "content": "Count to ten."}]),
{"max_completion_tokens": 64, "stream_options": {"include_usage": True}, "include_reasoning": True},
),
+ "responses_text": (
+ "responses",
+ ("Qwen/Qwen3-4B-Instruct-2507", "Write a haiku about the sea."),
+ {"max_output_tokens": 64},
+ ),
+ "responses_tools": (
+ "responses",
+ ("Qwen/Qwen3-4B-Instruct-2507", [{"role": "user", "content": "What is the weather in Paris?"}]),
+ {
+ "instructions": "Use the tools when they help.",
+ "max_output_tokens": 256,
+ "tools": [_WEATHER_TOOL, {"type": "custom", "name": "run_python", "description": "Run a Python snippet."}],
+ "tool_choice": {"type": "function", "name": "get_weather"},
+ "parallel_tool_calls": False,
+ "reasoning": {"effort": "low"},
+ },
+ ),
+ "responses_image_and_tool_output": (
+ "responses",
+ (
+ "Qwen/Qwen3-VL-8B-Instruct",
+ [
+ {
+ "role": "user",
+ "content": [
+ {"type": "input_text", "text": "Which city is this, and what is its weather?"},
+ {"type": "input_image", "image_url": f"data:image/png;base64,{_FIXTURE['media']['png']}"},
+ ],
+ },
+ {"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": '{"city":"Paris"}'},
+ {"type": "function_call_output", "call_id": "call_1", "output": "Sunny, 21 C"},
+ ],
+ ),
+ {"max_output_tokens": 128, "tools": [{"type": "function", "name": "get_weather"}]},
+ ),
+ "stream_responses": (
+ "stream_responses",
+ ("Qwen/Qwen3-4B-Instruct-2507", "Extract the invoice fields."),
+ {
+ "instructions": "Answer in JSON.",
+ "temperature": 0,
+ "seed": 7,
+ "text": {"format": {"type": "json_schema", "name": "invoice", "strict": True, "schema": _SCHEMA}},
+ "metadata": {"tenant": "tenant-1"},
+ "prompt_cache_key": "invoice-v1",
+ "user": "user-9",
+ "safety_identifier": "safety-9",
+ },
+ ),
}
@@ -171,6 +226,9 @@ def _success(path: str, accept: str, item_count: int) -> tuple[bytes, str]:
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"
+ if path == "/v1/responses":
+ response = {"id": "resp-1", "object": "response", "model": "m", "status": "completed", "output": []}
+ return json.dumps(response).encode(), "application/json"
chat = {"id": "chat-1", "object": "chat.completion", "model": "m", "choices": []}
return json.dumps(chat).encode(), "application/json"
diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.md
index ceaf2928e..851ad7792 100644
--- a/packages/sie_ts_sdk/README.md
+++ b/packages/sie_ts_sdk/README.md
@@ -156,6 +156,24 @@ 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`:
+
+```typescript
+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
@@ -268,8 +286,9 @@ retries it. Branch on `.code`:
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` and `chatCompletions` accept a per-call `timeoutMs`; set it to
-at least the model profile's `overall_timeout_s` for long generations.
+`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.
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index cc241bf01..e1b82d32e 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -152,6 +152,9 @@ import type {
RecommendOptions,
Recommendation,
RequestMetadata,
+ ResponseRequest,
+ ResponseResult,
+ ResponseStreamEvent,
SIEClientOptions,
File as SIEFile,
ScoreOptions,
@@ -736,6 +739,15 @@ function extractChatChunkError(chunk: ChatCompletionChunk): SIEStreamError | nul
});
}
+function extractResponseEventError(event: ResponseStreamEvent): SIEStreamError | null {
+ const record = event as unknown as Record<string, unknown>;
+ if (record.error) return extractChatChunkError(record as unknown as ChatCompletionChunk);
+ if (record.type !== "response.failed") return null;
+ const response = record.response as Partial<ResponseResult> | undefined;
+ const error = response?.error;
+ return new SIEStreamError(error?.message ?? "stream error", { code: error?.code });
+}
+
/**
* Return only the `scheme://host[:port]` origin of `url`.
*
@@ -1752,6 +1764,109 @@ export class SIEClient {
);
}
+ /**
+ * Non-streaming OpenAI-compatible Responses call against `/v1/responses`.
+ *
+ * The gateway serves Responses statelessly as a translation onto chat
+ * completions: send the whole conversation in `req.input` every turn,
+ * including earlier output items and the tool results that answer them.
+ * Retry and error semantics match {@link chatCompletions}, and like it this
+ * method throws `RequestError` immediately when `req.stream === true` — use
+ * {@link streamResponses} instead.
+ *
+ * @example
+ * ```typescript
+ * const result = await client.responses({
+ * model: "Qwen/Qwen3-4B-Instruct-2507",
+ * instructions: "Answer in one sentence.",
+ * input: "Why is the sea salty?",
+ * max_output_tokens: 64,
+ * });
+ * for (const item of result.output) {
+ * if (item.type === "message") console.log(item.content[0]?.text);
+ * }
+ * ```
+ */
+ async responses(
+ req: ResponseRequest,
+ options: ChatCompletionOptions = {},
+ ): Promise<ResponseResult> {
+ if (req.stream === true) {
+ throw new RequestError(
+ "responses() cannot be used with stream:true — use streamResponses() instead.",
+ "invalid_request",
+ 400,
+ );
+ }
+ if (req.seed !== undefined) {
+ validateGenerationSeed(req.seed);
+ }
+
+ const body = { ...req, stream: false };
+ const url = `${this.baseUrl}/v1/responses`;
+ const headers = this.buildChatHeaders("application/json");
+ const waitForCapacity = options.waitForCapacity ?? this.defaultWaitForCapacity;
+ const provisionTimeoutMs = options.provisionTimeoutMs ?? this.provisionTimeout;
+ const timeoutMs = options.timeoutMs ?? this.timeout;
+ const response = await withProvisioningRetry(
+ () => this.performJsonPost(url, body, headers, timeoutMs),
+ {
+ model: req.model,
+ gpu: undefined,
+ waitForCapacity,
+ provisionTimeoutMs,
+ },
+ );
+
+ this.checkServerVersion(response);
+
+ const data = (await parseTerminalJsonObject(response, "response")) as unknown as ResponseResult;
+ attachRequestMetadata([data], response.headers, data);
+ return data;
+ }
+
+ /**
+ * Streaming OpenAI-compatible Responses call against `/v1/responses` with
+ * `Accept: text/event-stream`.
+ *
+ * Yields `ResponseStreamEvent` events in `sequence_number` order:
+ * `response.created` and `response.in_progress`, then output item, content
+ * part, text delta and tool call argument events, and finally
+ * `response.completed` or `response.incomplete` carrying the whole result
+ * with `usage`. Error semantics match {@link streamChatCompletions}: a
+ * `response.failed` event or an error event throws {@link SIEStreamError}
+ * and is never yielded, and EOF before a terminal event throws
+ * `SIEConnectionError`. `req.stream` is set to `true` automatically.
+ *
+ * @example
+ * ```typescript
+ * for await (const event of client.streamResponses({
+ * model: "Qwen/Qwen3-4B-Instruct-2507",
+ * input: "Count to ten.",
+ * })) {
+ * if (event.type === "response.output_text.delta") process.stdout.write(event.delta);
+ * }
+ * ```
+ */
+ async *streamResponses(
+ req: ResponseRequest,
+ signal?: AbortSignal,
+ ): AsyncGenerator<ResponseStreamEvent, void, undefined> {
+ if (req.seed !== undefined) {
+ validateGenerationSeed(req.seed);
+ }
+ const body = { ...req, stream: true };
+ const url = `${this.baseUrl}/v1/responses`;
+ yield* this.consumeSseStream<ResponseStreamEvent>(
+ url,
+ body,
+ req.model,
+ signal,
+ (event) => extractResponseEventError(event),
+ new SSECompletion(undefined, true),
+ );
+ }
+
/**
* Streaming companion to {@link generate} — opens an SSE connection to
* `/v1/generate/{model}` with `stream: true` and yields the SIE-native
diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.ts
index b0a6c940d..c9428474e 100644
--- a/packages/sie_ts_sdk/src/index.ts
+++ b/packages/sie_ts_sdk/src/index.ts
@@ -158,6 +158,40 @@ export type {
ChatCompletionChunk,
ChatChunkChoice,
ChatDelta,
+ // Responses (OpenAI-compatible)
+ ResponseInputText,
+ ResponseInputImage,
+ ResponseInputContent,
+ ResponseItemStatus,
+ ResponseInputMessage,
+ ResponseFunctionCall,
+ ResponseCustomToolCall,
+ ResponseFunctionCallOutput,
+ ResponseCustomToolCallOutput,
+ ResponseOutputText,
+ ResponseOutputMessage,
+ ResponseOutputItem,
+ ResponseInputItem,
+ ResponseFunctionTool,
+ ResponseCustomTool,
+ ResponseTool,
+ ResponseToolChoice,
+ ResponseReasoning,
+ ResponseTextFormat,
+ ResponseTextConfig,
+ ResponseRequest,
+ ResponseUsage,
+ ResponseResult,
+ ResponseLifecycleEvent,
+ ResponseOutputItemEvent,
+ ResponseContentPartEvent,
+ ResponseOutputTextDeltaEvent,
+ ResponseOutputTextDoneEvent,
+ ResponseFunctionCallArgumentsDeltaEvent,
+ ResponseFunctionCallArgumentsDoneEvent,
+ ResponseCustomToolCallInputDeltaEvent,
+ ResponseCustomToolCallInputDoneEvent,
+ ResponseStreamEvent,
// Cost-estimate dry run (client.estimate)
AppliedRate,
RateIdentity,
diff --git a/packages/sie_ts_sdk/src/sse.ts b/packages/sie_ts_sdk/src/sse.ts
index 8cd5978fb..2f71c87a0 100644
--- a/packages/sie_ts_sdk/src/sse.ts
+++ b/packages/sie_ts_sdk/src/sse.ts
@@ -14,8 +14,9 @@
* - the literal `data: [DONE]\n\n` terminator
* - keep-alive comment lines (`: <text>\n`), which are skipped
*
- * Other SSE features (`event:`, `id:`, `retry:`, multi-line `data:`
- * continuations) are not produced by `sse.rs` and are not handled here.
+ * Responses events also carry an `event:` line, which is skipped because the
+ * payload repeats it as `type`. Other SSE features (`id:`, `retry:`,
+ * multi-line `data:` continuations) are not produced and are not handled here.
* If the gateway grows new event shapes, extend this parser deliberately
* rather than adding a generic SSE dependency.
*/
@@ -24,14 +25,27 @@ import { SIEConnectionError, SIEStreamError } from "./errors.js";
const SSE_DONE = "[DONE]";
-/** Track generation completion separately from a clean HTTP body EOF. */
+const RESPONSES_TERMINAL_EVENTS: ReadonlySet<unknown> = new Set([
+ "response.completed",
+ "response.incomplete",
+]);
+
+/**
+ * Track generation completion separately from a clean HTTP body EOF.
+ *
+ * `[DONE]` ends every surface. Without it, native generation must emit
+ * `done: true`, chat must finish every requested choice, and Responses must
+ * emit `response.completed` or `response.incomplete`.
+ */
export class SSECompletion {
done = false;
private nativeTerminal = false;
private readonly chatChoices: number | undefined;
+ private readonly responses: boolean;
private readonly finishedChoices = new Set<number>();
- constructor(chatChoices?: number) {
+ constructor(chatChoices?: number, responses = false) {
+ this.responses = responses;
this.chatChoices =
chatChoices === undefined
? undefined
@@ -43,6 +57,10 @@ export class SSECompletion {
observe(chunk: unknown): void {
if (typeof chunk !== "object" || chunk === null) return;
const record = chunk as Record<string, unknown>;
+ if (this.responses) {
+ if (RESPONSES_TERMINAL_EVENTS.has(record.type)) this.nativeTerminal = true;
+ return;
+ }
if (this.chatChoices === undefined) {
if (record.done === true) this.nativeTerminal = true;
return;
diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.ts
index f1e7a47af..7390a2e61 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -1595,10 +1595,11 @@ export interface ChatCompletionChunk {
}
/**
- * Per-call options for `chatCompletions` controlling the pre-execution
- * provisioning / retry loop. The request body itself is the separate
- * {@link ChatCompletionRequest} argument; these knobs only govern HOW the
- * SDK talks to the gateway, not WHAT it asks for.
+ * Per-call options for `chatCompletions` and `responses` controlling the
+ * pre-execution provisioning / retry loop. The request body itself is the
+ * separate {@link ChatCompletionRequest} or {@link ResponseRequest} argument;
+ * these knobs only govern HOW the SDK talks to the gateway, not WHAT it asks
+ * for.
*
* All fields are optional and fall back to the client-level defaults
* (`waitForCapacity`, `provisionTimeout`) when omitted.
@@ -1637,6 +1638,337 @@ export interface ChatCompletionOptions {
timeoutMs?: number;
}
+// ---------------------------------------------------------------------------
+// Responses (OpenAI-compatible) — /v1/responses
+// ---------------------------------------------------------------------------
+
+/** One text content part of a Responses input message or tool output. */
+export interface ResponseInputText {
+ type: "input_text" | "output_text" | "text";
+ text: string;
+}
+
+/**
+ * One image content part of a user message or tool output. `image_url` is a
+ * base64 `data:` URI; remote URLs and file ids are rejected. `detail` is
+ * accepted and ignored.
+ */
+export interface ResponseInputImage {
+ type: "input_image";
+ image_url: string;
+ detail?: "auto" | "low" | "high";
+}
+
+/** Content part of a Responses input message or tool output. */
+export type ResponseInputContent = ResponseInputText | ResponseInputImage;
+
+/** Status of a Responses output item. */
+export type ResponseItemStatus = "in_progress" | "completed" | "incomplete";
+
+/**
+ * One message of a stateless Responses conversation. `input_image` parts are
+ * accepted on user messages only.
+ */
+export interface ResponseInputMessage {
+ type?: "message";
+ role: "system" | "user" | "assistant" | "developer";
+ content: string | ResponseInputContent[];
+}
+
+/** A function tool call, returned as an output item and replayed as an input item. */
+export interface ResponseFunctionCall {
+ type: "function_call";
+ call_id: string;
+ name: string;
+ arguments: string;
+ id?: string;
+ status?: ResponseItemStatus;
+}
+
+/** A custom tool call, returned as an output item and replayed as an input item. */
+export interface ResponseCustomToolCall {
+ type: "custom_tool_call";
+ call_id: string;
+ name: string;
+ input: string;
+ id?: string;
+ status?: ResponseItemStatus;
+}
+
+/** The result of a function tool call, sent back as an input item. */
+export interface ResponseFunctionCallOutput {
+ type: "function_call_output";
+ call_id: string;
+ output: string | ResponseInputContent[];
+}
+
+/** The result of a custom tool call, sent back as an input item. */
+export interface ResponseCustomToolCallOutput {
+ type: "custom_tool_call_output";
+ call_id: string;
+ output: string | ResponseInputContent[];
+}
+
+/** One text content part of a Responses output message. */
+export interface ResponseOutputText {
+ type: "output_text";
+ text: string;
+ annotations: unknown[];
+}
+
+/** One assistant message output item; may also be replayed as an input item. */
+export interface ResponseOutputMessage {
+ type: "message";
+ id: string;
+ role: "assistant";
+ status: ResponseItemStatus;
+ content: ResponseOutputText[];
+}
+
+/** One item of `ResponseResult.output`. */
+export type ResponseOutputItem =
+ | ResponseOutputMessage
+ | ResponseFunctionCall
+ | ResponseCustomToolCall;
+
+/** One item of a Responses `input` array. */
+export type ResponseInputItem =
+ | ResponseInputMessage
+ | ResponseOutputMessage
+ | ResponseFunctionCall
+ | ResponseFunctionCallOutput
+ | ResponseCustomToolCall
+ | ResponseCustomToolCallOutput;
+
+/**
+ * A function tool the model may call. `strict` may be omitted or `false`;
+ * strict function schemas are rejected.
+ */
+export interface ResponseFunctionTool {
+ type: "function";
+ name: string;
+ description?: string;
+ /** JSON Schema describing the function arguments. */
+ parameters?: Record<string, unknown>;
+ strict?: false;
+}
+
+/**
+ * A custom tool whose call carries one free-text `input`. `format` is
+ * accepted and not enforced.
+ */
+export interface ResponseCustomTool {
+ type: "custom";
+ name: string;
+ description?: string;
+ format?: Record<string, unknown>;
+}
+
+/** A tool definition accepted by `tools`. */
+export type ResponseTool = ResponseFunctionTool | ResponseCustomTool;
+
+/** A `tool_choice` value: a mode, or one declared function or custom tool. */
+export type ResponseToolChoice =
+ | "auto"
+ | "none"
+ | "required"
+ | { type: "function" | "custom"; name: string };
+
+/**
+ * Reasoning configuration. `effort` is forwarded as the chat
+ * `reasoning_effort` and checked against the model's advertised values
+ * (`ModelReasoning.effort`).
+ */
+export interface ResponseReasoning {
+ effort?: string | null;
+}
+
+/** Structured-output format of `text.format`. */
+export type ResponseTextFormat =
+ | { type: "text" }
+ | { type: "json_object" }
+ | {
+ type: "json_schema";
+ name: string;
+ schema: Record<string, unknown>;
+ strict?: boolean;
+ description?: string;
+ };
+
+/** Text output configuration. */
+export interface ResponseTextConfig {
+ format?: ResponseTextFormat;
+}
+
+/**
+ * Request body for `responses` / `streamResponses`.
+ *
+ * Field names are snake_case (the wire shape). The gateway serves Responses
+ * statelessly as a translation onto chat completions: send the whole
+ * conversation in `input` every turn, including earlier output items and the
+ * tool results that answer them. Stored responses, background mode and hosted
+ * tools are refused.
+ */
+export interface ResponseRequest {
+ model: string;
+ /** A raw prompt string or typed input items. */
+ input: string | ResponseInputItem[];
+ /** System text placed before any leading system or developer messages. */
+ instructions?: string | null;
+ max_output_tokens?: number;
+ temperature?: number;
+ top_p?: number;
+ /**
+ * Optional per-request sampling seed. Must be a JavaScript safe integer;
+ * the SDK throws `RangeError` before network I/O for invalid values.
+ */
+ seed?: number;
+ /** Set to `true` to use `streamResponses`. `responses` rejects this. */
+ stream?: boolean;
+ tools?: ResponseTool[];
+ tool_choice?: ResponseToolChoice;
+ /** Parallel tool calls toggle (default `true`). */
+ parallel_tool_calls?: boolean;
+ reasoning?: ResponseReasoning | null;
+ text?: ResponseTextConfig | null;
+ metadata?: Record<string, string>;
+ prompt_cache_key?: string;
+ /** End-user identifier. */
+ user?: string;
+ /** Opaque safety identifier; accepted but not logged. */
+ safety_identifier?: string;
+}
+
+/** Token usage of a Responses result. */
+export interface ResponseUsage {
+ input_tokens: number;
+ input_tokens_details?: { cached_tokens: number };
+ output_tokens: number;
+ output_tokens_details?: { reasoning_tokens: number };
+ total_tokens: number;
+}
+
+/**
+ * A Responses result. Returned by `responses` and carried by the lifecycle
+ * events of `streamResponses`, where `status` is `"in_progress"`, `output` is
+ * empty and `usage` is `null` until the terminal event.
+ */
+export interface ResponseResult {
+ id: string;
+ object: "response";
+ created_at: number;
+ model: string;
+ status: "in_progress" | "completed" | "incomplete" | "failed";
+ incomplete_details: { reason: "max_output_tokens" | "content_filter" } | null;
+ error: { code: string; message: string } | null;
+ store: boolean;
+ parallel_tool_calls: boolean;
+ tool_choice: ResponseToolChoice;
+ output: ResponseOutputItem[];
+ usage: ResponseUsage | null;
+ /** Request-scoped usage and settled debit, when supplied by the gateway. */
+ request?: RequestMetadata;
+}
+
+/**
+ * A stream event carrying the whole response object.
+ * `response.completed` and `response.incomplete` end the stream.
+ */
+export interface ResponseLifecycleEvent {
+ type: "response.created" | "response.in_progress" | "response.completed" | "response.incomplete";
+ sequence_number: number;
+ response: ResponseResult;
+}
+
+/** An output item opened (`added`) or finished (`done`). */
+export interface ResponseOutputItemEvent {
+ type: "response.output_item.added" | "response.output_item.done";
+ sequence_number: number;
+ output_index: number;
+ item: ResponseOutputItem;
+}
+
+/** A message content part opened (`added`) or finished (`done`). */
+export interface ResponseContentPartEvent {
+ type: "response.content_part.added" | "response.content_part.done";
+ sequence_number: number;
+ item_id: string;
+ output_index: number;
+ content_index: number;
+ part: ResponseOutputText;
+}
+
+/** Incremental message text. */
+export interface ResponseOutputTextDeltaEvent {
+ type: "response.output_text.delta";
+ sequence_number: number;
+ item_id: string;
+ output_index: number;
+ content_index: number;
+ delta: string;
+}
+
+/** The complete message text. */
+export interface ResponseOutputTextDoneEvent {
+ type: "response.output_text.done";
+ sequence_number: number;
+ item_id: string;
+ output_index: number;
+ content_index: number;
+ text: string;
+}
+
+/** Incremental function call arguments. */
+export interface ResponseFunctionCallArgumentsDeltaEvent {
+ type: "response.function_call_arguments.delta";
+ sequence_number: number;
+ item_id: string;
+ output_index: number;
+ delta: string;
+}
+
+/** The complete function call arguments. */
+export interface ResponseFunctionCallArgumentsDoneEvent {
+ type: "response.function_call_arguments.done";
+ sequence_number: number;
+ item_id: string;
+ output_index: number;
+ arguments: string;
+}
+
+/** The decoded custom tool call input, emitted once when the call ends. */
+export interface ResponseCustomToolCallInputDeltaEvent {
+ type: "response.custom_tool_call_input.delta";
+ sequence_number: number;
+ item_id: string;
+ output_index: number;
+ delta: string;
+}
+
+/** The complete custom tool call input. */
+export interface ResponseCustomToolCallInputDoneEvent {
+ type: "response.custom_tool_call_input.done";
+ sequence_number: number;
+ item_id: string;
+ output_index: number;
+ input: string;
+}
+
+/**
+ * One event yielded by `streamResponses`. A `response.failed` event is never
+ * yielded: the SDK throws `SIEStreamError` instead.
+ */
+export type ResponseStreamEvent =
+ | ResponseLifecycleEvent
+ | ResponseOutputItemEvent
+ | ResponseContentPartEvent
+ | ResponseOutputTextDeltaEvent
+ | ResponseOutputTextDoneEvent
+ | ResponseFunctionCallArgumentsDeltaEvent
+ | ResponseFunctionCallArgumentsDoneEvent
+ | ResponseCustomToolCallInputDeltaEvent
+ | ResponseCustomToolCallInputDoneEvent;
+
// ---------------------------------------------------------------------------
// Streaming generate — /v1/generate/{model} with stream:true
// ---------------------------------------------------------------------------
diff --git a/packages/sie_ts_sdk/tests/responses.test.ts b/packages/sie_ts_sdk/tests/responses.test.ts
new file mode 100644
index 000000000..569e6df74
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/responses.test.ts
@@ -0,0 +1,592 @@
+/**
+ * SIEClient.responses() and SIEClient.streamResponses() tests.
+ *
+ * All tests use a mocked `fetch`; SSE bodies are built inline as
+ * `event: <type>\ndata: <json>\n\n` frames with no `[DONE]` terminator.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+import {
+ ProvisioningError,
+ RequestError,
+ SIEConnectionError,
+ SIEStreamError,
+} from "../src/errors.js";
+import type {
+ ResponseInputItem,
+ ResponseOutputItem,
+ ResponseRequest,
+ ResponseResult,
+ ResponseStreamEvent,
+ ResponseTool,
+} from "../src/types.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+function jsonResponse(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json", ...headers },
+ });
+}
+
+type Frame = Record<string, unknown>;
+
+function sseResponse(frames: Frame[]): Response {
+ const encoder = new TextEncoder();
+ const text = frames
+ .map((frame, sequence_number) => {
+ const event = typeof frame.type === "string" ? `event: ${frame.type}\n` : "";
+ return `${event}data: ${JSON.stringify({ ...frame, sequence_number })}\n\n`;
+ })
+ .join("");
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(encoder.encode(text));
+ controller.close();
+ },
+ });
+ return new Response(stream, {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream" },
+ });
+}
+
+function response(
+ status: ResponseResult["status"],
+ output: ResponseOutputItem[] = [],
+ fields: Partial<ResponseResult> = {},
+): ResponseResult {
+ return {
+ id: "resp-req-1",
+ object: "response",
+ created_at: 0,
+ model: "m",
+ status,
+ incomplete_details: null,
+ error: null,
+ store: false,
+ parallel_tool_calls: true,
+ tool_choice: "auto",
+ output,
+ usage:
+ status === "in_progress"
+ ? null
+ : {
+ input_tokens: 3,
+ input_tokens_details: { cached_tokens: 0 },
+ output_tokens: 2,
+ output_tokens_details: { reasoning_tokens: 0 },
+ total_tokens: 5,
+ },
+ ...fields,
+ };
+}
+
+const opening: Frame[] = [
+ { type: "response.created", response: response("in_progress") },
+ { type: "response.in_progress", response: response("in_progress") },
+];
+
+function message(text: string, status: "in_progress" | "completed"): ResponseOutputItem {
+ return {
+ type: "message",
+ id: "msg-req-1",
+ role: "assistant",
+ status,
+ content: status === "in_progress" ? [] : [{ type: "output_text", text, annotations: [] }],
+ };
+}
+
+function textEvents(...deltas: string[]): Frame[] {
+ const text = deltas.join("");
+ const part = { type: "output_text", text, annotations: [] };
+ const location = { item_id: "msg-req-1", output_index: 0, content_index: 0 };
+ return [
+ { type: "response.output_item.added", output_index: 0, item: message("", "in_progress") },
+ { type: "response.content_part.added", ...location, part: { ...part, text: "" } },
+ ...deltas.map((delta) => ({ type: "response.output_text.delta", ...location, delta })),
+ { type: "response.output_text.done", ...location, text },
+ { type: "response.content_part.done", ...location, part },
+ { type: "response.output_item.done", output_index: 0, item: message(text, "completed") },
+ ];
+}
+
+function functionCall(status: "in_progress" | "completed", args: string): ResponseOutputItem {
+ return {
+ type: "function_call",
+ id: "fc-req-1-0",
+ call_id: "call_1",
+ name: "get_weather",
+ arguments: args,
+ status,
+ };
+}
+
+function customToolCall(status: "in_progress" | "completed", input: string): ResponseOutputItem {
+ return {
+ type: "custom_tool_call",
+ id: "ctc-req-1-0",
+ call_id: "call_2",
+ name: "run_python",
+ input,
+ status,
+ };
+}
+
+const functionCallEvents: Frame[] = [
+ { type: "response.output_item.added", output_index: 0, item: functionCall("in_progress", "") },
+ {
+ type: "response.function_call_arguments.delta",
+ item_id: "fc-req-1-0",
+ output_index: 0,
+ delta: '{"city":',
+ },
+ {
+ type: "response.function_call_arguments.delta",
+ item_id: "fc-req-1-0",
+ output_index: 0,
+ delta: '"Paris"}',
+ },
+ {
+ type: "response.function_call_arguments.done",
+ item_id: "fc-req-1-0",
+ output_index: 0,
+ arguments: '{"city":"Paris"}',
+ },
+ {
+ type: "response.output_item.done",
+ output_index: 0,
+ item: functionCall("completed", '{"city":"Paris"}'),
+ },
+];
+
+const customToolCallEvents: Frame[] = [
+ { type: "response.output_item.added", output_index: 0, item: customToolCall("in_progress", "") },
+ {
+ type: "response.custom_tool_call_input.delta",
+ item_id: "ctc-req-1-0",
+ output_index: 0,
+ delta: "print(1)",
+ },
+ {
+ type: "response.custom_tool_call_input.done",
+ item_id: "ctc-req-1-0",
+ output_index: 0,
+ input: "print(1)",
+ },
+ {
+ type: "response.output_item.done",
+ output_index: 0,
+ item: customToolCall("completed", "print(1)"),
+ },
+];
+
+const IMAGE = "data:image/png;base64,iVBORw0KGgo=";
+
+const TOOLS: ResponseTool[] = [
+ {
+ type: "function",
+ name: "get_weather",
+ description: "Look up the weather",
+ parameters: { type: "object", properties: { city: { type: "string" } } },
+ strict: false,
+ },
+ { type: "custom", name: "run_python", description: "Run code", format: { type: "text" } },
+];
+
+const INPUT: ResponseInputItem[] = [
+ { role: "developer", content: "Be brief." },
+ {
+ role: "user",
+ content: [
+ { type: "input_text", text: "What is this?" },
+ { type: "input_image", image_url: IMAGE, detail: "low" },
+ ],
+ },
+ { type: "function_call", call_id: "call_1", name: "get_weather", arguments: '{"city":"Paris"}' },
+ { type: "function_call_output", call_id: "call_1", output: "sunny" },
+ { type: "custom_tool_call", call_id: "call_2", name: "run_python", input: "print(1)" },
+ {
+ type: "custom_tool_call_output",
+ call_id: "call_2",
+ output: [
+ { type: "input_text", text: "1" },
+ { type: "input_image", image_url: IMAGE },
+ ],
+ },
+];
+
+const FULL_REQUEST: ResponseRequest = {
+ model: "m",
+ input: INPUT,
+ instructions: "You are a helpful assistant.",
+ max_output_tokens: 64,
+ temperature: 0.2,
+ top_p: 0.9,
+ seed: -7,
+ tools: TOOLS,
+ tool_choice: { type: "custom", name: "run_python" },
+ parallel_tool_calls: false,
+ reasoning: { effort: "low" },
+ text: {
+ format: { type: "json_schema", name: "answer", schema: { type: "object" }, strict: true },
+ },
+ metadata: { tenant: "t-1" },
+ prompt_cache_key: "cache-1",
+ user: "user-1",
+ safety_identifier: "safety-1",
+};
+
+async function collect(stream: AsyncIterable<ResponseStreamEvent>): Promise<ResponseStreamEvent[]> {
+ const events: ResponseStreamEvent[] = [];
+ for await (const event of stream) events.push(event);
+ return events;
+}
+
+describe("SIEClient.responses", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("POSTs every typed field to /v1/responses with stream:false", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse(response("completed", [message("Hello", "completed")]), 200, {
+ "x-sie-request-id": "req-1",
+ "x-sie-units-output-tokens": "2",
+ "x-sie-credits-debited": "9",
+ }),
+ );
+
+ const client = new SIEClient("http://localhost:8080");
+ const result = await client.responses(FULL_REQUEST);
+
+ expect(result.status).toBe("completed");
+ expect(result.output[0]).toEqual(message("Hello", "completed"));
+ expect(result.request).toEqual({ id: "req-1", usage: { outputTokens: 2 }, creditsDebited: 9 });
+ const [url, init] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://localhost:8080/v1/responses");
+ expect(init.method).toBe("POST");
+ expect(init.headers.Accept).toBe("application/json");
+ expect(JSON.parse(init.body)).toEqual({ ...FULL_REQUEST, stream: false });
+ });
+
+ it.each<[keyof ResponseRequest, unknown]>([
+ ["tool_choice", "required"],
+ ["tool_choice", { type: "function", name: "get_weather" }],
+ ["reasoning", { effort: null }],
+ ["text", { format: { type: "json_object" } }],
+ ["instructions", null],
+ ])("forwards %s unchanged", async (field, value) => {
+ mockFetch.mockResolvedValueOnce(jsonResponse(response("completed")));
+
+ const client = new SIEClient("http://localhost:8080");
+ await client.responses({ model: "m", input: "Hi", [field]: value } as ResponseRequest);
+
+ const [, init] = mockFetch.mock.calls[0];
+ expect(JSON.parse(init.body)).toEqual({
+ model: "m",
+ input: "Hi",
+ [field]: value,
+ stream: false,
+ });
+ });
+
+ it("returns function and custom tool call output items", async () => {
+ const output = [
+ functionCall("completed", '{"city":"Paris"}'),
+ customToolCall("completed", "1"),
+ ];
+ mockFetch.mockResolvedValueOnce(jsonResponse(response("completed", output)));
+
+ const client = new SIEClient("http://localhost:8080");
+ const result = await client.responses({ model: "m", input: "Hi", tools: TOOLS });
+
+ expect(result.output).toEqual(output);
+ });
+
+ it("throws RequestError when stream:true is passed", async () => {
+ const client = new SIEClient("http://localhost:8080");
+ await expect(
+ client.responses({ model: "m", input: "Hi", stream: true }),
+ ).rejects.toBeInstanceOf(RequestError);
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it("rejects an unsafe seed before network I/O", async () => {
+ const client = new SIEClient("http://localhost:8080");
+ await expect(client.responses({ model: "m", input: "Hi", seed: 1.5 })).rejects.toThrow(
+ RangeError,
+ );
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it("throws ProvisioningError on 503 PROVISIONING when waitForCapacity is false", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({ error: { code: "PROVISIONING", message: "warming" } }, 503, {
+ "Retry-After": "7",
+ }),
+ );
+
+ const client = new SIEClient("http://localhost:8080");
+ await expect(
+ client.responses({ model: "m", input: "Hi" }, { waitForCapacity: false }),
+ ).rejects.toBeInstanceOf(ProvisioningError);
+ expect(mockFetch).toHaveBeenCalledOnce();
+ });
+
+ it("retries 503 MODEL_LOADING then returns the result", async () => {
+ vi.useFakeTimers();
+ try {
+ mockFetch
+ .mockResolvedValueOnce(
+ jsonResponse({ error: { code: "MODEL_LOADING", message: "loading" } }, 503),
+ )
+ .mockResolvedValueOnce(jsonResponse(response("completed")));
+
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+ const promise = client.responses({ model: "m", input: "Hi" });
+ await vi.advanceTimersByTimeAsync(5_000);
+ const result = await promise;
+
+ expect(result.status).toBe("completed");
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe("SIEClient.streamResponses", () => {
+ beforeEach(() => {
+ mockFetch.mockReset();
+ });
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it.each<[string, Frame[], string]>([
+ [
+ "text",
+ [
+ ...opening,
+ ...textEvents("Hel", "lo"),
+ {
+ type: "response.completed",
+ response: response("completed", [message("Hello", "completed")]),
+ },
+ ],
+ "response.completed",
+ ],
+ [
+ "function call",
+ [
+ ...opening,
+ ...functionCallEvents,
+ {
+ type: "response.completed",
+ response: response("completed", [functionCall("completed", '{"city":"Paris"}')]),
+ },
+ ],
+ "response.completed",
+ ],
+ [
+ "custom tool call",
+ [
+ ...opening,
+ ...customToolCallEvents,
+ {
+ type: "response.completed",
+ response: response("completed", [customToolCall("completed", "print(1)")]),
+ },
+ ],
+ "response.completed",
+ ],
+ [
+ "incomplete",
+ [
+ ...opening,
+ ...textEvents("Hel"),
+ {
+ type: "response.incomplete",
+ response: response("incomplete", [message("Hel", "completed")], {
+ incomplete_details: { reason: "max_output_tokens" },
+ }),
+ },
+ ],
+ "response.incomplete",
+ ],
+ ])("yields typed %s events until the terminal event", async (_name, frames, terminal) => {
+ mockFetch.mockResolvedValueOnce(sseResponse(frames));
+
+ const client = new SIEClient("http://localhost:8080");
+ const events = await collect(client.streamResponses(FULL_REQUEST));
+
+ expect(events).toEqual(frames.map((frame, sequence_number) => ({ ...frame, sequence_number })));
+ expect(events.at(-1)?.type).toBe(terminal);
+ const [url, init] = mockFetch.mock.calls[0];
+ expect(url).toBe("http://localhost:8080/v1/responses");
+ expect(init.headers.Accept).toBe("text/event-stream");
+ expect(JSON.parse(init.body)).toEqual({ ...FULL_REQUEST, stream: true });
+ });
+
+ it("narrows events by type", async () => {
+ mockFetch.mockResolvedValueOnce(
+ sseResponse([
+ ...opening,
+ ...textEvents("Hel", "lo"),
+ {
+ type: "response.completed",
+ response: response("completed", [message("Hello", "completed")]),
+ },
+ ]),
+ );
+
+ const client = new SIEClient("http://localhost:8080");
+ let text = "";
+ let usage: ResponseResult["usage"] = null;
+ for await (const event of client.streamResponses({ model: "m", input: "Hi" })) {
+ if (event.type === "response.output_text.delta") text += event.delta;
+ if (event.type === "response.completed") usage = event.response.usage;
+ }
+
+ expect(text).toBe("Hello");
+ expect(usage).toMatchObject({ total_tokens: 5 });
+ });
+
+ it("throws SIEStreamError on response.failed and never yields it", async () => {
+ mockFetch.mockResolvedValueOnce(
+ sseResponse([
+ ...opening,
+ ...textEvents("Hel"),
+ {
+ type: "response.failed",
+ response: response("failed", [], { error: { code: "inference_error", message: "boom" } }),
+ },
+ ]),
+ );
+
+ const client = new SIEClient("http://localhost:8080");
+ const seen: string[] = [];
+ const error = await (async () => {
+ try {
+ for await (const event of client.streamResponses({ model: "m", input: "Hi" })) {
+ seen.push(event.type);
+ }
+ } catch (err) {
+ return err;
+ }
+ return undefined;
+ })();
+
+ expect(error).toBeInstanceOf(SIEStreamError);
+ expect((error as SIEStreamError).code).toBe("inference_error");
+ expect((error as SIEStreamError).message).toBe("boom");
+ expect(seen).not.toContain("response.failed");
+ expect(seen).toHaveLength(opening.length + textEvents("Hel").length);
+ expect(mockFetch).toHaveBeenCalledOnce();
+ });
+
+ it("throws SIEStreamError on response.failed without an error object", async () => {
+ mockFetch.mockResolvedValueOnce(
+ sseResponse([...opening, { type: "response.failed", response: response("failed") }]),
+ );
+
+ const client = new SIEClient("http://localhost:8080");
+ await expect(collect(client.streamResponses({ model: "m", input: "Hi" }))).rejects.toThrow(
+ SIEStreamError,
+ );
+ });
+
+ it("throws SIEStreamError on an SSE error frame with its request id", async () => {
+ mockFetch.mockResolvedValueOnce(
+ sseResponse([
+ ...opening,
+ {
+ error: { code: "first_chunk_timeout", message: "timed out", param: null },
+ request_id: "req-err",
+ },
+ ]),
+ );
+
+ const client = new SIEClient("http://localhost:8080");
+ const error = await collect(client.streamResponses({ model: "m", input: "Hi" })).catch(
+ (err: unknown) => err,
+ );
+
+ expect(error).toBeInstanceOf(SIEStreamError);
+ expect((error as SIEStreamError).code).toBe("first_chunk_timeout");
+ expect((error as SIEStreamError).requestId).toBe("req-err");
+ });
+
+ it("throws SIEConnectionError when the stream ends before a terminal event", async () => {
+ mockFetch.mockResolvedValueOnce(sseResponse([...opening, ...textEvents("Hel")]));
+
+ const client = new SIEClient("http://localhost:8080");
+ await expect(collect(client.streamResponses({ model: "m", input: "Hi" }))).rejects.toThrow(
+ SIEConnectionError,
+ );
+ });
+
+ it("rejects an unsafe seed before opening the stream", async () => {
+ const client = new SIEClient("http://localhost:8080");
+ await expect(
+ collect(client.streamResponses({ model: "m", input: "Hi", seed: Number.NaN })),
+ ).rejects.toThrow(RangeError);
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["PROVISIONING", 5_000],
+ ["MODEL_LOADING", 5_000],
+ ])("retries a 503 %s before the first event", async (code, delayMs) => {
+ vi.useFakeTimers();
+ try {
+ mockFetch
+ .mockResolvedValueOnce(jsonResponse({ error: { code, message: "not yet" } }, 503))
+ .mockResolvedValueOnce(
+ sseResponse([
+ ...opening,
+ { type: "response.completed", response: response("completed") },
+ ]),
+ );
+
+ const client = new SIEClient("http://localhost:8080", {
+ timeout: 30_000,
+ provisionTimeout: 60_000,
+ });
+ const consume = collect(client.streamResponses({ model: "m", input: "Hi" }));
+ await vi.advanceTimersByTimeAsync(delayMs);
+ const events = await consume;
+
+ expect(mockFetch).toHaveBeenCalledTimes(2);
+ expect(events.map((event) => event.type)).toEqual([
+ "response.created",
+ "response.in_progress",
+ "response.completed",
+ ]);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("throws ProvisioningError without retrying when the client opts out of waiting", async () => {
+ mockFetch.mockResolvedValueOnce(
+ jsonResponse({ error: { code: "PROVISIONING", message: "warming" } }, 503),
+ );
+
+ const client = new SIEClient("http://localhost:8080", { waitForCapacity: false });
+ await expect(collect(client.streamResponses({ model: "m", input: "Hi" }))).rejects.toThrow(
+ ProvisioningError,
+ );
+ expect(mockFetch).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/sie_ts_sdk/tests/sdkRequests.test.ts b/packages/sie_ts_sdk/tests/sdkRequests.test.ts
index 9aa1f4fa0..c120da927 100644
--- a/packages/sie_ts_sdk/tests/sdkRequests.test.ts
+++ b/packages/sie_ts_sdk/tests/sdkRequests.test.ts
@@ -64,6 +64,16 @@ const DOCUMENTS = [
{ id: "doc-2", text: "Python is a programming language." },
];
const ENTITY_TEXT = { text: "Apple was founded by Steve Jobs." };
+const WEATHER_TOOL = {
+ type: "function" as const,
+ name: "get_weather",
+ description: "Look up the current weather in a city.",
+ parameters: {
+ type: "object",
+ properties: { city: { type: "string" } },
+ required: ["city"],
+ },
+};
async function drain(stream: AsyncIterable<unknown>): Promise<void> {
for await (const _chunk of stream) {
@@ -204,6 +214,63 @@ const CALLS: Record<string, (client: SIEClient) => Promise<unknown>> = {
include_reasoning: true,
}),
),
+ responses_text: (client) =>
+ client.responses({
+ model: "Qwen/Qwen3-4B-Instruct-2507",
+ input: "Write a haiku about the sea.",
+ max_output_tokens: 64,
+ }),
+ responses_tools: (client) =>
+ client.responses({
+ model: "Qwen/Qwen3-4B-Instruct-2507",
+ input: [{ role: "user", content: "What is the weather in Paris?" }],
+ instructions: "Use the tools when they help.",
+ max_output_tokens: 256,
+ tools: [
+ WEATHER_TOOL,
+ { type: "custom", name: "run_python", description: "Run a Python snippet." },
+ ],
+ tool_choice: { type: "function", name: "get_weather" },
+ parallel_tool_calls: false,
+ reasoning: { effort: "low" },
+ }),
+ responses_image_and_tool_output: (client) =>
+ client.responses({
+ model: "Qwen/Qwen3-VL-8B-Instruct",
+ input: [
+ {
+ role: "user",
+ content: [
+ { type: "input_text", text: "Which city is this, and what is its weather?" },
+ { type: "input_image", image_url: `data:image/png;base64,${fixture.media.png}` },
+ ],
+ },
+ {
+ type: "function_call",
+ call_id: "call_1",
+ name: "get_weather",
+ arguments: '{"city":"Paris"}',
+ },
+ { type: "function_call_output", call_id: "call_1", output: "Sunny, 21 C" },
+ ],
+ max_output_tokens: 128,
+ tools: [{ type: "function", name: "get_weather" }],
+ }),
+ stream_responses: (client) =>
+ drain(
+ client.streamResponses({
+ model: "Qwen/Qwen3-4B-Instruct-2507",
+ input: "Extract the invoice fields.",
+ instructions: "Answer in JSON.",
+ temperature: 0,
+ seed: 7,
+ text: { format: { type: "json_schema", name: "invoice", strict: true, schema: SCHEMA } },
+ metadata: { tenant: "tenant-1" },
+ prompt_cache_key: "invoice-v1",
+ user: "user-9",
+ safety_identifier: "safety-9",
+ }),
+ ),
};
function msgpackResponse(body: unknown): Response {
@@ -236,7 +303,9 @@ function successFor(path: string, accept: string | undefined, itemCount: number)
}
const body = path.startsWith("/v1/generate/")
? { model: "m", text: "ok", finish_reason: "stop" }
- : { id: "chat-1", object: "chat.completion", model: "m", choices: [] };
+ : path === "/v1/responses"
+ ? { id: "resp-1", object: "response", model: "m", status: "completed", output: [] }
+ : { id: "chat-1", object: "chat.completion", model: "m", choices: [] };
return new Response(JSON.stringify(body), {
status: 200,
headers: { "Content-Type": "application/json" },
diff --git a/packages/wire-fixtures/README.md b/packages/wire-fixtures/README.md
index c302a7dab..8c85ab900 100644
--- a/packages/wire-fixtures/README.md
+++ b/packages/wire-fixtures/README.md
@@ -39,8 +39,9 @@ executable.
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;
+ encode, score, extract, generate, the chat route and the Responses 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
diff --git a/packages/wire-fixtures/sdk_requests.json b/packages/wire-fixtures/sdk_requests.json
index 081da4134..2b1229d48 100644
--- a/packages/wire-fixtures/sdk_requests.json
+++ b/packages/wire-fixtures/sdk_requests.json
@@ -1,5 +1,5 @@
{
- "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.",
+ "description": "The HTTP request each SDK sends for the same call to a native primitive, the chat route or the Responses 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"
},
@@ -453,6 +453,136 @@
"include_reasoning": true
}
}
+ },
+ {
+ "id": "responses_text",
+ "summary": "a Responses call with a plain text input",
+ "request": {
+ "method": "POST",
+ "path": "/v1/responses",
+ "headers": {
+ "accept": "application/json",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/json"
+ },
+ "body": {
+ "model": "Qwen/Qwen3-4B-Instruct-2507",
+ "input": "Write a haiku about the sea.",
+ "max_output_tokens": 64
+ },
+ "may_send_default": { "stream": false }
+ }
+ },
+ {
+ "id": "responses_tools",
+ "summary": "a Responses call with instructions, function and custom tools, a forced tool choice and a reasoning effort",
+ "request": {
+ "method": "POST",
+ "path": "/v1/responses",
+ "headers": {
+ "accept": "application/json",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/json"
+ },
+ "body": {
+ "model": "Qwen/Qwen3-4B-Instruct-2507",
+ "input": [{ "role": "user", "content": "What is the weather in Paris?" }],
+ "instructions": "Use the tools when they help.",
+ "max_output_tokens": 256,
+ "tools": [
+ {
+ "type": "function",
+ "name": "get_weather",
+ "description": "Look up the current weather in a city.",
+ "parameters": {
+ "type": "object",
+ "properties": { "city": { "type": "string" } },
+ "required": ["city"]
+ }
+ },
+ { "type": "custom", "name": "run_python", "description": "Run a Python snippet." }
+ ],
+ "tool_choice": { "type": "function", "name": "get_weather" },
+ "parallel_tool_calls": false,
+ "reasoning": { "effort": "low" }
+ },
+ "may_send_default": { "stream": false }
+ }
+ },
+ {
+ "id": "responses_image_and_tool_output",
+ "summary": "a Responses call replaying an image part, a function call and its output",
+ "request": {
+ "method": "POST",
+ "path": "/v1/responses",
+ "headers": {
+ "accept": "application/json",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/json"
+ },
+ "body": {
+ "model": "Qwen/Qwen3-VL-8B-Instruct",
+ "input": [
+ {
+ "role": "user",
+ "content": [
+ { "type": "input_text", "text": "Which city is this, and what is its weather?" },
+ {
+ "type": "input_image",
+ "image_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
+ }
+ ]
+ },
+ {
+ "type": "function_call",
+ "call_id": "call_1",
+ "name": "get_weather",
+ "arguments": "{\"city\":\"Paris\"}"
+ },
+ { "type": "function_call_output", "call_id": "call_1", "output": "Sunny, 21 C" }
+ ],
+ "max_output_tokens": 128,
+ "tools": [{ "type": "function", "name": "get_weather" }]
+ },
+ "may_send_default": { "stream": false }
+ }
+ },
+ {
+ "id": "stream_responses",
+ "summary": "stream a Responses call with a json_schema text format and identity fields",
+ "request": {
+ "method": "POST",
+ "path": "/v1/responses",
+ "headers": {
+ "accept": "text/event-stream",
+ "authorization": "Bearer sk-sie-fixture",
+ "content-type": "application/json"
+ },
+ "body": {
+ "model": "Qwen/Qwen3-4B-Instruct-2507",
+ "input": "Extract the invoice fields.",
+ "stream": true,
+ "instructions": "Answer in JSON.",
+ "temperature": 0,
+ "seed": 7,
+ "text": {
+ "format": {
+ "type": "json_schema",
+ "name": "invoice",
+ "strict": true,
+ "schema": {
+ "type": "object",
+ "properties": { "vendor": { "type": "string" }, "total": { "type": "number" } },
+ "required": ["vendor", "total"]
+ }
+ }
+ },
+ "metadata": { "tenant": "tenant-1" },
+ "prompt_cache_key": "invoice-v1",
+ "user": "user-9",
+ "safety_identifier": "safety-9"
+ }
+ }
}
]
}