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