repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

ai(SMH-PLAN-AIAG0001): add the Gemini adapter through the shared conformance kit

dd0f7bb66b9e38eb52107ce61a01dd0f2db05e72

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Complete-in-one-part function calls, safety filter stops, and quota
errors normalize through the same decoder boundary. Gemini has no
terminal marker, so the finishReason chunk is terminal and a later
chunk is a protocol fault.

Changed files (2)

+303 / −0 text lines

Diff layout

smith-ai/src/gemini.rs

Added
new file mode 100644

+300 / −0 text lines

1//! Google Gemini stream adapter.
2//!
3//! Translates `streamGenerateContent` server-sent chunks, where function
4//! calls arrive complete in one part, into the normalized vocabulary.
5
6use crate::conformance::StreamDecoder;
7use smith::error::{ProviderFault, Result, SmithError};
8use smith::id::{MessageId, ToolCallId};
9use smith::stream::{StopReason, StreamEvent, Usage};
11/// Incremental decoder for one Gemini stream.
12#[derive(Debug)]
13pub struct GeminiDecoder {
14 buffer: String,
15 message_id: MessageId,
16 usage: Usage,
17 stop_reason: Option<StopReason>,
18 stopped: bool,
19}
21impl GeminiDecoder {
22 /// A decoder for a fresh assistant message.
23 #[must_use]
24 pub fn new() -> Self {
25 Self {
26 buffer: String::new(),
27 message_id: MessageId::new(),
28 usage: Usage::new(),
29 stop_reason: None,
30 stopped: false,
31 }
32 }
34 fn process_chunk(&mut self, data: &str, events: &mut Vec<StreamEvent>) -> Result<()> {
35 if self.stopped || self.stop_reason.is_some() {
36 return Err(protocol("chunk after terminal"));
37 }
38 let chunk: serde_json::Value = serde_json::from_str(data.trim())
39 .map_err(|e| protocol(format!("chunk is not JSON: {e}")))?;
40 if let Some(error) = chunk.get("error") {
41 return Err(map_error(error));
42 }
43 if let Some(usage) = chunk.get("usageMetadata") {
44 if let Some(prompt) = usage
45 .get("promptTokenCount")
46 .and_then(serde_json::Value::as_u64)
47 {
48 self.usage.input_tokens = prompt;
49 }
50 if let Some(total) = usage
51 .get("candidatesTokenCount")
52 .and_then(serde_json::Value::as_u64)
53 {
54 self.usage.output_tokens = total;
55 }
56 if let Some(cached) = usage
57 .get("cachedContentTokenCount")
58 .and_then(serde_json::Value::as_u64)
59 {
60 self.usage.input_cache_hit_tokens = cached;
61 }
62 }
63 let Some(candidate) = chunk
64 .get("candidates")
65 .and_then(serde_json::Value::as_array)
66 .and_then(|candidates| candidates.first())
67 else {
68 return Ok(());
69 };
70 if let Some(parts) = candidate
71 .get("content")
72 .and_then(|content| content.get("parts"))
73 .and_then(serde_json::Value::as_array)
74 {
75 for part in parts {
76 if let Some(text) = part.get("text").and_then(serde_json::Value::as_str)
77 && !text.is_empty()
78 {
79 events.push(StreamEvent::text_delta(self.message_id, text));
80 }
81 if let Some(call) = part.get("functionCall") {
82 // Gemini delivers function calls complete in one part.
83 let name = call
84 .get("name")
85 .and_then(serde_json::Value::as_str)
86 .ok_or_else(|| protocol("functionCall without name"))?;
87 let input = call
88 .get("args")
89 .cloned()
90 .unwrap_or_else(|| serde_json::json!({}));
91 events.push(StreamEvent::tool_use(
92 self.message_id,
93 name,
94 input,
95 ToolCallId::new(),
96 ));
97 }
98 }
99 }
100 if let Some(reason) = candidate
101 .get("finishReason")
102 .and_then(serde_json::Value::as_str)
103 {
104 self.stop_reason = Some(map_finish_reason(reason)?);
105 }
106 Ok(())
107 }
108}
110impl Default for GeminiDecoder {
111 fn default() -> Self {
112 Self::new()
113 }
114}
116impl StreamDecoder for GeminiDecoder {
117 fn push(&mut self, bytes: &[u8]) -> Result<Vec<StreamEvent>> {
118 self.buffer.push_str(&String::from_utf8_lossy(bytes));
119 let mut events = Vec::new();
120 while let Some((data, rest)) = take_sse_data(&self.buffer) {
121 self.buffer = rest;
122 self.process_chunk(&data, &mut events)?;
123 }
124 Ok(events)
125 }
127 fn finish(&mut self) -> Result<Vec<StreamEvent>> {
128 let mut events = Vec::new();
129 if !self.buffer.trim().is_empty() {
130 let data = std::mem::take(&mut self.buffer);
131 self.process_chunk(data.trim_end(), &mut events)?;
132 }
133 match self.stop_reason.take() {
134 // Gemini has no terminal marker; the finishReason chunk is terminal.
135 Some(reason) => {
136 self.stopped = true;
137 events.push(StreamEvent::stop(reason, Some(self.usage)));
138 Ok(events)
139 }
140 None => Err(SmithError::Provider {
141 fault: ProviderFault::Incomplete,
142 }),
143 }
144 }
145}
147fn take_sse_data(buffer: &str) -> Option<(String, String)> {
148 let mut data = String::new();
149 let mut consumed = 0;
150 for line in buffer.split_inclusive('\n') {
151 let trimmed = line.trim_end_matches(['\r', '\n']);
152 if trimmed.is_empty() {
153 if data.is_empty() {
154 consumed += line.len();
155 continue;
156 }
157 let rest = buffer[consumed + line.len()..].to_string();
158 return Some((data, rest));
159 }
160 if let Some(payload) = trimmed.strip_prefix("data:") {
161 data.push_str(payload.strip_prefix(' ').unwrap_or(payload));
162 }
163 consumed += line.len();
164 }
165 None
166}
168fn map_finish_reason(reason: &str) -> Result<StopReason> {
169 match reason {
170 "STOP" => Ok(StopReason::EndTurn),
171 "MAX_TOKENS" => Ok(StopReason::Limit),
172 "SAFETY" | "PROHIBITED_CONTENT" | "RECITATION" => Ok(StopReason::ContentFilter),
173 other => Err(protocol(format!("unmapped finishReason {other}"))),
174 }
175}
177fn map_error(error: &serde_json::Value) -> SmithError {
178 let code = error.get("code").and_then(serde_json::Value::as_i64);
179 let message = error
180 .get("message")
181 .and_then(serde_json::Value::as_str)
182 .unwrap_or("unknown provider error")
183 .to_string();
184 let fault = match code {
185 Some(429) => ProviderFault::RateLimit {
186 retry_after_ms: None,
187 },
188 Some(400 | 404) => ProviderFault::Invalid {
189 field: None,
190 message,
191 },
192 Some(401 | 403) => ProviderFault::Authentication { message },
193 Some(503) => ProviderFault::Overloaded { message },
194 Some(500 | 504) => ProviderFault::Transient { message },
195 _ => ProviderFault::Protocol { message },
196 };
197 SmithError::Provider { fault }
198}
200fn protocol(message: impl Into<String>) -> SmithError {
201 SmithError::Provider {
202 fault: ProviderFault::Protocol {
203 message: message.into(),
204 },
205 }
206}
208#[cfg(test)]
209mod tests {
210 use super::*;
211 use crate::conformance::{Expected, Fixture, conformance_report};
212 use smith::stream::StopReason;
214 fn sse(lines: &[&str]) -> Vec<u8> {
215 let mut out = String::new();
216 for line in lines {
217 out.push_str("data: ");
218 out.push_str(line);
219 out.push_str("\n\n");
220 }
221 out.into_bytes()
222 }
224 fn complete_tool_fixture() -> Fixture {
225 Fixture {
226 name: "text and complete function call",
227 chunks: vec![sse(&[
228 r#"{"candidates":[{"content":{"parts":[{"text":"Writing"}]}}]}"#,
229 r#"{"candidates":[{"content":{"parts":[{"functionCall":{"name":"write","args":{"path":"f","content":"hi"}}}]}}],"usageMetadata":{"promptTokenCount":5,"candidatesTokenCount":9,"cachedContentTokenCount":2}}"#,
230 r#"{"candidates":[{"content":{"parts":[{"text":" now"}]}}]}"#,
231 r#"{"candidates":[{"content":{},"finishReason":"STOP"}]}"#,
232 ])],
233 expected: vec![
234 Expected::Text("Writing".to_string()),
235 Expected::Tool {
236 name: "write".to_string(),
237 input: serde_json::json!({"path": "f", "content": "hi"}),
238 },
239 Expected::Text(" now".to_string()),
240 Expected::Stop {
241 reason: StopReason::EndTurn,
242 usage: Some(Usage {
243 input_tokens: 5,
244 output_tokens: 9,
245 input_cache_hit_tokens: 2,
246 input_cache_write_tokens: 0,
247 }),
248 },
249 ],
250 }
251 }
253 fn fault_fixtures() -> Vec<Fixture> {
254 vec![
255 Fixture {
256 name: "safety filter stop",
257 chunks: vec![sse(&[
258 r#"{"candidates":[{"content":{},"finishReason":"SAFETY"}]}"#,
259 ])],
260 expected: vec![Expected::Stop {
261 reason: StopReason::ContentFilter,
262 usage: Some(Usage::new()),
263 }],
264 },
265 Fixture {
266 name: "quota error",
267 chunks: vec![sse(&[r#"{"error":{"code":429,"message":"quota"}}"#])],
268 expected: vec![Expected::Fault("PROVIDER_RATE_LIMIT".to_string())],
269 },
270 Fixture {
271 name: "truncated without finish reason",
272 chunks: vec![sse(&[
273 r#"{"candidates":[{"content":{"parts":[{"text":"partial"}]}}]}"#,
274 ])],
275 expected: vec![
276 Expected::Text("partial".to_string()),
277 Expected::Fault("PROVIDER_INCOMPLETE".to_string()),
278 ],
279 },
280 Fixture {
281 name: "chunk after terminal",
282 chunks: vec![
283 sse(&[r#"{"candidates":[{"content":{},"finishReason":"STOP"}]}"#]),
284 sse(&[r#"{"candidates":[{"content":{"parts":[{"text":"late"}]}}]}"#]),
285 ],
286 // The terminal Stop is emitted by finish(); the late chunk
287 // faults first, so the stream ends in the protocol fault.
288 expected: vec![Expected::Fault("PROVIDER_PROTOCOL".to_string())],
289 },
290 ]
291 }
293 #[test]
294 fn gemini_adapter_satisfies_conformance() {
295 let mut fixtures = vec![complete_tool_fixture()];
296 fixtures.extend(fault_fixtures());
297 let failures = conformance_report(&|| Box::new(GeminiDecoder::new()), &fixtures);
298 assert!(failures.is_empty(), "{failures:?}");
299 }
300}

smith-ai/src/lib.rs

Modified

+3 / −0 text lines

1111pub mod anthropic;
1212/// Stream conformance kit shared by all vendor adapters.
1313pub mod conformance;
14/// Google Gemini adapter.
15pub mod gemini;
1416/// OpenAI-compatible chat-completions adapter.
1517pub mod openai;
1719pub use anthropic::AnthropicDecoder;
1820pub use conformance::{Expected, Fixture, StreamDecoder};
21pub use gemini::GeminiDecoder;
1922pub use openai::OpenAiDecoder;