Skip to main content

adk_model/muse/
responses.rs

1//! Responses API client (`POST /v1/responses`): the stateful surface.
2//!
3//! Unlike Chat Completions (stateless, no server memory), Responses is the only
4//! endpoint carrying reasoning across turns: `previous_response_id` chains turns,
5//! `store` persists them server-side, and `background` runs long generations
6//! asynchronously. This is the loop the legal-agent-workshop pattern is built on.
7//!
8//! The workshop loop, in ADK terms: one [`MuseResponsesClient::create`] per turn
9//! with the previous response id, one tool at a time, progress saved between turns.
10
11use super::config::MuseConfig;
12use adk_core::{AdkError, ErrorComponent};
13use reqwest::Client;
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16
17/// One Responses input item (`input_text`, `input_image`, `input_file`,
18/// `function_call`, `function_call_output`, ...). Untagged JSON, API-shaped.
19pub type ResponseItem = Value;
20
21/// A Responses generation request.
22#[derive(Debug, Clone, Serialize, Default)]
23pub struct ResponseRequest {
24    /// Model (for example `muse-spark-1.3`).
25    pub model: String,
26    /// Text input, or structured input items via [`ResponseRequest::with_items`].
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub input: Option<Value>,
29    /// Per-request instructions (not persisted).
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub instructions: Option<String>,
32    /// Chain onto a stored response (carries reasoning across turns).
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub previous_response_id: Option<String>,
35    /// Persist the response server-side (default true server-side).
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub store: Option<bool>,
38    /// Run asynchronously (poll with [`MuseResponsesClient::get`]).
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub background: Option<bool>,
41    /// Sampling temperature.
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub temperature: Option<f32>,
44    /// Nucleus sampling threshold.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub top_p: Option<f32>,
47    /// Output cap (minimum 16 server-side).
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub max_output_tokens: Option<u32>,
50    /// Function/custom tools (caller-executed) or server-side built-ins.
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub tools: Option<Vec<Value>>,
53    /// Tool choice.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub tool_choice: Option<Value>,
56    /// Whether tools may run in parallel in one turn.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub parallel_tool_calls: Option<bool>,
59    /// Output format, for example strict JSON Schema via `text.format`.
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub text: Option<Value>,
62    /// Include values, for example `reasoning.encrypted_content`.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub include: Option<Vec<String>>,
65}
66
67impl ResponseRequest {
68    /// A request with plain-text input.
69    pub fn text(model: impl Into<String>, input: impl Into<String>) -> Self {
70        Self { model: model.into(), input: Some(Value::String(input.into())), ..Default::default() }
71    }
72
73    /// Attach structured input items (images, files, function outputs).
74    pub fn with_items(mut self, items: Vec<ResponseItem>) -> Self {
75        self.input = Some(Value::Array(items));
76        self
77    }
78
79    /// Chain onto a stored response.
80    pub fn with_previous(mut self, previous_response_id: impl Into<String>) -> Self {
81        self.previous_response_id = Some(previous_response_id.into());
82        self
83    }
84
85    /// Constrain output to a strict JSON Schema (Responses `text.format`).
86    pub fn with_json_schema(mut self, name: &str, schema: Value) -> Self {
87        self.text = Some(serde_json::json!({
88            "format": {"type": "json_schema", "name": name, "schema": schema, "strict": true},
89        }));
90        self
91    }
92}
93
94/// One function call the model wants executed.
95#[derive(Debug, Clone)]
96pub struct FunctionCallItem {
97    /// Call id to answer with `function_call_output`.
98    pub call_id: String,
99    /// Function name.
100    pub name: String,
101    /// Raw JSON arguments.
102    pub arguments: String,
103}
104
105/// A Responses generation.
106#[derive(Debug, Clone, Deserialize)]
107pub struct ResponseObject {
108    /// Response id (`resp-..`), chainable via `previous_response_id`.
109    pub id: String,
110    /// Lifecycle status (`completed`, `failed`, `in_progress`, ...).
111    #[serde(default)]
112    pub status: Option<String>,
113    /// Error object when the generation failed.
114    #[serde(default)]
115    pub error: Option<Value>,
116    /// Output items (messages, function calls, reasoning).
117    #[serde(default)]
118    pub output: Vec<Value>,
119    /// Usage object as received.
120    #[serde(default)]
121    pub usage: Option<Value>,
122}
123
124impl ResponseObject {
125    /// All `output_text` content, joined.
126    pub fn text(&self) -> String {
127        let mut texts = Vec::new();
128        for item in &self.output {
129            if item.get("type").and_then(Value::as_str) == Some("message")
130                && let Some(content) = item.get("content").and_then(Value::as_array)
131            {
132                for part in content {
133                    if part.get("type").and_then(Value::as_str) == Some("output_text")
134                        && let Some(text) = part.get("text").and_then(Value::as_str)
135                    {
136                        texts.push(text);
137                    }
138                }
139            }
140        }
141        texts.join("\n")
142    }
143
144    /// Function calls the caller must execute and answer.
145    pub fn function_calls(&self) -> Vec<FunctionCallItem> {
146        self.output
147            .iter()
148            .filter(|item| item.get("type").and_then(Value::as_str) == Some("function_call"))
149            .filter_map(|item| {
150                Some(FunctionCallItem {
151                    call_id: item.get("call_id")?.as_str()?.to_string(),
152                    name: item.get("name")?.as_str()?.to_string(),
153                    arguments: item
154                        .get("arguments")
155                        .and_then(Value::as_str)
156                        .unwrap_or_default()
157                        .to_string(),
158                })
159            })
160            .collect()
161    }
162
163    /// Normalized usage, when present.
164    pub fn usage_metadata(&self) -> Option<adk_core::UsageMetadata> {
165        use crate::usage_json::count;
166
167        // Responses counts `input_tokens`/`output_tokens`, not Chat Completions'
168        // `prompt_tokens`/`completion_tokens`.
169        let usage = self.usage.as_ref().filter(|usage| usage.is_object())?;
170        let input = count(usage, "/input_tokens").unwrap_or_default();
171        let output = count(usage, "/output_tokens").unwrap_or_default();
172        Some(adk_core::UsageMetadata {
173            prompt_token_count: input,
174            candidates_token_count: output,
175            total_token_count: count(usage, "/total_tokens")
176                .unwrap_or_else(|| input.saturating_add(output)),
177            cache_read_input_token_count: count(usage, "/input_tokens_details/cached_tokens"),
178            thinking_token_count: count(usage, "/output_tokens_details/reasoning_tokens"),
179            provider_usage: Some(usage.clone()),
180            ..Default::default()
181        })
182    }
183
184    /// Whether the generation finished successfully.
185    pub fn is_completed(&self) -> bool {
186        self.status.as_deref() == Some("completed")
187    }
188}
189
190/// Responses API client.
191///
192/// # Example
193///
194/// ```rust,ignore
195/// use adk_model::muse::{MuseConfig, MuseResponsesClient, ResponseRequest};
196///
197/// let responses = MuseResponsesClient::new(MuseConfig::spark_1_3(api_key))?;
198/// let first = responses.create(ResponseRequest::text("muse-spark-1.3", "Plan the memo.")).await?;
199/// let next = responses
200///     .create(ResponseRequest::text("muse-spark-1.3", "Now execute step one.").with_previous(&first.id))
201///     .await?;
202/// ```
203pub struct MuseResponsesClient {
204    client: Client,
205    config: MuseConfig,
206}
207
208impl MuseResponsesClient {
209    /// Create a Responses client.
210    pub fn new(config: MuseConfig) -> Result<Self, AdkError> {
211        let client = crate::HttpTimeouts::default()
212            .apply(Client::builder())
213            .build()
214            .map_err(|e| AdkError::model(format!("Failed to create HTTP client: {e}")))?;
215        Ok(Self { client, config })
216    }
217
218    /// Create a response (one turn).
219    ///
220    /// # Errors
221    ///
222    /// Returns the API error (HTTP status, code `model.muse.api_error`) on rejection.
223    pub async fn create(&self, request: ResponseRequest) -> Result<ResponseObject, AdkError> {
224        let response = self
225            .client
226            .post(format!("{}/responses", self.base()))
227            .header("Authorization", self.auth())
228            .header("Content-Type", "application/json")
229            .json(&request)
230            .send()
231            .await
232            .map_err(|e| self.transport(e))?;
233        self.read_json(response).await
234    }
235
236    /// Retrieve a stored response (poll background generations here).
237    ///
238    /// # Errors
239    ///
240    /// Returns the API error on rejection.
241    pub async fn get(&self, response_id: &str) -> Result<ResponseObject, AdkError> {
242        let response = self
243            .client
244            .get(format!("{}/responses/{response_id}", self.base()))
245            .header("Authorization", self.auth())
246            .send()
247            .await
248            .map_err(|e| self.transport(e))?;
249        self.read_json(response).await
250    }
251
252    /// Delete a stored response.
253    ///
254    /// # Errors
255    ///
256    /// Returns the API error on rejection.
257    pub async fn delete(&self, response_id: &str) -> Result<(), AdkError> {
258        let response = self
259            .client
260            .delete(format!("{}/responses/{response_id}", self.base()))
261            .header("Authorization", self.auth())
262            .send()
263            .await
264            .map_err(|e| self.transport(e))?;
265        if !response.status().is_success() {
266            return Err(self.api_error(response).await);
267        }
268        Ok(())
269    }
270
271    /// Cancel a background response.
272    ///
273    /// # Errors
274    ///
275    /// Returns the API error on rejection.
276    pub async fn cancel(&self, response_id: &str) -> Result<ResponseObject, AdkError> {
277        let response = self
278            .client
279            .post(format!("{}/responses/{response_id}/cancel", self.base()))
280            .header("Authorization", self.auth())
281            .send()
282            .await
283            .map_err(|e| self.transport(e))?;
284        self.read_json(response).await
285    }
286
287    /// Count input tokens for a request without generating.
288    ///
289    /// # Errors
290    ///
291    /// Returns the API error on rejection.
292    pub async fn input_tokens(&self, request: &ResponseRequest) -> Result<u64, AdkError> {
293        let response = self
294            .client
295            .post(format!("{}/responses/input_tokens", self.base()))
296            .header("Authorization", self.auth())
297            .header("Content-Type", "application/json")
298            .json(request)
299            .send()
300            .await
301            .map_err(|e| self.transport(e))?;
302        let body: Value = self.read_json(response).await?;
303        body.get("input_tokens")
304            .and_then(Value::as_u64)
305            .ok_or_else(|| AdkError::model("input_tokens response carried no count"))
306    }
307
308    fn base(&self) -> String {
309        self.config.effective_base_url().trim_end_matches('/').to_string()
310    }
311
312    fn auth(&self) -> String {
313        format!("Bearer {}", self.config.api_key)
314    }
315
316    fn transport(&self, error: reqwest::Error) -> AdkError {
317        AdkError::new(
318            ErrorComponent::Model,
319            crate::http_timeouts::transport_category(&error),
320            "model.muse.request",
321            format!("Muse responses request failed: {error}"),
322        )
323        .with_provider("muse")
324    }
325
326    async fn api_error(&self, response: reqwest::Response) -> AdkError {
327        let status = response.status();
328        let status_code = status.as_u16();
329        let error_text = response.text().await.unwrap_or_default();
330        AdkError::new(
331            ErrorComponent::Model,
332            crate::retry::category_for_status_code(status_code),
333            "model.muse.api_error",
334            format!(
335                "Muse responses API error (HTTP {status}): {}",
336                adk_core::upstream_excerpt(&error_text)
337            ),
338        )
339        .with_upstream_status(status_code)
340        .with_provider("muse")
341    }
342
343    async fn read_json<T: serde::de::DeserializeOwned>(
344        &self,
345        response: reqwest::Response,
346    ) -> Result<T, AdkError> {
347        if !response.status().is_success() {
348            return Err(self.api_error(response).await);
349        }
350        let text = response
351            .text()
352            .await
353            .map_err(|e| AdkError::model(format!("Failed to read responses body: {e}")))?;
354        serde_json::from_str(&text).map_err(|e| {
355            AdkError::model(format!(
356                "Failed to parse responses body: {}",
357                adk_core::json_error_summary(&e)
358            ))
359        })
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    #[test]
368    fn response_text_and_calls_are_extracted() {
369        let response: ResponseObject = serde_json::from_value(serde_json::json!({
370            "id": "resp-1",
371            "status": "completed",
372            "output": [
373                {"type": "message", "content": [{"type": "output_text", "text": "Memo plan ready."}]},
374                {"type": "function_call", "call_id": "call-1", "name": "analyze_document", "arguments": "{\"id\":\"D1\"}"},
375            ],
376            "usage": {
377                "input_tokens": 10,
378                "input_tokens_details": {"cached_tokens": 4},
379                "output_tokens": 5,
380                "output_tokens_details": {"reasoning_tokens": 3},
381                "total_tokens": 15,
382            },
383        }))
384        .unwrap();
385        assert!(response.is_completed());
386        assert_eq!(response.text(), "Memo plan ready.");
387        let usage = response.usage_metadata().unwrap();
388        assert_eq!(
389            (
390                usage.prompt_token_count,
391                usage.candidates_token_count,
392                usage.total_token_count,
393                usage.cache_read_input_token_count,
394                usage.thinking_token_count,
395            ),
396            (10, 5, 15, Some(4), Some(3))
397        );
398        let calls = response.function_calls();
399        assert_eq!(calls.len(), 1);
400        assert_eq!(calls[0].name, "analyze_document");
401    }
402
403    #[test]
404    fn request_chains_and_constrains() {
405        let request = ResponseRequest::text("muse-spark-1.3", "next step")
406            .with_previous("resp-1")
407            .with_json_schema("memo", serde_json::json!({"type": "object"}));
408        let wire = serde_json::to_value(&request).unwrap();
409        assert_eq!(wire["previous_response_id"], "resp-1");
410        assert_eq!(wire["text"]["format"]["type"], "json_schema");
411    }
412}