Skip to main content

gadk_model/
live.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Live (bidi streaming) connection abstraction: [`LiveConnection`], its error type and the
17//! rule for when a failed connection can be resumed.
18
19use std::error::Error;
20use std::fmt;
21
22use async_trait::async_trait;
23use gadk_genai::{Blob, Content};
24
25use crate::LlmResponse;
26
27/// Realtime input for [`LiveConnection::send_realtime`]: a blob, activity start/end markers
28/// and the end of the audio stream. Moved from gadk-gemini, which re-exports it.
29#[derive(Debug, Clone, PartialEq)]
30pub enum RealtimeInput {
31    /// Audio or image data. An empty MIME type is detected by the connection.
32    Blob(Blob),
33    /// Start of user activity (manual activity detection).
34    ActivityStart,
35    /// End of user activity (manual activity detection).
36    ActivityEnd,
37    /// The audio stream has ended (automatic activity detection).
38    AudioStreamEnd,
39}
40
41/// What kind of failure a [`LiveConnError`] is, as [`LiveConnError::is_resumable`] checks it.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43#[non_exhaustive]
44pub enum LiveConnErrorKind {
45    /// The socket of an established connection failed, or the stream ended without a close
46    /// frame.
47    ConnectionLost,
48    /// A close frame was received; a frame without a payload is 1005.
49    Closed {
50        /// The close code.
51        code: u16,
52    },
53    /// Anything else.
54    Other,
55}
56
57/// A failure on a live connection. `message` is the full error text.
58#[derive(Debug)]
59pub struct LiveConnError {
60    /// The classification.
61    pub kind: LiveConnErrorKind,
62    /// The full error text.
63    pub message: String,
64    /// The underlying error, if any.
65    pub source: Option<Box<dyn Error + Send + Sync>>,
66}
67
68/// The text fragments that mark an error as a lost connection.
69const RESUMABLE_TEXT: [&str; 4] = ["broken pipe", "connection reset", "EOF", "GoAway"];
70
71/// The WebSocket close code for a policy violation.
72const CLOSE_POLICY_VIOLATION: u16 = 1008;
73
74impl LiveConnError {
75    /// An error with no source.
76    pub fn new(kind: LiveConnErrorKind, message: impl Into<String>) -> Self {
77        Self {
78            kind,
79            message: message.into(),
80            source: None,
81        }
82    }
83
84    /// Attaches the underlying error.
85    pub fn with_source(mut self, source: impl Into<Box<dyn Error + Send + Sync>>) -> Self {
86        self.source = Some(source.into());
87        self
88    }
89
90    /// The stream ended without a close frame.
91    pub fn eof() -> Self {
92        Self::new(LiveConnErrorKind::ConnectionLost, "EOF")
93    }
94
95    /// Whether the session can be resumed after this error: a lost connection, a close frame
96    /// with code 1008, or text naming a dropped connection. The text rule applies to every
97    /// kind, including a close frame with any other code.
98    pub fn is_resumable(&self) -> bool {
99        match self.kind {
100            LiveConnErrorKind::ConnectionLost => true,
101            LiveConnErrorKind::Closed { code } if code == CLOSE_POLICY_VIOLATION => true,
102            _ => RESUMABLE_TEXT.iter().any(|t| self.message.contains(t)),
103        }
104    }
105}
106
107impl fmt::Display for LiveConnError {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        f.write_str(&self.message)
110    }
111}
112
113impl Error for LiveConnError {
114    fn source(&self) -> Option<&(dyn Error + 'static)> {
115        self.source.as_deref().map(|e| e as &(dyn Error + 'static))
116    }
117}
118
119/// A live (bidi streaming) connection to a model, model-agnostic. `recv` must be cancel-safe
120/// and may run concurrently with a send.
121#[async_trait]
122pub trait LiveConnection: Send + Sync {
123    /// Sends the earlier conversation turns to the model.
124    async fn send_history(&self, history: &[Content]) -> Result<(), LiveConnError>;
125    /// Sends one content turn.
126    async fn send_content(&self, content: Content) -> Result<(), LiveConnError>;
127    /// Sends realtime input (audio or image data, or an activity marker).
128    async fn send_realtime(&self, input: RealtimeInput) -> Result<(), LiveConnError>;
129    /// Receives the next response. `Ok(None)`: the stream ended without a close frame (callers
130    /// treat it as [`LiveConnError::eof`]). A received close frame is `Err` with kind
131    /// `Closed { code }`.
132    async fn recv(&self) -> Result<Option<LlmResponse>, LiveConnError>;
133    /// Closes the connection.
134    async fn close(&self) -> Result<(), LiveConnError>;
135}
136
137#[cfg(test)]
138#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
139mod tests {
140    use std::any::Any;
141    use std::error::Error;
142
143    use futures::stream::BoxStream;
144    use gadk_genai::LiveConnectConfig;
145
146    use super::{LiveConnError, LiveConnErrorKind};
147    use crate::{Llm, LlmRequest, LlmResponse, ModelError};
148
149    struct NoLive;
150
151    impl Llm for NoLive {
152        fn name(&self) -> &str {
153            "no-live"
154        }
155        fn generate_content(
156            &self,
157            _req: LlmRequest,
158            _stream: bool,
159        ) -> BoxStream<'static, Result<LlmResponse, ModelError>> {
160            Box::pin(futures::stream::empty())
161        }
162        fn as_any(&self) -> &dyn Any {
163            self
164        }
165    }
166
167    #[tokio::test]
168    async fn live_default_connect_live_is_unsupported() {
169        let m: &dyn Llm = &NoLive;
170        let Err(err) = m.connect_live(LiveConnectConfig::default()).await else {
171            panic!("the default connect_live must fail");
172        };
173        assert!(matches!(err, ModelError::Other(_)), "{err:?}");
174        assert_eq!(err.to_string(), "model does not support live connection");
175    }
176
177    fn other(msg: &str) -> LiveConnError {
178        LiveConnError::new(LiveConnErrorKind::Other, msg)
179    }
180
181    #[test]
182    fn live_is_resumable_follows_go_is_resumable() {
183        let cases: Vec<(&str, LiveConnError, bool)> = vec![
184            ("eof", LiveConnError::eof(), true),
185            (
186                "connection lost",
187                LiveConnError::new(
188                    LiveConnErrorKind::ConnectionLost,
189                    "failed to send message: IO error: x",
190                ),
191                true,
192            ),
193            (
194                "close 1008",
195                LiveConnError::new(
196                    LiveConnErrorKind::Closed { code: 1008 },
197                    "websocket: close 1008 (policy violation)",
198                ),
199                true,
200            ),
201            (
202                "close 1002",
203                LiveConnError::new(
204                    LiveConnErrorKind::Closed { code: 1002 },
205                    "websocket: close 1002 (protocol error): fatal",
206                ),
207                false,
208            ),
209            // Go falls through to the text rule after a non-1008 close error.
210            (
211                "close 1002 with EOF in reason",
212                LiveConnError::new(
213                    LiveConnErrorKind::Closed { code: 1002 },
214                    "websocket: close 1002 (protocol error): unexpected EOF",
215                ),
216                true,
217            ),
218            (
219                "close 1002 with 1008 in reason",
220                LiveConnError::new(
221                    LiveConnErrorKind::Closed { code: 1002 },
222                    "websocket: close 1002 (protocol error): error 1008",
223                ),
224                false,
225            ),
226            ("broken pipe text", other("write: broken pipe"), true),
227            (
228                "connection reset text",
229                other("read: connection reset by peer"),
230                true,
231            ),
232            (
233                "EOF text",
234                other(
235                    "failed to receive message: websocket: close 1006 (abnormal closure): unexpected EOF",
236                ),
237                true,
238            ),
239            ("GoAway text", other("GoAway received"), true),
240            (
241                "1008 in a port is not a code",
242                other(
243                    "failed to receive message: read tcp 127.0.0.1:41008->127.0.0.1:42207: i/o timeout",
244                ),
245                false,
246            ),
247            (
248                "application error",
249                other("model refused the request"),
250                false,
251            ),
252        ];
253        for (name, err, want) in cases {
254            assert_eq!(err.is_resumable(), want, "{name}: {err}");
255        }
256    }
257
258    #[test]
259    fn live_display_is_message_and_source_is_kept() {
260        let src = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pipe");
261        let err = LiveConnError::new(
262            LiveConnErrorKind::ConnectionLost,
263            "failed to send message: pipe",
264        )
265        .with_source(src);
266        assert_eq!(err.to_string(), "failed to send message: pipe");
267        assert_eq!(err.kind, LiveConnErrorKind::ConnectionLost);
268        let source = err.source().expect("source kept");
269        assert!(source.downcast_ref::<std::io::Error>().is_some());
270        let eof = LiveConnError::eof();
271        assert_eq!(
272            (eof.kind, eof.message.as_str()),
273            (LiveConnErrorKind::ConnectionLost, "EOF")
274        );
275        assert!(eof.source.is_none());
276    }
277}