1use 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
27pub mod streaming;
29
30use super::completion::PROVIDER_NAME;
31
32pub const DEEP_RESEARCH_PREVIEW_04_2026: &str = "deep-research-preview-04-2026";
36pub const DEEP_RESEARCH_MAX_PREVIEW_04_2026: &str = "deep-research-max-preview-04-2026";
39
40const API: crate::message::Api = crate::message::Api::from_static("gemini.interactions");
42
43const BLOB_SLOTS: &[&str] = &["/signature"];
45
46#[non_exhaustive]
49#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
50#[serde(untagged)]
51pub enum InteractionSpeechConfig {
52 Voice([InteractionSpeech; 1]),
54 Speakers {
57 speakers: Vec<InteractionSpeech>,
59 },
60}
61
62impl InteractionSpeechConfig {
63 pub fn voice(voice: InteractionSpeech) -> Self {
65 Self::Voice([voice])
66 }
67
68 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#[non_exhaustive]
83#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)]
84pub struct InteractionSpeech {
85 #[serde(skip_serializing_if = "Option::is_none")]
87 pub voice: Option<String>,
88 #[serde(skip_serializing_if = "Option::is_none")]
90 pub language: Option<String>,
91 #[serde(skip_serializing_if = "Option::is_none")]
93 pub speaker: Option<String>,
94}
95
96impl InteractionSpeech {
97 pub fn voice(voice: impl Into<String>) -> Self {
99 Self {
100 voice: Some(voice.into()),
101 ..Self::default()
102 }
103 }
104
105 pub fn language(mut self, language: impl Into<String>) -> Self {
107 self.language = Some(language.into());
108 self
109 }
110
111 pub fn speaker(mut self, speaker: impl Into<String>) -> Self {
113 self.speaker = Some(speaker.into());
114 self
115 }
116}
117
118#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
121pub struct Interactions {
122 pub provider: crate::providers::gemini::GeminiConfig,
124 pub model: String,
126 #[serde(skip)]
128 pub facts: crate::catalog::ModelFacts,
129}
130
131impl Interactions {
132 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 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 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 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 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 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 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 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 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
276fn 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#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
299pub struct InteractionResume {
300 pub provider: crate::providers::gemini::GeminiConfig,
302 pub interaction_id: String,
304 pub last_event_id: Option<String>,
307 #[serde(skip)]
310 pub facts: crate::catalog::ModelFacts,
311}
312
313impl InteractionResume {
314 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 pub fn with_facts(mut self, facts: crate::catalog::ModelFacts) -> Self {
329 self.facts = facts;
330 self
331 }
332
333 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 fn describe(&self) -> Descriptor<'_> {
352 Descriptor::new(PROVIDER_NAME)
353 .facts(&self.facts)
354 .telemetry(|_| GenAiOperation::Chat)
355 .replay(self)
356 }
357
358 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 |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 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 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
485pub(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
516fn 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
577fn 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 [
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
645fn 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
653fn 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
662fn 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
680fn 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
700fn 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;