Skip to main content

adk_model/muse/
client.rs

1//! Muse client implementation.
2
3use super::config::{MUSE_API_BASE, MuseApi, MuseConfig};
4use super::convert::{self, ChatCompletionRequest, ChatCompletionResponse};
5use crate::retry::{RetryConfig, execute_with_retry, is_retryable_model_error};
6use adk_core::{
7    AdkError, ErrorCategory, ErrorComponent, FinishReason, Llm, LlmRequest, LlmResponse,
8    LlmResponseStream, Part,
9};
10use async_stream::try_stream;
11use async_trait::async_trait;
12use futures::StreamExt;
13use reqwest::Client;
14use serde_json::Value;
15
16/// Strict structured-output format for Muse, named after the model (Meta JSON
17/// Schema mode guarantees schema-conformant JSON). Mirrors the OpenAI pattern.
18fn response_format_for(model: &str, schema: &Value) -> convert::ResponseFormat {
19    /// Strict mode requires `additionalProperties: false` on every object schema.
20    fn close_objects(value: &mut Value) {
21        match value {
22            Value::Object(object) => {
23                if object.get("type").and_then(Value::as_str) == Some("object") {
24                    object
25                        .entry("additionalProperties".to_string())
26                        .or_insert(serde_json::json!(false));
27                }
28                for child in object.values_mut() {
29                    close_objects(child);
30                }
31            }
32            Value::Array(items) => items.iter_mut().for_each(close_objects),
33            _ => {}
34        }
35    }
36    let mut schema = schema.clone();
37    close_objects(&mut schema);
38    let mut name: String = model
39        .chars()
40        .map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' })
41        .take(64)
42        .collect();
43    if name.is_empty() {
44        name.push_str("response");
45    }
46    convert::ResponseFormat {
47        format_type: "json_schema".to_string(),
48        json_schema: convert::JsonSchema { name, schema, strict: true },
49    }
50}
51
52/// Stream that ended, or whose connection failed, before the response finished.
53const INCOMPLETE_STREAM: &str = "model.muse.incomplete_stream";
54/// Stream chunk that is not valid JSON or not a chat completion chunk.
55const INVALID_CHUNK: &str = "model.muse.invalid_chunk";
56/// Error Muse reported inside the stream.
57const STREAM_ERROR: &str = "model.muse.stream_error";
58
59/// Muse client for Meta's Muse Spark models.
60///
61/// Calls Chat Completions by default, or the Responses API with
62/// [`MuseConfig::with_api`]`(`[`MuseApi::Responses`]`)` (feature `muse-responses`).
63///
64/// # Example
65///
66/// ```rust,ignore
67/// use adk_model::muse::{MuseClient, MuseConfig};
68///
69/// let client = MuseClient::new(MuseConfig::spark_1_3(
70///     std::env::var("META_API_KEY").unwrap()
71/// ))?;
72/// ```
73pub struct MuseClient {
74    client: Client,
75    config: MuseConfig,
76    retry_config: RetryConfig,
77    /// The Open Responses engine, when the config selects [`MuseApi::Responses`].
78    #[cfg(feature = "muse-responses")]
79    responses: Option<crate::openai::OpenAIResponsesClient>,
80}
81
82impl MuseClient {
83    /// Create a new Muse client.
84    ///
85    /// # Errors
86    ///
87    /// Returns `model.muse.invalid_config` when the config selects [`MuseApi::Responses`]
88    /// without the `muse-responses` feature, or an error when an HTTP client cannot be
89    /// built.
90    ///
91    /// # Example
92    ///
93    /// ```
94    /// use adk_model::muse::{MuseApi, MuseClient, MuseConfig};
95    ///
96    /// let chat = MuseClient::new(MuseConfig::spark_1_3("LLM-key"))?;
97    /// assert_eq!(chat.api(), MuseApi::ChatCompletions);
98    /// # Ok::<(), adk_core::AdkError>(())
99    /// ```
100    pub fn new(config: MuseConfig) -> Result<Self, AdkError> {
101        crate::catalog::warn_if_obsolete("muse", &config.model);
102        let client = crate::HttpTimeouts::default()
103            .apply(Client::builder())
104            .build()
105            .map_err(|e| AdkError::model(format!("Failed to create HTTP client: {e}")))?;
106        #[cfg(feature = "muse-responses")]
107        let responses = match config.api {
108            MuseApi::ChatCompletions => None,
109            MuseApi::Responses => Some(
110                crate::openai::OpenAIResponsesClient::new(
111                    crate::openai::OpenAIResponsesConfig::new(
112                        config.api_key.clone(),
113                        config.model.clone(),
114                    )
115                    .with_base_url(config.effective_base_url().trim_end_matches('/'))
116                    .with_open_responses_mode(true),
117                )?
118                .with_provider_name("muse"),
119            ),
120        };
121        #[cfg(not(feature = "muse-responses"))]
122        if config.api == MuseApi::Responses {
123            return Err(AdkError::new(
124                ErrorComponent::Model,
125                ErrorCategory::InvalidInput,
126                "model.muse.invalid_config",
127                "MuseApi::Responses needs the adk-model `muse-responses` feature",
128            )
129            .with_provider("muse"));
130        }
131
132        Ok(Self {
133            client,
134            config,
135            retry_config: RetryConfig::default(),
136            #[cfg(feature = "muse-responses")]
137            responses,
138        })
139    }
140
141    /// The endpoint the client calls.
142    pub fn api(&self) -> MuseApi {
143        self.config.api
144    }
145
146    /// Sets the connect and idle timeouts of the HTTP transport, so a stalled stream fails
147    /// with a `Timeout` error instead of holding the run.
148    ///
149    /// See [`HttpTimeouts`](crate::HttpTimeouts) for the defaults.
150    ///
151    /// # Example
152    ///
153    /// ```
154    /// use std::time::Duration;
155    ///
156    /// use adk_model::muse::{MuseClient, MuseConfig};
157    /// use adk_model::HttpTimeouts;
158    ///
159    /// let client = MuseClient::new(MuseConfig::new("LLM-key", "muse-spark-1.3"))?
160    ///     .with_timeouts(HttpTimeouts::new(Duration::from_secs(10), Duration::from_secs(120)))?;
161    /// # let _ = client;
162    /// # Ok::<(), adk_core::AdkError>(())
163    /// ```
164    ///
165    /// # Errors
166    ///
167    /// Returns an error when the Muse HTTP client cannot be built.
168    pub fn with_timeouts(mut self, timeouts: crate::HttpTimeouts) -> Result<Self, AdkError> {
169        self.client = timeouts
170            .apply(Client::builder())
171            .build()
172            .map_err(|e| AdkError::model(format!("Failed to create HTTP client: {e}")))?;
173        #[cfg(feature = "muse-responses")]
174        {
175            self.responses =
176                self.responses.map(|responses| responses.with_timeouts(timeouts)).transpose()?;
177        }
178        Ok(self)
179    }
180
181    /// Set the retry configuration (builder pattern).
182    #[must_use]
183    pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
184        self.set_retry_config(retry_config);
185        self
186    }
187
188    /// Set the retry configuration (mutable reference).
189    pub fn set_retry_config(&mut self, retry_config: RetryConfig) {
190        #[cfg(feature = "muse-responses")]
191        if let Some(responses) = self.responses.as_mut() {
192            responses.set_retry_config(retry_config.clone());
193        }
194        self.retry_config = retry_config;
195    }
196
197    /// Returns the current retry configuration.
198    pub fn retry_config(&self) -> &RetryConfig {
199        &self.retry_config
200    }
201
202    /// Build the API URL for chat completions.
203    fn api_url(&self) -> String {
204        let base = self.config.base_url.as_deref().unwrap_or(MUSE_API_BASE);
205        format!("{}/chat/completions", base.trim_end_matches('/'))
206    }
207
208    /// The request the Responses engine sends: the Muse request profile checked, the
209    /// `extensions["muse"]` options moved to the engine's namespace, and the output cap
210    /// raised to [`MUSE_MIN_MAX_TOKENS`](super::config::MUSE_MIN_MAX_TOKENS).
211    ///
212    /// # Errors
213    ///
214    /// Returns `model.unsupported_config` for a setting the Meta Responses API rejects.
215    #[cfg(feature = "muse-responses")]
216    fn responses_request(
217        &self,
218        mut request: LlmRequest,
219        stream: bool,
220    ) -> Result<LlmRequest, AdkError> {
221        crate::generation_config::reject_unsupported(
222            "muse",
223            request.config.as_ref(),
224            crate::generation_config::Supports {
225                stop_sequences: false,
226                seed: false,
227                penalties: false,
228                top_logprobs: false,
229            },
230        )?;
231        let unsupported = |message: &str| {
232            AdkError::new(
233                ErrorComponent::Model,
234                ErrorCategory::InvalidInput,
235                "model.unsupported_config",
236                message,
237            )
238            .with_provider("muse")
239        };
240        let config = request.config.get_or_insert_with(Default::default);
241        let options = config.extensions.remove("muse");
242        let option = |key: &str| options.as_ref().and_then(|options| options.get(key));
243        if stream && option("background").and_then(Value::as_bool) == Some(true) {
244            return Err(unsupported(
245                "the Meta Responses API rejects `background` with streaming; send the background request without streaming and poll it",
246            ));
247        }
248        if option("reasoning").and_then(|reasoning| reasoning.get("effort")).and_then(Value::as_str)
249            == Some("none")
250        {
251            return Err(unsupported(
252                "the Meta Responses API rejects reasoning effort `none`; use `low`",
253            ));
254        }
255        let encrypted = option("include").and_then(Value::as_array).is_some_and(|include| {
256            include.iter().any(|item| item.as_str() == Some("reasoning.encrypted_content"))
257        });
258        if encrypted && option("previous_response_id").is_some() {
259            return Err(unsupported(
260                "the Meta Responses API rejects `reasoning.encrypted_content` with `previous_response_id`; chain turns with `previous_response_id` alone",
261            ));
262        }
263        // The engine reads `extensions["openai"]`; an OpenAI namespace set for another client
264        // is not sent to Meta.
265        let forwarded: serde_json::Map<String, Value> =
266            ["previous_response_id", "store", "reasoning", "include", "background"]
267                .into_iter()
268                .filter_map(|key| option(key).map(|value| (key.to_string(), value.clone())))
269                .collect();
270        config.extensions.insert("openai".to_string(), Value::Object(forwarded));
271        let cap = config
272            .max_output_tokens
273            .and_then(|tokens| u32::try_from(tokens).ok())
274            .or(self.config.max_tokens);
275        config.max_output_tokens = cap
276            .map(|cap| cap.max(super::config::MUSE_MIN_MAX_TOKENS))
277            .and_then(|cap| i32::try_from(cap).ok());
278        Ok(request)
279    }
280
281    /// Build a chat completion request from an LLM request.
282    ///
283    /// # Errors
284    ///
285    /// Returns `model.unsupported_config` when the config sets `top_logprobs`, which the
286    /// Meta Model API does not document for Chat Completions.
287    fn build_request(
288        &self,
289        request: &LlmRequest,
290        stream: bool,
291    ) -> Result<ChatCompletionRequest, AdkError> {
292        let config = request.config.as_ref();
293        crate::generation_config::reject_unsupported(
294            "muse",
295            config,
296            crate::generation_config::Supports {
297                stop_sequences: true,
298                seed: true,
299                penalties: true,
300                top_logprobs: false,
301            },
302        )?;
303        // A tool message carries only text, so images a tool returned follow it.
304        let messages: Vec<_> = crate::tool_result::with_images(&request.contents)
305            .iter()
306            .flat_map(convert::content_to_messages)
307            .collect();
308
309        let tools = if request.tools.is_empty() {
310            None
311        } else {
312            Some(convert::convert_tools(&request.tools))
313        };
314
315        let temperature = request.config.as_ref().and_then(|c| c.temperature);
316        let top_p = request.config.as_ref().and_then(|c| c.top_p);
317        let max_tokens = request
318            .config
319            .as_ref()
320            .and_then(|c| c.max_output_tokens)
321            .map(|t| t as u32)
322            .or(self.config.max_tokens)
323            .map(|cap| cap.max(super::config::MUSE_MIN_MAX_TOKENS));
324        let reasoning_effort =
325            config.and_then(|c| c.effort).map(|level| level.as_str().to_string());
326        let options = config.and_then(|c| c.extensions.get("muse"));
327        let response_format = config
328            .and_then(|c| c.response_schema.as_ref())
329            .map(|schema| response_format_for(&self.config.model, schema));
330
331        Ok(ChatCompletionRequest {
332            model: self.config.model.clone(),
333            messages,
334            temperature,
335            top_p,
336            max_tokens,
337            stream: Some(stream),
338            tools,
339            stop: config.map(|c| c.stop_sequences.clone()).filter(|stop| !stop.is_empty()),
340            seed: config.and_then(|c| c.seed),
341            frequency_penalty: config.and_then(|c| c.frequency_penalty),
342            presence_penalty: config.and_then(|c| c.presence_penalty),
343            reasoning_effort,
344            response_format,
345            tool_choice: options.and_then(|options| options.get("tool_choice").cloned()),
346            parallel_tool_calls: options
347                .and_then(|options| options.get("parallel_tool_calls"))
348                .and_then(Value::as_bool),
349            prompt_cache_key: options
350                .and_then(|options| options.get("prompt_cache_key"))
351                .and_then(Value::as_str)
352                .map(str::to_string),
353            prompt_cache_retention: options
354                .and_then(|options| options.get("prompt_cache_retention"))
355                .and_then(Value::as_str)
356                .map(str::to_string),
357        })
358    }
359}
360
361#[async_trait]
362impl Llm for MuseClient {
363    fn max_cost_micro_usd(&self, request: &adk_core::LlmRequest) -> Option<u64> {
364        crate::pricing::PricingCatalog::standard().max_cost_micro_usd(
365            Some("muse"),
366            self.name(),
367            request,
368            None,
369        )
370    }
371
372    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
373        vec![adk_core::DataDestination::of_url("muse", self.config.effective_base_url())]
374    }
375
376    fn name(&self) -> &str {
377        &self.config.model
378    }
379
380    #[tracing::instrument(
381        name = "model.generate_content",
382        skip_all,
383        fields(
384            model.name = %self.name(),
385            stream = %stream,
386            request.contents_count = %request.contents.len(),
387            request.tools_count = %request.tools.len()
388        )
389    )]
390    async fn generate_content(
391        &self,
392        mut request: LlmRequest,
393        stream: bool,
394    ) -> Result<LlmResponseStream, AdkError> {
395        // Native items reach this provider only from the turns its own origin marks.
396        adk_core::history::retain_replayable(
397            &mut request.contents,
398            &adk_core::history::ProviderOrigin::new("muse", &self.config.model),
399        );
400        #[cfg(feature = "muse-responses")]
401        if let Some(responses) = &self.responses {
402            let request = self.responses_request(request, stream)?;
403            return responses.generate_content(request, stream).await;
404        }
405        let usage_span =
406            crate::telemetry::inference_span("muse", &self.config.model, stream, &request);
407        let api_url = self.api_url();
408        let api_key = self.config.api_key.clone();
409        let chat_request = self.build_request(&request, stream)?;
410        let client = self.client.clone();
411        let retry_config = self.retry_config.clone();
412
413        let response_stream = try_stream! {
414            // Retries only cover request setup/execution. Stream failures after start are surfaced
415            // directly and are not auto-replayed.
416            let response = execute_with_retry(&retry_config, is_retryable_model_error, || {
417                let client = client.clone();
418                let api_url = api_url.clone();
419                let api_key = api_key.clone();
420                let chat_request = chat_request.clone();
421                async move {
422                    let response = client
423                        .post(&api_url)
424                        .header("Authorization", format!("Bearer {api_key}"))
425                        .header("Content-Type", "application/json")
426                        .json(&chat_request)
427                        .send()
428                        .await
429                        .map_err(|e| AdkError::new(
430                            ErrorComponent::Model,
431                            crate::http_timeouts::transport_category(&e),
432                            "model.muse.request",
433                            format!("Muse API request failed: {e}"),
434                        ).with_provider("muse"))?;
435
436                    if !response.status().is_success() {
437                        let status = response.status();
438                        let status_code = status.as_u16();
439                        let retry_after = response
440                            .headers()
441                            .get(reqwest::header::RETRY_AFTER)
442                            .and_then(|value| value.to_str().ok())
443                            .and_then(crate::retry::parse_retry_after);
444                        let error_text = response.text().await.unwrap_or_default();
445                        let error = AdkError::new(
446                            ErrorComponent::Model,
447                            crate::retry::category_for_status_code(status_code),
448                            "model.muse.api_error",
449                            format!(
450                                "Muse API error (HTTP {status}): {}",
451                                adk_core::upstream_excerpt(&error_text)
452                            ),
453                        ).with_upstream_status(status_code).with_provider("muse");
454                        return Err(crate::retry::with_retry_after(error, retry_after));
455                    }
456
457                    Ok(response)
458                }
459            })
460            .await?;
461
462            if stream {
463                // Streaming mode - process SSE events
464                let mut byte_stream = response.bytes_stream();
465                // Bytes, not text: a network chunk can end inside a UTF-8 character.
466                let mut buffer = Vec::new();
467                // A finish reason or `[DONE]` marks a complete response; without one the
468                // answer or a tool call may be truncated.
469                let mut finished = false;
470                let mut ended = false;
471
472                // Accumulate tool calls across chunks
473                let mut tool_call_accumulators: std::collections::HashMap<u32, (String, String, String)> =
474                    std::collections::HashMap::new();
475
476                while !ended {
477                    match byte_stream.next().await {
478                        Some(chunk) => buffer.extend_from_slice(&chunk.map_err(|error| {
479                            crate::stream_error::interrupted("muse", INCOMPLETE_STREAM, &error)
480                        })?),
481                        None => {
482                            ended = true;
483                            // The last line may arrive without its line ending.
484                            buffer.push(b'\n');
485                        }
486                    }
487
488                    // Process complete SSE events
489                    while let Some(line) = crate::sse::take_line(&mut buffer)? {
490                        let Some(data) = crate::sse::data(&line) else {
491                            continue;
492                        };
493
494                        if data == "[DONE]" {
495                            if !tool_call_accumulators.is_empty() {
496                                Err(crate::stream_error::incomplete(
497                                    "muse",
498                                    INCOMPLETE_STREAM,
499                                    "its tool calls finished",
500                                ))?;
501                            }
502                            finished = true;
503                            continue;
504                        }
505
506                        let parsed = serde_json::from_str::<serde_json::Value>(data);
507                        // A cut-off trailer after a finished response loses nothing.
508                        if parsed.is_err() && ended && finished {
509                            continue;
510                        }
511                        let value = parsed.map_err(|error| {
512                            crate::stream_error::undecodable("muse", INVALID_CHUNK, &error)
513                        })?;
514                        if let Some(error) = value.get("error").filter(|error| !error.is_null()) {
515                            Err(crate::stream_error::reported("muse", STREAM_ERROR, error))?;
516                        }
517                        // A chunk that does not decode can be the one finishing the turn,
518                        // so it fails the stream rather than dropping its tool calls.
519                        let chunk_response: ChatCompletionResponse = serde_json::from_value(value)
520                            .map_err(|error| {
521                                crate::stream_error::undecodable("muse", INVALID_CHUNK, &error)
522                            })?;
523                        if let Some(choice) = chunk_response.choices.first() {
524                            // Handle tool call accumulation
525                            if let Some(delta) = &choice.delta
526                                && let Some(tool_calls) = &delta.tool_calls {
527                                    for tc in tool_calls {
528                                        let index = tc.index;
529                                        let entry = tool_call_accumulators
530                                            .entry(index)
531                                            .or_insert_with(|| {
532                                                let call_id = tc.id.clone().unwrap_or_else(|| {
533                                                    format!("call_{index}")
534                                                });
535                                                (call_id, String::new(), String::new())
536                                            });
537
538                                        if let Some(id) = &tc.id {
539                                            entry.0 = id.clone();
540                                        }
541
542                                        if let Some(func) = &tc.function {
543                                            if let Some(name) = &func.name {
544                                                entry.1 = name.clone();
545                                            }
546                                            if let Some(args_chunk) = &func.arguments {
547                                                entry.2.push_str(args_chunk);
548                                            }
549                                        }
550                                    }
551                                }
552
553                            // Check for finish
554                            if let Some(reason) = choice.finish_reason.as_deref() {
555                                if reason == "error" {
556                                    Err(crate::stream_error::reported(
557                                        "muse",
558                                        STREAM_ERROR,
559                                        &serde_json::Value::Null,
560                                    ))?;
561                                }
562                                finished = true;
563                                let finish_reason = Some(match reason {
564                                    "stop" | "tool_calls" => FinishReason::Stop,
565                                    "length" => FinishReason::MaxTokens,
566                                    "content_filter" => FinishReason::Safety,
567                                    _ => FinishReason::Other,
568                                });
569
570                                // Emit tool calls if any
571                                if !tool_call_accumulators.is_empty() {
572                                    let mut sorted_calls: Vec<_> =
573                                        tool_call_accumulators.drain().collect();
574                                    sorted_calls.sort_by_key(|(idx, _)| *idx);
575
576                                    let tool_calls = sorted_calls
577                                        .into_iter()
578                                        .map(|(_, (id, name, args_str))| {
579                                            let args = crate::tool_args::streamed_tool_arguments(
580                                                "muse",
581                                                &name,
582                                                &args_str,
583                                            );
584                                            (id, name, args)
585                                        })
586                                        .collect::<Vec<_>>();
587
588                                    let mut response = convert::create_tool_call_response(
589                                        tool_calls,
590                                        finish_reason,
591                                    );
592                                    response.usage_metadata = chunk_response.usage_metadata();
593                                    yield response;
594                                    continue;
595                                }
596
597                                // Emit final response
598                                let mut parts = Vec::new();
599
600                                if let Some(delta) = &choice.delta
601                                    && let Some(text) = &delta.content
602                                        && !text.is_empty() {
603                                            parts.push(Part::Text { text: text.clone() });
604                                        }
605
606                                yield LlmResponse {
607                                    content: if parts.is_empty() {
608                                        None
609                                    } else {
610                                        Some(adk_core::Content {
611                                            role: "model".to_string(),
612                                            parts,
613                                        })
614                                    },
615                                    usage_metadata: chunk_response.usage_metadata(),
616                                    finish_reason,
617                                    citation_metadata: None,
618                                    partial: false,
619                                    turn_complete: true,
620                                    interrupted: false,
621                                    error_code: None,
622                                    error_message: None,
623                                    provider_metadata: None,
624                                    interaction_id: None,
625                                    model: None,
626                                    provider: None,
627                                };
628                            } else {
629                                // Emit partial text content
630                                if let Some(delta) = &choice.delta
631                                    && let Some(text) = &delta.content
632                                        && !text.is_empty() {
633                                            yield LlmResponse {
634                                                content: Some(adk_core::Content {
635                                                    role: "model".to_string(),
636                                                    parts: vec![Part::Text {
637                                                        text: text.clone(),
638                                                    }],
639                                                }),
640                                                usage_metadata: None,
641                                                finish_reason: None,
642                                                citation_metadata: None,
643                                                partial: true,
644                                                turn_complete: false,
645                                                interrupted: false,
646                                                error_code: None,
647                                                error_message: None,
648                                                provider_metadata: None,
649                                                interaction_id: None,
650                                                model: None,
651                                                provider: None,
652                                            };
653                                        }
654                            }
655                        }
656                    }
657                }
658                if !finished {
659                    Err(crate::stream_error::incomplete(
660                        "muse",
661                        INCOMPLETE_STREAM,
662                        if tool_call_accumulators.is_empty() {
663                            "the response finished"
664                        } else {
665                            "its tool calls finished"
666                        },
667                    ))?;
668                }
669            } else {
670                // Non-streaming mode
671                let response_text = response.text().await.map_err(|e| AdkError::new(
672                    ErrorComponent::Model,
673                    crate::http_timeouts::transport_category(&e),
674                    "model.muse.request",
675                    format!("Failed to read response: {e}"),
676                ).with_provider("muse"))?;
677
678                let chat_response: ChatCompletionResponse = serde_json::from_str(&response_text)
679                    .map_err(|e| AdkError::model(format!(
680                        "Failed to parse response: {}",
681                        adk_core::json_error_summary(&e)
682                    )))?;
683
684                yield convert::from_response(&chat_response);
685            }
686        };
687
688        Ok(crate::usage_tracking::with_priced_usage_tracking(
689            Box::pin(response_stream),
690            usage_span,
691            "muse",
692            &self.config.model,
693        ))
694    }
695}
696
697#[cfg(test)]
698mod tests {
699    use super::*;
700    use adk_core::{Content, GenerateContentConfig};
701
702    fn request(config: GenerateContentConfig) -> LlmRequest {
703        let mut request =
704            LlmRequest::new("muse-spark-1.3", vec![Content::new("user").with_text("hi")]);
705        request.config = Some(config);
706        request
707    }
708
709    #[test]
710    fn stop_seed_and_penalties_are_sent_and_logprobs_are_rejected() {
711        let client = MuseClient::new(MuseConfig::new("test-key", "muse-spark-1.3")).unwrap();
712        let built = client
713            .build_request(
714                &request(GenerateContentConfig {
715                    stop_sequences: vec!["END".to_string()],
716                    seed: Some(42),
717                    presence_penalty: Some(0.5),
718                    frequency_penalty: Some(0.25),
719                    ..Default::default()
720                }),
721                false,
722            )
723            .unwrap();
724        let wire = serde_json::to_value(built).unwrap();
725        assert_eq!(wire["stop"], serde_json::json!(["END"]));
726        assert_eq!(wire["seed"], 42);
727        assert_eq!(wire["presence_penalty"], 0.5);
728        assert_eq!(wire["frequency_penalty"], 0.25);
729
730        let error = client
731            .build_request(
732                &request(GenerateContentConfig { top_logprobs: Some(2), ..Default::default() }),
733                false,
734            )
735            .expect_err("Muse Chat Completions does not document log probabilities");
736        assert_eq!(error.code, "model.unsupported_config");
737    }
738
739    #[test]
740    fn small_caps_are_raised_to_the_reasoning_floor() {
741        use adk_core::Effort;
742
743        let client = MuseClient::new(MuseConfig::new("test-key", "muse-spark-1.3")).unwrap();
744        let tiny = client
745            .build_request(
746                &request(GenerateContentConfig {
747                    max_output_tokens: Some(256),
748                    ..Default::default()
749                }),
750                false,
751            )
752            .unwrap();
753        assert_eq!(tiny.max_tokens, Some(crate::muse::config::MUSE_MIN_MAX_TOKENS));
754
755        let roomy = client
756            .build_request(
757                &request(GenerateContentConfig {
758                    max_output_tokens: Some(4096),
759                    ..Default::default()
760                }),
761                false,
762            )
763            .unwrap();
764        assert_eq!(roomy.max_tokens, Some(4096));
765
766        let effort = client
767            .build_request(
768                &request(GenerateContentConfig { effort: Some(Effort::Low), ..Default::default() }),
769                false,
770            )
771            .unwrap();
772        assert_eq!(effort.reasoning_effort.as_deref(), Some("low"));
773
774        let no_effort = client.build_request(&request(Default::default()), false).unwrap();
775        assert_eq!(no_effort.reasoning_effort, None);
776        assert_eq!(no_effort.max_tokens, None);
777    }
778
779    #[test]
780    fn response_schema_and_options_are_sent() {
781        let client = MuseClient::new(MuseConfig::new("test-key", "muse-spark-1.3")).unwrap();
782        let mut config = GenerateContentConfig {
783            max_output_tokens: Some(256),
784            response_schema: Some(serde_json::json!({
785                "type": "object",
786                "properties": {
787                    "title": {"type": "string"},
788                    "card": {"type": "object", "properties": {"x": {"type": "string"}}},
789                },
790                "required": ["title"],
791            })),
792            ..Default::default()
793        };
794        config.extensions.insert(
795            "muse".to_string(),
796            serde_json::json!({
797                "prompt_cache_key": "ideate",
798                "prompt_cache_retention": "24h",
799                "tool_choice": "required",
800                "parallel_tool_calls": false,
801            }),
802        );
803        let built = client.build_request(&request(config), false).unwrap();
804        let wire = serde_json::to_value(built).unwrap();
805        assert_eq!(wire["response_format"]["type"], "json_schema");
806        assert_eq!(wire["response_format"]["json_schema"]["strict"], true);
807        assert_eq!(wire["response_format"]["json_schema"]["schema"]["additionalProperties"], false);
808        assert_eq!(
809            wire["response_format"]["json_schema"]["schema"]["properties"]["card"]["additionalProperties"],
810            false
811        );
812        assert_eq!(wire["prompt_cache_key"], "ideate");
813        assert_eq!(wire["prompt_cache_retention"], "24h");
814        assert_eq!(wire["tool_choice"], "required");
815        assert_eq!(wire["parallel_tool_calls"], false);
816        assert_eq!(wire["max_completion_tokens"], 1024);
817        assert!(wire.get("max_tokens").is_none());
818    }
819
820    #[test]
821    fn chat_url_appends_completions_to_base() {
822        let client = MuseClient::new(MuseConfig::spark_1_3("test-key")).unwrap();
823        assert_eq!(client.api_url(), "https://api.meta.ai/v1/chat/completions");
824
825        let custom = MuseClient::new(
826            MuseConfig::spark_1_3("test-key").with_base_url("https://proxy.local/meta/"),
827        )
828        .unwrap();
829        assert_eq!(custom.api_url(), "https://proxy.local/meta/chat/completions");
830    }
831}