README Source History Refs Reviews Compare Notes Search Review guide ai(SMH-PLAN-AIAG0001): add the Gemini adapter through the shared conformance kit dd0f7bb66b9e38eb52107ce61a01dd0f2db05e72
Oliver Jan Krylow <oliver@bugabinga.net > · 11 Sep 2026
unsigned
Browse files Compare 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) Diff layout Auto Unified Split
smith-ai/src/gemini.rs Added new file mode 100644+300 / −0 text lines
6 + use crate ::conformance::StreamDecoder;7 + use smith::error::{ProviderFault, Result , SmithError};8 + use smith::id::{MessageId, ToolCallId};9 + use smith::stream::{StopReason, StreamEvent, Usage};13 + pub struct GeminiDecoder {15 + message_id: MessageId,17 + stop_reason: Option <StopReason>,24 + pub fn new () -> Self {26 + buffer: String ::new(),27 + message_id: MessageId::new(),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" ));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));43 + if let Some (usage) = chunk.get ("usageMetadata" ) {44 + if let Some (prompt) = usage45 + .get ("promptTokenCount" )46 + .and_then (serde_json::Value::as_u64)48 + self.usage.input_tokens = prompt;50 + if let Some (total) = usage51 + .get ("candidatesTokenCount" )52 + .and_then (serde_json::Value::as_u64)54 + self.usage.output_tokens = total;56 + if let Some (cached) = usage57 + .get ("cachedContentTokenCount" )58 + .and_then (serde_json::Value::as_u64)60 + self.usage.input_cache_hit_tokens = cached;63 + let Some (candidate) = chunk65 + .and_then (serde_json::Value::as_array)66 + .and_then (|candidates| candidates.first ())70 + if let Some (parts) = candidate72 + .and_then (|content| content.get ("parts" ))73 + .and_then (serde_json::Value::as_array)76 + if let Some (text) = part.get ("text" ).and_then (serde_json::Value::as_str)79 + events.push (StreamEvent::text_delta(self.message_id, text));81 + if let Some (call) = part.get ("functionCall" ) {85 + .and_then (serde_json::Value::as_str)86 + .ok_or_else (|| protocol ("functionCall without name" ))? ;90 + .unwrap_or_else (|| serde_json::json! ({}));91 + events.push (StreamEvent::tool_use(100 + if let Some (reason) = candidate101 + .get ("finishReason" )102 + .and_then (serde_json::Value::as_str)104 + self.stop_reason = Some (map_finish_reason (reason)? );110 + impl Default for GeminiDecoder {111 + fn default () -> Self {116 + impl 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) {122 + self.process_chunk (& data, &mut events)? ;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)? ;133 + match self.stop_reason.take () {136 + self.stopped = true ;137 + events.push (StreamEvent::stop(reason, Some (self.usage)));140 + None => Err (SmithError::Provider {141 + fault: ProviderFault::Incomplete,147 + fn 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 ();157 + let rest = buffer[consumed + line.len ().. ].to_string ();158 + return Some ((data, rest));160 + if let Some (payload) = trimmed.strip_prefix ("data:" ) {161 + data.push_str (payload.strip_prefix (' ' ).unwrap_or (payload));163 + consumed += line.len ();168 + fn map_finish_reason (reason: &str ) -> Result <StopReason> {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}" ))),177 + fn map_error (error: & serde_json::Value) -> SmithError {178 + let code = error.get ("code" ).and_then (serde_json::Value::as_i64);181 + .and_then (serde_json::Value::as_str)182 + .unwrap_or ("unknown provider error" )184 + let fault = match code {185 + Some (429 ) => ProviderFault::RateLimit {186 + retry_after_ms: None ,188 + Some (400 | 404 ) => ProviderFault::Invalid {192 + Some (401 | 403 ) => ProviderFault::Authentication { message },193 + Some (503 ) => ProviderFault::Overloaded { message },194 + Some (500 | 504 ) => ProviderFault::Transient { message },195 + _ => ProviderFault::Protocol { message },197 + SmithError::Provider { fault }200 + fn protocol (message: impl Into <String >) -> SmithError {201 + SmithError::Provider {202 + fault: ProviderFault::Protocol {203 + message: message.into (),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();217 + out.push_str ("data: " );219 + out.push_str ("\n\n" );224 + fn complete_tool_fixture () -> Fixture {226 + name: "text and complete function call" ,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"}]}"# ,234 + Expected::Text("Writing" .to_string ()),236 + name: "write" .to_string (),237 + input: serde_json::json! ({"path" : "f" , "content" : "hi" }),239 + Expected::Text(" now" .to_string ()),241 + reason: StopReason::EndTurn,245 + input_cache_hit_tokens: 2 ,246 + input_cache_write_tokens: 0 ,253 + fn fault_fixtures () -> Vec <Fixture> {256 + name: "safety filter stop" ,258 + r #"{"candidates":[{"content":{},"finishReason":"SAFETY"}]}"# ,260 + expected: vec! [Expected::Stop {261 + reason: StopReason::ContentFilter,262 + usage: Some (Usage::new()),266 + name: "quota error" ,267 + chunks: vec! [sse (& [r #"{"error":{"code":429,"message":"quota"}}"# ])],268 + expected: vec! [Expected::Fault("PROVIDER_RATE_LIMIT" .to_string ())],271 + name: "truncated without finish reason" ,273 + r #"{"candidates":[{"content":{"parts":[{"text":"partial"}]}}]}"# ,276 + Expected::Text("partial" .to_string ()),277 + Expected::Fault("PROVIDER_INCOMPLETE" .to_string ()),281 + name: "chunk after terminal" ,283 + sse (& [r #"{"candidates":[{"content":{},"finishReason":"STOP"}]}"# ]),284 + sse (& [r #"{"candidates":[{"content":{"parts":[{"text":"late"}]}}]}"# ]),288 + expected: vec! [Expected::Fault("PROVIDER_PROTOCOL" .to_string ())],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:?}" );smith-ai/src/lib.rs Modified +3 / −0 text lines
11 11 pub mod anthropic ;pub mod anthropic ;13 13 pub mod conformance ;pub mod conformance ;15 17 pub mod openai ;pub mod openai ;17 19 pub use anthropic::AnthropicDecoder;pub use anthropic::AnthropicDecoder;18 20 pub use conformance::{Expected, Fixture, StreamDecoder};pub use conformance::{Expected, Fixture, StreamDecoder};
21 + pub use gemini::GeminiDecoder;19 22 pub use openai::OpenAiDecoder;pub use openai::OpenAiDecoder;