OpenResponses Client
The OpenResponsesClient uses OpenAI's Responses API (POST /v1/responses) instead of the Chat Completions API. This client is useful for providers that implement the newer Responses API format.
Key Differences from ChatCompletionsClient
| Feature | ChatCompletionsClient | OpenResponsesClient |
|---|---|---|
| API endpoint | chat.completions.create() |
responses.create() |
| System messages | Included in messages array |
Passed as instructions parameter |
| Message format | {"role": "user", "content": [...]} |
{"role": "user", "content": [{"type": "input_text", ...}]} |
| Tool call IDs | tool_call_id |
call_id |
| Reasoning config | reasoning_effort param |
reasoning: {"effort": ...} object |
Usage
For reasoning models such as the GPT-5.6 family, you can configure the reasoning effort:
import asyncio
from stirrup import Agent
from stirrup.clients import OpenResponsesClient
async def main() -> None:
"""Run an agent using the OpenResponses API with a reasoning model."""
# Create client using OpenResponsesClient
# Uses the OpenAI Responses API (responses.create)
# For reasoning models, you can set reasoning_effort
client = OpenResponsesClient(
model="gpt-5.6-luna",
max_tokens=8_192,
context_window_tokens=1_000_000,
reasoning_effort="medium",
)
agent = Agent(client=client, name="reasoning-agent", max_turns=19)
async with agent.session(output_dir="output/open_responses_example") as session:
_finish_params, _history, _metadata = await session.run(
"Plan a software release with these tasks: Design (5 days), Backend (10 days, needs Design), "
"Frontend (8 days, needs Design), Testing (4 days, needs Backend and Frontend), "
"Documentation (3 days, can start after Backend). Two developers are available. "
"What's the minimum time to complete? Output an Excel Gantt chart with the schedule."
)
if __name__ == "__main__":
asyncio.run(main())
Constructor Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
model |
str |
required | Model identifier (e.g., "gpt-5.6-luna", "gpt-5.6-sol") |
max_tokens |
int |
64_000 |
Maximum output tokens |
context_window_tokens |
int |
required | Context capacity for summarization |
base_url |
str \| None |
None |
Custom API base URL |
api_key |
str \| None |
None |
API key (falls back to OPENAI_API_KEY env var) |
reasoning_effort |
str \| None |
None |
Reasoning effort for reasoning models: "low", "medium", "high" |
timeout |
float \| None |
None |
Request timeout in seconds |
max_retries |
int |
2 |
Number of retries for transient errors |
instructions |
str \| None |
None |
Default system instructions |
kwargs |
dict \| None |
None |
Additional arguments passed to responses.create() |
API Reference
stirrup.clients.open_responses_client
OpenAI SDK-based LLM client for the Responses API.
This client uses the official OpenAI Python SDK's responses.create() method,
supporting both OpenAI's API and any OpenAI-compatible endpoint that implements
the Responses API via the base_url parameter.
_OWNED_REQUEST_KEYS
module-attribute
_OWNED_REQUEST_KEYS = frozenset(
{
"background",
"conversation",
"input",
"instructions",
"max_output_tokens",
"model",
"previous_response_id",
"store",
"stream",
}
)
AssistantBlock
AssistantBlock = Annotated[
TextBlock
| ReasoningBlock
| SignedReasoningBlock
| RedactedReasoningBlock
| ReasoningRefBlock
| EncryptedReasoningBlock
| OpaqueBlock
| ToolCall
| ImageContentBlock
| VideoContentBlock
| AudioContentBlock,
Field(discriminator=kind),
]
One block of an assistant turn, discriminated on kind.
ChatMessage
ChatMessage = Annotated[
SystemMessage
| UserRoleMessage
| AssistantMessage
| ToolMessage,
Field(discriminator=role),
]
Discriminated union of all message types, automatically parsed based on role field.
Content
Content = list[ContentBlock] | str
Message content: either a plain string or list of mixed content blocks.
ContextOverflowError
Bases: Exception
Raised when request input exceeds the model's context capacity.
IncompleteResponseError
Bases: Exception
Raised when a provider returns an incomplete response Stirrup cannot recover from.
Covers stop reasons other than the context and output-budget cases, such as a content filter. Retrying the same request is not expected to help.
OutputTokenLimitError
Bases: Exception
Raised when a provider exhausts the configured response-token budget.
Source code in src/stirrup/core/exceptions.py
AssistantMessage
Bases: BaseModel
LLM response message: an ordered sequence of assistant blocks.
blocks is the only stored content. The channel-era content and
tool_calls attributes remain deprecated views; reasoning raises because
an ordered reasoning block sequence has no faithful channel-shaped projection.
Serialized v0.1 payloads upgrade to blocks during validation. Channel-shaped
construction is not part of the v0.2 API; new code constructs blocks directly.
Mixing blocks with non-empty legacy channel keys raises.
provider_response_id
class-attribute
instance-attribute
provider_response_id: str | None = None
Provider-attached continuation state, e.g. an OpenAI Responses resp_... id.
This is turn metadata rather than emitted assistant content, so it lives beside
blocks instead of inside their emission order. It is distinct from id
(Stirrup's message identity) and ReasoningRefBlock.id (an emitted reasoning
item handle).
content
property
content: list[AssistantBlock] | str
Bare text for one text block, empty text for no blocks, or the block list.
reasoning
property
reasoning: Reasoning | None
Deprecated channel accessor retained only to fail with migration guidance.
AudioContentBlock
Bases: BinaryContentBlock
Audio content supporting MPEG, WAV, AAC, and other common audio formats.
to_base64_url
Transcode to MP3 and return base64 data URL.
Source code in src/stirrup/core/models.py
EmptyParams
Bases: BaseModel
Empty parameter model for tools that don't require parameters.
EncryptedReasoningBlock
Bases: BaseModel
Reasoning returned as an opaque encrypted payload for stateless passback.
E.g. OpenAI Responses reasoning items requested with
include: ["reasoning.encrypted_content"] (store=false /
zero-data-retention): the item — id, summary parts, and encrypted payload —
is re-emitted verbatim in position on passback. The payload is opaque and
non-inspectable.
ImageContentBlock
Bases: BinaryContentBlock
Image content supporting PNG, JPEG, WebP, PSD formats with automatic downscaling.
to_base64_url
to_base64_url(
max_pixels: int | None = RESOLUTION_1MP,
) -> str
Convert image to base64 data URL, optionally resizing to max pixel count.
Source code in src/stirrup/core/models.py
LLMClient
Bases: Protocol
Protocol defining the interface for LLM client implementations.
Any LLM client must implement this protocol to work with the Agent class. Provides text generation with tool support and model capability inspection.
OpaqueBlock
Bases: BaseModel
Provider-native block the framework carries uninterpreted.
For provider-issued marker/control blocks that must round-trip untouched:
data holds the block's raw JSON (self-describing — the provider's own
type field travels inside it). The framework preserves it in position
through history, projections, and serialization so a client that understands
the payload can re-emit it verbatim on passback; other clients fail loudly.
ReasoningBlock
Bases: BaseModel
In-band reasoning text with no passback token.
E.g. reasoning_content on Chat Completions-compatible hosts, or
ReasoningRefBlock
Bases: BaseModel
Reasoning held provider-side and passed back by reference.
This is retained for providers that require an item-level handle on replay.
OpenAI Responses continuation uses AssistantMessage.provider_response_id
instead and does not create this block.
RedactedReasoningBlock
Bases: BaseModel
Reasoning the provider withheld, replaced by an opaque payload.
E.g. Anthropic redacted_thinking: data must be re-emitted verbatim as a
redacted_thinking block on passback. Carries no readable content.
SignedReasoningBlock
Bases: BaseModel
Reasoning bound to an opaque provider signature re-emitted verbatim on passback.
E.g. Anthropic signed thinking blocks.
SystemMessage
Bases: BaseModel
System-level instructions and context for the LLM.
TextBlock
Bases: BaseModel
One contiguous run of answer text in an assistant turn.
signature carries opaque passback state attached to this exact block,
e.g. a Google thought signature emitted on a visible text part. A client
that cannot re-emit the signature must reject passback rather than silently
stripping it.
TokenUsage
Bases: BaseModel
Token counts for LLM usage.
Token terminology: output = reasoning + answer.
__add__
__add__(other: TokenUsage) -> TokenUsage
Add two TokenUsage objects together, summing each field independently.
Source code in src/stirrup/core/models.py
Tool
Bases: BaseModel
Tool definition with name, description, parameter schema, and executor function.
Generic over
P: Parameter model type (Pydantic BaseModel subclass, or EmptyParams for parameterless tools) M: Metadata type (should implement Addable for aggregation; use None for tools without metadata)
Tools are simple, stateless callables. For tools requiring lifecycle management (setup/teardown, resource pooling), use a ToolProvider instead.
Example with parameters
Example without parameters (uses EmptyParams by default):
time_tool = Tool[EmptyParams, None](
name="time",
description="Get current time",
executor=lambda _: ToolResult(content=datetime.now().isoformat()),
)
ToolCall
Bases: BaseModel
Represents a tool invocation request from the LLM.
Also a member of the AssistantBlock union: the kind discriminator is
defaulted, so legacy payloads without the key still validate anywhere ToolCall
is used as a plain input, and new dumps always carry it.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name of the tool to invoke |
arguments |
str
|
JSON string containing tool parameters |
tool_call_id |
str
|
Unique identifier for tracking this tool call and its result |
signature
class-attribute
instance-attribute
signature: str | None = None
Opaque passback state attached to this exact block, e.g. a Google thought signature.
has_provider_tool_call_id
class-attribute
instance-attribute
has_provider_tool_call_id: bool = True
Whether tool_call_id was present on the provider's original block.
A client may synthesize tool_call_id for internal call/result matching
while retaining that it must be omitted from provider-attached passback.
from_provider
classmethod
from_provider(
*,
provider_id: str | None,
name: str,
arguments: str,
signature: str | None = None,
) -> Self
Capture one provider call with a stable internal correlation ID.
Source code in src/stirrup/core/models.py
ToolMessage
Bases: BaseModel
Tool execution result returned to the LLM.
Attributes:
| Name | Type | Description |
|---|---|---|
role |
Literal['tool']
|
Always "tool" |
content |
Content
|
The tool result content |
tool_call_id |
str
|
ID linking this result to the corresponding tool call |
name |
str | None
|
Name of the tool that was called |
args_was_valid |
bool
|
Whether the tool arguments were valid |
success |
bool
|
Whether the tool executed successfully (used by finish tool to control termination) |
UserMessage
Bases: BaseModel
User input message to the LLM.
VideoContentBlock
Bases: BinaryContentBlock
MP4 video content with automatic transcoding and resolution downscaling.
to_base64_url
to_base64_url(
max_pixels: int | None = RESOLUTION_480P,
fps: int | None = None,
) -> str
Transcode to MP4 and return base64 data URL.
Source code in src/stirrup/core/models.py
OpenResponsesClient
OpenResponsesClient(
model: str,
max_tokens: int = 64000,
*,
context_window_tokens: int,
base_url: str | None = None,
api_key: str | None = None,
reasoning_effort: str | None = None,
encrypted_reasoning: bool = False,
timeout: float | None = None,
max_retries: int = 2,
instructions: str | None = None,
kwargs: dict[str, Any] | None = None,
)
Bases: LLMClient
OpenAI SDK-based client using the Responses API.
Uses the official OpenAI Python SDK's responses.create() method. Supports custom base_url for OpenAI-compatible providers that implement the Responses API.
Delegates retries for transient failures to the OpenAI SDK and tracks token usage.
Example
Standard OpenAI usage
client = OpenResponsesClient( ... model="gpt-5.6-luna", ... max_tokens=8_192, ... context_window_tokens=1_000_000, ... )
Custom OpenAI-compatible endpoint
client = OpenResponsesClient( ... model="gpt-5.6-luna", ... context_window_tokens=1_000_000, ... base_url="http://localhost:8000/v1", ... api_key="your-api-key", ... )
Initialize OpenAI SDK client with model configuration for Responses API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
Model identifier (e.g., 'gpt-5.6-luna', 'gpt-5.6-sol'). |
required |
max_tokens
|
int
|
Maximum output tokens. Defaults to 64,000. |
64000
|
context_window_tokens
|
int
|
Context capacity used to decide when Agent history should be summarized. |
required |
base_url
|
str | None
|
API base URL. If None, uses OpenAI's standard URL. Use for OpenAI-compatible providers. |
None
|
api_key
|
str | None
|
API key for authentication. If None, reads from OPENROUTER_API_KEY environment variable. |
None
|
reasoning_effort
|
str | None
|
Reasoning effort level for extended thinking models (e.g., 'low', 'medium', 'high'). Only used with reasoning models. |
None
|
encrypted_reasoning
|
bool
|
Run stateless ( |
False
|
timeout
|
float | None
|
Request timeout in seconds. If None, uses OpenAI SDK default. |
None
|
max_retries
|
int
|
Number of retries for transient errors. Defaults to 2. The OpenAI SDK handles retries internally. |
2
|
instructions
|
str | None
|
Default system-level instructions. Can be overridden by SystemMessage in the messages list. |
None
|
kwargs
|
dict[str, Any] | None
|
Additional arguments passed to responses.create(). Structural
request keys owned by this client are rejected. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stirrup/clients/open_responses_client.py
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 | |
context_window_tokens
property
context_window_tokens: int
Context capacity used by agents for history summarization.
generate
async
generate(
messages: list[ChatMessage], tools: dict[str, Tool]
) -> AssistantMessage
Generate assistant response with optional tool calls using Responses API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
|
list[ChatMessage]
|
List of conversation messages. |
required |
tools
|
dict[str, Tool]
|
Dictionary mapping tool names to Tool objects. |
required |
Returns:
| Type | Description |
|---|---|
AssistantMessage
|
AssistantMessage containing the model's response, any tool calls, |
AssistantMessage
|
and token usage statistics. |
Raises:
| Type | Description |
|---|---|
ContextOverflowError
|
If the provider rejects the request because the input exceeds the model's context capacity. |
OutputTokenLimitError
|
If the provider exhausts |
IncompleteResponseError
|
If the response is incomplete for another provider reason, such as a content filter. |
Source code in src/stirrup/clients/open_responses_client.py
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 | |
validate_token_budgets
Reject an invalid budget pair at client construction.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/stirrup/clients/utils.py
_is_missing_previous_response
_is_missing_previous_response(
error: APIStatusError,
) -> bool
Match only the provider error that identifies an unavailable continuation.
Source code in src/stirrup/clients/open_responses_client.py
_content_to_open_responses_input
Convert Content blocks to OpenResponses input content format.
Uses input_text for text content (vs output_text for responses).
Source code in src/stirrup/clients/open_responses_client.py
_content_to_open_responses_output
Convert Content blocks to OpenResponses output content format.
Uses output_text for assistant message content.
Source code in src/stirrup/clients/open_responses_client.py
_to_open_responses_tools
Convert Tool objects to OpenResponses function format.
OpenResponses API expects tools with name/description/parameters at top level, not nested under a 'function' key like Chat Completions API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tools
|
dict[str, Tool]
|
Dictionary mapping tool names to Tool objects. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of tool definitions in OpenResponses format. |
Source code in src/stirrup/clients/open_responses_client.py
_to_open_responses_input
_to_open_responses_input(
msgs: Sequence[ChatMessage],
*,
allow_reference_reasoning: bool = True,
) -> tuple[str | None, list[dict[str, Any]]]
Convert ChatMessage list to OpenResponses (instructions, input) tuple.
SystemMessage content is extracted as the instructions parameter. Other messages are converted to input items.
Returns:
| Type | Description |
|---|---|
str | None
|
Tuple of (instructions, input_items) where instructions is the system |
list[dict[str, Any]]
|
message content (or None) and input_items is the list of input items. |
Source code in src/stirrup/clients/open_responses_client.py
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
_to_open_responses_request
_to_open_responses_request(
msgs: Sequence[ChatMessage],
*,
use_provider_response_id: bool,
) -> tuple[str | None, str | None, list[dict[str, Any]]]
Build one Responses request while preserving response-level continuation state.
previous_response_id replaces only the earlier input items. System instructions
are extracted from the complete local history because the Responses API does not
carry a previous response's instructions into the next request.
Source code in src/stirrup/clients/open_responses_client.py
_get_attr
Get attribute from object or dict, with fallback default.
Source code in src/stirrup/clients/open_responses_client.py
_parse_response_output
_parse_response_output(
output: list[Any],
*,
allow_reference_reasoning: bool = True,
) -> list[AssistantBlock]
Parse response output items into ordered assistant blocks.
One exhaustive pass in item order: each message item becomes its own
TextBlock (refusal content surfaces as answer text), each function_call
a ToolCall block, and each reasoning item an EncryptedReasoningBlock or
readable ReasoningBlock. Stored continuation state lives on the assistant
message as provider_response_id; reasoning item IDs are not duplicated
into blocks. Unknown item and content types raise until their semantics and
passback behavior are explicitly implemented.
Source code in src/stirrup/clients/open_responses_client.py
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |