Skip to main content

rig_core/providers/openai/responses_api/
wire.rs

1//! Responses endpoint encoding for configured OpenAI dialects.
2//!
3//! ```
4//! use rig_core::providers::openai::OpenAI;
5//! let wire = OpenAI::new("key").responses("gpt-5.2");
6//! ```
7
8use crate::catalog::ModelFacts;
9use crate::completion::{self, ProviderCapabilities};
10use crate::error::EncodeError;
11use crate::json_utils::Lenient;
12use crate::operation::Completion;
13use crate::providers::openai::wire::OpenAIConfig;
14pub(crate) use crate::providers::openai::wire::ResponsesContract;
15use crate::wire::{Capabilities, Descriptor, Encoded, Framing, Mode, Wire};
16use serde::{Deserialize, Serialize};
17use serde_json::{Map, Value};
18
19use super::streaming::ResponsesDecoder;
20use super::{ResponsesToolDefinition, SystemInstructionsPlacement};
21
22/// The Responses wire: `POST /responses`, SSE when streamed.
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24pub struct Responses {
25    /// The provider this wire speaks to.
26    pub provider: OpenAIConfig,
27    /// The model to address.
28    pub model: String,
29    /// Tools added to every request from this wire.
30    pub tools: Vec<ResponsesToolDefinition>,
31    /// Whether Rig-generated tools request OpenAI's strict validation.
32    pub strict_tools: bool,
33    /// The `store` every request from this wire sends unless the request
34    /// sets its own. `None` sends none, so the provider's default applies.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub store: Option<bool>,
37    /// Where this wire puts Rig's system instructions. Defaults to the
38    /// dialect's placement.
39    pub system_instructions: SystemInstructionsPlacement,
40    /// The model facts the encoder reads and replies are priced by.
41    #[serde(skip)]
42    pub facts: ModelFacts,
43}
44
45impl Responses {
46    /// Create a wire with the provider's instruction placement and dialect's
47    /// strict-tool default, without additional tools.
48    pub fn new(provider: OpenAIConfig, model: impl Into<String>) -> Self {
49        Self {
50            system_instructions: provider.system_instructions_placement(),
51            strict_tools: provider.dialect.quirks.responses.strict_tools_by_default,
52            provider,
53            model: model.into(),
54            tools: Vec::new(),
55            store: None,
56            facts: ModelFacts::default(),
57        }
58    }
59
60    /// The same wire, encoding with `facts` and pricing its replies by
61    /// them.
62    pub fn with_facts(mut self, facts: ModelFacts) -> Self {
63        self.facts = facts;
64        self
65    }
66
67    /// Sanitize function schemas for strict mode and send `strict: true`.
68    pub fn with_strict_tools(mut self) -> Self {
69        self.strict_tools = true;
70        self
71    }
72
73    /// Send `store` on every request from this wire. A request that sets
74    /// `store` in its provider options or `additional_params` sends its own.
75    /// With `false`, every request replays prior reasoning by its ciphertext
76    /// rather than by stored item id.
77    pub fn with_store(mut self, store: bool) -> Self {
78        self.store = Some(store);
79        self
80    }
81
82    /// Add a tool to every request from this wire.
83    pub fn with_tool(mut self, tool: impl Into<ResponsesToolDefinition>) -> Self {
84        self.tools.push(tool.into());
85        self
86    }
87
88    /// Add tools to every request from this wire.
89    pub fn with_tools<I, Tool>(mut self, tools: I) -> Self
90    where
91        I: IntoIterator<Item = Tool>,
92        Tool: Into<ResponsesToolDefinition>,
93    {
94        self.tools.extend(tools.into_iter().map(Into::into));
95        self
96    }
97
98    /// Put Rig's system instructions somewhere other than the dialect's
99    /// default placement.
100    pub fn with_system_instructions_placement(
101        mut self,
102        placement: SystemInstructionsPlacement,
103    ) -> Self {
104        self.system_instructions = placement;
105        self
106    }
107
108    /// Send Rig's system instructions as `system` messages in `input`, for a
109    /// backend that rejects or ignores top-level `instructions`.
110    pub fn with_system_instructions_as_messages(self) -> Self {
111        self.with_system_instructions_placement(SystemInstructionsPlacement::InputSystemMessages)
112    }
113}
114
115impl Wire for Responses {
116    type Op = Completion;
117    type Payload = crate::wire::Encoded;
118    type Frame = crate::wire::WireFrame;
119    type Event = super::streaming::ResponsesEvent;
120    type Decoder<'id> = ResponsesDecoder;
121    type Reassembler = super::streaming::document::Response;
122
123    /// The xAI contract does not compose native structured output with tools.
124    fn describe(&self) -> Descriptor<'_> {
125        Descriptor::new(self.provider.dialect.name)
126            .model(self.model.as_str())
127            .facts(&self.facts)
128            .capabilities(Capabilities::completion(
129                ProviderCapabilities::default().with_native_output_tool_composition(
130                    self.provider.dialect.quirks.responses.contract != ResponsesContract::Xai,
131                ),
132            ))
133            .replay(self)
134    }
135
136    fn encode(
137        &self,
138        request: completion::CompletionRequest,
139        mode: Mode,
140    ) -> Result<Encoded, EncodeError> {
141        let quirks = &self.provider.dialect.quirks.responses;
142        // The codex gateway only ever answers with an event stream, and
143        // names no content type on it. It is asked for one whatever the
144        // caller wanted: the reply is framed the same way either way, and
145        // the driver folds it.
146        let codex = quirks.contract == ResponsesContract::Codex;
147        let streaming = matches!(mode, Mode::Streaming) || codex;
148        let builder = self.provider.completion_headers(
149            &request,
150            http::Request::post(self.provider.uri(quirks.path, None)),
151        );
152        let mode = if streaming {
153            Mode::Streaming
154        } else {
155            Mode::Unary
156        };
157        let body = self.responses_request(&request, super::Delivery::Http(mode))?;
158        crate::providers::internal::trace_json(
159            crate::providers::internal::LogTarget::Completions,
160            "Responses completion request",
161            &body,
162        );
163        let request = builder
164            .header(http::header::CONTENT_TYPE, "application/json")
165            .body(body.into_body())?;
166
167        let framing = if streaming {
168            Framing::Sse
169        } else {
170            Framing::Whole
171        };
172        let encoded = Encoded::new(request, framing)
173            .with_request_id_header(self.provider.dialect.request_id_header);
174        Ok(if codex {
175            encoded.with_relaxed_content_type()
176        } else {
177            encoded
178        })
179    }
180
181    fn decoder<'id>(&self) -> Self::Decoder<'id> {
182        ResponsesDecoder::new()
183    }
184}
185
186impl crate::completion::ReplayTarget for Responses {
187    /// Whether the catalog prices this dialect's replies
188    /// ([`Quirks::catalog_priced`](crate::providers::openai::wire::Quirks::catalog_priced)).
189    fn catalog_priced(&self) -> bool {
190        self.provider.dialect.quirks.catalog_priced
191    }
192
193    /// Section 6.3 of the typed-options design, by dialect.
194    fn map_options(
195        &self,
196        request: &crate::completion::CompletionRequest,
197        fields: crate::completion::options::OptionFields<'_>,
198    ) -> crate::completion::options::OptionMap {
199        crate::providers::openai::options::responses_options(self, request, fields)
200    }
201
202    fn facts(&self) -> Option<&ModelFacts> {
203        Some(&self.facts)
204    }
205
206    fn api(&self) -> crate::message::Api {
207        crate::message::Api::from_static("openai.responses")
208    }
209
210    fn provider(&self) -> &str {
211        self.provider.dialect.name
212    }
213
214    fn model(&self) -> &str {
215        &self.model
216    }
217
218    /// The wire's own tools are declared beside the request's.
219    fn declares_tools(&self, request: &completion::CompletionRequest) -> bool {
220        !self.tools.is_empty() || crate::completion::history::declares_tools(request)
221    }
222
223    /// A call item names its id in `call_id`.
224    fn call_id_slot(&self) -> Option<&'static str> {
225        Some("/call_id")
226    }
227
228    fn blob_slots(&self) -> &'static [&'static str] {
229        &["/encrypted_content"]
230    }
231
232    /// An edited block keeps its item's `id` and `type`, a message its
233    /// `phase`, and reasoning its ciphertext, so the items after it stay
234    /// paired.
235    fn identity(&self, item: &Value) -> Map<String, Value> {
236        let keys: &[&str] = match item.str("type") {
237            Some("message") => &["type", "id", "phase"],
238            Some("reasoning") => &["type", "id", "encrypted_content"],
239            Some("function_call" | "custom_tool_call") => &["type", "id"],
240            _ => &[],
241        };
242        keys.iter()
243            .filter_map(|key| Some(((*key).to_owned(), item.get(*key)?.clone())))
244            .collect()
245    }
246
247    /// A reasoning item goes only with the item it preceded.
248    fn needs_next(&self, item: &Value) -> bool {
249        item.str("type") == Some("reasoning")
250    }
251
252    /// Responses reads images in user input and in function outputs, never
253    /// in assistant messages, and only on a model with vision input. Every
254    /// documented model calls tools except `o1-mini` and `o1-preview`, past
255    /// a `vendor/` prefix.
256    fn accepts(&self, model: &str) -> crate::completion::Accepts {
257        let images = reads_images(
258            &self.facts,
259            self.provider.dialect.quirks.responses.contract,
260            model,
261        );
262        let model = model
263            .rsplit('/')
264            .next()
265            .unwrap_or(model)
266            .to_ascii_lowercase();
267        crate::completion::Accepts {
268            user_images: images,
269            assistant_images: false,
270            tool_result_images: images,
271            tools: !(model.starts_with("o1-mini") || model.starts_with("o1-preview")),
272            // A reasoning item replays only as the provider made it.
273            foreign_reasoning: false,
274        }
275    }
276
277    /// Responses carries user and tool-result images as data URLs, URLs or
278    /// file ids, documents as files or text, and no audio, video or
279    /// assistant image. File ids need a dialect that resolves them, and
280    /// xAI's `input_image` takes none.
281    fn encodes(&self, _model: &str, media: crate::completion::Media<'_>) -> bool {
282        use crate::completion::{Media, Place};
283        use crate::message::{DocumentData, DocumentSourceKind as Source};
284        let quirks = &self.provider.dialect.quirks;
285        let file_ids = quirks.accepts_file_ids;
286        match media {
287            Media::Image(_, Place::Assistant) | Media::Audio(_) | Media::Video(_) => false,
288            Media::Image(image, _) => {
289                super::image_part(image).is_some()
290                    && (!matches!(image.data, Source::FileId(_))
291                        || file_ids && quirks.responses.contract != ResponsesContract::Xai)
292            }
293            Media::Document(document) => {
294                super::document_part(document).is_some()
295                    && (file_ids || !matches!(document.data, DocumentData::File(Source::FileId(_))))
296            }
297        }
298    }
299
300    /// A request naming `previous_response_id` or a `conversation`
301    /// continues state the provider stores, and one with caller-built
302    /// `input` items state the caller holds. Either holds the calls its
303    /// first results answer.
304    fn continues_stored(&self, request: &completion::CompletionRequest) -> bool {
305        ["previous_response_id", "conversation", "input"]
306            .iter()
307            .any(|key| {
308                crate::completion::options::param(self, request, key)
309                    .is_some_and(|value| !value.is_null())
310            })
311    }
312
313    /// Characters outside `[a-zA-Z0-9_-]` become `_`, and the id is cut to
314    /// 64 characters and loses its trailing `_`.
315    fn normalize_tool_call_id(
316        &self,
317        id: &str,
318        _model: &str,
319        _source: Option<&crate::message::Origin>,
320    ) -> String {
321        use crate::providers::internal::wire_ids::{legal_call_id, short_hash};
322        let legal = legal_call_id(id, 64);
323        match legal.trim_end_matches('_') {
324            // An id with nothing legal in it still names its call.
325            "" => short_hash(id),
326            trimmed => trimmed.to_owned(),
327        }
328    }
329}
330
331/// Whether `model` reads images, past a `vendor/` prefix: its catalog
332/// entry's input, or for a model the catalog does not list its vendor's
333/// documented text-only models. An unknown model reads them.
334fn reads_images(facts: &ModelFacts, contract: ResponsesContract, model: &str) -> bool {
335    let model = model.rsplit('/').next().unwrap_or_default();
336    match contract {
337        ResponsesContract::Xai => facts.reads_images_or(
338            crate::providers::xai::DIALECT.name,
339            model,
340            crate::providers::xai::reads_images,
341        ),
342        ResponsesContract::OpenAi | ResponsesContract::Codex => facts.reads_images_or(
343            crate::providers::openai::wire::OPENAI.name,
344            model,
345            crate::providers::openai::reads_images,
346        ),
347    }
348}
349
350#[cfg(test)]
351mod tests;