rig_core/providers/openai/responses_api/
wire.rs1use 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24pub struct Responses {
25 pub provider: OpenAIConfig,
27 pub model: String,
29 pub tools: Vec<ResponsesToolDefinition>,
31 pub strict_tools: bool,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub store: Option<bool>,
37 pub system_instructions: SystemInstructionsPlacement,
40 #[serde(skip)]
42 pub facts: ModelFacts,
43}
44
45impl Responses {
46 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 pub fn with_facts(mut self, facts: ModelFacts) -> Self {
63 self.facts = facts;
64 self
65 }
66
67 pub fn with_strict_tools(mut self) -> Self {
69 self.strict_tools = true;
70 self
71 }
72
73 pub fn with_store(mut self, store: bool) -> Self {
78 self.store = Some(store);
79 self
80 }
81
82 pub fn with_tool(mut self, tool: impl Into<ResponsesToolDefinition>) -> Self {
84 self.tools.push(tool.into());
85 self
86 }
87
88 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 pub fn with_system_instructions_placement(
101 mut self,
102 placement: SystemInstructionsPlacement,
103 ) -> Self {
104 self.system_instructions = placement;
105 self
106 }
107
108 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 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 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 fn catalog_priced(&self) -> bool {
190 self.provider.dialect.quirks.catalog_priced
191 }
192
193 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 fn declares_tools(&self, request: &completion::CompletionRequest) -> bool {
220 !self.tools.is_empty() || crate::completion::history::declares_tools(request)
221 }
222
223 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 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 fn needs_next(&self, item: &Value) -> bool {
249 item.str("type") == Some("reasoning")
250 }
251
252 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 foreign_reasoning: false,
274 }
275 }
276
277 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 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 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 "" => short_hash(id),
326 trimmed => trimmed.to_owned(),
327 }
328 }
329}
330
331fn 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;