adk_model/openai/background.rs
1//! Background mode operations for long-running OpenAI Responses API requests.
2//!
3//! Provides polling and cancellation support for background responses submitted
4//! with `background: true`. Deep research models (`o3-deep-research`,
5//! `o4-mini-deep-research`) automatically enable background mode since they
6//! require asynchronous execution.
7//!
8//! A non-streaming background submission returns while the response is still
9//! `queued` or `in_progress`: the yielded `LlmResponse` carries `response_id` and
10//! `status` in `provider_metadata["openai"]` and no content. Pass the ID to
11//! [`OpenAIResponsesClient::poll_response`] until the status is terminal.
12
13use super::responses_client::{OpenAIResponsesClient, map_openai_error};
14use super::responses_convert;
15use adk_core::{AdkError, LlmResponse};
16use async_openai::types::responses::Status;
17
18impl OpenAIResponsesClient {
19 /// Poll a background response by ID.
20 ///
21 /// Calls `GET /v1/responses/{response_id}` and returns the current status
22 /// or completed result as an `LlmResponse`.
23 ///
24 /// # Status Handling
25 ///
26 /// - **Completed**: Returns a full `LlmResponse` with content, usage, and metadata.
27 /// - **In Progress / Queued**: Returns an `LlmResponse` with `provider_metadata`
28 /// containing `response_id` and `status`, but no content.
29 /// - **Failed**: Returns an `LlmResponse` with `error_code` and `error_message`
30 /// populated from the response error object.
31 ///
32 /// # Errors
33 ///
34 /// Returns `AdkError` if the HTTP request fails (network error, auth error, etc.).
35 ///
36 /// # Example
37 ///
38 /// ```rust,ignore
39 /// let response = client.poll_response("resp_abc123").await?;
40 /// if let Some(metadata) = &response.provider_metadata {
41 /// let status = metadata["openai"]["status"].as_str();
42 /// println!("Response status: {:?}", status);
43 /// }
44 /// ```
45 pub async fn poll_response(&self, response_id: &str) -> Result<LlmResponse, AdkError> {
46 let response = self
47 .openai_client()
48 .responses()
49 .retrieve(response_id)
50 .await
51 .map_err(map_openai_error)?;
52
53 match &response.status {
54 Status::Completed | Status::Incomplete => {
55 // Use existing conversion logic for completed/incomplete responses
56 let mut llm_response = responses_convert::from_response(&response);
57 // Ensure status is in provider_metadata
58 inject_status_metadata(&mut llm_response, response_id, &response.status);
59 Ok(llm_response)
60 }
61 Status::InProgress | Status::Queued => {
62 // Return a minimal response with status metadata
63 let status_str = status_to_str(&response.status);
64 let provider_metadata = serde_json::json!({
65 "openai": {
66 "response_id": response_id,
67 "status": status_str
68 }
69 });
70 Ok(LlmResponse {
71 provider_metadata: Some(provider_metadata),
72 partial: false,
73 turn_complete: false,
74 ..Default::default()
75 })
76 }
77 Status::Failed => {
78 // Extract error details from the response
79 let (error_code, error_message) = if let Some(err) = &response.error {
80 (Some(err.code.clone()), Some(err.message.clone()))
81 } else {
82 (Some("unknown".to_string()), Some("Background response failed".to_string()))
83 };
84
85 let provider_metadata = serde_json::json!({
86 "openai": {
87 "response_id": response_id,
88 "status": "failed"
89 }
90 });
91
92 Ok(LlmResponse {
93 error_code,
94 error_message,
95 provider_metadata: Some(provider_metadata),
96 partial: false,
97 turn_complete: true,
98 ..Default::default()
99 })
100 }
101 Status::Cancelled => {
102 let provider_metadata = serde_json::json!({
103 "openai": {
104 "response_id": response_id,
105 "status": "cancelled"
106 }
107 });
108
109 Ok(LlmResponse {
110 error_code: Some("cancelled".to_string()),
111 error_message: Some("Background response was cancelled".to_string()),
112 provider_metadata: Some(provider_metadata),
113 partial: false,
114 turn_complete: true,
115 ..Default::default()
116 })
117 }
118 }
119 }
120
121 /// Cancel a background response by ID.
122 ///
123 /// Calls `POST /v1/responses/{response_id}/cancel` to cancel a response
124 /// that was created with `background: true`. Only background responses
125 /// can be cancelled.
126 ///
127 /// # Returns
128 ///
129 /// Returns an `LlmResponse` with `status: "cancelled"` in `provider_metadata`
130 /// on success.
131 ///
132 /// # Errors
133 ///
134 /// Returns `AdkError` if:
135 /// - The HTTP request fails (network error, auth error)
136 /// - The response is not a background response
137 /// - The response has already completed
138 ///
139 /// # Example
140 ///
141 /// ```rust,ignore
142 /// let response = client.cancel_response("resp_abc123").await?;
143 /// println!("Response cancelled: {:?}", response.provider_metadata);
144 /// ```
145 pub async fn cancel_response(&self, response_id: &str) -> Result<LlmResponse, AdkError> {
146 let url = format!("{}/responses/{}/cancel", self.base_url(), response_id);
147
148 let response = self
149 .http_client()
150 .post(&url)
151 .header("Authorization", format!("Bearer {}", self.api_key()))
152 .header("Content-Type", "application/json")
153 .send()
154 .await
155 .map_err(|e| AdkError::model(format!("cancel request failed: {e}")))?;
156
157 let status_code = response.status();
158 let body = response
159 .text()
160 .await
161 .map_err(|e| AdkError::model(format!("failed to read cancel response body: {e}")))?;
162
163 if !status_code.is_success() {
164 return Err(AdkError::model(format!(
165 "cancel response failed with status {status_code}: {body}"
166 )));
167 }
168
169 // Parse the response to extract status confirmation
170 let json: serde_json::Value = serde_json::from_str(&body)
171 .map_err(|e| AdkError::model(format!("failed to parse cancel response: {e}")))?;
172
173 let response_status = json.get("status").and_then(|v| v.as_str()).unwrap_or("cancelled");
174
175 let provider_metadata = serde_json::json!({
176 "openai": {
177 "response_id": response_id,
178 "status": response_status
179 }
180 });
181
182 Ok(LlmResponse {
183 error_code: Some("cancelled".to_string()),
184 error_message: Some("Background response was cancelled".to_string()),
185 provider_metadata: Some(provider_metadata),
186 partial: false,
187 turn_complete: true,
188 ..Default::default()
189 })
190 }
191}
192
193/// Inject `response_id` and `status` into existing provider_metadata.
194fn inject_status_metadata(response: &mut LlmResponse, response_id: &str, status: &Status) {
195 let status_str = status_to_str(status);
196
197 if let Some(ref mut metadata) = response.provider_metadata {
198 if let Some(openai) = metadata.get_mut("openai")
199 && let Some(obj) = openai.as_object_mut()
200 {
201 obj.insert("status".to_string(), serde_json::Value::String(status_str.to_string()));
202 // response_id should already be present from from_response, but ensure it
203 obj.entry("response_id".to_string())
204 .or_insert_with(|| serde_json::Value::String(response_id.to_string()));
205 }
206 } else {
207 response.provider_metadata = Some(serde_json::json!({
208 "openai": {
209 "response_id": response_id,
210 "status": status_str
211 }
212 }));
213 }
214}
215
216/// Convert a `Status` enum to its string representation.
217fn status_to_str(status: &Status) -> &'static str {
218 match status {
219 Status::Completed => "completed",
220 Status::Failed => "failed",
221 Status::InProgress => "in_progress",
222 Status::Cancelled => "cancelled",
223 Status::Queued => "queued",
224 Status::Incomplete => "incomplete",
225 }
226}