Documentation
¶
Overview ¶
Package openresponses is an idiomatic Go implementation of the Open Responses specification — an open, multi-provider standard for LLM "Responses" APIs.
Open Responses defines a single API surface for streaming, multi-turn, agentic LLM interactions across providers. It centers on three primitives:
- Items: the atomic units of context (messages, function calls, reasoning, compactions). Items flow into and out of the model on each turn.
- Tools: function-shaped capabilities the model can invoke. Implementations may also expose provider-hosted tools.
- Streaming events: semantic, typed events emitted as the model produces output — not raw token deltas.
This package bundles a client and a server:
- The Client (NewClient) talks to any Open Responses–compatible endpoint.
- The Handler (NewHandler) wraps a user-supplied Adapter to serve the spec from any net/http server.
Provider adapters live in subpackages — e.g. openresponses/openrouter is a thin wrapper that returns a Client preconfigured for OpenRouter, including its app-attribution headers.
Quick start ¶
Create a client and call the model:
client := openresponses.NewClient(
openresponses.WithBaseURL("https://api.example.com/v1"),
openresponses.WithAPIKey(os.Getenv("API_KEY")),
)
resp, err := client.Create(ctx, openresponses.Request{
Model: "openai/gpt-5.2",
Input: openresponses.UserText("What is the capital of France?"),
})
Stream a response:
stream, err := client.CreateStream(ctx, openresponses.Request{
Model: "openai/gpt-5.2",
Input: openresponses.UserText("Write a haiku about Go."),
})
defer stream.Close()
for stream.Next() {
switch e := stream.Event().(type) {
case *openresponses.OutputTextDeltaEvent:
fmt.Print(e.Delta)
}
}
See package examples for tool calling, reasoning, custom servers, and provider adapters.
Conformance ¶
This package implements the Open Responses specification as published at https://www.openresponses.org. It covers:
- POST /v1/responses (JSON and text/event-stream)
- POST /v1/responses/compact
- WebSocket transport at /v1/responses (both client Dial and server upgrade, including the per-connection turn cache and 60-minute lifetime limit)
- The full Item, Content, Tool, and StreamEvent unions
- Required state-machine semantics for items and responses
- All required error envelopes
Index ¶
- Constants
- Variables
- func InferErrorType(status int) string
- func IsWebSocketUpgrade(r *http.Request) bool
- func RegisterAnnotation[T Annotation](sample T)
- func RegisterAnnotationType(typ string, decode func(json.RawMessage) (Annotation, error))
- func RegisterContent[T Content](sample T)
- func RegisterContentType(typ string, decode func(json.RawMessage) (Content, error))
- func RegisterItem[T Item](sample T)
- func RegisterItemType(typ string, decode func(json.RawMessage) (Item, error))
- func RegisterTool[T Tool](sample T)
- func RegisterToolType(typ string, decode func(json.RawMessage) (Tool, error))
- type APIError
- type Adapter
- type AllowedToolsChoice
- type Annotation
- type AnnotationList
- type BaseEvent
- type Client
- func (c *Client) BaseURL() string
- func (c *Client) Compact(ctx context.Context, req CompactRequest) (*CompactResponse, error)
- func (c *Client) Create(ctx context.Context, req Request) (*Response, error)
- func (c *Client) CreateStream(ctx context.Context, req Request) (*EventStream, error)
- func (c *Client) Dial(ctx context.Context) (*WebSocketStream, error)
- type ClientOption
- func WithAPIKey(key string) ClientOption
- func WithBaseURL(rawURL string) ClientOption
- func WithHTTPClient(h *http.Client) ClientOption
- func WithHeader(key, value string) ClientOption
- func WithHeaders(h http.Header) ClientOption
- func WithMiddleware(m Middleware) ClientOption
- func WithUserAgent(ua string) ClientOption
- type CompactRequest
- type CompactResponse
- type Compaction
- type Content
- type ContentList
- type ContentPartAddedEvent
- type ContentPartDoneEvent
- type Error
- type ErrorEvent
- type ErrorPayload
- type EventSink
- type EventStream
- type FunctionCall
- type FunctionCallArgumentsDeltaEvent
- type FunctionCallArgumentsDoneEvent
- type FunctionCallOutput
- type FunctionCallOutputData
- type FunctionTool
- func FunctionToolFor[In any](name, description string) (FunctionTool, error)
- func MustFunctionTool(name, description string, parameters any) FunctionTool
- func MustFunctionToolFor[In any](name, description string) FunctionTool
- func NewFunctionTool(name, description string, parameters any) (FunctionTool, error)
- type HTTPStatus
- type Handler
- type HandlerOption
- type ImageDetail
- type Include
- type IncompleteDetails
- type Input
- type InputFile
- type InputImage
- type InputText
- type InputTokensDetails
- type InputVideo
- type Item
- type ItemReference
- type ItemStatus
- type Items
- type LogProb
- type Message
- type MessagePhase
- type MessageRole
- type Middleware
- type OutputItemAddedEvent
- type OutputItemDoneEvent
- type OutputText
- type OutputTextAnnotationAddedEvent
- type OutputTextDeltaEvent
- type OutputTextDoneEvent
- type OutputTokensDetails
- type Reasoning
- type ReasoningDeltaEvent
- type ReasoningDoneEvent
- type ReasoningEffort
- type ReasoningParam
- type ReasoningSummary
- type ReasoningSummaryDeltaEvent
- type ReasoningSummaryDoneEvent
- type ReasoningSummaryPartAddedEvent
- type ReasoningSummaryPartDoneEvent
- type ReasoningTextPart
- type Refusal
- type RefusalDeltaEvent
- type RefusalDoneEvent
- type Request
- type Response
- type ResponseCompletedEvent
- type ResponseCreatedEvent
- type ResponseFailedEvent
- type ResponseInProgressEvent
- type ResponseIncompleteEvent
- type ResponseQueuedEvent
- type ResponseReasoning
- type ResponseStatus
- type RoundTripperFunc
- type ServiceTier
- type SpecError
- type SpecificToolChoice
- type StreamEvent
- type StreamOptions
- type SummaryText
- type TextConfig
- type TextFormat
- type TextFormatJSONObject
- type TextFormatJSONSchema
- type TextFormatText
- type TextParam
- type TextPart
- type Tool
- type ToolChoice
- type ToolChoiceValue
- type Tools
- type TopLogProb
- type Truncation
- type URLCitation
- type UnknownAnnotation
- type UnknownContent
- type UnknownEvent
- type UnknownItem
- type UnknownTool
- type UnsupportedCompaction
- type UnsupportedStreaming
- type Usage
- type Verbosity
- type WebSocketErrorEvent
- type WebSocketResponseCreateEvent
- type WebSocketStream
Constants ¶
const ( ContentTypeInputText = "input_text" ContentTypeOutputText = "output_text" ContentTypeText = "text" ContentTypeSummaryText = "summary_text" ContentTypeReasoningText = "reasoning_text" ContentTypeRefusal = "refusal" ContentTypeInputImage = "input_image" ContentTypeInputFile = "input_file" ContentTypeInputVideo = "input_video" )
Standard `type` discriminators for the spec Content union. Provider extensions use a slug-prefixed form (e.g. "openai:tool_result") and are not enumerated here.
const ( // ErrorTypeInvalidRequest is returned for any 4xx that isn't a more // specific case (e.g. 400, 401, 403, 422). ErrorTypeInvalidRequest = "invalid_request" // ErrorTypeNotFound is returned for HTTP 404. ErrorTypeNotFound = "not_found" // ErrorTypeTooManyRequests is returned for HTTP 429. ErrorTypeTooManyRequests = "too_many_requests" // ErrorTypeModelError indicates a failure inside the model or inference // layer; the provider must set it explicitly (not derived from status). ErrorTypeModelError = "model_error" // ErrorTypeServerError is returned for HTTP 5xx and any other unmapped // status. ErrorTypeServerError = "server_error" )
Spec error types — the five values the Open Responses spec defines for the `type` field on an error envelope.
const ( ItemTypeMessage = "message" ItemTypeFunctionCall = "function_call" ItemTypeFunctionCallOutput = "function_call_output" ItemTypeReasoning = "reasoning" ItemTypeCompaction = "compaction" ItemTypeItemReference = "item_reference" )
Standard `type` discriminators for the spec Item union. Provider extension items use a slug-prefixed form (e.g. "openai:web_search_call") and are not enumerated here.
const ( EventTypeResponseCreated = "response.created" EventTypeResponseInProgress = "response.in_progress" EventTypeResponseQueued = "response.queued" EventTypeResponseCompleted = "response.completed" EventTypeResponseFailed = "response.failed" EventTypeResponseIncomplete = "response.incomplete" EventTypeOutputItemAdded = "response.output_item.added" EventTypeOutputItemDone = "response.output_item.done" EventTypeContentPartAdded = "response.content_part.added" EventTypeContentPartDone = "response.content_part.done" EventTypeOutputTextDelta = "response.output_text.delta" EventTypeOutputTextDone = "response.output_text.done" EventTypeOutputTextAnnotationAdded = "response.output_text.annotation.added" EventTypeRefusalDelta = "response.refusal.delta" EventTypeRefusalDone = "response.refusal.done" EventTypeReasoningDelta = "response.reasoning.delta" EventTypeReasoningDone = "response.reasoning.done" EventTypeReasoningSummaryTextDelta = "response.reasoning_summary_text.delta" EventTypeReasoningSummaryTextDone = "response.reasoning_summary_text.done" EventTypeReasoningSummaryPartAdded = "response.reasoning_summary_part.added" EventTypeReasoningSummaryPartDone = "response.reasoning_summary_part.done" EventTypeFunctionCallArgumentsDelta = "response.function_call_arguments.delta" EventTypeFunctionCallArgumentsDone = "response.function_call_arguments.done" EventTypeError = "error" )
Spec event-type discriminators. Each entry matches the `type` field on the corresponding StreamEvent variant defined above.
const AnnotationTypeURLCitation = "url_citation"
AnnotationTypeURLCitation is the `type` discriminator for the spec's only standard annotation kind.
const DefaultBaseURL = "https://api.openai.com/v1"
DefaultBaseURL is the canonical Open Responses endpoint (OpenAI's Responses API). Providers will override this via WithBaseURL.
const ToolTypeFunction = "function"
ToolTypeFunction is the spec discriminator for FunctionTool.
const Version = "0.1.0"
Version is bumped on each release. Surfaced in the default User-Agent.
const WebSocketConnectionLifetime = 60 * time.Minute
WebSocketConnectionLifetime caps a single Open Responses WebSocket connection's lifetime. Per the spec, servers MAY enforce a 60-minute limit; when the deadline elapses the server emits `websocket_connection_limit_reached` and closes.
Variables ¶
var ( // ErrStreamClosed indicates that an EventStream has been fully consumed // or explicitly closed. ErrStreamClosed = errors.New("openresponses: stream closed") // ErrUnknownEvent is returned by the stream decoder when it sees a // `type` value not defined in the spec. The decoder still surfaces // the event as an UnknownEvent so callers can choose to inspect it. ErrUnknownEvent = errors.New("openresponses: unknown event type") // ErrMissingType is returned when an item or content part lacks a // `type` discriminator field during unmarshaling. ErrMissingType = errors.New("openresponses: missing type discriminator") )
Sentinel errors for common, programmatically-actionable conditions. Wrap or return these so callers can use errors.Is.
Functions ¶
func InferErrorType ¶
InferErrorType maps an HTTP status code to the spec's error type taxonomy. Used as a fallback when a provider returns an error envelope without a `type` field (e.g. OpenRouter's {"error": {"code": ..., "message": ...}}).
The spec defines exactly five error types — server_error, invalid_request, not_found, model_error, too_many_requests — so only those values are returned here. Provider-supplied types (even non-spec ones like "authentication_error" or "rate_limit_exceeded") should be preserved verbatim; this function only runs when the provider gave us nothing.
400 / 401 / 403 / 4xx other → invalid_request 404 → not_found 429 → too_many_requests 5xx → server_error anything else → server_error
model_error is excluded from this mapping because the HTTP status alone cannot distinguish a model failure from a generic server fault — that determination requires payload context the provider would have to supply explicitly.
func IsWebSocketUpgrade ¶
IsWebSocketUpgrade reports whether r is requesting a WebSocket upgrade. Useful when composing custom routing on top of the Handler.
func RegisterAnnotation ¶
func RegisterAnnotation[T Annotation](sample T)
RegisterAnnotation registers a Go type T as the typed decode target for its wire `type` discriminator. Adapter packages call this from init() so wire values like "openai:file_citation" round-trip as their typed Go value instead of falling back to UnknownAnnotation:
func init() {
openresponses.RegisterAnnotation(FileCitation{})
}
For types with custom decoding needs, use RegisterAnnotationType.
func RegisterAnnotationType ¶
func RegisterAnnotationType(typ string, decode func(json.RawMessage) (Annotation, error))
RegisterAnnotationType is the low-level form of RegisterAnnotation. Prefer RegisterAnnotation for the typical case.
func RegisterContent ¶
func RegisterContent[T Content](sample T)
RegisterContent registers a Go type T as the typed decode target for its wire `type` discriminator. Adapter packages call this from init() so wire values like "openai:tool_result" round-trip as their typed Go value instead of falling back to UnknownContent:
func init() {
openresponses.RegisterContent(ToolResult{})
}
The sample argument is unused at runtime — it exists only to let Go infer T. Registration is process-global.
For types with custom decoding needs, use RegisterContentType.
func RegisterContentType ¶
func RegisterContentType(typ string, decode func(json.RawMessage) (Content, error))
RegisterContentType is the low-level form of RegisterContent. Prefer RegisterContent for the typical case.
func RegisterItem ¶
func RegisterItem[T Item](sample T)
RegisterItem registers a Go type T as the typed decode target for its wire `type` discriminator. Adapter packages call this from init() so wire values like "openai:web_search_call" round-trip as their typed Go value instead of falling back to UnknownItem:
func init() {
openresponses.RegisterItem(WebSearchCall{})
}
The sample argument is unused at runtime — it exists only to let Go infer T. Registration is process-global; duplicate registrations for the same discriminator overwrite the earlier one.
For types with custom decoding needs, use RegisterItemType.
func RegisterItemType ¶
func RegisterItemType(typ string, decode func(json.RawMessage) (Item, error))
RegisterItemType is the low-level form of RegisterItem. Use it when one wire type fans out to multiple Go types via inner-field discrimination, or decoding requires custom validation. For the typical "decode JSON into a single struct" case, prefer RegisterItem.
func RegisterTool ¶
func RegisterTool[T Tool](sample T)
RegisterTool registers a Go type T as the typed decode target for its wire `type` discriminator. Adapter packages call this from init() so wire values like "openrouter:web_search" round-trip as their typed Go value instead of falling back to UnknownTool:
func init() {
openresponses.RegisterTool(WebSearch{})
}
The sample argument is unused at runtime — it exists only to let Go infer T. Registration is process-global; duplicate registrations for the same discriminator overwrite the earlier one. Prefer the "yourorg:thing" type-prefix convention so adapter namespaces don't collide.
For types with custom decoding needs (polymorphic inner fields, version routing, validation at decode), use RegisterToolType instead.
func RegisterToolType ¶
func RegisterToolType(typ string, decode func(json.RawMessage) (Tool, error))
RegisterToolType is the low-level form of RegisterTool. Use it when the generic shortcut isn't a fit — e.g. one wire type fans out to multiple Go types via inner-field discrimination, or decoding requires custom validation. For the typical "decode JSON into a single struct" case, prefer RegisterTool.
Types ¶
type APIError ¶
type APIError struct {
// StatusCode is the HTTP status returned by the server.
StatusCode int `json:"-"`
// Type is the spec error type (server_error, invalid_request, not_found,
// model_error, too_many_requests, …). Empty if the server did not return
// a structured envelope.
Type string `json:"type"`
// Code is a more specific machine-readable identifier within the type.
Code string `json:"code,omitempty"`
// Message is a human-readable explanation.
Message string `json:"message"`
// Param names the offending request parameter, if applicable.
Param string `json:"param,omitempty"`
// Headers carries any provider-specific headers attached to the error
// (e.g. retry-after on 429s). Always present even if empty.
Headers map[string]string `json:"headers,omitempty"`
// RawBody is the unparsed response body, useful for debugging when the
// server returns something off-spec.
RawBody []byte `json:"-"`
}
APIError is returned when a request fails at the HTTP layer — either with a non-2xx status code, or when the response body cannot be parsed.
The Open Responses spec defines an error envelope with type, code, message, and param. We surface all four, plus the original HTTP status, so callers can switch on whatever level of granularity they need.
func (*APIError) Error ¶
Error returns a human-readable summary of the APIError, including the HTTP status code and any spec-shaped fields the server returned.
func (*APIError) HTTPStatus ¶
HTTPStatus reports the underlying HTTP status. When a server proxies a request through this client, returning the APIError from an Adapter lets the Handler propagate the original status (instead of folding everything into a generic 500).
type Adapter ¶
type Adapter interface {
// Create handles a non-streaming POST /v1/responses.
//
// Return either the final Response (preferred), or an error. If the
// returned error implements HTTPStatus(), its status code is used in
// the response; otherwise the Handler picks a sensible default
// (500 for ordinary errors, 400 for the spec invalid_request type).
Create(ctx context.Context, req Request) (*Response, error)
// CreateStream handles a streaming POST /v1/responses. The adapter
// should emit events by calling sink.Send for each event in spec order:
//
// response.created → response.in_progress → (item/content/delta...) →
// response.completed | .failed | .incomplete
//
// CreateStream returns nil on success; if it returns an error, the
// Handler emits a terminal `error` event with the error's message before
// closing the connection.
CreateStream(ctx context.Context, req Request, sink EventSink) error
// Compact handles POST /v1/responses/compact.
Compact(ctx context.Context, req CompactRequest) (*CompactResponse, error)
}
Adapter is the contract a backend implements to power an Open Responses server. The two required entry points are Create (returns a non-streaming Response) and CreateStream (writes SSE events).
If your backend doesn't support streaming, embed UnsupportedStreaming and the Handler will translate that into a clean 501 for streaming clients.
If your backend doesn't support compaction, embed UnsupportedCompaction.
type AllowedToolsChoice ¶
type AllowedToolsChoice struct {
// Mode is the tool-choice value to apply within the allowed subset
// ("none", "auto", or "required"). Defaults to "auto" if empty.
Mode ToolChoiceValue
Tools []SpecificToolChoice
}
AllowedToolsChoice narrows the model's tool choice to a subset of the declared tools, without re-sending the full tool list. The server is required to enforce this as a hard constraint — any out-of-set call must be rejected or suppressed.
func (AllowedToolsChoice) MarshalJSON ¶
func (c AllowedToolsChoice) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type Annotation ¶
type Annotation interface {
// AnnotationType returns the JSON `type` discriminator (e.g.
// "url_citation", "openai:file_citation").
AnnotationType() string
}
Annotation is a citation or other inline reference attached to model output. Only url_citation is in the standard spec today; provider extensions surface as UnknownAnnotation, or — when the adapter package has registered them via RegisterAnnotationType — as their typed Go value.
type AnnotationList ¶
type AnnotationList []Annotation
AnnotationList is a slice of Annotation with a custom JSON codec.
func (AnnotationList) MarshalJSON ¶
func (al AnnotationList) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. Nil encodes as "[]".
func (*AnnotationList) UnmarshalJSON ¶
func (al *AnnotationList) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler. Accepts "null" as an empty list.
type BaseEvent ¶
BaseEvent is the common header (type + sequence_number) shared by every streaming event. It's embedded by every event type defined in this package and is exported so adapter authors can compose their own custom events when extending the stream with provider-specific data.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to a remote Open Responses server.
A Client is safe for concurrent use. It owns no goroutines; all requests run on the caller's goroutine. The zero value is not usable — construct one with NewClient.
Configuration is purely option-based. Common patterns:
client := openresponses.NewClient(
openresponses.WithBaseURL("https://api.openai.com/v1"),
openresponses.WithAPIKey(os.Getenv("OPENAI_API_KEY")),
)
// Or with an adapter:
client := openrouter.New(openrouter.WithAppTitle("my-app"))
func NewClient ¶
func NewClient(opts ...ClientOption) *Client
NewClient builds a Client with the supplied options applied in order. At minimum you should set the API key. If you don't set a base URL, the default points at OpenAI (which implements the Responses spec).
func (*Client) Compact ¶
func (c *Client) Compact(ctx context.Context, req CompactRequest) (*CompactResponse, error)
Compact calls POST /v1/responses/compact, which collapses a conversation into an opaque Compaction item suitable for use as input on a fresh response without resending the full transcript.
func (*Client) Create ¶
Create sends a non-streaming /v1/responses request and returns the final Response. Streaming is implicitly disabled — if the caller set req.Stream, it is cleared.
func (*Client) CreateStream ¶
CreateStream sends a streaming /v1/responses request and returns an EventStream the caller iterates with Next(). The returned EventStream MUST be Close()d to free the underlying HTTP connection — typically with `defer stream.Close()`.
Streaming overrides req.Stream regardless of the caller's setting.
func (*Client) Dial ¶
func (c *Client) Dial(ctx context.Context) (*WebSocketStream, error)
Dial opens a WebSocket connection to the configured base URL's /responses endpoint and returns a stream the caller drives with Send/Next.
The base URL's scheme is translated: http → ws, https → wss.
Example:
stream, err := client.Dial(ctx)
if err != nil { return err }
defer stream.Close()
if err := stream.Send(req); err != nil { return err }
for stream.Next() {
switch e := stream.Event().(type) {
case *openresponses.OutputTextDeltaEvent:
fmt.Print(e.Delta)
}
}
type ClientOption ¶
type ClientOption func(*Client)
ClientOption configures a Client at construction time. Pass options to NewClient; you can also stack a provider preset with custom options (see openrouter.New(opts...) — it composes its presets with user options).
func WithAPIKey ¶
func WithAPIKey(key string) ClientOption
WithAPIKey sets a bearer token sent on every request as the Authorization header. Most providers expect this.
func WithBaseURL ¶
func WithBaseURL(rawURL string) ClientOption
WithBaseURL sets the API endpoint. The trailing "/v1" segment is preserved as given. Default: "https://api.openai.com/v1" (the Open Responses reference target).
func WithHTTPClient ¶
func WithHTTPClient(h *http.Client) ClientOption
WithHTTPClient overrides the underlying http.Client. Use this to plug in custom transports, timeouts, retry layers, or test doubles.
By default, the package uses a client with the standard transport and no timeout — that's intentional, because streaming responses can run arbitrarily long. If you set a Timeout on the http.Client you supply, it WILL fire on streaming requests and cut the stream off.
func WithHeader ¶
func WithHeader(key, value string) ClientOption
WithHeader sets a single request header on every outgoing request. Pass multiple WithHeader options to set several. The header replaces any prior value for the same key.
Use this to attach provider-specific headers like OpenRouter's `HTTP-Referer` and `X-Title` for app attribution.
func WithHeaders ¶
func WithHeaders(h http.Header) ClientOption
WithHeaders merges a set of headers into the client's default headers. Each entry replaces any prior value for the same key.
func WithMiddleware ¶
func WithMiddleware(m Middleware) ClientOption
WithMiddleware wraps the underlying http.Client transport with a middleware. Middlewares run in registration order, with the first registered being closest to the wire.
Use this for retries, logging, response inspection, or any cross-cutting concern. Each middleware receives the incoming request and the next RoundTripper in the chain:
openresponses.WithMiddleware(func(next http.RoundTripper) http.RoundTripper {
return openresponses.RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
log.Println(">", r.Method, r.URL)
return next.RoundTrip(r)
})
})
func WithUserAgent ¶
func WithUserAgent(ua string) ClientOption
WithUserAgent overrides the User-Agent sent with each request. Default: "openresponses-go/<version>".
type CompactRequest ¶
type CompactRequest struct {
Model string `json:"model"`
Input Input `json:"input"`
PreviousResponseID string `json:"previous_response_id,omitempty"`
Instructions string `json:"instructions,omitempty"`
PromptCacheKey string `json:"prompt_cache_key,omitempty"`
}
CompactRequest is the body of POST /v1/responses/compact.
type CompactResponse ¶
type CompactResponse struct {
ID string `json:"id"`
Object string `json:"object"` // always "response.compaction"
Output Items `json:"output"`
CreatedAt int64 `json:"created_at"`
Usage Usage `json:"usage"`
}
CompactResponse is the body returned by POST /v1/responses/compact.
type Compaction ¶
type Compaction struct {
ID string `json:"id"`
EncryptedContent string `json:"encrypted_content"`
CreatedBy string `json:"created_by,omitempty"`
}
Compaction is the opaque, encrypted summary of a prior conversation produced by POST /v1/responses/compact. Send it back as an input item to resume the conversation without resending the full transcript.
func (Compaction) MarshalJSON ¶
func (c Compaction) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type Content ¶
type Content interface {
// ContentType returns the JSON `type` discriminator (e.g. "input_text",
// "openai:tool_result").
ContentType() string
}
Content is one part inside a Message or Reasoning item's content array.
The spec defines two asymmetric content unions: UserContent (what the user hands the model — text, images, files, video) and ModelContent (what the model produces — text, reasoning text, refusals). The wire protocol mixes them inside a single content array discriminated by `type`, so this package uses a single Content interface; each variant carries only the fields valid for its direction.
Implementations: InputText, OutputText, TextPart, SummaryText, ReasoningTextPart, Refusal, InputImage, InputFile, InputVideo.
Provider adapter packages can ship typed Content for extension parts (e.g. an OpenAI hosted tool's structured output) and register them via RegisterContentType so they decode as the typed value instead of UnknownContent.
type ContentList ¶
type ContentList []Content
ContentList is a slice of Content with a custom JSON codec that dispatches on the `type` discriminator. Use it anywhere the spec expects an array of content parts (Message.content, Reasoning.content, Reasoning.summary, FunctionCallOutput.output when array-shaped, …).
func (ContentList) MarshalJSON ¶
func (cl ContentList) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. Nil encodes as "[]" so the wire representation is always a JSON array.
func (*ContentList) UnmarshalJSON ¶
func (cl *ContentList) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler. Accepts "null" as an empty list.
type ContentPartAddedEvent ¶
type ContentPartAddedEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
ContentIndex int `json:"content_index"`
Part Content `json:"part"`
}
ContentPartAddedEvent fires before deltas for a new content part inside a Message item.
func (*ContentPartAddedEvent) UnmarshalJSON ¶
func (e *ContentPartAddedEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, dispatching the embedded Content part via unmarshalContent.
type ContentPartDoneEvent ¶
type ContentPartDoneEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
ContentIndex int `json:"content_index"`
Part Content `json:"part"`
}
ContentPartDoneEvent fires after deltas for a content part complete.
func (*ContentPartDoneEvent) UnmarshalJSON ¶
func (e *ContentPartDoneEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, dispatching the embedded Content part via unmarshalContent.
type Error ¶
type Error struct {
// Code is a stable, machine-readable identifier (e.g. "rate_limit_exceeded").
Code string `json:"code"`
// Message is a human-readable description.
Message string `json:"message"`
}
Error is the error object embedded in a completed-but-failed Response. Compare with APIError, which represents transport- or HTTP-level failures returned outside of a Response body.
type ErrorEvent ¶
type ErrorEvent struct {
BaseEvent
Error ErrorPayload `json:"error"`
}
ErrorEvent fires when an error interrupts the stream. The next event will be either response.failed or end-of-stream.
type ErrorPayload ¶
type ErrorPayload struct {
Type string `json:"type"`
Code *string `json:"code"`
Message string `json:"message"`
Param *string `json:"param"`
Headers map[string]string `json:"headers,omitempty"`
}
ErrorPayload is the full error envelope emitted in streaming error events.
type EventSink ¶
type EventSink interface {
// Send marshals an event to JSON and writes it as an SSE data record.
// Returns the error from the network write, if any.
Send(ev StreamEvent) error
// Flush pushes any buffered output to the underlying transport.
// Most Adapters don't need to call this; Send already flushes after
// each event.
Flush() error
}
EventSink is the channel a streaming Adapter writes events to. The Handler implements it on top of an http.ResponseWriter; tests can pass an in-memory implementation.
Send is safe to call concurrently from the adapter; the Handler serializes writes internally. Sequence numbers are assigned automatically if the event's SequenceNumber field is zero.
type EventStream ¶
type EventStream struct {
// contains filtered or unexported fields
}
EventStream is an iterator over the SSE response body of a streaming /v1/responses request. Use it like:
stream, err := client.CreateStream(ctx, req)
if err != nil { return err }
defer stream.Close()
for stream.Next() {
switch ev := stream.Event().(type) {
case *openresponses.OutputTextDeltaEvent:
fmt.Print(ev.Delta)
case *openresponses.ResponseCompletedEvent:
final = &ev.Response
}
}
return stream.Err()
EventStream is single-use and not safe for concurrent use.
func NewEventStream ¶
func NewEventStream(ctx context.Context, r io.ReadCloser) *EventStream
NewEventStream wraps an io.ReadCloser carrying an SSE byte stream. Most callers won't need this directly — Client.CreateStream returns one for you. It's exported so server-side code and tests can build streams without an HTTP layer.
func (*EventStream) Close ¶
func (s *EventStream) Close() error
Close releases the underlying reader. It is safe to call multiple times and safe to call concurrently with a final Next iteration.
func (*EventStream) Err ¶
func (s *EventStream) Err() error
Err returns the first error encountered while reading the stream. It is nil on clean EOF (including the "[DONE]" sentinel).
func (*EventStream) Event ¶
func (s *EventStream) Event() StreamEvent
Event returns the event most recently produced by Next. Calling Event before Next is undefined; calling it after Next returns false returns the last successfully decoded event (or nil if none ever was).
func (*EventStream) Events ¶
func (s *EventStream) Events() iter.Seq[StreamEvent]
Events returns a Go 1.23+ range-over-func iterator over the stream's events. Iteration stops at end-of-stream, on error, or when the caller breaks out of the loop. Inspect Err after the loop returns to distinguish a clean close from a failure.
for ev := range stream.Events() {
switch e := ev.(type) {
case *openresponses.OutputTextDeltaEvent:
fmt.Print(e.Delta)
case *openresponses.ResponseCompletedEvent:
final = &e.Response
}
}
if err := stream.Err(); err != nil { return err }
func (*EventStream) Next ¶
func (s *EventStream) Next() bool
Next advances the stream to the next event. Returns true if an event was read successfully, false at end-of-stream or on error. After Next returns false, check Err() to distinguish clean EOF from a failure.
type FunctionCall ¶
type FunctionCall struct {
ID string `json:"id"`
CallID string `json:"call_id"`
Name string `json:"name"`
Arguments string `json:"arguments"`
Status ItemStatus `json:"status,omitempty"`
}
FunctionCall is a tool invocation generated by the model. Arguments are emitted as a JSON-encoded string (not a parsed object) so they can be streamed token-by-token.
func (FunctionCall) MarshalJSON ¶
func (f FunctionCall) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type FunctionCallArgumentsDeltaEvent ¶
type FunctionCallArgumentsDeltaEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
Delta string `json:"delta"`
Obfuscation string `json:"obfuscation,omitempty"`
}
FunctionCallArgumentsDeltaEvent streams chunks of a function call's arguments JSON string.
type FunctionCallArgumentsDoneEvent ¶
type FunctionCallArgumentsDoneEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
Arguments string `json:"arguments"`
}
FunctionCallArgumentsDoneEvent fires when a function call's arguments finish streaming. Arguments is the full JSON string.
type FunctionCallOutput ¶
type FunctionCallOutput struct {
ID string `json:"id,omitempty"`
CallID string `json:"call_id"`
Output FunctionCallOutputData `json:"output"`
Status ItemStatus `json:"status,omitempty"`
}
FunctionCallOutput is the developer-supplied result of a FunctionCall. The Output field is a oneOf on the wire: either a JSON-encoded string, or an array of content parts. We model both with FunctionCallOutputData.
func (FunctionCallOutput) ItemType ¶
func (FunctionCallOutput) ItemType() string
ItemType implements Item.
func (FunctionCallOutput) MarshalJSON ¶
func (f FunctionCallOutput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type FunctionCallOutputData ¶
type FunctionCallOutputData struct {
// Text is the simple string form. Most function tools return a JSON
// string or arbitrary text.
Text string
// Parts is the structured array form, for tools that return rich
// multi-modal content (e.g. images from a code interpreter).
Parts ContentList
}
FunctionCallOutputData captures the oneOf shape of FunctionCallOutput.output. Exactly one of Text or Parts should be non-zero. Use the helper constructors (TextOutput, PartsOutput) for clarity.
func PartsOutput ¶
func PartsOutput(parts ...Content) FunctionCallOutputData
PartsOutput builds a FunctionCallOutputData carrying structured parts.
func TextOutput ¶
func TextOutput(s string) FunctionCallOutputData
TextOutput builds a FunctionCallOutputData carrying a plain string.
func (FunctionCallOutputData) MarshalJSON ¶
func (d FunctionCallOutputData) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. When Parts is non-empty it encodes as the structured array form; otherwise it encodes as a bare JSON string.
func (*FunctionCallOutputData) UnmarshalJSON ¶
func (d *FunctionCallOutputData) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler. Accepts either a bare JSON string or a structured content-parts array.
type FunctionTool ¶
type FunctionTool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters json.RawMessage `json:"parameters,omitempty"`
// Strict enables stricter JSON-Schema enforcement on the model's
// generated arguments. Defaults to true on the wire if omitted —
// surface it via *bool so callers can explicitly opt out.
Strict *bool `json:"strict,omitempty"`
}
FunctionTool is the canonical externally-hosted tool: a developer-defined function with a JSON-Schema parameter spec. The model emits FunctionCall items; the developer executes the function and replies with FunctionCallOutput items.
func FunctionToolFor ¶
func FunctionToolFor[In any](name, description string) (FunctionTool, error)
FunctionToolFor builds a FunctionTool whose JSON-Schema parameters are derived from the In type via reflection. Use this when you're writing the tool in Go and would otherwise hand-roll the same schema as a map[string]any:
type WeatherIn struct {
City string `json:"city" jsonschema:"the city, e.g. \"Paris\""`
Units string `json:"units,omitempty" jsonschema:"\"c\" or \"f\""`
}
tool, err := openresponses.FunctionToolFor[WeatherIn](
"get_weather", "Look up the current weather for a city")
At call time you JSON-unmarshal FunctionCall.Arguments into the same In type — the struct is the single source of truth for both directions.
Field tagging follows google/jsonschema-go: `json:"..."` controls property names and omission; `jsonschema:"..."` supplies the description. Fields without `omitempty`/`omitzero` are emitted as required.
For schemas that arrive as bytes or a pre-built map, use NewFunctionTool instead.
func MustFunctionTool ¶
func MustFunctionTool(name, description string, parameters any) FunctionTool
MustFunctionTool is NewFunctionTool that panics on encoding error. Useful in package-level var blocks where the schema is a literal.
func MustFunctionToolFor ¶
func MustFunctionToolFor[In any](name, description string) FunctionTool
MustFunctionToolFor is FunctionToolFor that panics on schema-derivation error. Useful in package-level var blocks where the input type is a literal that should always derive cleanly.
func NewFunctionTool ¶
func NewFunctionTool(name, description string, parameters any) (FunctionTool, error)
NewFunctionTool is the ergonomic constructor: pass a Go value or a JSON string for the parameters and we'll handle the rest.
Accepted parameter forms:
- nil (no parameters)
- json.RawMessage (used verbatim)
- []byte / string (parsed as JSON-Schema)
- any struct/map (encoded via json.Marshal)
func (FunctionTool) MarshalJSON ¶
func (f FunctionTool) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type HTTPStatus ¶
HTTPStatus is an optional interface an error may implement to control the HTTP status code the Handler writes for non-streaming failures. Returning 0 (or not implementing the interface) defers to a default of 500.
HTTPStatus embeds error so errors.AsType can target it. Any value implementing HTTPStatus must already be returned as an error in practice, so this constraint is a no-op for the realistic implementers.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler is the net/http entry point. It implements http.Handler and dispatches to the wrapped Adapter.
Handler is safe for concurrent use.
func NewHandler ¶
func NewHandler(a Adapter, opts ...HandlerOption) *Handler
NewHandler builds a Handler wrapping the given Adapter.
type HandlerOption ¶
type HandlerOption func(*Handler)
HandlerOption configures a Handler.
func WithErrorLog ¶
func WithErrorLog(fn func(op string, err error)) HandlerOption
WithErrorLog installs a logger that's called for every internal failure (decode errors, write errors, panics). Nil disables logging. The logger receives the operation that failed plus the error.
func WithPathPrefix ¶
func WithPathPrefix(prefix string) HandlerOption
WithPathPrefix sets the URL prefix the Handler matches against. Default: "/v1". Set it to "" to match paths verbatim, or to a custom prefix if you are routing under a different mount point.
func WithWebSocketConnectionLifetime ¶
func WithWebSocketConnectionLifetime(d time.Duration) HandlerOption
WithWebSocketConnectionLifetime overrides the per-connection lifetime limit. Default: WebSocketConnectionLifetime (60 minutes).
A non-positive value falls back to the spec default — the limit cannot be disabled because the spec mandates a 60-minute cap (clients receive `websocket_connection_limit_reached` when reached). Values longer than 60 minutes are honored by this server but violate the spec, so prefer values in (0, 60min].
func WithWebSocketOriginPatterns ¶
func WithWebSocketOriginPatterns(patterns ...string) HandlerOption
WithWebSocketOriginPatterns sets the list of allowed Origin patterns for WebSocket handshakes. Each pattern is matched against the request's Origin header (case-insensitive, exact host match unless "*").
Default: nil — Origin checking is enforced by coder/websocket's defaults (same-origin only). Pass {"*"} during development to allow any origin (e.g. when pointing the published compliance UI at a localhost server).
type ImageDetail ¶
type ImageDetail string
ImageDetail controls how aggressively the model processes an input image.
const ( ImageDetailLow ImageDetail = "low" ImageDetailHigh ImageDetail = "high" ImageDetailAuto ImageDetail = "auto" )
ImageDetail values defined by the spec.
type Include ¶
type Include string
Include opts into optional fields on the response that providers otherwise omit (e.g. encrypted reasoning content, per-token log probabilities).
type IncompleteDetails ¶
type IncompleteDetails struct {
// Reason is a machine-readable code like "max_output_tokens".
Reason string `json:"reason"`
}
IncompleteDetails explains why a response ended in `incomplete` status — typically because the model hit max_output_tokens before finishing.
type Input ¶
type Input struct {
// Text is the "input is a plain string" form. Send it when you have a
// single user message and no prior conversation state.
Text string
// Items is the "input is an array" form. Use it for multi-turn input
// or anything beyond a single text message.
Items Items
}
Input is the polymorphic body of Request.Input — either a string (handed to the model as a single user message) or an array of items.
You'll usually construct one of:
- openresponses.UserText("Hello") → Items
- openresponses.Items{...} → Items
- openresponses.InputString("Hello") → string form, exact wire
Both shapes are accepted; pick whichever is clearer.
func InputString ¶
InputString wraps a string into an Input that serializes as the plain string form. Equivalent to setting Input{Text: s}.
func NewInput ¶
NewInput builds an Input from a list of items. Use this for multi-turn or multi-modal input:
req.Input = openresponses.NewInput(
openresponses.SystemMessage("Be terse."),
openresponses.UserMessage(openresponses.InputText{Text: "Hi"}),
)
func UserText ¶
UserText builds an Input carrying a single user message with one input_text part. The most common starting point for a Request.
req := openresponses.Request{Model: "...", Input: openresponses.UserText("Hi")}
func (Input) AsItems ¶
AsItems returns the input as a flat Items slice, converting the string form to a single user message if needed.
func (Input) IsZero ¶
IsZero reports whether the Input carries neither text nor any items. Used by encoders that want to omit empty inputs.
func (Input) MarshalJSON ¶
MarshalJSON implements json.Marshaler. Items take precedence over Text; a zero-valued Input encodes as JSON null.
func (Input) String ¶
String returns a human-readable summary of the Input — useful for logs. Not a faithful round-trip.
func (*Input) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler. Accepts either a bare string (which populates Text) or a JSON array (which populates Items).
type InputFile ¶
type InputFile struct {
Filename string `json:"filename,omitempty"`
FileURL string `json:"file_url,omitempty"`
FileData string `json:"file_data,omitempty"`
}
InputFile is a user-supplied file. Exactly one of FileURL or FileData (base64) should be set, plus an optional filename.
func (InputFile) ContentType ¶
ContentType implements Content.
func (InputFile) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
type InputImage ¶
type InputImage struct {
ImageURL string `json:"image_url"`
Detail ImageDetail `json:"detail,omitempty"`
}
InputImage is a user-supplied image, identified by URL (which may be a `data:` URL containing base64-encoded bytes).
func (InputImage) ContentType ¶
func (InputImage) ContentType() string
ContentType implements Content.
func (InputImage) MarshalJSON ¶
func (c InputImage) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type InputText ¶
type InputText struct {
Text string `json:"text"`
}
InputText is plain user-supplied text. The most common content part.
func (InputText) ContentType ¶
ContentType implements Content.
func (InputText) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
type InputTokensDetails ¶
type InputTokensDetails struct {
CachedTokens int `json:"cached_tokens"`
}
InputTokensDetails breaks the input token count down by category.
type InputVideo ¶
type InputVideo struct {
VideoURL string `json:"video_url"`
}
InputVideo is a user-supplied video, identified by URL or data URL.
func (InputVideo) ContentType ¶
func (InputVideo) ContentType() string
ContentType implements Content.
func (InputVideo) MarshalJSON ¶
func (c InputVideo) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type Item ¶
type Item interface {
// ItemType returns the JSON `type` discriminator (e.g. "message",
// "openai:web_search_call").
ItemType() string
}
Item is one entry in an input or output sequence. The spec calls items "the fundamental unit of context" — every message, tool call, tool output, reasoning trace, or compaction summary is an Item.
The wire format discriminates items by the `type` field. Standard types: message, function_call, function_call_output, reasoning, compaction, item_reference. Provider extensions use a slug prefix (e.g. "openai:web_search_call"); register a constructor with RegisterItemType to surface them as typed values, otherwise they decode as UnknownItem.
Use a type switch to inspect a concrete item:
switch it := item.(type) {
case openresponses.Message: // ...
case openresponses.FunctionCall: // ...
case *openai.WebSearchCall: // provider-typed (registered)
case openresponses.UnknownItem: // unregistered; Raw holds JSON
}
Implementations supply the JSON `type` discriminator via ItemType and a MarshalJSON that emits it. Provider adapter packages can ship custom Item types and register them via RegisterItemType.
func UnmarshalItem ¶
func UnmarshalItem(raw json.RawMessage) (Item, error)
UnmarshalItem decodes a single Item from its JSON object representation. It is exposed for callers (e.g. server adapters) that need to handle one item at a time outside of an array context.
type ItemReference ¶
type ItemReference struct {
ID string `json:"id"`
}
ItemReference points to an item by ID, letting the server look up the full body server-side rather than requiring the client to resend it. Useful when store=true and you want to chain turns by reference.
func (ItemReference) MarshalJSON ¶
func (r ItemReference) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type ItemStatus ¶
type ItemStatus string
ItemStatus is the lifecycle of an Item.
Items begin as in_progress while the model is sampling them, and end in either completed (model finished) or incomplete (model was interrupted, e.g. by exhausting its token budget). Incomplete is terminal: a stream that emits an incomplete item must close out without further items.
const ( StatusInProgress ItemStatus = "in_progress" StatusCompleted ItemStatus = "completed" StatusIncomplete ItemStatus = "incomplete" )
ItemStatus values defined by the spec.
type Items ¶
type Items []Item
Items is a slice of Item with a JSON codec that handles the discriminated union on both directions of the wire.
func (Items) MarshalJSON ¶
MarshalJSON implements json.Marshaler. Nil encodes as "[]".
func (*Items) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler. Accepts "null" as empty.
type LogProb ¶
type LogProb struct {
Token string `json:"token"`
Logprob float64 `json:"logprob"`
Bytes []int `json:"bytes"`
TopLogprobs []TopLogProb `json:"top_logprobs"`
}
LogProb is one token's log-probability and the top alternatives the model considered. Returned when the request includes IncludeMessageOutputTextLogprobs.
type Message ¶
type Message struct {
ID string `json:"id,omitempty"`
Role MessageRole `json:"role"`
Status ItemStatus `json:"status,omitempty"`
Content ContentList `json:"content"`
Phase MessagePhase `json:"phase,omitempty"`
}
Message is a turn in the conversation — from the user, the assistant, a system prompt, or a developer-supplied guidance message.
On the wire, Message.content is an array of polymorphic content parts. In Go, we expose it as a ContentList that knows how to round-trip the discriminated union.
func AssistantText ¶
AssistantText builds a Message item carrying the assistant's prior reply. Used when you're rehydrating a conversation manually rather than passing previous_response_id.
func DeveloperMessage ¶
DeveloperMessage builds a developer-role Message. The spec treats these as guidance similar to system messages but distinct in provenance.
func SystemMessage ¶
SystemMessage builds a system-role Message.
func UserMessage ¶
UserMessage builds a user-role Message with arbitrary content parts — use this when you need images, files, or multi-part text in a single turn.
func (Message) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (*Message) UnmarshalJSON ¶
UnmarshalJSON decodes a Message, with one piece of spec-mandated nuance: `content` may be either an array of content parts OR a bare string. The correct concrete type for the string form depends on the message's role:
user / system / developer → InputText assistant → OutputText
(Source: UserMessageItemParam / AssistantMessageItemParam / SystemMessageItemParam / DeveloperMessageItemParam in the spec.)
Sending input_text inside an assistant message is what causes providers to reject the request with "Invalid value: 'input_text'. Supported values are: 'output_text' and 'refusal'." — so this branching is load-bearing.
type MessagePhase ¶
type MessagePhase string
MessagePhase distinguishes intermediate assistant commentary from the final answer. The spec notes that for models that emit phased outputs, the phase must be preserved on follow-up requests or quality will degrade.
const ( PhaseCommentary MessagePhase = "commentary" PhaseFinalAnswer MessagePhase = "final_answer" )
MessagePhase values defined by the spec.
type MessageRole ¶
type MessageRole string
MessageRole identifies who produced a Message item.
const ( RoleUser MessageRole = "user" RoleAssistant MessageRole = "assistant" RoleSystem MessageRole = "system" RoleDeveloper MessageRole = "developer" )
MessageRole values defined by the spec.
type Middleware ¶
type Middleware func(next http.RoundTripper) http.RoundTripper
Middleware wraps a RoundTripper, producing a new RoundTripper that may inspect or mutate requests and responses.
type OutputItemAddedEvent ¶
type OutputItemAddedEvent struct {
BaseEvent
OutputIndex int `json:"output_index"`
Item Item `json:"item"`
}
OutputItemAddedEvent fires once for each new item the model emits, before the item's content begins streaming.
func (*OutputItemAddedEvent) UnmarshalJSON ¶
func (e *OutputItemAddedEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, dispatching the embedded Item via UnmarshalItem.
type OutputItemDoneEvent ¶
type OutputItemDoneEvent struct {
BaseEvent
OutputIndex int `json:"output_index"`
Item Item `json:"item"`
}
OutputItemDoneEvent fires once per item, after all of its content has streamed. The carried Item is the final state.
func (*OutputItemDoneEvent) UnmarshalJSON ¶
func (e *OutputItemDoneEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, dispatching the embedded Item via UnmarshalItem.
type OutputText ¶
type OutputText struct {
Text string `json:"text"`
Annotations []Annotation `json:"annotations"`
Logprobs []LogProb `json:"logprobs,omitempty"`
}
OutputText is model-emitted text, possibly with citations and per-token log probabilities.
func (OutputText) ContentType ¶
func (OutputText) ContentType() string
ContentType implements Content.
func (OutputText) MarshalJSON ¶
func (c OutputText) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type OutputTextAnnotationAddedEvent ¶
type OutputTextAnnotationAddedEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
ContentIndex int `json:"content_index"`
AnnotationIndex int `json:"annotation_index"`
Annotation Annotation `json:"annotation"`
}
OutputTextAnnotationAddedEvent fires when an annotation (citation) is attached to a span of streaming output text.
func (*OutputTextAnnotationAddedEvent) UnmarshalJSON ¶
func (e *OutputTextAnnotationAddedEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, dispatching the embedded Annotation via unmarshalAnnotation.
type OutputTextDeltaEvent ¶
type OutputTextDeltaEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
ContentIndex int `json:"content_index"`
Delta string `json:"delta"`
Logprobs []LogProb `json:"logprobs,omitempty"`
Obfuscation string `json:"obfuscation,omitempty"`
}
OutputTextDeltaEvent is the workhorse: one fires for each chunk of model text. Concatenating Delta across these gives the running output text.
type OutputTextDoneEvent ¶
type OutputTextDoneEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
ContentIndex int `json:"content_index"`
Text string `json:"text"`
Logprobs []LogProb `json:"logprobs,omitempty"`
}
OutputTextDoneEvent fires when a text content part finishes streaming. Text is the full text of that content part (not the cumulative response).
type OutputTokensDetails ¶
type OutputTokensDetails struct {
ReasoningTokens int `json:"reasoning_tokens"`
}
OutputTokensDetails breaks the output token count down by category — notably, reasoning tokens which are billed but not part of the visible final message.
type Reasoning ¶
type Reasoning struct {
ID string `json:"id"`
Status ItemStatus `json:"status,omitempty"`
Content ContentList `json:"content,omitempty"`
Summary ContentList `json:"summary"`
EncryptedContent string `json:"encrypted_content,omitempty"`
}
Reasoning carries the model's chain-of-thought for one step.
Providers vary in what they expose: some emit only Summary (safe to show users), some emit EncryptedContent (opaque but rehydratable on follow-up requests via the include parameter), some emit raw Content. Per the spec all three are optional.
func (Reasoning) MarshalJSON ¶
MarshalJSON implements json.Marshaler. Summary is required by the spec; MarshalJSON substitutes an empty list when the caller left it nil.
type ReasoningDeltaEvent ¶
type ReasoningDeltaEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
ContentIndex int `json:"content_index"`
Delta string `json:"delta"`
Obfuscation string `json:"obfuscation,omitempty"`
}
ReasoningDeltaEvent streams raw reasoning text for a Reasoning item. Most providers do not emit these for safety reasons; many will emit only the summary variants below.
type ReasoningDoneEvent ¶
type ReasoningDoneEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
ContentIndex int `json:"content_index"`
Text string `json:"text"`
}
ReasoningDoneEvent fires when a reasoning content part finishes.
type ReasoningEffort ¶
type ReasoningEffort string
ReasoningEffort hints at how much compute the model should spend on internal reasoning before answering. Not every model honors every level.
const ( // ReasoningEffortNone disables reasoning where the model supports doing so. ReasoningEffortNone ReasoningEffort = "none" // ReasoningEffortMinimal is OpenAI's lowest gpt-5 reasoning tier — less // than Low but more than None. Forwarded through OpenRouter unchanged. ReasoningEffortMinimal ReasoningEffort = "minimal" ReasoningEffortLow ReasoningEffort = "low" ReasoningEffortMedium ReasoningEffort = "medium" ReasoningEffortHigh ReasoningEffort = "high" // ReasoningEffortXHigh is a non-standard extension used by some // providers for "extra-high" reasoning budgets. ReasoningEffortXHigh ReasoningEffort = "xhigh" )
ReasoningEffort values. Standard tiers are Low/Medium/High; None disables reasoning where supported, Minimal is OpenAI's gpt-5 sub-Low tier, and XHigh is a non-standard provider extension.
type ReasoningParam ¶
type ReasoningParam struct {
Effort ReasoningEffort `json:"effort,omitempty"`
Summary ReasoningSummary `json:"summary,omitempty"`
}
ReasoningParam configures whether and how the model performs internal reasoning. Set Effort to opt into reasoning at a given level; set Summary to request a user-safe summary of that reasoning.
type ReasoningSummary ¶
type ReasoningSummary string
ReasoningSummary controls whether the model emits a user-safe summary alongside its (otherwise opaque or encrypted) reasoning.
const ( ReasoningSummaryConcise ReasoningSummary = "concise" ReasoningSummaryDetailed ReasoningSummary = "detailed" ReasoningSummaryAuto ReasoningSummary = "auto" )
ReasoningSummary values defined by the spec.
type ReasoningSummaryDeltaEvent ¶
type ReasoningSummaryDeltaEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
SummaryIndex int `json:"summary_index"`
Delta string `json:"delta"`
Obfuscation string `json:"obfuscation,omitempty"`
}
ReasoningSummaryDeltaEvent streams the user-safe summary of reasoning.
type ReasoningSummaryDoneEvent ¶
type ReasoningSummaryDoneEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
SummaryIndex int `json:"summary_index"`
Text string `json:"text"`
}
ReasoningSummaryDoneEvent fires when a reasoning summary text completes.
type ReasoningSummaryPartAddedEvent ¶
type ReasoningSummaryPartAddedEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
SummaryIndex int `json:"summary_index"`
Part Content `json:"part"`
}
ReasoningSummaryPartAddedEvent fires before deltas for a new summary part.
func (*ReasoningSummaryPartAddedEvent) UnmarshalJSON ¶
func (e *ReasoningSummaryPartAddedEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, dispatching the embedded Content part via unmarshalContent.
type ReasoningSummaryPartDoneEvent ¶
type ReasoningSummaryPartDoneEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
SummaryIndex int `json:"summary_index"`
Part Content `json:"part"`
}
ReasoningSummaryPartDoneEvent fires after deltas for a summary part finish.
func (*ReasoningSummaryPartDoneEvent) UnmarshalJSON ¶
func (e *ReasoningSummaryPartDoneEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, dispatching the embedded Content part via unmarshalContent.
type ReasoningTextPart ¶
type ReasoningTextPart struct {
Text string `json:"text"`
}
ReasoningTextPart is the raw, model-readable reasoning trace. Many providers omit this in favor of summary_text + encrypted_content.
func (ReasoningTextPart) ContentType ¶
func (ReasoningTextPart) ContentType() string
ContentType implements Content.
func (ReasoningTextPart) MarshalJSON ¶
func (c ReasoningTextPart) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type Refusal ¶
type Refusal struct {
Refusal string `json:"refusal"`
}
Refusal is the model's explicit refusal to produce content for a request.
func (Refusal) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
type RefusalDeltaEvent ¶
type RefusalDeltaEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
ContentIndex int `json:"content_index"`
Delta string `json:"delta"`
}
RefusalDeltaEvent streams the model's refusal text.
type RefusalDoneEvent ¶
type RefusalDoneEvent struct {
BaseEvent
ItemID string `json:"item_id"`
OutputIndex int `json:"output_index"`
ContentIndex int `json:"content_index"`
Refusal string `json:"refusal"`
}
RefusalDoneEvent fires when a refusal content part finishes.
type Request ¶
type Request struct {
Model string `json:"model,omitempty"`
Input Input `json:"input"`
PreviousResponseID string `json:"previous_response_id,omitempty"`
Include []Include `json:"include,omitempty"`
Tools Tools `json:"tools,omitempty"`
ToolChoice ToolChoice `json:"tool_choice,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Text *TextParam `json:"text,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
PresencePenalty *float64 `json:"presence_penalty,omitempty"`
FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"`
Stream *bool `json:"stream,omitempty"`
StreamOptions *StreamOptions `json:"stream_options,omitempty"`
Background *bool `json:"background,omitempty"`
MaxOutputTokens *int `json:"max_output_tokens,omitempty"`
MaxToolCalls *int `json:"max_tool_calls,omitempty"`
Reasoning *ReasoningParam `json:"reasoning,omitempty"`
SafetyIdentifier string `json:"safety_identifier,omitempty"`
PromptCacheKey string `json:"prompt_cache_key,omitempty"`
Truncation Truncation `json:"truncation,omitempty"`
Instructions string `json:"instructions,omitempty"`
Store *bool `json:"store,omitempty"`
ServiceTier ServiceTier `json:"service_tier,omitempty"`
TopLogprobs *int `json:"top_logprobs,omitempty"`
// Extra carries provider-specific request fields not defined by the
// Open Responses spec. Entries are flattened into the top-level JSON
// object on marshal, alongside the typed fields; non-standard top-
// level keys are captured here on unmarshal so server adapters can
// read them.
//
// Typed-field values always win — if Extra contains "model", the
// typed Model field overwrites it.
//
// Provider adapter packages ship typed helpers that build a properly-
// shaped map for you. For OpenRouter:
//
// req := openresponses.Request{
// Model: "openai/o4-mini",
// Input: openresponses.UserText("..."),
// Extra: openrouter.With(openrouter.WebSearch{MaxResults: 3}),
// }
Extra map[string]any `json:"-"`
}
Request is the body of POST /v1/responses.
Most fields are optional and use Go's zero value as "don't send". For fields where the server's default is sensitive (Stream, Store, Background) we use *bool so callers can explicitly send false vs. Omit. The Open Responses spec marks none of these required at the schema level, so omission is always legal.
The Input field is the workhorse: it's either a plain string (interpreted as a single user message) or a list of Items. Use UserText, UserMessage, or assemble an Items slice manually.
Streaming notes: do NOT set Stream yourself; use Client.CreateStream which flips the flag at the transport layer. Setting it manually on Create will cause the JSON response decoder to fail.
func (Request) MarshalJSON ¶
MarshalJSON flattens the ToolChoice wrapper and merges any Extra provider-specific fields into the top-level object.
func (*Request) UnmarshalJSON ¶
UnmarshalJSON decodes a Request, handles the tool_choice union (string | {"type":"function",...} | {"type":"allowed_tools",...}), and captures any non-standard top-level keys into Extra so server adapters can read provider-specific fields.
type Response ¶
type Response struct {
ID string `json:"id"`
Object string `json:"object"` // always "response"
CreatedAt int64 `json:"created_at"`
CompletedAt *int64 `json:"completed_at"`
Status ResponseStatus `json:"status"`
IncompleteDetails *IncompleteDetails `json:"incomplete_details"`
Model string `json:"model"`
PreviousResponseID *string `json:"previous_response_id"`
Instructions *string `json:"instructions"`
Output Items `json:"output"`
Error *Error `json:"error"`
Tools Tools `json:"tools"`
ToolChoice ToolChoice `json:"tool_choice"`
Truncation Truncation `json:"truncation"`
ParallelToolCalls bool `json:"parallel_tool_calls"`
Text TextConfig `json:"text"`
TopP float64 `json:"top_p"`
PresencePenalty float64 `json:"presence_penalty"`
FrequencyPenalty float64 `json:"frequency_penalty"`
TopLogprobs int `json:"top_logprobs"`
Temperature float64 `json:"temperature"`
Reasoning *ResponseReasoning `json:"reasoning"`
Usage *Usage `json:"usage"`
MaxOutputTokens *int `json:"max_output_tokens"`
MaxToolCalls *int `json:"max_tool_calls"`
Store bool `json:"store"`
Background bool `json:"background"`
ServiceTier ServiceTier `json:"service_tier"`
Metadata map[string]string `json:"metadata"`
SafetyIdentifier *string `json:"safety_identifier"`
PromptCacheKey *string `json:"prompt_cache_key"`
// Extra carries provider-specific response fields not defined by the
// spec. Captured from the wire on unmarshal; flattened back into the
// top-level JSON on marshal. Symmetrical with Request.Extra.
Extra map[string]any `json:"-"`
}
Response is the canonical response object returned by POST /v1/responses (when non-streaming) or carried inside the response.created / .in_progress / .completed / .failed / .incomplete streaming events.
Per spec, every field is required on the wire — providers echo the effective configuration so clients have a complete record of what produced the output. Pointer-typed fields (*int, *Error, *Usage, etc.) are nullable; non-pointer fields always have a value.
func (*Response) FinalMessage ¶
FinalMessage scans the response output for the last assistant Message and returns it, or nil if no assistant message is present. Convenience for the common "just give me the model's reply" case.
func (*Response) FinalText ¶
FinalText returns the concatenated output_text of the final assistant message, or the empty string if none is present. Convenience.
func (*Response) FunctionCalls ¶
func (r *Response) FunctionCalls() []FunctionCall
FunctionCalls returns all FunctionCall items in the response output, in emission order. Use this to drive a tool-calling loop:
for _, call := range resp.FunctionCalls() {
result := execute(call)
inputs = append(inputs, openresponses.FunctionCallOutput{
CallID: call.CallID,
Output: openresponses.TextOutput(result),
})
}
func (Response) MarshalJSON ¶
MarshalJSON flattens the tool_choice wrapper and merges Extra into the top-level object.
func (*Response) UnmarshalJSON ¶
UnmarshalJSON decodes a Response, handling the tool_choice union and capturing provider-specific top-level keys into Extra.
type ResponseCompletedEvent ¶
ResponseCompletedEvent is the terminal success event. The Response carries the full final output.
type ResponseCreatedEvent ¶
ResponseCreatedEvent fires when the server has accepted the request and allocated a Response. Carries the initial Response snapshot.
type ResponseFailedEvent ¶
ResponseFailedEvent is the terminal error event. Response.Error contains the failure detail.
type ResponseInProgressEvent ¶
ResponseInProgressEvent fires when the model begins streaming output.
type ResponseIncompleteEvent ¶
ResponseIncompleteEvent is the terminal interrupted event — the model stopped before completing (e.g. token budget exhausted). Response.IncompleteDetails describes why.
type ResponseQueuedEvent ¶
ResponseQueuedEvent fires when a background response is queued for execution. Background flag must be true to receive this event.
type ResponseReasoning ¶
type ResponseReasoning struct {
Effort *ReasoningEffort `json:"effort"`
Summary *ReasoningSummary `json:"summary"`
}
ResponseReasoning echoes the reasoning configuration applied to a response — typically just whatever the request asked for. Distinct from the Reasoning *item* type, which carries actual reasoning content.
type ResponseStatus ¶
type ResponseStatus string
ResponseStatus is the lifecycle of a Response. Streaming events report transitions between these states (response.created → response.in_progress → response.completed | response.failed | response.incomplete).
const ( ResponseStatusInProgress ResponseStatus = "in_progress" ResponseStatusQueued ResponseStatus = "queued" ResponseStatusCompleted ResponseStatus = "completed" ResponseStatusFailed ResponseStatus = "failed" ResponseStatusIncomplete ResponseStatus = "incomplete" )
ResponseStatus values defined by the spec.
type RoundTripperFunc ¶
RoundTripperFunc adapts a function to the http.RoundTripper interface.
type ServiceTier ¶
type ServiceTier string
ServiceTier is a priority hint to the provider. Higher tiers get better scheduling and resource allocation at higher cost. Providers document which tiers they accept.
const ( ServiceTierAuto ServiceTier = "auto" ServiceTierDefault ServiceTier = "default" ServiceTierFlex ServiceTier = "flex" ServiceTierPriority ServiceTier = "priority" )
ServiceTier values defined by the spec.
type SpecError ¶
SpecError is a convenience error type that carries every field of the spec's error envelope. Most adapters will return this so the Handler can emit a proper {"error": {...}} body.
func InvalidRequest ¶
InvalidRequest builds a 400 SpecError. Use param to point at the offending field name in the request body.
func ModelError ¶
ModelError builds a 500 SpecError representing a failure inside the model or inference layer.
func ServerError ¶
ServerError builds a 500 SpecError representing an unexpected server fault.
func TooManyRequests ¶
TooManyRequests builds a 429 SpecError.
func (*SpecError) HTTPStatus ¶
HTTPStatus returns the configured HTTP status, defaulting to 500.
func (*SpecError) MarshalJSON ¶
MarshalJSON renders the spec error envelope:
{"error":{"type":"...","code":"...","message":"...","param":"..."}}
type SpecificToolChoice ¶
type SpecificToolChoice struct {
// Type is the JSON `type` discriminator. Defaults to "function" if empty.
Type string
// Name is the function name when Type == "function"; otherwise empty.
Name string
}
SpecificToolChoice forces the model to call a particular tool on its next step. For a function tool, set Name (Type defaults to "function"). For a hosted/provider tool, set Type to the wire discriminator (e.g. "openrouter:web_search") and leave Name empty.
openresponses.SpecificToolChoice{Name: "get_weather"} // function tool
openresponses.SpecificToolChoice{Type: "openrouter:web_search"} // hosted tool
func (SpecificToolChoice) MarshalJSON ¶
func (c SpecificToolChoice) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type StreamEvent ¶
StreamEvent is one event in an Open Responses Server-Sent Events stream.
The spec defines a closed set of standard events plus an open-ended extension space (provider events prefixed "slug:..."). Every standard event carries a SequenceNumber that lets clients detect drops and reorder if they buffer.
Standard variants:
Response lifecycle: ResponseCreatedEvent, ResponseInProgressEvent,
ResponseQueuedEvent, ResponseCompletedEvent,
ResponseFailedEvent, ResponseIncompleteEvent
Item lifecycle: OutputItemAddedEvent, OutputItemDoneEvent
Content lifecycle: ContentPartAddedEvent, ContentPartDoneEvent
Text deltas: OutputTextDeltaEvent, OutputTextDoneEvent
Refusal deltas: RefusalDeltaEvent, RefusalDoneEvent
Reasoning deltas: ReasoningDeltaEvent, ReasoningDoneEvent,
ReasoningSummaryDeltaEvent, ReasoningSummaryDoneEvent,
ReasoningSummaryPartAddedEvent, ReasoningSummaryPartDoneEvent
Annotations: OutputTextAnnotationAddedEvent
Function args: FunctionCallArgumentsDeltaEvent, FunctionCallArgumentsDoneEvent
Errors: ErrorEvent
Anything else is exposed as UnknownEvent so callers can still observe and log it. Switch on the concrete type to handle events:
switch e := ev.(type) {
case *openresponses.OutputTextDeltaEvent:
fmt.Print(e.Delta)
case *openresponses.ResponseCompletedEvent:
finalResp = e.Response
}
func DecodeEvent ¶
func DecodeEvent(data []byte) (StreamEvent, error)
DecodeEvent parses one stream event from its JSON object representation. Exposed for testing and for server-side code that wants to round-trip events.
type StreamOptions ¶
type StreamOptions struct {
// IncludeObfuscation controls whether the server emits the `obfuscation`
// field on text/reasoning delta events (designed to prevent prompt
// reconstruction via token-length side channels). Default true; set to
// pointer-false to disable.
IncludeObfuscation *bool `json:"include_obfuscation,omitempty"`
}
StreamOptions controls streaming-specific behavior.
type SummaryText ¶
type SummaryText struct {
Text string `json:"text"`
}
SummaryText is the user-safe surface of model reasoning. Providers that keep the raw reasoning trace opaque will return this so clients can show users *something* about the model's thinking.
func (SummaryText) ContentType ¶
func (SummaryText) ContentType() string
ContentType implements Content.
func (SummaryText) MarshalJSON ¶
func (c SummaryText) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type TextConfig ¶
type TextConfig struct {
Format TextFormat `json:"format"`
Verbosity Verbosity `json:"verbosity,omitempty"`
}
TextConfig echoes the response's text formatting: the format the model was asked to use and the verbosity setting applied.
func (*TextConfig) UnmarshalJSON ¶
func (t *TextConfig) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, dispatching the embedded Format value via unmarshalTextFormat.
type TextFormat ¶
type TextFormat interface {
// contains filtered or unexported methods
}
TextFormat is the discriminated union for response text formatting. Variants: TextFormatText (plain), TextFormatJSONObject, TextFormatJSONSchema.
type TextFormatJSONObject ¶
type TextFormatJSONObject struct{}
TextFormatJSONObject requires the model to emit valid JSON. Schema-less.
func (TextFormatJSONObject) MarshalJSON ¶
func (TextFormatJSONObject) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type TextFormatJSONSchema ¶
type TextFormatJSONSchema struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Schema json.RawMessage `json:"schema"`
Strict *bool `json:"strict,omitempty"`
}
TextFormatJSONSchema requires the model's output to validate against the given JSON Schema.
func JSONSchemaFormat ¶
func JSONSchemaFormat(name string, schema any) (TextFormatJSONSchema, error)
JSONSchemaFormat builds a TextFormatJSONSchema, coercing the schema into raw JSON from any Go value (map, struct, json.RawMessage, string).
func (TextFormatJSONSchema) MarshalJSON ¶
func (f TextFormatJSONSchema) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type TextFormatText ¶
type TextFormatText struct{}
TextFormatText is unstructured plain text — the default for chat-like use.
func (TextFormatText) MarshalJSON ¶
func (TextFormatText) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type TextParam ¶
type TextParam struct {
Format TextFormat `json:"format,omitempty"`
Verbosity Verbosity `json:"verbosity,omitempty"`
}
TextParam configures the request-side text output. Mirror of TextConfig on the response side — the difference is that TextConfig.Format is required on the response while TextParam.Format may be omitted (provider default).
func (TextParam) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
func (*TextParam) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler, dispatching the embedded Format value via unmarshalTextFormat.
type TextPart ¶
type TextPart struct {
Text string `json:"text"`
}
TextPart is the bare "text" content type — distinct from input_text / output_text, used inside some reasoning/summary bodies.
func (TextPart) MarshalJSON ¶
MarshalJSON implements json.Marshaler.
type Tool ¶
type Tool interface {
// ToolType returns the JSON `type` discriminator (e.g. "function",
// "openrouter:web_search").
ToolType() string
}
Tool is a capability the model may invoke during generation. The standard Open Responses tool catalog is just `function`; provider-hosted tools (web search, code interpreter, file search, …) either round-trip via UnknownTool or — when the adapter registers them — decode as their typed Go value.
Implementations supply the JSON `type` discriminator via ToolType and a MarshalJSON that emits it. Provider adapter packages can ship custom Tool types and register them via RegisterToolType.
type ToolChoice ¶
type ToolChoice interface {
// contains filtered or unexported methods
}
ToolChoice constrains which tool the model may (or must) call. Use one of:
- ToolChoiceValue ("none" | "auto" | "required")
- SpecificToolChoice (force a specific function by name)
- AllowedToolsChoice (restrict to a subset without rewriting the tool list)
A nil ToolChoice means the server's default applies (effectively "auto").
type ToolChoiceValue ¶
type ToolChoiceValue string
ToolChoiceValue is the simple, string-valued form of tool_choice. For "force this specific function" semantics, build a SpecificToolChoice or AllowedToolsChoice instead.
const ( ToolChoiceNone ToolChoiceValue = "none" ToolChoiceAuto ToolChoiceValue = "auto" ToolChoiceRequired ToolChoiceValue = "required" )
ToolChoiceValue values defined by the spec.
type Tools ¶
type Tools []Tool
Tools is a slice of Tool with discriminated-union JSON.
func (Tools) MarshalJSON ¶
MarshalJSON implements json.Marshaler. Nil encodes as "[]".
The spec requires "tools" on the Response to be a JSON array (no anyOf-null), so nil encodes as []. On a Request the field's omitempty skips nil/empty slices before MarshalJSON runs, so this default is safe there too.
func (*Tools) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler. Accepts "null" as empty.
type TopLogProb ¶
type TopLogProb struct {
Token string `json:"token"`
Logprob float64 `json:"logprob"`
Bytes []int `json:"bytes"`
}
TopLogProb is one alternative token the model considered at a given position.
type Truncation ¶
type Truncation string
Truncation controls how the service handles context that exceeds the model's window. "auto" lets the service drop earlier context; "disabled" forces the request to fail (HTTP 400) rather than silently truncate.
const ( TruncationAuto Truncation = "auto" TruncationDisabled Truncation = "disabled" )
Truncation values defined by the spec.
type URLCitation ¶
type URLCitation struct {
URL string `json:"url"`
Title string `json:"title"`
StartIndex int `json:"start_index"`
EndIndex int `json:"end_index"`
}
URLCitation marks a span of output text [StartIndex, EndIndex) as supported by an external URL.
func (URLCitation) AnnotationType ¶
func (URLCitation) AnnotationType() string
AnnotationType implements Annotation.
func (URLCitation) MarshalJSON ¶
func (c URLCitation) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type UnknownAnnotation ¶
type UnknownAnnotation struct {
Type string `json:"type"`
Raw json.RawMessage `json:"-"`
}
UnknownAnnotation captures any annotation whose `type` field isn't recognized. The Open Responses spec explicitly permits implementer-prefixed extensions (e.g. "acme:trace"); callers that care can inspect Raw.
func (UnknownAnnotation) AnnotationType ¶
func (u UnknownAnnotation) AnnotationType() string
AnnotationType implements Annotation.
func (UnknownAnnotation) MarshalJSON ¶
func (u UnknownAnnotation) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type UnknownContent ¶
type UnknownContent struct {
Type string `json:"type"`
Raw json.RawMessage `json:"-"`
}
UnknownContent preserves any content type the package doesn't recognize. The spec explicitly allows implementer-prefixed extensions (e.g. "acme:tool_result"); callers can switch on the Type and read Raw.
func (UnknownContent) ContentType ¶
func (u UnknownContent) ContentType() string
ContentType implements Content. It returns the wire-encoded discriminator preserved from the original payload.
func (UnknownContent) MarshalJSON ¶
func (u UnknownContent) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. When the original wire bytes are preserved in Raw, MarshalJSON returns them verbatim so round-tripping is lossless.
type UnknownEvent ¶
type UnknownEvent struct {
BaseEvent
Raw json.RawMessage `json:"-"`
}
UnknownEvent is returned for any `type` value the package doesn't recognize. Providers are explicitly allowed to emit prefixed extension events (e.g. "openai:web_search.search.completed"); UnknownEvent.Raw preserves the full payload so proxy adapters that do `sink.Send(stream.Event())` re-emit the original bytes verbatim instead of dropping the provider-specific fields.
func (UnknownEvent) MarshalJSON ¶
func (u UnknownEvent) MarshalJSON() ([]byte, error)
MarshalJSON preserves the original payload when one is set, falling back to the BaseEvent header (type + sequence_number) only when the event was built programmatically rather than decoded from the wire.
type UnknownItem ¶
type UnknownItem struct {
Type string `json:"type"`
ID string `json:"id,omitempty"`
Raw json.RawMessage `json:"-"`
}
UnknownItem is the catch-all for provider-extension items (e.g. "openai:web_search_call"). The full original JSON is preserved in Raw.
func (UnknownItem) ItemType ¶
func (u UnknownItem) ItemType() string
ItemType implements Item. It returns the wire-encoded discriminator preserved from the original payload.
func (UnknownItem) MarshalJSON ¶
func (u UnknownItem) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. When the original wire bytes are preserved in Raw, MarshalJSON returns them verbatim so round-tripping is lossless.
type UnknownTool ¶
type UnknownTool struct {
Type string `json:"type"`
Raw json.RawMessage `json:"-"`
}
UnknownTool preserves a tool entry whose `type` discriminator isn't one of the standard values. Providers may emit hosted tools here (e.g. "openai:web_search", "openai:file_search"); inspecting Raw and switching on Type lets callers handle them without losing data on round-trips.
func (UnknownTool) MarshalJSON ¶
func (u UnknownTool) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. When the original wire bytes are preserved in Raw, MarshalJSON returns them verbatim so round-tripping is lossless.
func (UnknownTool) ToolType ¶
func (u UnknownTool) ToolType() string
ToolType implements Tool. It returns the wire-encoded discriminator preserved from the original payload.
type UnsupportedCompaction ¶
type UnsupportedCompaction struct{}
UnsupportedCompaction can be embedded into an Adapter implementation to signal that compaction is not supported. The Handler returns 404 to compact clients (matching the spec's "endpoint not implemented" path).
func (UnsupportedCompaction) Compact ¶
func (UnsupportedCompaction) Compact(_ context.Context, _ CompactRequest) (*CompactResponse, error)
Compact returns an unsupported error. The first return value is always nil; the second carries the spec-shaped failure.
type UnsupportedStreaming ¶
type UnsupportedStreaming struct{}
UnsupportedStreaming can be embedded into an Adapter implementation to signal that streaming is not supported. The Handler will return 501 to streaming clients.
func (UnsupportedStreaming) CreateStream ¶
CreateStream returns an unsupported error.
type Usage ¶
type Usage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
TotalTokens int `json:"total_tokens"`
InputTokensDetails InputTokensDetails `json:"input_tokens_details"`
OutputTokensDetails OutputTokensDetails `json:"output_tokens_details"`
}
Usage is the token-accounting record attached to every Response.
type Verbosity ¶
type Verbosity string
Verbosity asks the model to be more or less wordy in its final answer.
type WebSocketErrorEvent ¶
type WebSocketErrorEvent struct {
Type string `json:"type"`
Status int `json:"status"`
Error ErrorPayload `json:"error"`
}
WebSocketErrorEvent is the WS-specific error envelope. Servers send it for connection-level failures (bad message, connection-limit reached, previous_response_not_found, …). The HTTP-status-style `Status` field lets clients reuse their HTTP error-handling logic.
func (WebSocketErrorEvent) EventType ¶
func (e WebSocketErrorEvent) EventType() string
EventType implements StreamEvent for routing convenience.
func (WebSocketErrorEvent) Sequence ¶
func (e WebSocketErrorEvent) Sequence() int64
Sequence implements StreamEvent. WS error events don't carry sequence numbers per spec — return 0.
type WebSocketResponseCreateEvent ¶
type WebSocketResponseCreateEvent struct {
// Request fields are embedded so client code can construct the event
// from a normal Request:
//
// ev := WebSocketResponseCreateEvent{Type: "response.create", Request: req}
Request
Type string `json:"type"`
}
WebSocketResponseCreateEvent is the client-sent message that starts a Responses turn over WebSocket. It carries the same body as a regular `POST /v1/responses` request, plus the required `type: "response.create"` discriminator.
Per spec, clients MUST NOT include `stream`, `stream_options`, or `background` — those are HTTP-streaming controls that don't apply to WS (every WS turn streams; nothing runs in the background).
func (WebSocketResponseCreateEvent) MarshalJSON ¶
func (e WebSocketResponseCreateEvent) MarshalJSON() ([]byte, error)
MarshalJSON ensures `type` is always emitted and that the embedded Request fields flatten onto the same object.
func (*WebSocketResponseCreateEvent) UnmarshalJSON ¶
func (e *WebSocketResponseCreateEvent) UnmarshalJSON(data []byte) error
UnmarshalJSON pulls `type` out and decodes the rest as a Request. The WS envelope's `type` field is consumed by this event — it MUST NOT leak into the inner Request.Extra (otherwise it would be re-marshaled and forwarded to upstream providers as a spurious request field).
type WebSocketStream ¶
type WebSocketStream struct {
// contains filtered or unexported fields
}
WebSocketStream is the client-side counterpart of EventStream for connections opened with Client.Dial. It owns a websocket.Conn and lets the caller send response.create events and iterate the resulting StreamEvents using the same Next/Event/Err pattern as EventStream.
Concurrent Send and Next are safe; the connection serializes writes internally. Always Close().
func (*WebSocketStream) Close ¶
func (s *WebSocketStream) Close() error
Close shuts down the WebSocket cleanly.
func (*WebSocketStream) Err ¶
func (s *WebSocketStream) Err() error
Err returns the first non-EOF error encountered.
func (*WebSocketStream) Event ¶
func (s *WebSocketStream) Event() StreamEvent
Event returns the most recent successfully-decoded event.
func (*WebSocketStream) Events ¶
func (s *WebSocketStream) Events() iter.Seq[StreamEvent]
Events returns a Go 1.23+ range-over-func iterator over events on the connection. The iterator yields events for as many turns as the caller drives via Send; iteration stops at clean close or on error. Inspect Err after the loop returns.
for ev := range stream.Events() {
if e, ok := ev.(*openresponses.OutputTextDeltaEvent); ok {
fmt.Print(e.Delta)
}
}
func (*WebSocketStream) Next ¶
func (s *WebSocketStream) Next() bool
Next reads the next event from the connection. Returns true on a successfully-decoded event, false at clean close or on error. Inspect Event() after a true return; inspect Err() after false.
func (*WebSocketStream) Send ¶
func (s *WebSocketStream) Send(req Request) error
Send writes a response.create event with the given Request. Returns the network write error, if any. The server will reply with streaming events readable via Next/Event until the response reaches a terminal state (completed/failed/incomplete).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package codex is a provider adapter for openresponses.Client that talks to OpenAI's Codex Responses backend at https://chatgpt.com/backend-api/codex, using ChatGPT subscription credentials issued via OAuth (the same flow the official `codex` CLI uses).
|
Package codex is a provider adapter for openresponses.Client that talks to OpenAI's Codex Responses backend at https://chatgpt.com/backend-api/codex, using ChatGPT subscription credentials issued via OAuth (the same flow the official `codex` CLI uses). |
|
examples
|
|
|
basic
command
Basic: a one-shot, non-streaming request.
|
Basic: a one-shot, non-streaming request. |
|
codex
command
Codex: use the openresponses library against OpenAI Codex, authenticated via the user's ChatGPT subscription.
|
Codex: use the openresponses library against OpenAI Codex, authenticated via the user's ChatGPT subscription. |
|
codex-login
command
Codex login: run the OAuth flow against auth.openai.com and write the resulting credentials to ~/.codex/auth.json — the same file the official `codex` CLI reads.
|
Codex login: run the OAuth flow against auth.openai.com and write the resulting credentials to ~/.codex/auth.json — the same file the official `codex` CLI reads. |
|
openrouter
command
OpenRouter: connect to OpenRouter with app-attribution headers.
|
OpenRouter: connect to OpenRouter with app-attribution headers. |
|
openrouter-tools
command
OpenRouter-tools: tool-calling against OpenRouter's stateless Responses API.
|
OpenRouter-tools: tool-calling against OpenRouter's stateless Responses API. |
|
reasoning
command
Reasoning: ask for a reasoning summary, then stream it.
|
Reasoning: ask for a reasoning summary, then stream it. |
|
server
command
A pass-through Open Responses server.
|
A pass-through Open Responses server. |
|
streaming
command
Streaming: print tokens as the model emits them.
|
Streaming: print tokens as the model emits them. |
|
tools
command
Tools: run a single round-trip agentic loop with a function tool.
|
Tools: run a single round-trip agentic loop with a function tool. |
|
Package openrouter is a provider adapter for openresponses.Client that connects to OpenRouter (https://openrouter.ai/api/v1/responses).
|
Package openrouter is a provider adapter for openresponses.Client that connects to OpenRouter (https://openrouter.ai/api/v1/responses). |