responses

package
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package responses / service.go contains the service layer for OpenAI responses API.

Index

Constants

View Source
const (
	// Text format types
	TextFormatTypeText       = "text"
	TextFormatTypeJSONObject = "json_object"
	TextFormatTypeJSONSchema = "json_schema"

	// Service tiers
	ServiceTierAuto     = "auto"     // service tier configured in the Project settings
	ServiceTierDefault  = "default"  // standard pricing and performance for the selected model
	ServiceTierFlex     = "flex"     // slower but cheaper
	ServiceTierPriority = "priority" // faster but more expensive
)

Variables

This section is empty.

Functions

func ForceFunction

func ForceFunction(name string) json.RawMessage

ForceFunction is a convenience function to force the use of a specific function tool. This is a backward-compatible wrapper around ForceToolChoice.

func ForceToolChoice

func ForceToolChoice(toolType string, name string) json.RawMessage

ForceToolChoice generates parameter value for ResponseRequest.ToolChoice field that forces the use of one specified tool.

Types

type Content

Content is an interface listing all types that can be used as content in Responses API. These types may appear in `Request.Input`, `Response.Outputs`, and `output.Message.Content` fields.

type Prompt added in v1.0.1

type Prompt struct {
	ID        string                     `json:"id"`
	Variables map[string]json.RawMessage `json:"variables"`
	Version   *string                    `json:"version"`
}

Prompt is a reference to a prompt template and its variables.

type ReasoningConfig

type ReasoningConfig struct {
	Effort          string `json:"effort,omitempty"`           // "minimal", "low", "medium", or "high"
	GenerateSummary string `json:"generate_summary,omitempty"` // "concise" or "detailed"
}

ReasoningConfig represents configuration options for reasoning models.

type Request

type Request struct {
	// Required
	Model string `json:"model"`
	Input any    `json:"input"` // string or []Any

	// Optional
	Include            []string          `json:"include,omitempty"`              // Additional data to include in response: "file_search_call.results", "message.input_image.image_url", "computer_call_output.output.image_url"
	Instructions       string            `json:"instructions,omitempty"`         // System message for context
	MaxOutputTokens    int               `json:"max_output_tokens,omitempty"`    // Max tokens to generate
	Metadata           map[string]string `json:"metadata,omitempty"`             // Key-value pairs
	ParallelToolCalls  *bool             `json:"parallel_tool_calls,omitempty"`  // Allow parallel tool calls, default true
	PreviousResponseID string            `json:"previous_response_id,omitempty"` // ID of previous response
	Prompt             *Prompt           `json:"prompt,omitempty"`               // Reference to a prompt template and its variables
	PromptCacheKey     string            `json:"prompt_cache_key,omitempty"`     // Used for matching similar requests with cached input
	Reasoning          *ReasoningConfig  `json:"reasoning,omitempty"`            // Reasoning configuration
	SafetyIdentifier   string            `json:"safety_identifier,omitempty"`    // Stable unique identifier for end user, preferably anonymized
	ServiceTier        string            `json:"service_tier,omitempty"`         // Service tier to use, default "auto"
	Store              *bool             `json:"store,omitempty"`                // Whether to store the response, default true
	Stream             bool              `json:"stream,omitempty"`               // Stream the response, default false
	StreamOptions      *StreamOptions    `json:"stream_options,omitempty"`       // Streaming configuration
	Temperature        float64           `json:"temperature,omitempty"`          // default 1
	Text               *TextOptions      `json:"text,omitempty"`                 // Text format configuration
	ToolChoice         json.RawMessage   `json:"tool_choice,omitempty"`          // default "auto", can be "none", "required", or an object
	TopP               float64           `json:"top_p,omitempty"`                // default 1
	Truncation         string            `json:"truncation,omitempty"`           // "auto" or "disabled"
	User               string            `json:"user,omitempty"`                 // Deprecated: use SafetyIdentifier and PromptCacheKey instead
	Background         bool              `json:"background,omitempty"`           // if true, the API returns immediately with only a response ID

	// names of tools/functions to include, will be marshaled as their full structs from tools registry
	Tools []string `json:"-"`

	// Custom (not part of the API)
	// If set, tool calls will be returned instead of executed.
	ReturnToolCalls bool `json:"-"` // default false
	// If set, will be called on messages received alongside other outputs (e.g., tool calls)
	// that would otherwise be returned in the response but can be handled sooner with this handler.
	IntermediateMessageHandler func(output.Message) `json:"-"`
}

Request is the request body for the Responses API.

func (*Request) Clone

func (data *Request) Clone() *Request

Clone creates a copy of the ResponseRequest with all fields copied.

type Response

type Response struct {
	ID            string
	Outputs       []output.Any
	ParsedOutputs []any
}

Response is a wrapper for outputs returned from the Responses API.

func (*Response) CustomToolCalls added in v1.0.1

func (r *Response) CustomToolCalls() []output.CustomToolCall

CustomToolCalls returns a slice of CustomToolCall objects from the response.

func (*Response) FirstText

func (r *Response) FirstText() string

FirstText returns the first text output in the response, or an empty string.

func (*Response) FunctionCalls

func (r *Response) FunctionCalls() []output.FunctionCall

FunctionCalls returns a slice of FunctionCall objects from the response.

func (*Response) JoinedReasoningSummaries

func (r *Response) JoinedReasoningSummaries() string

JoinedReasoningSummaries returns all reasoning summaries joined by newlines.

func (*Response) JoinedTexts

func (r *Response) JoinedTexts() string

JoinedTexts returns a single string joined from all text outputs in the response with newlines. Normally there's only one text output.

func (*Response) LastText

func (r *Response) LastText() string

LastText returns the last text output in the response, or an empty string.

func (*Response) MCPApprovalRequests

func (r *Response) MCPApprovalRequests() []output.MCPApprovalRequest

MCPApprovalRequests returns a slice of MCPApprovalRequest objects from the response.

func (*Response) Parse

func (r *Response) Parse() error

Parse parses the []output.Any and places the parsed objects in ParsedOutputs.

func (*Response) ReasoningSummaries

func (r *Response) ReasoningSummaries() []string

ReasoningSummaries returns a slice of summary texts from reasoning outputs.

func (*Response) Reasonings

func (r *Response) Reasonings() []output.Reasoning

Reasonings returns a slice of Reasoning objects from the response.

func (*Response) Refusals

func (r *Response) Refusals() []string

Refusals returns a slice of Refusal objects from the response.

func (*Response) Texts

func (r *Response) Texts() []string

Texts returns a slice of strings gathered from text output objects in the response. Parsing of the content is done automatically if not already done, and errors are ignored. To have errors checked, use Response.Parse() first.

type Service

type Service interface {
	// Send sends a request to the Responses API.
	Send(req *Request) (response *Response, err error)

	// Stream sends a request with parameter "stream":true and returns a streaming iterator.
	Stream(ctx context.Context, req *Request) (*streaming.StreamIterator, error)

	// NewMessage creates a new empty message.
	NewMessage() *output.Message

	// NewRequest creates a new empty request.
	NewRequest() *Request

	// Poll continuously fetches a background response until completion or failure.
	// ctx controls cancellation; interval is time to wait between subsequent polls.
	Poll(ctx context.Context, responseID string, interval time.Duration) (*Response, error)
}

Service is the service layer for OpenAI responses API.

type StreamOptions added in v1.0.1

type StreamOptions struct {
	// Stream obfuscation adds random characters to an obfuscation field on streaming delta events
	// to normalize payload sizes as a mitigation to certain side-channel attacks.
	// These obfuscation fields are included by default, but add a small amount of overhead
	// to the data stream.
	// You can set include_obfuscation to false to optimize for bandwidth if you trust the network
	// links between your application and the OpenAI API.
	IncludeObfuscation bool `json:"include_obfuscation,omitempty"`
}

StreamOptions is a set of options for streaming responses.

type TextFormatType

type TextFormatType struct {
	Type        string          `json:"type"`                  // "text", "json_object", or "json_schema"
	Schema      json.RawMessage `json:"schema,omitempty"`      // Schema for json_schema type
	Name        string          `json:"name,omitempty"`        // Name for json_schema type
	Description string          `json:"description,omitempty"` // Description for json_schema type
	Strict      bool            `json:"strict,omitempty"`      // Whether to enforce strict schema validation
}

TextFormatType represents the type of text format.

type TextOptions added in v1.0.1

type TextOptions struct {
	Format    TextFormatType `json:"format"`
	Verbosity string         `json:"verbosity,omitempty"` // "low", "medium", or "high", default "medium"
}

TextOptions represents the format configuration for text responses.

Directories

Path Synopsis
Package streaming provides a streaming iterator API for OpenAI Responses API.
Package streaming provides a streaming iterator API for OpenAI Responses API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL