Skip to main content

rig_core/providers/gemini/interactions_api/
mod.rs

1//! Wires for the [Gemini Interactions API](https://ai.google.dev/api/interactions-api).
2//! A request is built as JSON steps, and a reply, a whole interaction or a
3//! stream of step events, is read by [`InteractionsDecoder`](streaming::InteractionsDecoder).
4//!
5//! ```no_run
6//! use rig_core::providers::gemini::{Gemini, completion::GEMINI_2_5_FLASH};
7//!
8//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
9//! let wire = Gemini::from_env()?.interactions(GEMINI_2_5_FLASH);
10//! # Ok(())
11//! # }
12//! ```
13
14use serde_json::{Map, Value, json};
15use url::form_urlencoded;
16
17use crate::completion::{CompletionRequest, Media, Replay, ReplayTarget};
18use crate::error::EncodeError;
19use crate::message::{
20    AssistantContent, DocumentData, DocumentMediaType, DocumentSourceKind as Source, Message,
21    MimeType, ToolChoice as Choice, ToolResultContent, UserContent,
22};
23use crate::providers::internal::wire_ids::WireIds;
24use crate::telemetry::GenAiOperation;
25use crate::wire::{Descriptor, Mode};
26
27/// Streaming helpers for the Interactions API.
28pub mod streaming;
29
30use super::completion::PROVIDER_NAME;
31
32/// `deep-research-preview-04-2026`, the Deep Research agent, built for
33/// speed. Name it with
34/// [`InteractionsOptions::agent`](super::extension::InteractionsOptions::agent).
35pub const DEEP_RESEARCH_PREVIEW_04_2026: &str = "deep-research-preview-04-2026";
36/// `deep-research-max-preview-04-2026`, Deep Research Max, built for
37/// thoroughness.
38pub const DEEP_RESEARCH_MAX_PREVIEW_04_2026: &str = "deep-research-max-preview-04-2026";
39
40/// The wire format both Interactions wires speak.
41const API: crate::message::Api = crate::message::Api::from_static("gemini.interactions");
42
43/// Where a thought step holds its signature.
44const BLOB_SLOTS: &[&str] = &["/signature"];
45
46/// The Interactions `speech_config`: one voice, or a voice per named
47/// speaker.
48#[non_exhaustive]
49#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
50#[serde(untagged)]
51pub enum InteractionSpeechConfig {
52    /// An array of one voice.
53    Voice([InteractionSpeech; 1]),
54    /// `{"speakers": [...]}`: each speaker's voice, matched by the name the
55    /// input's `speech_metadata` gives the speaker.
56    Speakers {
57        /// `speakers`.
58        speakers: Vec<InteractionSpeech>,
59    },
60}
61
62impl InteractionSpeechConfig {
63    /// Speak with `voice`.
64    pub fn voice(voice: InteractionSpeech) -> Self {
65        Self::Voice([voice])
66    }
67
68    /// Speak each `(speaker, voice)` pair's turns in its voice.
69    pub fn speakers<S: Into<String>, V: Into<String>>(
70        speakers: impl IntoIterator<Item = (S, V)>,
71    ) -> Self {
72        Self::Speakers {
73            speakers: speakers
74                .into_iter()
75                .map(|(speaker, voice)| InteractionSpeech::voice(voice).speaker(speaker))
76                .collect(),
77        }
78    }
79}
80
81/// One voice of the Interactions `speech_config`.
82#[non_exhaustive]
83#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)]
84pub struct InteractionSpeech {
85    /// `voice`.
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub voice: Option<String>,
88    /// `language`.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub language: Option<String>,
91    /// `speaker`: the name the prompt gives the speaker.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub speaker: Option<String>,
94}
95
96impl InteractionSpeech {
97    /// Speak with `voice`.
98    pub fn voice(voice: impl Into<String>) -> Self {
99        Self {
100            voice: Some(voice.into()),
101            ..Self::default()
102        }
103    }
104
105    /// `language`.
106    pub fn language(mut self, language: impl Into<String>) -> Self {
107        self.language = Some(language.into());
108        self
109    }
110
111    /// `speaker`.
112    pub fn speaker(mut self, speaker: impl Into<String>) -> Self {
113        self.speaker = Some(speaker.into());
114        self
115    }
116}
117
118/// Create interactions with `POST /v1beta/interactions`.
119/// Streaming mode sets `alt=sse` and `stream: true`; unary mode reads a whole resource.
120#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
121pub struct Interactions {
122    /// The key and the API root.
123    pub provider: crate::providers::gemini::GeminiConfig,
124    /// The model to address.
125    pub model: String,
126    /// The model facts the encoder reads and replies are priced by.
127    #[serde(skip)]
128    pub facts: crate::catalog::ModelFacts,
129}
130
131impl Interactions {
132    /// The wire for `model`.
133    pub fn new(provider: crate::providers::gemini::GeminiConfig, model: impl Into<String>) -> Self {
134        Self {
135            provider,
136            model: model.into(),
137            facts: crate::catalog::ModelFacts::default(),
138        }
139    }
140
141    /// The same wire, encoding with `facts` and pricing its replies by
142    /// them.
143    pub fn with_facts(mut self, facts: crate::catalog::ModelFacts) -> Self {
144        self.facts = facts;
145        self
146    }
147}
148
149impl crate::wire::Wire for Interactions {
150    type Op = crate::operation::Completion;
151    type Payload = crate::wire::Encoded;
152    type Frame = crate::wire::WireFrame;
153    type Event = streaming::InteractionsEvent;
154    type Decoder<'id> = streaming::InteractionsDecoder;
155    type Reassembler = streaming::document::Interaction;
156
157    fn describe(&self) -> Descriptor<'_> {
158        Descriptor::new(PROVIDER_NAME)
159            .model(self.model.as_str())
160            .facts(&self.facts)
161            .telemetry(|_| GenAiOperation::Chat)
162            .replay(self)
163    }
164
165    fn encode(
166        &self,
167        request: CompletionRequest,
168        mode: Mode,
169    ) -> Result<crate::wire::Encoded, EncodeError> {
170        use crate::providers::internal::LogTarget;
171        // `stream` is part of the request body on this wire, so the mode is
172        // in the bytes as well as in the path.
173        let streaming = matches!(mode, Mode::Streaming);
174        let body = create_request_body(self, &request, Some(streaming))?;
175        let (path, framing, target) = match streaming {
176            true => (
177                "/v1beta/interactions?alt=sse",
178                crate::wire::Framing::Sse,
179                LogTarget::Streaming,
180            ),
181            false => (
182                "/v1beta/interactions",
183                crate::wire::Framing::Whole,
184                LogTarget::Completions,
185            ),
186        };
187        crate::providers::internal::trace_json(
188            target,
189            "Gemini interactions completion request",
190            &body,
191        );
192        let request = self.provider.post_json(path, body.into_body())?;
193        // Gemini supplies no transport request-id response header.
194        Ok(crate::wire::Encoded::new(request, framing))
195    }
196
197    fn decoder<'id>(&self) -> Self::Decoder<'id> {
198        streaming::InteractionsDecoder::default()
199    }
200}
201
202impl ReplayTarget for Interactions {
203    /// Section 6.4 of the typed-options design, for Interactions.
204    fn map_options(
205        &self,
206        request: &CompletionRequest,
207        fields: crate::completion::options::OptionFields<'_>,
208    ) -> crate::completion::options::OptionMap {
209        let model = request.model.as_deref().unwrap_or(&self.model);
210        super::options::interactions(&self.facts, model, fields)
211    }
212
213    fn facts(&self) -> Option<&crate::catalog::ModelFacts> {
214        Some(&self.facts)
215    }
216
217    fn api(&self) -> crate::message::Api {
218        API
219    }
220
221    fn provider(&self) -> &str {
222        PROVIDER_NAME
223    }
224
225    fn model(&self) -> &str {
226        &self.model
227    }
228
229    /// What the model reads, by the classifier every Gemini wire shares.
230    fn accepts(&self, model: &str) -> crate::completion::Accepts {
231        super::completion::accepts(model)
232    }
233
234    fn encodes(&self, _model: &str, media: Media<'_>) -> bool {
235        encodes(media)
236    }
237
238    /// A request naming `previous_interaction_id` continues an interaction
239    /// the API stored, which holds the calls its first results answer.
240    fn continues_stored(&self, request: &CompletionRequest) -> bool {
241        crate::completion::options::param(self, request, "previous_interaction_id")
242            .is_some_and(|id| !id.is_null())
243    }
244
245    fn normalize_tool_call_id(
246        &self,
247        id: &str,
248        _model: &str,
249        _: Option<&crate::message::Origin>,
250    ) -> String {
251        crate::providers::internal::wire_ids::legal_call_id(id, 64)
252    }
253
254    /// Gemini takes system text only in `systemInstruction`: later system
255    /// messages fold into the leading one.
256    fn later_system(&self, _model: &str) -> crate::completion::LaterSystem {
257        crate::completion::LaterSystem::Leading
258    }
259
260    fn call_id_slot(&self) -> Option<&'static str> {
261        Some("/id")
262    }
263
264    fn blob_slots(&self) -> &'static [&'static str] {
265        BLOB_SLOTS
266    }
267
268    /// A step's `id` survives an edit of its block.
269    fn identity(&self, item: &Value) -> Map<String, Value> {
270        item.get("id")
271            .map(|id| Map::from_iter([("id".to_owned(), id.clone())]))
272            .unwrap_or_default()
273    }
274}
275
276/// Whether this API takes `media`: data or a URL with a media type, an
277/// image of a type Gemini reads, a PDF, and a text document, which is sent
278/// as text. A file id is never taken.
279fn encodes(media: Media<'_>) -> bool {
280    let carried = |source: &Source| matches!(source, Source::Url(_) | Source::Base64(_));
281    match media {
282        Media::Image(image, place) => {
283            super::completion::reads_image(image.media_type.as_ref(), place) && carried(&image.data)
284        }
285        Media::Audio(audio) => audio.media_type.is_some() && carried(&audio.data),
286        Media::Video(video) => video.media_type.is_some() && carried(&video.data),
287        Media::Document(document) => match (&document.media_type, &document.data) {
288            (_, DocumentData::Text(_)) => true,
289            (Some(DocumentMediaType::PDF), DocumentData::File(data)) => carried(data),
290            _ => false,
291        },
292    }
293}
294
295/// Read an existing interaction resource or resume its event stream.
296/// Unary mode retrieves the resource once. Streaming mode resumes after
297/// `last_event_id`, or from the beginning if no event id is supplied.
298#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
299pub struct InteractionResume {
300    /// The key and the API root.
301    pub provider: crate::providers::gemini::GeminiConfig,
302    /// The interaction to read.
303    pub interaction_id: String,
304    /// The last event the consumer saw, so a resumed stream does not
305    /// redeliver it. `None` resumes from the beginning, as the API defaults.
306    pub last_event_id: Option<String>,
307    /// The model facts the reply, from the model the interaction names, is
308    /// priced by.
309    #[serde(skip)]
310    pub facts: crate::catalog::ModelFacts,
311}
312
313impl InteractionResume {
314    /// The wire for the interaction `interaction_id`.
315    pub fn new(
316        provider: crate::providers::gemini::GeminiConfig,
317        interaction_id: impl Into<String>,
318    ) -> Self {
319        Self {
320            provider,
321            interaction_id: interaction_id.into(),
322            last_event_id: None,
323            facts: crate::catalog::ModelFacts::default(),
324        }
325    }
326
327    /// The same wire, pricing its replies by `facts`.
328    pub fn with_facts(mut self, facts: crate::catalog::ModelFacts) -> Self {
329        self.facts = facts;
330        self
331    }
332
333    /// Resume a streamed read after the event `last_event_id`.
334    pub fn after_event(mut self, last_event_id: impl Into<String>) -> Self {
335        self.last_event_id = Some(last_event_id.into());
336        self
337    }
338}
339
340impl crate::wire::Wire for InteractionResume {
341    type Op = crate::operation::Completion;
342    type Payload = crate::wire::Encoded;
343    type Frame = crate::wire::WireFrame;
344    type Event = streaming::InteractionsEvent;
345    type Decoder<'id> = streaming::InteractionsDecoder;
346    type Reassembler = streaming::document::Interaction;
347
348    /// The interaction names its own model; this wire addresses no model id.
349    /// The decoder reports the model the interaction names, which the turn's
350    /// origin takes.
351    fn describe(&self) -> Descriptor<'_> {
352        Descriptor::new(PROVIDER_NAME)
353            .facts(&self.facts)
354            .telemetry(|_| GenAiOperation::Chat)
355            .replay(self)
356    }
357
358    /// Reads an existing interaction, so the request carries no body: what
359    /// to read is the wire's own data. A request that sets options,
360    /// provider options or `additional_params` is refused, since nothing
361    /// would send them.
362    fn encode(
363        &self,
364        request: CompletionRequest,
365        mode: Mode,
366    ) -> Result<crate::wire::Encoded, EncodeError> {
367        let params = crate::completion::options::request_params(
368            self,
369            &request,
370            // `request_params` takes `additional_params.tools` (provider
371            // tools included) out of the raw layer for the base to append,
372            // so the base refuses them here or they would vanish.
373            |input| {
374                if input.raw_tools()?.is_empty() {
375                    Ok(Map::new())
376                } else {
377                    Err(EncodeError::request(
378                        "a resumed interaction takes no `additional_params.tools` or provider \
379                         tools: it is read, not created",
380                    ))
381                }
382            },
383            crate::completion::options::RawAt::Top,
384            &[],
385        )?;
386        if !params.is_empty() {
387            return Err(EncodeError::request(
388                "a resumed interaction takes no provider options or `additional_params`: it is \
389                 read, not created",
390            ));
391        }
392        let id = &self.interaction_id;
393        if !super::cached_content::is_resource_id(id) {
394            return Err(EncodeError::request(format!(
395                "`{id}` is not an interaction id: expected letters, digits, `-` and `_`, since \
396                 the id is spliced into the request path"
397            )));
398        }
399        let (path, framing) = match mode {
400            Mode::Unary => (
401                format!("/v1beta/interactions/{id}"),
402                crate::wire::Framing::Whole,
403            ),
404            Mode::Streaming => {
405                let mut query = form_urlencoded::Serializer::new(String::new());
406                query.append_pair("stream", "true");
407                if let Some(last_event_id) = &self.last_event_id {
408                    query.append_pair("last_event_id", last_event_id);
409                }
410                let path = format!("/v1beta/interactions/{id}?{}&alt=sse", query.finish());
411                (path, crate::wire::Framing::Sse)
412            }
413        };
414        let request = self
415            .provider
416            .request(http::Method::GET, &path)
417            .body(crate::wire::Body::empty())?;
418        Ok(crate::wire::Encoded::new(request, framing))
419    }
420
421    fn decoder<'id>(&self) -> Self::Decoder<'id> {
422        streaming::InteractionsDecoder::resuming(self.interaction_id.as_str())
423    }
424}
425
426impl ReplayTarget for InteractionResume {
427    /// A resumed interaction is read, not created, so every set option is
428    /// refused.
429    fn map_options(
430        &self,
431        _request: &CompletionRequest,
432        fields: crate::completion::options::OptionFields<'_>,
433    ) -> crate::completion::options::OptionMap {
434        crate::providers::internal::refuse_all(
435            fields,
436            "a resumed interaction is read, not created; its options were fixed when it was \
437             created",
438        )
439    }
440
441    fn facts(&self) -> Option<&crate::catalog::ModelFacts> {
442        Some(&self.facts)
443    }
444
445    fn api(&self) -> crate::message::Api {
446        API
447    }
448
449    fn provider(&self) -> &str {
450        PROVIDER_NAME
451    }
452
453    fn model(&self) -> &str {
454        ""
455    }
456
457    fn accepts(&self, model: &str) -> crate::completion::Accepts {
458        super::completion::accepts(model)
459    }
460
461    fn normalize_tool_call_id(
462        &self,
463        id: &str,
464        _model: &str,
465        _: Option<&crate::message::Origin>,
466    ) -> String {
467        crate::providers::internal::wire_ids::legal_call_id(id, 64)
468    }
469
470    /// Gemini takes system text only in `systemInstruction`: later system
471    /// messages fold into the leading one.
472    fn later_system(&self, _model: &str) -> crate::completion::LaterSystem {
473        crate::completion::LaterSystem::Leading
474    }
475
476    fn call_id_slot(&self) -> Option<&'static str> {
477        Some("/id")
478    }
479
480    fn blob_slots(&self) -> &'static [&'static str] {
481        BLOB_SLOTS
482    }
483}
484
485/// The create-interaction body `request` sends on `wire`: the wire's own
486/// encoding, then the mapped options, then `additional_params`, merged by
487/// [`request_params`](crate::completion::options::request_params). Its
488/// `generation_config` merges over the typed fields key by key, its `tools`
489/// add to the request's, and an `agent` takes the place of the model.
490/// System messages become the system instruction. `stream`, when set,
491/// overrides the one the parameters name.
492///
493/// # Errors
494///
495/// When an option is refused, `additional_params` is not an object, its
496/// `tools` are not an array, or it sets `response_format` without
497/// `response_mime_type`.
498pub(crate) fn create_request_body(
499    wire: &Interactions,
500    request: &CompletionRequest,
501    stream: Option<bool>,
502) -> Result<crate::completion::options::FinalBody, EncodeError> {
503    let rewrites: Vec<_> = stream
504        .map(crate::completion::options::Rewrite::Stream)
505        .into_iter()
506        .collect();
507    crate::completion::options::request_params(
508        wire,
509        request,
510        |input| create_base(wire, request, input),
511        crate::completion::options::RawAt::Top,
512        &rewrites,
513    )
514}
515
516/// The wire's own encoding of `request`: model, input steps, system
517/// instruction, tools and the typed fields in `generation_config`.
518fn create_base(
519    wire: &Interactions,
520    request: &CompletionRequest,
521    input: &mut crate::completion::options::BaseInput<'_>,
522) -> Result<Map<String, Value>, EncodeError> {
523    let model = request.model.clone().unwrap_or_else(|| wire.model.clone());
524    let set = |key: &str| input.param(key).is_some_and(|value| !value.is_null());
525    let agent = set("agent");
526    if set("response_format") && !set("response_mime_type") {
527        return Err(EncodeError::request(
528            "response_mime_type is required when response_format is set",
529        ));
530    }
531    let choice = request.tool_choice.clone().map(|choice| match choice {
532        Choice::Auto => json!("auto"),
533        Choice::None => json!("none"),
534        Choice::Required => json!("any"),
535        Choice::Specific { function_names } => {
536            json!({ "allowed_tools": { "mode": "validated", "tools": function_names } })
537        }
538    });
539    let config = crate::providers::internal::set_fields([
540        ("temperature", request.temperature.map(Value::from)),
541        ("max_output_tokens", request.max_tokens.map(Value::from)),
542        ("tool_choice", choice),
543    ]);
544    let mut tools: Vec<Value> = request
545        .tools
546        .iter()
547        .map(|tool| json!({ "type": "function", "name": tool.name, "description": tool.description, "parameters": tool.parameters }))
548        .collect();
549    tools.extend(input.raw_tools()?);
550    let (mut system, mut history) = (Vec::new(), Vec::new());
551    for message in &request.chat_history {
552        match &**message {
553            Message::System { content } => system.push(content.as_str()),
554            message => history.push(message),
555        }
556    }
557    let mut body = Map::new();
558    if !config.is_empty() {
559        body.insert("generation_config".to_owned(), Value::Object(config));
560    }
561    if !tools.is_empty() {
562        body.insert("tools".to_owned(), Value::Array(tools));
563    }
564    if !system.is_empty() {
565        body.insert("system_instruction".to_owned(), json!(system.join("\n\n")));
566    }
567    if !agent {
568        body.insert("model".to_owned(), json!(model));
569    }
570    body.insert(
571        "input".to_owned(),
572        Value::Array(steps(&history, wire, &model)?),
573    );
574    Ok(body)
575}
576
577/// The steps `history` sends: a user message's content grouped into
578/// `user_input` steps around its function results, each a step of its own,
579/// and one step per assistant block.
580fn steps(
581    history: &[&Message],
582    target: &dyn ReplayTarget,
583    model: &str,
584) -> Result<Vec<Value>, EncodeError> {
585    let ids = WireIds::for_target(history, target, model);
586    let mut steps = Vec::new();
587    for message in history {
588        match message {
589            Message::System { content } => {
590                steps.push(json!({ "type": "user_input", "content": [{ "type": "text", "text": content }] }));
591            }
592            Message::User { content } => {
593                let mut run = Vec::new();
594                for part in content {
595                    let UserContent::ToolResult(result) = part else {
596                        run.push(user_content(part)?);
597                        continue;
598                    };
599                    if !run.is_empty() {
600                        steps.push(user_input(std::mem::take(&mut run)));
601                    }
602                    let value = match result.content.as_slice() {
603                        [ToolResultContent::Text(text)] => Value::from(text.text.as_str()),
604                        // A scalar or array JSON result is wrapped as the
605                        // generate wire wraps it: sent as a text block it is a
606                        // multimodal response, which the models refuse.
607                        [
608                            ToolResultContent::Json {
609                                value: value @ (Value::String(_) | Value::Object(_)),
610                            },
611                        ] => value.clone(),
612                        [ToolResultContent::Json { value }] => json!({ "result": value }),
613                        contents => Value::Array(
614                            contents
615                                .iter()
616                                .map(result_content)
617                                .collect::<Result<_, _>>()?,
618                        ),
619                    };
620                    let mut step = Map::from_iter([
621                        ("type".to_owned(), Value::from("function_result")),
622                        ("name".to_owned(), Value::from(result.name.as_str())),
623                        ("call_id".to_owned(), Value::from(ids.of(&result.call))),
624                        ("result".to_owned(), value),
625                    ]);
626                    if result.is_error {
627                        step.insert("is_error".to_owned(), Value::Bool(true));
628                    }
629                    steps.push(Value::Object(step));
630                }
631                if !run.is_empty() {
632                    steps.push(user_input(run));
633                }
634            }
635            Message::Assistant(turn) => {
636                for block in &turn.content {
637                    steps.extend(assistant_step(block, target, &ids)?);
638                }
639            }
640        }
641    }
642    Ok(steps)
643}
644
645/// A `user_input` step of `content`.
646fn user_input(content: Vec<Value>) -> Value {
647    Value::Object(Map::from_iter([
648        ("type".to_owned(), Value::from("user_input")),
649        ("content".to_owned(), Value::Array(content)),
650    ]))
651}
652
653/// A block of a tool result as a content item.
654fn result_content(content: &ToolResultContent) -> Result<Value, EncodeError> {
655    Ok(match content {
656        ToolResultContent::Text(text) => json!({ "type": "text", "text": text.text }),
657        ToolResultContent::Json { value } => json!({ "type": "text", "text": value.to_string() }),
658        ToolResultContent::Image(image) => media("image", image.media_type.clone(), &image.data)?,
659    })
660}
661
662/// A user part as a content item. A text document goes as text, so that RAG
663/// context reads as prose.
664fn user_content(part: &UserContent) -> Result<Value, EncodeError> {
665    match part {
666        UserContent::Text(text) => Ok(json!({ "type": "text", "text": text.text })),
667        UserContent::Image(image) => media("image", image.media_type.clone(), &image.data),
668        UserContent::Audio(audio) => media("audio", audio.media_type.clone(), &audio.data),
669        UserContent::Video(video) => media("video", video.media_type.clone(), &video.data),
670        UserContent::Document(document) => match &document.data {
671            DocumentData::Text(text) => Ok(json!({ "type": "text", "text": text })),
672            DocumentData::File(data) => media("document", document.media_type.clone(), data),
673        },
674        UserContent::ToolResult(_) => {
675            Err(EncodeError::request("a tool result is a step of its own"))
676        }
677    }
678}
679
680/// A media content item of `kind`: a URL as its `uri`, and base64 data as its
681/// `data`. [`encodes`] refuses every other form, so the adapter passes none.
682fn media<M: MimeType>(
683    kind: &str,
684    media_type: Option<M>,
685    source: &Source,
686) -> Result<Value, EncodeError> {
687    let unsendable = || {
688        EncodeError::request(format!(
689            "Gemini Interactions cannot receive this {kind} in its form"
690        ))
691    };
692    let mime_type = media_type.ok_or_else(unsendable)?.to_mime_type().to_owned();
693    let key = match super::completion::carried(source)? {
694        (true, uri) => ("uri", uri),
695        (false, data) => ("data", data),
696    };
697    Ok(json!({ "type": kind, key.0: key.1, "mime_type": mime_type }))
698}
699
700/// An assistant block as its step: the provider's step while the block is
701/// current, else one rebuilt from its canonical fields, keeping the keys
702/// its edited step names; `None` for reasoning with nothing to send.
703fn assistant_step(
704    block: &AssistantContent,
705    target: &dyn ReplayTarget,
706    ids: &WireIds,
707) -> Result<Option<Value>, EncodeError> {
708    let identity = match block.replay(target, ids) {
709        Replay::Item(item) => return Ok(Some(item.into_owned())),
710        Replay::Identity(identity) => identity,
711        Replay::Rebuild => Map::new(),
712    };
713    let output = |content: Value| {
714        Value::Object(Map::from_iter([
715            ("type".to_owned(), Value::from("model_output")),
716            ("content".to_owned(), Value::Array(vec![content])),
717        ]))
718    };
719    let mut step = match block {
720        AssistantContent::Text(text) => output(json!({ "type": "text", "text": text.text })),
721        AssistantContent::Reasoning(reasoning)
722            if reasoning.redacted || reasoning.text.trim().is_empty() =>
723        {
724            return Ok(None);
725        }
726        AssistantContent::Reasoning(reasoning) => {
727            json!({ "type": "thought", "summary": [{ "type": "text", "text": reasoning.text }] })
728        }
729        AssistantContent::ToolCall(call) => json!({
730            "type": "function_call",
731            "name": call.function.name,
732            "arguments": call.function.arguments,
733        }),
734        AssistantContent::Image(image) => {
735            output(media("image", image.media_type.clone(), &image.data)?)
736        }
737        AssistantContent::Opaque(opaque) => return Ok(Some(opaque.item.clone())),
738    };
739    if let Some(fields) = step.as_object_mut() {
740        fields.extend(identity);
741        if let AssistantContent::ToolCall(call) = block {
742            fields.insert("id".to_owned(), json!(ids.of(&call.id)));
743        }
744    }
745    Ok(Some(step))
746}
747
748#[cfg(test)]
749mod tests;
750
751#[cfg(test)]
752mod history_tests;