1use super::openai::error_chain;
48use super::retry::{is_retryable_status, parse_retry_after, RetryPolicy};
49use super::{DeltaStream, Provider, ProviderError};
50use crate::pricing::PriceTable;
51use crate::secrets::redact;
52use crate::types::{
53 Completion, CompletionDelta, CompletionRequest, Message, Role, StopReason, ToolCall, Usage,
54 INVALID_TOOL_ARGS_KEY,
55};
56use serde_json::{json, Map, Value};
57use std::collections::{HashMap, VecDeque};
58use std::fmt;
59use std::sync::atomic::{AtomicU64, Ordering};
60use std::sync::Mutex;
61use std::time::Duration;
62
63pub const DEFAULT_BASE_URL: &str = "https://generativelanguage.googleapis.com/v1";
65pub const DEFAULT_API_KEY_ENV: &str = "GEMINI_API_KEY";
66
67pub const SKIP_SIGNATURE: &str = "skip_thought_signature_validator";
71
72pub const STOPPED_PREFIX: &str = "stopped:";
75
76const ERROR_BODY_LIMIT: usize = 2000;
78
79const REMEMBERED_CALLS: usize = 4096;
81
82#[derive(Debug, Clone, PartialEq, Eq)]
84struct CallMeta {
85 signature: Option<String>,
86 google_id: bool,
88}
89
90#[derive(Debug, Clone, PartialEq)]
92pub struct GoogleConfig {
93 pub base_url: Option<String>,
94 pub api_key_env: String,
95 pub config_name: String,
97 pub max_tokens: Option<u32>,
98 pub connect_timeout: Duration,
99 pub read_timeout: Duration,
101 pub max_retries: u32,
102 pub store: bool,
104}
105
106impl Default for GoogleConfig {
107 fn default() -> Self {
108 Self {
109 base_url: None,
110 api_key_env: DEFAULT_API_KEY_ENV.to_owned(),
111 config_name: "google".to_owned(),
112 max_tokens: None,
113 connect_timeout: Duration::from_secs(10),
114 read_timeout: Duration::from_secs(1200),
115 max_retries: super::retry::DEFAULT_MAX_RETRIES,
116 store: false,
117 }
118 }
119}
120
121pub struct GoogleProvider {
122 model: String,
123 url: String,
124 api_key: String,
125 config: GoogleConfig,
126 client: reqwest::Client,
127 pricing: PriceTable,
128 price_ref: String,
129 calls: Mutex<HashMap<String, CallMeta>>,
131 next_id: AtomicU64,
133}
134
135impl fmt::Debug for GoogleProvider {
136 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137 formatter
138 .debug_struct("GoogleProvider")
139 .field("model", &self.model)
140 .field("url", &self.url)
141 .field("api_key", &"***redacted***")
142 .field("config", &self.config)
143 .finish()
144 }
145}
146
147impl GoogleProvider {
148 pub fn new(
149 model: impl Into<String>,
150 config: GoogleConfig,
151 api_key: Option<String>,
152 ) -> Result<Self, ProviderError> {
153 let Some(api_key) = api_key.filter(|key| !key.is_empty()) else {
154 return Err(ProviderError::MissingApiKey {
155 env: config.api_key_env.clone(),
156 account: config.config_name.clone(),
157 });
158 };
159 let model = model.into();
160 let bare = model.strip_prefix("models/").unwrap_or(&model).to_owned();
162 let base = config
163 .base_url
164 .as_deref()
165 .unwrap_or(DEFAULT_BASE_URL)
166 .trim_end_matches('/');
167 let url = format!("{base}/models/{bare}:streamGenerateContent?alt=sse");
168 let client = build_client(&config)?;
169 Ok(Self {
170 price_ref: bare.clone(),
171 model: bare,
172 url,
173 api_key,
174 config,
175 client,
176 pricing: PriceTable::builtin(),
177 calls: Mutex::new(HashMap::new()),
178 next_id: AtomicU64::new(0),
179 })
180 }
181
182 pub fn with_pricing(mut self, pricing: PriceTable, price_ref: impl Into<String>) -> Self {
184 self.pricing = pricing;
185 self.price_ref = price_ref.into();
186 self
187 }
188
189 pub fn url(&self) -> &str {
191 &self.url
192 }
193
194 pub fn payload(&self, request: &CompletionRequest) -> Value {
196 self.prepare(request).0
197 }
198
199 fn prepare(&self, request: &CompletionRequest) -> (Value, HashMap<String, String>) {
201 let mut declared: HashMap<String, String> = HashMap::new();
202 let mut taken: Vec<String> = request.tools.iter().map(|tool| tool.name.clone()).collect();
203 let mut rename = |name: &str| -> String {
204 if let Some(known) = declared.get(name) {
205 return known.clone();
206 }
207 let wire = gemini_name(name, &taken);
208 if wire != name {
209 taken.push(wire.clone());
210 }
211 declared.insert(name.to_owned(), wire.clone());
212 wire
213 };
214 let declarations: Vec<Value> = request
215 .tools
216 .iter()
217 .map(|tool| {
218 json!({
219 "name": rename(&tool.name),
220 "description": tool.description,
221 "parametersJsonSchema": tool.parameters,
222 })
223 })
224 .collect();
225 let calls = {
226 let mut calls = self.calls.lock().unwrap_or_else(|p| p.into_inner());
227 if calls.len() > REMEMBERED_CALLS {
228 let live: std::collections::HashSet<&str> = request
229 .messages
230 .iter()
231 .flat_map(|message| message.tool_calls.iter().map(|call| call.id.as_str()))
232 .collect();
233 calls.retain(|id, _| live.contains(id.as_str()));
234 }
235 calls.clone()
236 };
237 let (system, contents) = to_contents_with(&request.messages, &calls, &mut rename);
238 let mut generation = json!({"thinkingConfig": {"includeThoughts": true}});
239 let cap = request
240 .max_tokens
241 .filter(|&cap| cap > 0)
242 .or(self.config.max_tokens.filter(|&cap| cap > 0));
243 if let Some(cap) = cap {
244 generation["maxOutputTokens"] = json!(cap);
245 }
246 let mut body = json!({
247 "contents": contents,
248 "generationConfig": generation,
249 "store": self.config.store,
250 });
251 if !system.is_empty() {
252 body["systemInstruction"] = json!({"parts": [{"text": system}]});
253 }
254 if !declarations.is_empty() {
255 body["tools"] = json!([{"functionDeclarations": declarations}]);
256 body["toolConfig"] = json!({"functionCallingConfig": {"mode": "AUTO"}});
257 }
258 let back = declared
259 .into_iter()
260 .filter(|(own, wire)| own != wire)
261 .map(|(own, wire)| (wire, own))
262 .collect();
263 (body, back)
264 }
265
266 fn redact(&self, text: &str) -> String {
267 redact(text, &[self.api_key.as_str()])
268 }
269
270 fn http_error(&self, status: u16, body: &str) -> ProviderError {
271 let body: String = self
272 .redact(body.trim())
273 .chars()
274 .take(ERROR_BODY_LIMIT)
275 .collect();
276 match status {
277 400 if body.contains("thought_signature") => ProviderError::HttpHint {
278 status,
279 body,
280 hint: "agent86 sent back a tool call without the signature Gemini gave it; \
281 this is a bug, please report it at \
282 https://github.com/Maetek-Technologies/agent86/issues"
283 .to_owned(),
284 },
285 402 => ProviderError::HttpHint {
286 status,
287 body,
288 hint: "the Google project's prepaid credits are used up; add credits in \
289 Google AI Studio's billing settings"
290 .to_owned(),
291 },
292 _ => ProviderError::Http { status, body },
293 }
294 }
295
296 fn connect_error(&self, error: &reqwest::Error) -> ProviderError {
297 if error.is_timeout() && error.is_connect() {
298 ProviderError::ConnectTimeout {
299 endpoint: self.url.clone(),
300 seconds: self.config.connect_timeout.as_secs_f64(),
301 }
302 } else if error.is_timeout() {
303 ProviderError::ReadTimeout {
304 endpoint: self.url.clone(),
305 seconds: self.config.read_timeout.as_secs_f64(),
306 }
307 } else if error.is_connect() {
308 ProviderError::Connect {
309 endpoint: self.url.clone(),
310 detail: self.redact(&error_chain(error)),
311 }
312 } else {
313 ProviderError::StreamInterrupted {
314 provider: "google".to_owned(),
315 endpoint: self.url.clone(),
316 model: self.model.clone(),
317 detail: self.redact(&error_chain(error)),
318 }
319 }
320 }
321}
322
323fn build_client(config: &GoogleConfig) -> Result<reqwest::Client, ProviderError> {
324 reqwest::Client::builder()
325 .connect_timeout(config.connect_timeout)
326 .read_timeout(config.read_timeout)
327 .build()
328 .map_err(|error| ProviderError::Client {
329 detail: error_chain(&error),
330 })
331}
332
333impl Provider for GoogleProvider {
334 fn name(&self) -> &str {
335 "google"
336 }
337
338 fn model(&self) -> &str {
339 &self.model
340 }
341
342 fn fresh(&self) -> Result<std::sync::Arc<dyn Provider>, ProviderError> {
343 Ok(std::sync::Arc::new(Self {
344 model: self.model.clone(),
345 url: self.url.clone(),
346 api_key: self.api_key.clone(),
347 config: self.config.clone(),
348 client: build_client(&self.config)?,
349 pricing: self.pricing.clone(),
350 price_ref: self.price_ref.clone(),
351 calls: Mutex::new(self.calls.lock().unwrap_or_else(|p| p.into_inner()).clone()),
352 next_id: AtomicU64::new(self.next_id.load(Ordering::Relaxed)),
353 }))
354 }
355
356 fn stream(&self, request: CompletionRequest) -> DeltaStream<'_> {
357 let (body, names) = self.prepare(&request);
358 let state = StreamState {
359 provider: self,
360 body: body.to_string(),
361 names,
362 policy: RetryPolicy::new(self.config.max_retries),
363 response: None,
364 buffer: Vec::new(),
365 pending: VecDeque::new(),
366 turn: TurnState::default(),
367 finished: false,
368 };
369 Box::pin(futures_util::stream::unfold(
370 state,
371 |mut state| async move {
372 let item = state.next_delta().await?;
373 Some((item, state))
374 },
375 ))
376 }
377}
378
379pub fn to_contents(messages: &[Message]) -> (String, Vec<Value>) {
390 to_contents_with(messages, &HashMap::new(), &mut |name: &str| name.to_owned())
391}
392
393fn to_contents_with(
397 messages: &[Message],
398 calls: &HashMap<String, CallMeta>,
399 rename: &mut dyn FnMut(&str) -> String,
400) -> (String, Vec<Value>) {
401 let mut system: Vec<&str> = Vec::new();
402 let mut contents: Vec<(String, Vec<Value>)> = Vec::new();
403 let mut names: HashMap<&str, &str> = HashMap::new();
404 let mut push = |role: &str, parts: Vec<Value>| {
405 if parts.is_empty() {
406 return;
407 }
408 match contents.last_mut() {
409 Some((last, existing)) if last == role => existing.extend(parts),
410 _ => contents.push((role.to_owned(), parts)),
411 }
412 };
413 for message in messages {
414 match message.role {
415 Role::System => {
416 if !message.content.trim().is_empty() {
417 system.push(&message.content);
418 }
419 }
420 Role::User => {
421 let parts = text_part(&message.content).into_iter().collect();
422 push("user", parts);
423 }
424 Role::Assistant => {
425 let mut parts: Vec<Value> = text_part(&message.content).into_iter().collect();
426 let signed = message.tool_calls.iter().any(|call| {
427 calls
428 .get(&call.id)
429 .is_some_and(|meta| meta.signature.is_some())
430 });
431 for (index, call) in message.tool_calls.iter().enumerate() {
432 names.insert(call.id.as_str(), call.name.as_str());
433 let args = if call.invalid_arguments().is_some() {
434 Map::new()
435 } else {
436 call.arguments.clone()
437 };
438 let meta = calls.get(&call.id);
439 let mut function = json!({"name": rename(&call.name), "args": args});
440 if meta.is_some_and(|meta| meta.google_id) {
441 function["id"] = json!(call.id);
442 }
443 let mut part = json!({"functionCall": function});
444 match meta.and_then(|meta| meta.signature.as_deref()) {
445 Some(signature) => part["thoughtSignature"] = json!(signature),
446 None if index == 0 && !signed => {
447 part["thoughtSignature"] = json!(SKIP_SIGNATURE);
448 }
449 None => {}
450 }
451 parts.push(part);
452 }
453 push("model", parts);
454 }
455 Role::Tool => {
456 let name = message
457 .name
458 .as_deref()
459 .or_else(|| {
460 message
461 .tool_call_id
462 .as_deref()
463 .and_then(|id| names.get(id).copied())
464 })
465 .unwrap_or("tool");
466 let mut response = json!({
467 "name": rename(name),
468 "response": {"result": message.content},
469 });
470 if let Some(id) = message
471 .tool_call_id
472 .as_deref()
473 .filter(|id| calls.get(*id).is_some_and(|meta| meta.google_id))
474 {
475 response["id"] = json!(id);
476 }
477 push("user", vec![json!({ "functionResponse": response })]);
478 }
479 }
480 }
481 let contents = contents
482 .into_iter()
483 .map(|(role, parts)| json!({"role": role, "parts": parts}))
484 .collect();
485 (system.join("\n\n"), contents)
486}
487
488fn text_part(text: &str) -> Option<Value> {
489 (!text.is_empty()).then(|| json!({"text": text}))
490}
491
492pub fn gemini_name(name: &str, taken: &[String]) -> String {
496 let starts_well = name
497 .chars()
498 .next()
499 .is_some_and(|ch| ch.is_ascii_alphabetic() || ch == '_');
500 if starts_well {
501 return name.to_owned();
502 }
503 let mut wire = format!("_{name}");
504 while taken.contains(&wire) {
505 wire.insert(0, '_');
506 }
507 wire
508}
509
510pub fn stop_reason(reason: Option<&str>, has_tool_calls: bool) -> Option<String> {
512 let wire = |reason: StopReason| {
513 serde_json::to_value(reason)
514 .ok()
515 .and_then(|value| value.as_str().map(str::to_owned))
516 };
517 match reason {
518 None if has_tool_calls => wire(StopReason::ToolUse),
519 None => None,
520 Some("STOP") if has_tool_calls => wire(StopReason::ToolUse),
521 Some("STOP") => wire(StopReason::EndTurn),
522 Some("MAX_TOKENS" | "CONTINUATION") => wire(StopReason::MaxTokens),
524 Some(other) => Some(format!("{STOPPED_PREFIX}{other}")),
525 }
526}
527
528#[derive(Default)]
530struct TurnState {
531 text: String,
532 thinking: String,
533 tool_calls: Vec<ToolCall>,
534 input_tokens: u64,
535 output_tokens: u64,
536 cached_tokens: u64,
537 finish_reason: Option<String>,
538 emitted: bool,
539}
540
541struct StreamState<'a> {
542 provider: &'a GoogleProvider,
543 body: String,
544 names: HashMap<String, String>,
546 policy: RetryPolicy,
547 response: Option<reqwest::Response>,
548 buffer: Vec<u8>,
549 pending: VecDeque<CompletionDelta>,
550 turn: TurnState,
551 finished: bool,
552}
553
554impl StreamState<'_> {
555 async fn next_delta(&mut self) -> Option<Result<CompletionDelta, ProviderError>> {
556 if let Some(delta) = self.pending.pop_front() {
557 return Some(Ok(delta));
558 }
559 if self.finished {
560 return None;
561 }
562 let result = self.advance().await;
563 if result.is_err() {
564 self.finished = true;
565 self.response = None;
566 }
567 result.map(|()| self.pending.pop_front()).transpose()
568 }
569
570 async fn advance(&mut self) -> Result<(), ProviderError> {
571 while self.pending.is_empty() && !self.finished {
572 if self.response.is_none() {
573 self.response = Some(self.connect().await?);
574 }
575 if let Some(line) = self.take_line() {
576 self.handle_line(&line)?;
577 continue;
578 }
579 let Some(response) = self.response.as_mut() else {
580 continue;
581 };
582 match response.chunk().await {
583 Ok(Some(bytes)) => self.buffer.extend_from_slice(&bytes),
584 Ok(None) => {
585 if !self.buffer.is_empty() {
586 let line = std::mem::take(&mut self.buffer);
587 self.handle_line(&line)?;
588 }
589 self.finish();
590 }
591 Err(error) => {
592 let failure = self.provider.connect_error(&error);
593 let retryable = !matches!(failure, ProviderError::ReadTimeout { .. });
594 match self.policy.next_delay(self.turn.emitted, None) {
595 Some(delay) if retryable => {
596 tokio::time::sleep(delay).await;
597 self.response = None;
598 self.turn = TurnState::default();
599 }
600 _ => return Err(failure),
601 }
602 }
603 }
604 }
605 Ok(())
606 }
607
608 async fn connect(&mut self) -> Result<reqwest::Response, ProviderError> {
609 let provider = self.provider;
610 loop {
611 let request = provider
612 .client
613 .post(&provider.url)
614 .header(reqwest::header::CONTENT_TYPE, "application/json")
615 .header("x-goog-api-key", &provider.api_key)
616 .body(self.body.clone());
617 let response = match request.send().await {
618 Ok(response) => response,
619 Err(error) => {
620 let failure = provider.connect_error(&error);
621 let retryable = matches!(
622 failure,
623 ProviderError::Connect { .. }
624 | ProviderError::ConnectTimeout { .. }
625 | ProviderError::StreamInterrupted { .. }
626 );
627 match self.policy.next_delay(false, None) {
628 Some(delay) if retryable => {
629 tokio::time::sleep(delay).await;
630 continue;
631 }
632 _ => return Err(failure),
633 }
634 }
635 };
636 let status = response.status().as_u16();
637 if status == 200 {
638 return Ok(response);
639 }
640 let retry_after = response
641 .headers()
642 .get(reqwest::header::RETRY_AFTER)
643 .and_then(|value| value.to_str().ok())
644 .and_then(parse_retry_after);
645 let body = response.text().await.unwrap_or_default();
646 if is_retryable_status(status) {
647 if let Some(delay) = self.policy.next_delay(false, retry_after) {
648 tokio::time::sleep(delay).await;
649 continue;
650 }
651 }
652 return Err(provider.http_error(status, &body));
653 }
654 }
655
656 fn take_line(&mut self) -> Option<Vec<u8>> {
657 let end = self.buffer.iter().position(|&byte| byte == b'\n')?;
658 let mut line: Vec<u8> = self.buffer.drain(..=end).collect();
659 line.pop();
660 Some(line)
661 }
662
663 fn handle_line(&mut self, line: &[u8]) -> Result<(), ProviderError> {
664 let line = String::from_utf8_lossy(line);
665 let line = line.trim_end_matches('\r');
666 let Some(data) = line.strip_prefix("data:") else {
667 return Ok(());
668 };
669 let data = data.trim();
670 if data.is_empty() {
671 return Ok(());
672 }
673 let chunk: Value =
674 serde_json::from_str(data).map_err(|error| ProviderError::MalformedChunk {
675 provider: "google".to_owned(),
676 endpoint: self.provider.url.clone(),
677 model: self.provider.model.clone(),
678 detail: error.to_string(),
679 })?;
680 if let Some(error) = chunk.get("error").filter(|error| error.is_object()) {
681 let status = error
682 .get("code")
683 .and_then(Value::as_u64)
684 .and_then(|code| u16::try_from(code).ok())
685 .unwrap_or(500);
686 return Err(self.provider.http_error(status, data));
687 }
688 if let Some(usage) = chunk.get("usageMetadata") {
689 let count = |key: &str| usage.get(key).and_then(Value::as_u64).unwrap_or(0);
690 self.turn.input_tokens = count("promptTokenCount") + count("toolUsePromptTokenCount");
692 self.turn.output_tokens = count("candidatesTokenCount") + count("thoughtsTokenCount");
693 self.turn.cached_tokens = count("cachedContentTokenCount");
694 }
695 if let Some(reason) = chunk
696 .pointer("/promptFeedback/blockReason")
697 .and_then(Value::as_str)
698 {
699 self.turn.finish_reason = Some(reason.to_owned());
700 }
701 let candidate = chunk.pointer("/candidates/0");
702 let parts = candidate
703 .and_then(|candidate| candidate.pointer("/content/parts"))
704 .and_then(Value::as_array);
705 for part in parts.into_iter().flatten() {
706 self.part(part);
707 }
708 if let Some(reason) = candidate
709 .and_then(|candidate| candidate.get("finishReason"))
710 .and_then(Value::as_str)
711 {
712 if reason == "MALFORMED_FUNCTION_CALL" {
713 if let Some(message) = candidate
716 .and_then(|candidate| candidate.get("finishMessage"))
717 .and_then(Value::as_str)
718 {
719 let mut arguments = Map::new();
720 arguments.insert(INVALID_TOOL_ARGS_KEY.to_owned(), json!(message));
721 let n = self.provider.next_id.fetch_add(1, Ordering::Relaxed);
722 let id = format!("call_g{n}");
723 self.turn.tool_calls.push(ToolCall {
724 id,
725 name: "unknown".to_owned(),
726 arguments,
727 });
728 }
729 }
730 self.turn.finish_reason = Some(reason.to_owned());
731 }
732 Ok(())
733 }
734
735 fn part(&mut self, part: &Value) {
736 if let Some(call) = part.get("functionCall") {
737 let wire = call.get("name").and_then(Value::as_str).unwrap_or_default();
738 let name = self.names.get(wire).map_or(wire, String::as_str).to_owned();
739 let arguments = call
740 .get("args")
741 .and_then(Value::as_object)
742 .cloned()
743 .unwrap_or_default();
744 let google = call
745 .get("id")
746 .and_then(Value::as_str)
747 .filter(|id| !id.is_empty());
748 let id = google.map_or_else(
749 || {
750 let n = self.provider.next_id.fetch_add(1, Ordering::Relaxed);
751 format!("call_g{n}")
752 },
753 str::to_owned,
754 );
755 let meta = CallMeta {
756 signature: part
757 .get("thoughtSignature")
758 .and_then(Value::as_str)
759 .filter(|signature| !signature.is_empty())
760 .map(str::to_owned),
761 google_id: google.is_some(),
762 };
763 self.provider
764 .calls
765 .lock()
766 .unwrap_or_else(|p| p.into_inner())
767 .insert(id.clone(), meta);
768 self.turn.tool_calls.push(ToolCall {
769 id,
770 name,
771 arguments,
772 });
773 return;
774 }
775 let Some(text) = part.get("text").and_then(Value::as_str) else {
776 return;
777 };
778 if text.is_empty() {
779 return;
780 }
781 let thought = part.get("thought").and_then(Value::as_bool) == Some(true);
782 self.turn.emitted = true;
783 if thought {
784 self.turn.thinking.push_str(text);
785 self.pending.push_back(CompletionDelta {
786 thinking: text.to_owned(),
787 ..CompletionDelta::default()
788 });
789 } else {
790 self.turn.text.push_str(text);
791 self.pending.push_back(CompletionDelta {
792 text: text.to_owned(),
793 ..CompletionDelta::default()
794 });
795 }
796 }
797
798 fn finish(&mut self) {
799 self.finished = true;
800 self.response = None;
801 let turn = std::mem::take(&mut self.turn);
802 let has_calls = !turn.tool_calls.is_empty();
803 let usage = Usage {
804 input_tokens: turn.input_tokens,
805 output_tokens: turn.output_tokens,
806 cache_read_tokens: turn.cached_tokens,
807 ..Usage::default()
808 };
809 self.pending.push_back(CompletionDelta {
810 done: true,
811 completion: Some(Completion {
812 text: turn.text,
813 tool_calls: turn.tool_calls,
814 usage: self
815 .provider
816 .pricing
817 .priced_usage(&self.provider.price_ref, usage),
818 stop_reason: stop_reason(turn.finish_reason.as_deref(), has_calls),
819 model: Some(self.provider.model.clone()),
820 thinking: turn.thinking,
821 }),
822 ..CompletionDelta::default()
823 });
824 }
825}
826
827#[cfg(test)]
828mod tests {
829 use super::*;
830 use crate::types::Role;
831
832 fn message(role: Role, content: &str) -> Message {
833 Message {
834 role,
835 content: content.to_owned(),
836 tool_calls: Vec::new(),
837 tool_call_id: None,
838 name: None,
839 }
840 }
841
842 #[test]
843 fn names_gemini_refuses_get_an_underscore_and_stay_unique() {
844 let taken = vec!["_1tool".to_owned()];
845 assert_eq!(gemini_name("read_file", &taken), "read_file");
846 assert_eq!(gemini_name("_private", &taken), "_private");
847 assert_eq!(gemini_name("1password-get", &taken), "_1password-get");
848 assert_eq!(gemini_name("-dash", &taken), "_-dash");
849 assert_eq!(gemini_name("1tool", &taken), "__1tool", "past a taken name");
850 }
851
852 #[test]
853 fn finish_reasons_map_and_the_rest_stop_the_turn() {
854 assert_eq!(
855 stop_reason(Some("STOP"), false).as_deref(),
856 Some("end_turn")
857 );
858 assert_eq!(stop_reason(Some("STOP"), true).as_deref(), Some("tool_use"));
859 assert_eq!(stop_reason(None, true).as_deref(), Some("tool_use"));
860 assert_eq!(stop_reason(None, false), None);
861 for cut in ["MAX_TOKENS", "CONTINUATION"] {
862 assert_eq!(stop_reason(Some(cut), false).as_deref(), Some("max_tokens"));
863 }
864 for stopped in [
865 "SAFETY",
866 "RECITATION",
867 "PROHIBITED_CONTENT",
868 "OTHER",
869 "SOMETHING_NEW",
870 ] {
871 assert_eq!(
872 stop_reason(Some(stopped), false),
873 Some(format!("stopped:{stopped}"))
874 );
875 }
876 }
877
878 #[test]
879 fn contents_merge_by_role_and_keep_calls_before_their_results() {
880 let mut assistant = message(Role::Assistant, "Looking.");
881 assistant.tool_calls = vec![
882 ToolCall {
883 id: "a".into(),
884 name: "read_file".into(),
885 arguments: json!({"path": "x"}).as_object().unwrap().clone(),
886 },
887 ToolCall {
888 id: "b".into(),
889 name: "list_dir".into(),
890 arguments: Map::new(),
891 },
892 ];
893 let mut first = message(Role::Tool, "contents of x");
894 first.tool_call_id = Some("a".into());
895 first.name = Some("read_file".into());
896 let mut second = message(Role::Tool, "a b c");
897 second.tool_call_id = Some("b".into());
898 let (system, contents) = to_contents(&[
899 message(Role::System, "You are a test."),
900 message(Role::User, "Hi"),
901 message(Role::User, "again"),
902 assistant,
903 first,
904 second,
905 ]);
906 assert_eq!(system, "You are a test.");
907 assert_eq!(
908 Value::Array(contents),
909 json!([
910 {"role": "user", "parts": [{"text": "Hi"}, {"text": "again"}]},
911 {"role": "model", "parts": [
912 {"text": "Looking."},
913 {"functionCall": {"name": "read_file", "args": {"path": "x"}},
914 "thoughtSignature": SKIP_SIGNATURE},
915 {"functionCall": {"name": "list_dir", "args": {}}},
916 ]},
917 {"role": "user", "parts": [
918 {"functionResponse": {"name": "read_file", "response": {"result": "contents of x"}}},
919 {"functionResponse": {"name": "list_dir", "response": {"result": "a b c"}}},
920 ]},
921 ])
922 );
923 }
924}