adk-gemini 3.0.0

Rust client for Google Gemini API
Documentation
//! Server-Sent Events (SSE) types for streaming interactions.
//!
//! When `stream = true`, `POST /v1beta/interactions` returns an SSE stream of
//! [`InteractionSseEvent`] values rather than a single [`Interaction`]. The event
//! model replaces the legacy `content.*` events with a step-oriented model:
//!
//! - `interaction.created` — the interaction resource was created (in progress).
//! - `step.start` — a new step begins. It carries the step's type and may already carry
//!   content: a `function_call` step's `name` and `id`, a `model_output` step's first
//!   content blocks, or a `thought` step's signature.
//! - `step.delta` — incremental content for the in-flight step.
//! - `step.stop` — the current step is complete.
//! - `interaction.status_update` — a lifecycle status change.
//! - `interaction.completed` — the interaction finished (no steps; accumulate the
//!   `step.start` and `step.delta` content for the output).
//! - `error` — a terminal error occurred.
//!
//! The stream ends with an `event: done` whose data is `[DONE]`, which is not an
//! [`InteractionSseEvent`]; the stream skips it. See
//! <https://aistudio.google.com/docs/streaming>.

use super::model::{
    AudioContent, Content, DocumentContent, ImageContent, Interaction, InteractionStatus, Step,
    VideoContent,
};
use serde::{Deserialize, Serialize};

/// A streamed interaction event.
///
/// Discriminated on the `event_type` field. Unknown future event types
/// deserialize into [`InteractionSseEvent::Other`] rather than failing the stream.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "event_type", rename_all = "snake_case")]
pub enum InteractionSseEvent {
    /// The interaction resource was created and is in progress.
    #[serde(rename = "interaction.created")]
    InteractionCreated {
        /// The newly created interaction (status `in_progress`).
        interaction: Interaction,
        /// Token for resuming the stream from this event.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        event_id: Option<String>,
    },
    /// The interaction completed. Steps are empty to reduce payload size —
    /// accumulate the preceding `step.delta` events for the output.
    #[serde(rename = "interaction.completed")]
    InteractionCompleted {
        /// The completed interaction (typically with empty steps).
        interaction: Interaction,
        /// Token for resuming the stream from this event.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        event_id: Option<String>,
    },
    /// A lifecycle status change for the interaction.
    #[serde(rename = "interaction.status_update")]
    InteractionStatusUpdate {
        /// The interaction ID this update applies to.
        interaction_id: String,
        /// The new status.
        status: InteractionStatus,
        /// Token for resuming the stream from this event.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        event_id: Option<String>,
        /// Opaque checkpoint token that resumes decoding after a disconnected stream.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        continuation_token: Option<String>,
    },
    /// A new step has begun. The `step` carries the step's type and whatever content the
    /// server sends with it: a `function_call` step's `name` and `id` (its arguments follow
    /// as [`StepDelta::ArgumentsDelta`]), a `model_output` step's first content blocks, or a
    /// `thought` step's signature. Further content arrives as `step.delta` events.
    #[serde(rename = "step.start")]
    StepStart {
        /// The index of the step in the timeline.
        index: i64,
        /// The step as the server starts it.
        step: Step,
        /// Token for resuming the stream from this event.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        event_id: Option<String>,
    },
    /// Incremental content for the in-flight step at `index`.
    #[serde(rename = "step.delta")]
    StepDelta {
        /// The index of the step this delta belongs to.
        index: i64,
        /// The incremental content fragment.
        delta: StepDelta,
        /// Token for resuming the stream from this event.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        event_id: Option<String>,
    },
    /// The step at `index` is complete.
    #[serde(rename = "step.stop")]
    StepStop {
        /// The index of the completed step.
        index: i64,
        /// Token for resuming the stream from this event.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        event_id: Option<String>,
    },
    /// A terminal error occurred during the interaction.
    Error {
        /// The error payload.
        error: InteractionStreamError,
        /// Token for resuming the stream from this event.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        event_id: Option<String>,
    },
    /// An event type not modelled by this crate version.
    #[serde(untagged)]
    Other(serde_json::Value),
}

impl InteractionSseEvent {
    /// Returns the incremental text fragment if this is a text `step.delta`.
    ///
    /// This is the most common accumulation path: collect `text_delta()` across
    /// the stream to build the final response text.
    pub fn text_delta(&self) -> Option<&str> {
        match self {
            InteractionSseEvent::StepDelta { delta: StepDelta::Text { text }, .. } => Some(text),
            _ => None,
        }
    }
}

/// The incremental payload carried by a `step.delta` event, discriminated on `type`.
///
/// A `model_output` step streams `text`, `image`, `audio`, `document` and `video` deltas; a
/// `function_call` step streams `arguments_delta` fragments of its arguments JSON, which
/// concatenate to the arguments object; a `thought` step streams `thought_summary` items and
/// ends with a `thought_signature`. Delta types this crate version does not model
/// deserialize into [`StepDelta::Other`]. The enum is `#[non_exhaustive]`.
///
/// # Example
///
/// ```
/// use adk_gemini::interactions::StepDelta;
///
/// // https://aistudio.google.com/docs/streaming#event-step-delta
/// let delta: StepDelta = serde_json::from_str(
///     r#"{"type": "arguments_delta", "arguments": "{\"location\": \"San Francisco, CA\"}"}"#,
/// )
/// .unwrap();
/// assert_eq!(
///     delta,
///     StepDelta::ArgumentsDelta {
///         arguments: Some(r#"{"location": "San Francisco, CA"}"#.to_string())
///     }
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum StepDelta {
    /// An incremental text fragment of a `model_output` step.
    Text {
        /// The text fragment to append.
        text: String,
    },
    /// Image content of a `model_output` step.
    Image(ImageContent),
    /// Audio content of a `model_output` step.
    Audio(AudioContent),
    /// Document content of a `model_output` step.
    Document(DocumentContent),
    /// Video content of a `model_output` step.
    Video(VideoContent),
    /// A fragment of a `function_call` step's arguments, as a partial JSON string. The
    /// step's `name` and `id` arrive on its `step.start`.
    ArgumentsDelta {
        /// Partial JSON string of arguments to accumulate.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        arguments: Option<String>,
    },
    /// A `thought` step's signature, sent as the step's last delta.
    ThoughtSignature {
        /// The signature that ties the thought to the backend's generation.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        signature: Option<String>,
    },
    /// A summary item of a `thought` step, sent when `thinking_summaries` is enabled.
    ThoughtSummary {
        /// The summary item, text or image.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        content: Option<Content>,
    },
    /// A delta type not modelled by this crate version.
    #[serde(untagged)]
    Other(serde_json::Value),
}

/// An error payload from an `error` SSE event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InteractionStreamError {
    /// A human-readable error message.
    #[serde(default)]
    pub message: String,
    /// A URI/code identifying the error type.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<String>,
}