1use super::config::MuseConfig;
12use adk_core::{AdkError, ErrorComponent};
13use reqwest::Client;
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16
17pub type ResponseItem = Value;
20
21#[derive(Debug, Clone, Serialize, Default)]
23pub struct ResponseRequest {
24 pub model: String,
26 #[serde(skip_serializing_if = "Option::is_none")]
28 pub input: Option<Value>,
29 #[serde(skip_serializing_if = "Option::is_none")]
31 pub instructions: Option<String>,
32 #[serde(skip_serializing_if = "Option::is_none")]
34 pub previous_response_id: Option<String>,
35 #[serde(skip_serializing_if = "Option::is_none")]
37 pub store: Option<bool>,
38 #[serde(skip_serializing_if = "Option::is_none")]
40 pub background: Option<bool>,
41 #[serde(skip_serializing_if = "Option::is_none")]
43 pub temperature: Option<f32>,
44 #[serde(skip_serializing_if = "Option::is_none")]
46 pub top_p: Option<f32>,
47 #[serde(skip_serializing_if = "Option::is_none")]
49 pub max_output_tokens: Option<u32>,
50 #[serde(skip_serializing_if = "Option::is_none")]
52 pub tools: Option<Vec<Value>>,
53 #[serde(skip_serializing_if = "Option::is_none")]
55 pub tool_choice: Option<Value>,
56 #[serde(skip_serializing_if = "Option::is_none")]
58 pub parallel_tool_calls: Option<bool>,
59 #[serde(skip_serializing_if = "Option::is_none")]
61 pub text: Option<Value>,
62 #[serde(skip_serializing_if = "Option::is_none")]
64 pub include: Option<Vec<String>>,
65}
66
67impl ResponseRequest {
68 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 pub fn with_items(mut self, items: Vec<ResponseItem>) -> Self {
75 self.input = Some(Value::Array(items));
76 self
77 }
78
79 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 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#[derive(Debug, Clone)]
96pub struct FunctionCallItem {
97 pub call_id: String,
99 pub name: String,
101 pub arguments: String,
103}
104
105#[derive(Debug, Clone, Deserialize)]
107pub struct ResponseObject {
108 pub id: String,
110 #[serde(default)]
112 pub status: Option<String>,
113 #[serde(default)]
115 pub error: Option<Value>,
116 #[serde(default)]
118 pub output: Vec<Value>,
119 #[serde(default)]
121 pub usage: Option<Value>,
122}
123
124impl ResponseObject {
125 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 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 pub fn usage_metadata(&self) -> Option<adk_core::UsageMetadata> {
165 use crate::usage_json::count;
166
167 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 pub fn is_completed(&self) -> bool {
186 self.status.as_deref() == Some("completed")
187 }
188}
189
190pub struct MuseResponsesClient {
204 client: Client,
205 config: MuseConfig,
206}
207
208impl MuseResponsesClient {
209 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 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 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 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 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 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}