Compare commits
28 Commits
494aab6d14
...
feat/retry
| Author | SHA1 | Date | |
|---|---|---|---|
| 440b3c7a87 | |||
| 2e0016eb25 | |||
| faa72a6d7a | |||
| a49d37f03d | |||
| cecc14d31e | |||
| 4791125943 | |||
| 6d49f9939c | |||
| c911fc382e | |||
| a8961b12e3 | |||
| 2f15b5298d | |||
| 01a4300bb3 | |||
| a2cff20aff | |||
| 7d5c6e3e28 | |||
| 8d1c9c3bb6 | |||
| 7264276232 | |||
| 763a1a5da6 | |||
| f9e74ee171 | |||
| 20f7a4a34c | |||
| e64a748d5c | |||
| 166bdefa89 | |||
| ebb49eb929 | |||
| 9bade7a1e6 | |||
| ba9870277c | |||
| 196d5a9f55 | |||
| 43cf7933fc | |||
| 69532ad110 | |||
| e120780006 | |||
| f4f275f2f9 |
18
.github/workflows/rust.yml
vendored
18
.github/workflows/rust.yml
vendored
@@ -10,13 +10,19 @@ env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build
|
||||
run: cargo build --verbose
|
||||
- name: Run tests
|
||||
run: cargo test --verbose
|
||||
# The Gitea runner image doesn't ship with Rust, unlike GitHub's.
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: clippy, rustfmt
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- name: Format
|
||||
run: cargo fmt --check
|
||||
- name: Clippy
|
||||
run: cargo clippy --all-targets -- -D warnings
|
||||
- name: Test
|
||||
run: cargo test
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "gemini-rs"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
@@ -18,6 +18,7 @@ tokio = { version = "1" }
|
||||
tokio-stream = "0.1.18"
|
||||
|
||||
[dev-dependencies]
|
||||
base64 = "0.23.1"
|
||||
console = "0.16.4"
|
||||
dialoguer = "0.12.0"
|
||||
image = "0.25.10"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use console::style;
|
||||
use dialoguer::{theme::ColorfulTheme, Input};
|
||||
use dialoguer::{Input, theme::ColorfulTheme};
|
||||
use gemini_rs::prelude::*;
|
||||
use std::time::Duration;
|
||||
|
||||
|
||||
135
examples/function-response-image.rs
Normal file
135
examples/function-response-image.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
//! Returns an image from a function call as a multimodal function response
|
||||
//! (`functionResponse.parts` with `inlineData`) and asks the model what it sees.
|
||||
//!
|
||||
//! The image is a solid square in a color picked at random, so a correct answer
|
||||
//! shows the model actually received the image.
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use base64::Engine;
|
||||
use gemini_rs::prelude::*;
|
||||
use image::{ImageFormat, Rgb, RgbImage};
|
||||
use serde_json::json;
|
||||
|
||||
const COLORS: [(&str, [u8; 3]); 4] = [
|
||||
("red", [220, 20, 20]),
|
||||
("green", [20, 180, 20]),
|
||||
("blue", [20, 40, 220]),
|
||||
("yellow", [240, 220, 20]),
|
||||
];
|
||||
|
||||
fn square_png(rgb: [u8; 3]) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let image = RgbImage::from_pixel(64, 64, Rgb(rgb));
|
||||
let mut bytes = Cursor::new(Vec::new());
|
||||
image.write_to(&mut bytes, ImageFormat::Png)?;
|
||||
Ok(base64::engine::general_purpose::STANDARD.encode(bytes.into_inner()))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let authentication_manager = gcp_auth::provider().await?;
|
||||
let api_endpoint = std::env::var("API_ENDPOINT")?;
|
||||
let project_id = std::env::var("PROJECT_ID")?;
|
||||
let location_id = std::env::var("LOCATION_ID")?;
|
||||
let model = std::env::var("MODEL").unwrap_or_else(|_| "gemini-3.8-flash".to_string());
|
||||
|
||||
let gemini = GeminiClient::new(
|
||||
authentication_manager,
|
||||
api_endpoint,
|
||||
project_id,
|
||||
location_id,
|
||||
);
|
||||
|
||||
let tools = vec![Tools {
|
||||
function_declarations: Some(vec![FunctionDeclaration {
|
||||
name: "take_snapshot".to_string(),
|
||||
description: "Takes a snapshot of the camera and returns it as an image.".to_string(),
|
||||
parameters: Some(json!({"type": "object", "properties": {}})),
|
||||
parameters_json_schema: None,
|
||||
}]),
|
||||
..Default::default()
|
||||
}];
|
||||
let mut contents = vec![
|
||||
Content::builder()
|
||||
.role(Role::User)
|
||||
.add_text_part(
|
||||
"Take a snapshot with the camera and tell me, in one word, the color it shows.",
|
||||
)
|
||||
.build(),
|
||||
];
|
||||
|
||||
let first = gemini
|
||||
.generate_content(
|
||||
&GenerateContentRequest::builder()
|
||||
.contents(contents.clone())
|
||||
.tools(tools.clone())
|
||||
.build(),
|
||||
&model,
|
||||
)
|
||||
.await?;
|
||||
let model_turn = first.candidates[0]
|
||||
.content
|
||||
.clone()
|
||||
.ok_or("first response has no content")?;
|
||||
let call = model_turn
|
||||
.parts
|
||||
.iter()
|
||||
.flatten()
|
||||
.find(|p| p.function_call.is_some())
|
||||
.ok_or("model did not call take_snapshot")?
|
||||
.clone();
|
||||
println!(
|
||||
"Model called: {}",
|
||||
call.function_call.as_ref().unwrap().name
|
||||
);
|
||||
|
||||
// `COLOR` picks one explicitly; otherwise pick by time (in microseconds, since
|
||||
// some platforms' clocks have 100ns resolution).
|
||||
let (color, rgb) = match std::env::var("COLOR") {
|
||||
Ok(name) => *COLORS
|
||||
.iter()
|
||||
.find(|(c, _)| *c == name)
|
||||
.ok_or_else(|| format!("unknown COLOR {name}"))?,
|
||||
Err(_) => {
|
||||
let micros = SystemTime::now().duration_since(UNIX_EPOCH)?.as_micros();
|
||||
COLORS[(micros % COLORS.len() as u128) as usize]
|
||||
}
|
||||
};
|
||||
println!("Returning a {color} image");
|
||||
|
||||
let mut response = Part::function_response("take_snapshot", json!({"status": "ok"}));
|
||||
response.thought_signature = call.thought_signature.clone();
|
||||
response.function_response.as_mut().unwrap().parts = vec![FunctionResponsePart {
|
||||
inline_data: InlineData {
|
||||
mime_type: "image/png".to_string(),
|
||||
data: square_png(rgb)?,
|
||||
},
|
||||
}];
|
||||
contents.push(model_turn);
|
||||
contents.push(
|
||||
Content::builder()
|
||||
.role(Role::User)
|
||||
.add_part(response)
|
||||
.build(),
|
||||
);
|
||||
|
||||
let second = gemini
|
||||
.generate_content(
|
||||
&GenerateContentRequest::builder()
|
||||
.contents(contents)
|
||||
.tools(tools)
|
||||
.build(),
|
||||
&model,
|
||||
)
|
||||
.await?;
|
||||
let answer = second.candidates[0].get_text().unwrap_or_default();
|
||||
println!("Model answered: {answer}");
|
||||
|
||||
if answer.to_lowercase().contains(color) {
|
||||
println!("OK: the model saw the {color} image");
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("expected the answer to mention {color}").into())
|
||||
}
|
||||
}
|
||||
@@ -19,10 +19,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.add_text_part("Answer as if you were Yoda")
|
||||
.build();
|
||||
|
||||
let user_prompt = vec![Content::builder()
|
||||
.role(Role::User)
|
||||
.add_text_part("What is the airspeed of an unladen swallow?")
|
||||
.build()];
|
||||
let user_prompt = vec![
|
||||
Content::builder()
|
||||
.role(Role::User)
|
||||
.add_text_part("What is the airspeed of an unladen swallow?")
|
||||
.build(),
|
||||
];
|
||||
|
||||
let request = GenerateContentRequest::builder()
|
||||
.contents(user_prompt)
|
||||
|
||||
@@ -15,10 +15,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
location_id,
|
||||
);
|
||||
|
||||
let prompt = vec![Content::builder()
|
||||
.role(Role::User)
|
||||
.add_text_part("Tell me the story of the genesis of the universe as a bedtime story.")
|
||||
.build()];
|
||||
let prompt = vec![
|
||||
Content::builder()
|
||||
.role(Role::User)
|
||||
.add_text_part("Tell me the story of the genesis of the universe as a bedtime story.")
|
||||
.build(),
|
||||
];
|
||||
|
||||
let request = GenerateContentRequest::builder().contents(prompt).build();
|
||||
|
||||
|
||||
@@ -14,10 +14,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
location_id,
|
||||
);
|
||||
|
||||
let prompt = vec![Content::builder()
|
||||
.role(Role::User)
|
||||
.add_text_part("What is the airspeed of an unladen swallow?")
|
||||
.build()];
|
||||
let prompt = vec![
|
||||
Content::builder()
|
||||
.role(Role::User)
|
||||
.add_text_part("What is the airspeed of an unladen swallow?")
|
||||
.build(),
|
||||
];
|
||||
|
||||
let request = GenerateContentRequest::builder().contents(prompt).build();
|
||||
let response = gemini.generate_content(&request, "gemini-pro").await?;
|
||||
|
||||
110
src/client.rs
110
src/client.rs
@@ -1,3 +1,4 @@
|
||||
use std::time::Duration;
|
||||
use std::vec;
|
||||
use tracing::error;
|
||||
|
||||
@@ -8,8 +9,8 @@ use crate::error::{Error, Result};
|
||||
use crate::network::event_source::{EventSource, ServerSentEvent};
|
||||
use crate::prelude::{
|
||||
Candidate, Content, CountTokensRequest, CountTokensResponse, GenerateContentRequest,
|
||||
GenerateContentResponse, GenerateContentResponseResult, TextEmbeddingRequest,
|
||||
TextEmbeddingResponse,
|
||||
GenerateContentResponse, GenerateContentResponseError, GenerateContentResponseResult,
|
||||
TextEmbeddingRequest, TextEmbeddingResponse,
|
||||
};
|
||||
use crate::types::{PredictImageRequest, PredictImageResponse, Role};
|
||||
use crate::{prelude::Part, token_provider::TokenProvider};
|
||||
@@ -42,16 +43,47 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
}
|
||||
}
|
||||
|
||||
fn endpoint_url(&self, version: &str, action: &str) -> String {
|
||||
let scheme = if self.api_endpoint.starts_with("http://")
|
||||
|| self.api_endpoint.starts_with("https://")
|
||||
{
|
||||
""
|
||||
} else {
|
||||
"https://"
|
||||
};
|
||||
format!(
|
||||
"{scheme}{}/{version}/projects/{}/locations/{}/publishers/google/models/{action}",
|
||||
self.api_endpoint, self.project_id, self.location_id
|
||||
)
|
||||
}
|
||||
|
||||
async fn error_for_status(response: reqwest::Response) -> Result<reqwest::Response> {
|
||||
if !response.status().is_success() {
|
||||
let status = response.status();
|
||||
let retry_after = parse_retry_after(response.headers());
|
||||
let body = response.text().await?;
|
||||
if let Ok(error_response) = serde_json::from_str::<GenerateContentResponseError>(&body)
|
||||
{
|
||||
let mut error = error_response.error;
|
||||
error.retry_after = retry_after;
|
||||
return Err(error.into());
|
||||
}
|
||||
return Err(Error::HttpStatus {
|
||||
status,
|
||||
body,
|
||||
retry_after,
|
||||
});
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
pub async fn generate_content(
|
||||
&self,
|
||||
request: &GenerateContentRequest,
|
||||
model: &str,
|
||||
) -> Result<GenerateContentResponseResult> {
|
||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||
let endpoint_url: String = format!(
|
||||
"https://{}/{}/projects/{}/locations/{}/publishers/google/models/{}:generateContent",
|
||||
self.api_endpoint, ENDPOINT_VERSION, self.project_id, self.location_id, model,
|
||||
);
|
||||
let endpoint_url = self.endpoint_url(ENDPOINT_VERSION, &format!("{model}:generateContent"));
|
||||
let resp = self
|
||||
.client
|
||||
.post(&endpoint_url)
|
||||
@@ -60,6 +92,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let resp = Self::error_for_status(resp).await?;
|
||||
let txt_json = resp.text().await?;
|
||||
tracing::debug!("generate_content response: {:?}", txt_json);
|
||||
match serde_json::from_str::<GenerateContentResponse>(&txt_json) {
|
||||
@@ -81,9 +114,9 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
model: &str,
|
||||
) -> Result<impl Stream<Item = Result<GenerateContentResponseResult>> + use<'_, T>> {
|
||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||
let endpoint_url = format!(
|
||||
"https://{}/{}/projects/{}/locations/{}/publishers/google/models/{}:streamGenerateContent?alt=sse",
|
||||
self.api_endpoint, ENDPOINT_VERSION, self.project_id, self.location_id, model,
|
||||
let endpoint_url = self.endpoint_url(
|
||||
ENDPOINT_VERSION,
|
||||
&format!("{model}:streamGenerateContent?alt=sse"),
|
||||
);
|
||||
let response = self
|
||||
.client
|
||||
@@ -92,18 +125,25 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
.json(request)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let response = Self::error_for_status(response).await?;
|
||||
Ok(response.event_stream().filter_map(Self::parse_sse_event))
|
||||
}
|
||||
|
||||
fn parse_sse_event(
|
||||
event_result: std::result::Result<ServerSentEvent, tokio_util::codec::LinesCodecError>,
|
||||
) -> Option<Result<GenerateContentResponseResult>> {
|
||||
let data = event_result.map_err(Error::from).ok()?.data?;
|
||||
Some(
|
||||
serde_json::from_str::<GenerateContentResponse>(&data)
|
||||
.map_err(Error::from)
|
||||
.and_then(|r| r.into_result()),
|
||||
)
|
||||
match event_result {
|
||||
Ok(event) => {
|
||||
let data = event.data?;
|
||||
Some(
|
||||
serde_json::from_str::<GenerateContentResponse>(&data)
|
||||
.map_err(Error::from)
|
||||
.and_then(|r| r.into_result()),
|
||||
)
|
||||
}
|
||||
Err(err) => Some(Err(Error::from(err))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompts a conversation to the model.
|
||||
@@ -146,10 +186,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
request: &TextEmbeddingRequest,
|
||||
model: &str,
|
||||
) -> Result<TextEmbeddingResponse> {
|
||||
let endpoint_url = format!(
|
||||
"https://{}/v1/projects/{}/locations/{}/publishers/google/models/{}:predict",
|
||||
self.api_endpoint, self.project_id, self.location_id, model,
|
||||
);
|
||||
let endpoint_url = self.endpoint_url("v1", &format!("{model}:predict"));
|
||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||
let resp = self
|
||||
.client
|
||||
@@ -158,6 +195,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
let resp = Self::error_for_status(resp).await?;
|
||||
let txt_json = resp.text().await?;
|
||||
tracing::debug!("text_embeddings response: {:?}", txt_json);
|
||||
Ok(serde_json::from_str::<TextEmbeddingResponse>(&txt_json)?)
|
||||
@@ -168,10 +206,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
request: &CountTokensRequest,
|
||||
model: &str,
|
||||
) -> Result<CountTokensResponse> {
|
||||
let endpoint_url = format!(
|
||||
"https://{}/{}/projects/{}/locations/{}/publishers/google/models/{}:countTokens",
|
||||
self.api_endpoint, ENDPOINT_VERSION, self.project_id, self.location_id, model,
|
||||
);
|
||||
let endpoint_url = self.endpoint_url(ENDPOINT_VERSION, &format!("{model}:countTokens"));
|
||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||
let resp = self
|
||||
.client
|
||||
@@ -180,7 +215,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let resp = Self::error_for_status(resp).await?;
|
||||
let txt_json = resp.text().await?;
|
||||
tracing::debug!("count_tokens response: {:?}", txt_json);
|
||||
Ok(serde_json::from_str(&txt_json)?)
|
||||
@@ -191,10 +226,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
request: &PredictImageRequest,
|
||||
model: &str,
|
||||
) -> Result<PredictImageResponse> {
|
||||
let endpoint_url = format!(
|
||||
"https://{}/v1/projects/{}/locations/{}/publishers/google/models/{}:predict",
|
||||
self.api_endpoint, self.project_id, self.location_id, model,
|
||||
);
|
||||
let endpoint_url = self.endpoint_url("v1", &format!("{model}:predict"));
|
||||
|
||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||
let resp = self
|
||||
@@ -204,7 +236,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let resp = Self::error_for_status(resp).await?;
|
||||
let txt_json = resp.text().await?;
|
||||
|
||||
match serde_json::from_str::<PredictImageResponse>(&txt_json) {
|
||||
@@ -216,3 +248,23 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a `Retry-After` header in its delay-seconds form (e.g. `Retry-After: 30`).
|
||||
///
|
||||
/// The HTTP-date form is not supported and yields `None`.
|
||||
fn parse_retry_after(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
|
||||
let value = headers
|
||||
.get(reqwest::header::RETRY_AFTER)?
|
||||
.to_str()
|
||||
.ok()?
|
||||
.trim();
|
||||
// `delay-seconds = 1*DIGIT`; `u64::from_str` alone would also accept a leading `+`.
|
||||
if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
value.parse().ok().map(Duration::from_secs)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "client_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
417
src/client_tests.rs
Normal file
417
src/client_tests.rs
Normal file
@@ -0,0 +1,417 @@
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use super::*;
|
||||
use crate::types::PredictImageRequestParameters;
|
||||
|
||||
type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MockTokenProvider;
|
||||
|
||||
impl TokenProvider for MockTokenProvider {
|
||||
async fn get_token(&self, _scope: &[&str]) -> crate::error::Result<String> {
|
||||
Ok("test-token".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a raw HTTP/1.1 response with a `Content-Length` matching `body`.
|
||||
///
|
||||
/// `headers` holds extra header lines, each terminated by `\r\n`.
|
||||
fn http_response(status_line: &str, content_type: &str, headers: &str, body: &str) -> String {
|
||||
format!(
|
||||
"HTTP/1.1 {status_line}\r\nContent-Type: {content_type}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
/// Starts a one-shot local server that answers the first request with `response`, and
|
||||
/// returns a client pointed at it.
|
||||
async fn mock_client(response: String) -> Result<GeminiClient<MockTokenProvider>> {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let addr = listener.local_addr()?;
|
||||
|
||||
tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut buf = [0u8; 4096];
|
||||
let _ = socket.read(&mut buf).await;
|
||||
socket.write_all(response.as_bytes()).await.unwrap();
|
||||
let _ = socket.shutdown().await;
|
||||
});
|
||||
|
||||
Ok(GeminiClient::new(
|
||||
MockTokenProvider,
|
||||
format!("http://{addr}"),
|
||||
"test-project".to_string(),
|
||||
"test-location".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_generate_content_returns_vertex_error_on_400_json() -> Result<()> {
|
||||
let body = r#"{"error": {"code": 400, "message": "Invalid JSON payload received. Unknown name \"$schema\" at 'tools[0].function_declarations[0].parameters': Cannot find field.", "status": "INVALID_ARGUMENT"}}"#;
|
||||
let client = mock_client(http_response(
|
||||
"400 Bad Request",
|
||||
"application/json",
|
||||
"",
|
||||
body,
|
||||
))
|
||||
.await?;
|
||||
let request = GenerateContentRequest::default();
|
||||
|
||||
let result = client
|
||||
.stream_generate_content(&request, "gemini-test")
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Err(Error::VertexError(err)) => {
|
||||
assert_eq!(err.code, 400);
|
||||
assert_eq!(err.status, "INVALID_ARGUMENT");
|
||||
assert!(err.message.contains("Invalid JSON payload received"));
|
||||
}
|
||||
Err(other) => panic!("Expected Error::VertexError, got: {other:?}"),
|
||||
Ok(_) => panic!("Expected error response, got Ok"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_generate_content_returns_http_status_on_non_json_error() -> Result<()> {
|
||||
let client = mock_client(http_response(
|
||||
"500 Internal Server Error",
|
||||
"text/plain",
|
||||
"",
|
||||
"Internal Server Error",
|
||||
))
|
||||
.await?;
|
||||
let request = GenerateContentRequest::default();
|
||||
|
||||
let result = client
|
||||
.stream_generate_content(&request, "gemini-test")
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Err(Error::HttpStatus { status, body, .. }) => {
|
||||
assert_eq!(status, reqwest::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
assert_eq!(body, "Internal Server Error");
|
||||
}
|
||||
Err(other) => panic!("Expected Error::HttpStatus, got: {other:?}"),
|
||||
Ok(_) => panic!("Expected error response, got Ok"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_generate_content_yields_events_on_200_sse() -> Result<()> {
|
||||
let sse_body = "data: {\"candidates\": [{\"content\": {\"role\": \"model\", \"parts\": [{\"text\": \"Hello world\"}]}}]}\n\n";
|
||||
let client = mock_client(http_response("200 OK", "text/event-stream", "", sse_body)).await?;
|
||||
let request = GenerateContentRequest::default();
|
||||
|
||||
let mut stream = client
|
||||
.stream_generate_content(&request, "gemini-test")
|
||||
.await?;
|
||||
let Some(item_res) = stream.next().await else {
|
||||
panic!("Stream should yield an item");
|
||||
};
|
||||
let item = item_res?;
|
||||
|
||||
assert_eq!(item.candidates.len(), 1);
|
||||
assert_eq!(
|
||||
item.candidates[0].get_text(),
|
||||
Some("Hello world".to_string())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_sse_event_propagates_lines_codec_error() {
|
||||
let io_err = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "connection reset");
|
||||
let result = GeminiClient::<MockTokenProvider>::parse_sse_event(Err(
|
||||
tokio_util::codec::LinesCodecError::Io(io_err),
|
||||
));
|
||||
|
||||
match result {
|
||||
Some(Err(Error::EventSourceError(tokio_util::codec::LinesCodecError::Io(err)))) => {
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::ConnectionReset);
|
||||
}
|
||||
other => panic!("Expected Some(Err(Error::EventSourceError(Io))), got: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_sse_event_returns_none_when_data_is_none() {
|
||||
let event = ServerSentEvent {
|
||||
event: Some("ping".to_string()),
|
||||
data: None,
|
||||
id: None,
|
||||
retry: None,
|
||||
};
|
||||
let result = GeminiClient::<MockTokenProvider>::parse_sse_event(Ok(event));
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_generate_content_yields_error_on_truncated_sse() -> Result<()> {
|
||||
// Incomplete event without trailing newline before EOF, and no Content-Length.
|
||||
let partial_sse = "data: {\"candidates\": [";
|
||||
let client = mock_client(format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{partial_sse}"
|
||||
))
|
||||
.await?;
|
||||
let request = GenerateContentRequest::default();
|
||||
|
||||
let mut stream = client
|
||||
.stream_generate_content(&request, "gemini-test")
|
||||
.await?;
|
||||
let item_res = stream.next().await;
|
||||
|
||||
match item_res {
|
||||
Some(Err(Error::EventSourceError(_))) => {}
|
||||
other => panic!("Expected Some(Err(Error::EventSourceError)), got: {other:?}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generate_content_returns_http_status_on_non_json_503() -> Result<()> {
|
||||
let client = mock_client(http_response(
|
||||
"503 Service Unavailable",
|
||||
"text/plain",
|
||||
"",
|
||||
"Service Unavailable",
|
||||
))
|
||||
.await?;
|
||||
let request = GenerateContentRequest::default();
|
||||
|
||||
let result = client.generate_content(&request, "gemini-test").await;
|
||||
|
||||
match result {
|
||||
Err(Error::HttpStatus {
|
||||
status,
|
||||
body,
|
||||
retry_after,
|
||||
}) => {
|
||||
assert_eq!(status, reqwest::StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(body, "Service Unavailable");
|
||||
assert_eq!(retry_after, None);
|
||||
}
|
||||
Err(other) => panic!("Expected Error::HttpStatus, got: {other:?}"),
|
||||
Ok(_) => panic!("Expected error response, got Ok"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generate_content_returns_vertex_error_on_400_json() -> Result<()> {
|
||||
let body =
|
||||
r#"{"error": {"code": 400, "message": "Invalid request", "status": "INVALID_ARGUMENT"}}"#;
|
||||
let client = mock_client(http_response(
|
||||
"400 Bad Request",
|
||||
"application/json",
|
||||
"",
|
||||
body,
|
||||
))
|
||||
.await?;
|
||||
let request = GenerateContentRequest::default();
|
||||
|
||||
let result = client.generate_content(&request, "gemini-test").await;
|
||||
|
||||
match result {
|
||||
Err(Error::VertexError(err)) => {
|
||||
assert_eq!(err.code, 400);
|
||||
assert_eq!(err.status, "INVALID_ARGUMENT");
|
||||
assert_eq!(err.retry_after, None);
|
||||
}
|
||||
Err(other) => panic!("Expected Error::VertexError, got: {other:?}"),
|
||||
Ok(_) => panic!("Expected error response, got Ok"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn count_tokens_returns_http_status_on_non_json_error() -> Result<()> {
|
||||
let client = mock_client(http_response(
|
||||
"502 Bad Gateway",
|
||||
"text/plain",
|
||||
"",
|
||||
"Bad Gateway",
|
||||
))
|
||||
.await?;
|
||||
let request = CountTokensRequest {
|
||||
contents: Content::default(),
|
||||
};
|
||||
|
||||
let result = client.count_tokens(&request, "gemini-test").await;
|
||||
|
||||
match result {
|
||||
Err(Error::HttpStatus { status, body, .. }) => {
|
||||
assert_eq!(status, reqwest::StatusCode::BAD_GATEWAY);
|
||||
assert_eq!(body, "Bad Gateway");
|
||||
}
|
||||
Err(other) => panic!("Expected Error::HttpStatus, got: {other:?}"),
|
||||
Ok(_) => panic!("Expected error response, got Ok"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn text_embeddings_returns_http_status_on_non_json_error() -> Result<()> {
|
||||
let client = mock_client(http_response(
|
||||
"500 Internal Server Error",
|
||||
"text/plain",
|
||||
"",
|
||||
"Internal Server Error",
|
||||
))
|
||||
.await?;
|
||||
let request = TextEmbeddingRequest { instances: vec![] };
|
||||
|
||||
let result = client.text_embeddings(&request, "gemini-test").await;
|
||||
|
||||
match result {
|
||||
Err(Error::HttpStatus { status, body, .. }) => {
|
||||
assert_eq!(status, reqwest::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
assert_eq!(body, "Internal Server Error");
|
||||
}
|
||||
Err(other) => panic!("Expected Error::HttpStatus, got: {other:?}"),
|
||||
Ok(_) => panic!("Expected error response, got Ok"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn predict_image_returns_http_status_on_non_json_error() -> Result<()> {
|
||||
let client = mock_client(http_response(
|
||||
"503 Service Unavailable",
|
||||
"text/plain",
|
||||
"",
|
||||
"Service Unavailable",
|
||||
))
|
||||
.await?;
|
||||
let request = PredictImageRequest {
|
||||
instances: vec![],
|
||||
parameters: PredictImageRequestParameters::default(),
|
||||
};
|
||||
|
||||
let result = client.predict_image(&request, "imagen-test").await;
|
||||
|
||||
match result {
|
||||
Err(Error::HttpStatus { status, body, .. }) => {
|
||||
assert_eq!(status, reqwest::StatusCode::SERVICE_UNAVAILABLE);
|
||||
assert_eq!(body, "Service Unavailable");
|
||||
}
|
||||
Err(other) => panic!("Expected Error::HttpStatus, got: {other:?}"),
|
||||
Ok(_) => panic!("Expected error response, got Ok"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generate_content_captures_retry_after_on_non_json_429() -> Result<()> {
|
||||
let client = mock_client(http_response(
|
||||
"429 Too Many Requests",
|
||||
"text/plain",
|
||||
"Retry-After: 30\r\n",
|
||||
"Too Many Requests",
|
||||
))
|
||||
.await?;
|
||||
let request = GenerateContentRequest::default();
|
||||
|
||||
let err = match client.generate_content(&request, "gemini-test").await {
|
||||
Err(err) => err,
|
||||
Ok(_) => panic!("Expected error response, got Ok"),
|
||||
};
|
||||
match &err {
|
||||
Error::HttpStatus {
|
||||
status,
|
||||
retry_after,
|
||||
..
|
||||
} => {
|
||||
assert_eq!(*status, reqwest::StatusCode::TOO_MANY_REQUESTS);
|
||||
assert_eq!(*retry_after, Some(Duration::from_secs(30)));
|
||||
}
|
||||
other => panic!("Expected Error::HttpStatus, got: {other:?}"),
|
||||
}
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(30)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generate_content_captures_retry_after_on_json_429_without_retry_info() -> Result<()> {
|
||||
let body = r#"{"error": {"code": 429, "message": "Resource exhausted", "status": "RESOURCE_EXHAUSTED"}}"#;
|
||||
let client = mock_client(http_response(
|
||||
"429 Too Many Requests",
|
||||
"application/json",
|
||||
"Retry-After: 30\r\n",
|
||||
body,
|
||||
))
|
||||
.await?;
|
||||
let request = GenerateContentRequest::default();
|
||||
|
||||
let err = match client.generate_content(&request, "gemini-test").await {
|
||||
Err(err) => err,
|
||||
Ok(_) => panic!("Expected error response, got Ok"),
|
||||
};
|
||||
match &err {
|
||||
Error::VertexError(vertex_err) => {
|
||||
assert_eq!(vertex_err.code, 429);
|
||||
assert_eq!(vertex_err.retry_after, Some(Duration::from_secs(30)));
|
||||
}
|
||||
other => panic!("Expected Error::VertexError, got: {other:?}"),
|
||||
}
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(30)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generate_content_prefers_retry_info_over_retry_after() -> Result<()> {
|
||||
let body = r#"{"error": {"code": 429, "message": "Resource exhausted", "status": "RESOURCE_EXHAUSTED", "details": [{"@type": "type.googleapis.com/google.rpc.RetryInfo", "retryDelay": "37s"}]}}"#;
|
||||
let client = mock_client(http_response(
|
||||
"429 Too Many Requests",
|
||||
"application/json",
|
||||
"Retry-After: 30\r\n",
|
||||
body,
|
||||
))
|
||||
.await?;
|
||||
let request = GenerateContentRequest::default();
|
||||
|
||||
let err = match client.generate_content(&request, "gemini-test").await {
|
||||
Err(err) => err,
|
||||
Ok(_) => panic!("Expected error response, got Ok"),
|
||||
};
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(37)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_retry_after_reads_delay_seconds() -> Result<()> {
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
assert_eq!(parse_retry_after(&headers), None);
|
||||
|
||||
headers.insert(reqwest::header::RETRY_AFTER, "30".parse()?);
|
||||
assert_eq!(parse_retry_after(&headers), Some(Duration::from_secs(30)));
|
||||
|
||||
headers.insert(reqwest::header::RETRY_AFTER, " 0 ".parse()?);
|
||||
assert_eq!(parse_retry_after(&headers), Some(Duration::ZERO));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_retry_after_rejects_invalid_values() -> Result<()> {
|
||||
let cases = [
|
||||
"Wed, 21 Oct 2015 07:28:00 GMT", // HTTP-date form is not supported
|
||||
"soon",
|
||||
"-1",
|
||||
"+30", // delay-seconds is digits only
|
||||
"1.5",
|
||||
"",
|
||||
];
|
||||
for case in cases {
|
||||
let mut headers = reqwest::header::HeaderMap::new();
|
||||
headers.insert(reqwest::header::RETRY_AFTER, case.parse()?);
|
||||
assert_eq!(
|
||||
parse_retry_after(&headers),
|
||||
None,
|
||||
"expected None for: {case:?}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
145
src/error.rs
145
src/error.rs
@@ -1,4 +1,5 @@
|
||||
use std::fmt::Display;
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio_util::codec::LinesCodecError;
|
||||
|
||||
@@ -16,6 +17,14 @@ pub enum Error {
|
||||
NoCandidatesError,
|
||||
/// An error occurred while decoding the SSE event stream.
|
||||
EventSourceError(LinesCodecError),
|
||||
/// An HTTP error status was returned by the server.
|
||||
HttpStatus {
|
||||
status: reqwest::StatusCode,
|
||||
body: String,
|
||||
/// The delay from the response's `Retry-After` header, if present and in
|
||||
/// delay-seconds form.
|
||||
retry_after: Option<Duration>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
@@ -28,6 +37,7 @@ impl Display for Error {
|
||||
Error::VertexError(e) => write!(f, "Vertex error: {e}"),
|
||||
Error::NoCandidatesError => write!(f, "No candidates returned for the prompt"),
|
||||
Error::EventSourceError(e) => write!(f, "EventSource error: {e}"),
|
||||
Error::HttpStatus { status, body, .. } => write!(f, "HTTP status {status}: {body}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,3 +79,138 @@ impl From<LinesCodecError> for Error {
|
||||
Error::EventSourceError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Returns whether this error is considered retryable per Vertex AI error guidance.
|
||||
///
|
||||
/// The following errors are treated as retryable:
|
||||
/// - `VertexError` with HTTP status code 429, 500, or 503, or status string
|
||||
/// `RESOURCE_EXHAUSTED`, `INTERNAL`, `UNKNOWN`, or `UNAVAILABLE`.
|
||||
/// - `HttpStatus` with status code 429, 500, 502, or 503.
|
||||
/// - `HttpClient` transport errors that are timeouts or connection failures.
|
||||
pub fn is_retryable(&self) -> bool {
|
||||
match self {
|
||||
Error::VertexError(err) => {
|
||||
matches!(err.code, 429 | 500 | 503)
|
||||
|| matches!(
|
||||
err.status.as_str(),
|
||||
"RESOURCE_EXHAUSTED" | "INTERNAL" | "UNKNOWN" | "UNAVAILABLE"
|
||||
)
|
||||
}
|
||||
Error::HttpStatus { status, .. } => {
|
||||
matches!(status.as_u16(), 429 | 500 | 502 | 503)
|
||||
}
|
||||
Error::HttpClient(err) => err.is_timeout() || err.is_connect(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the server-recommended retry delay, if any.
|
||||
///
|
||||
/// - `VertexError`: the delay from a `google.rpc.RetryInfo` detail entry, falling
|
||||
/// back to the response's `Retry-After` header.
|
||||
/// - `HttpStatus`: the delay from the response's `Retry-After` header.
|
||||
pub fn retry_delay(&self) -> Option<Duration> {
|
||||
match self {
|
||||
Error::VertexError(e) => e.retry_delay(),
|
||||
Error::HttpStatus { retry_after, .. } => *retry_after,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn vertex_error(code: i32, status: &str, details: Option<Vec<serde_json::Value>>) -> Error {
|
||||
Error::VertexError(types::VertexApiError {
|
||||
code,
|
||||
message: "test".to_string(),
|
||||
status: status.to_string(),
|
||||
details,
|
||||
retry_after: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn http_status_error(status: reqwest::StatusCode, retry_after: Option<Duration>) -> Error {
|
||||
Error::HttpStatus {
|
||||
status,
|
||||
body: "error".to_string(),
|
||||
retry_after,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertex_error_retryable_classification() {
|
||||
let make_err = |code: i32, status: &str| vertex_error(code, status, None);
|
||||
|
||||
// Retryable codes
|
||||
assert!(make_err(429, "TOO_MANY_REQUESTS").is_retryable());
|
||||
assert!(make_err(500, "INTERNAL").is_retryable());
|
||||
assert!(make_err(500, "UNKNOWN").is_retryable());
|
||||
assert!(make_err(503, "UNAVAILABLE").is_retryable());
|
||||
|
||||
// Retryable status strings regardless of code
|
||||
assert!(make_err(400, "RESOURCE_EXHAUSTED").is_retryable());
|
||||
assert!(make_err(400, "INTERNAL").is_retryable());
|
||||
assert!(make_err(400, "UNKNOWN").is_retryable());
|
||||
assert!(make_err(400, "UNAVAILABLE").is_retryable());
|
||||
|
||||
// Non-retryable
|
||||
assert!(!make_err(400, "INVALID_ARGUMENT").is_retryable());
|
||||
assert!(!make_err(403, "PERMISSION_DENIED").is_retryable());
|
||||
assert!(!make_err(404, "NOT_FOUND").is_retryable());
|
||||
assert!(!make_err(504, "DEADLINE_EXCEEDED").is_retryable());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_status_retryable_classification() {
|
||||
let make_err = |status: reqwest::StatusCode| http_status_error(status, None);
|
||||
|
||||
assert!(make_err(reqwest::StatusCode::TOO_MANY_REQUESTS).is_retryable());
|
||||
assert!(make_err(reqwest::StatusCode::INTERNAL_SERVER_ERROR).is_retryable());
|
||||
assert!(make_err(reqwest::StatusCode::BAD_GATEWAY).is_retryable());
|
||||
assert!(make_err(reqwest::StatusCode::SERVICE_UNAVAILABLE).is_retryable());
|
||||
|
||||
assert!(!make_err(reqwest::StatusCode::BAD_REQUEST).is_retryable());
|
||||
assert!(!make_err(reqwest::StatusCode::UNAUTHORIZED).is_retryable());
|
||||
assert!(!make_err(reqwest::StatusCode::FORBIDDEN).is_retryable());
|
||||
assert!(!make_err(reqwest::StatusCode::NOT_FOUND).is_retryable());
|
||||
assert!(!make_err(reqwest::StatusCode::GATEWAY_TIMEOUT).is_retryable());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_delegates_to_vertex_error() {
|
||||
let err = vertex_error(
|
||||
429,
|
||||
"RESOURCE_EXHAUSTED",
|
||||
Some(vec![serde_json::json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "15s"
|
||||
})]),
|
||||
);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(15)));
|
||||
|
||||
assert_eq!(Error::NoCandidatesError.retry_delay(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_returns_http_status_retry_after() {
|
||||
let err = http_status_error(
|
||||
reqwest::StatusCode::TOO_MANY_REQUESTS,
|
||||
Some(Duration::from_secs(30)),
|
||||
);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(30)));
|
||||
|
||||
let err = http_status_error(reqwest::StatusCode::TOO_MANY_REQUESTS, None);
|
||||
assert_eq!(err.retry_delay(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_errors_not_retryable() {
|
||||
assert!(!Error::NoCandidatesError.is_retryable());
|
||||
let serde_err = serde_json::from_str::<String>("invalid").unwrap_err();
|
||||
assert!(!Error::Serde(serde_err).is_retryable());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,35 +63,36 @@ impl Decoder for ServerSentEventsCodec {
|
||||
&mut self,
|
||||
src: &mut tokio_util::bytes::BytesMut,
|
||||
) -> Result<Option<Self::Item>, Self::Error> {
|
||||
let Some(mut line) = self.lines_codec.decode(src)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
if line.is_empty() {
|
||||
return Ok(Some(mem::take(&mut self.next)));
|
||||
}
|
||||
|
||||
if line.starts_with(EVENT) {
|
||||
line.drain(..EVENT.len());
|
||||
self.next.event = Some(line);
|
||||
} else if line.starts_with(DATA) {
|
||||
line.drain(..DATA.len());
|
||||
if let Some(ref mut existing) = self.next.data {
|
||||
existing.push('\n');
|
||||
existing.push_str(&line);
|
||||
} else {
|
||||
self.next.data = Some(line);
|
||||
// Keep reading lines until an event is complete: returning `None`
|
||||
// tells `FramedRead` to wait for more bytes, even if `src` still
|
||||
// holds the rest of the event.
|
||||
while let Some(mut line) = self.lines_codec.decode(src)? {
|
||||
if line.is_empty() {
|
||||
return Ok(Some(mem::take(&mut self.next)));
|
||||
}
|
||||
|
||||
if line.starts_with(EVENT) {
|
||||
line.drain(..EVENT.len());
|
||||
self.next.event = Some(line);
|
||||
} else if line.starts_with(DATA) {
|
||||
line.drain(..DATA.len());
|
||||
if let Some(ref mut existing) = self.next.data {
|
||||
existing.push('\n');
|
||||
existing.push_str(&line);
|
||||
} else {
|
||||
self.next.data = Some(line);
|
||||
}
|
||||
} else if line.starts_with(ID) {
|
||||
line.drain(..ID.len());
|
||||
self.next.id = Some(line);
|
||||
} else if line.starts_with(RETRY) {
|
||||
line.drain(..RETRY.len());
|
||||
let Ok(retry) = line.parse() else {
|
||||
warn!(line, "Received invalid retry value");
|
||||
continue;
|
||||
};
|
||||
self.next.retry = Some(retry);
|
||||
}
|
||||
} else if line.starts_with(ID) {
|
||||
line.drain(..ID.len());
|
||||
self.next.id = Some(line);
|
||||
} else if line.starts_with(RETRY) {
|
||||
line.drain(..RETRY.len());
|
||||
let Ok(retry) = line.parse() else {
|
||||
warn!(line, "Received invalid retry value");
|
||||
return Ok(None);
|
||||
};
|
||||
self.next.retry = Some(retry);
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
@@ -106,3 +107,7 @@ pub fn stream_response(
|
||||
let body_reader = StreamReader::new(bytes_stream.map(|r| r.map_err(std::io::Error::other)));
|
||||
FramedRead::new(body_reader, ServerSentEventsCodec::new())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "event_source_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
45
src/network/event_source_tests.rs
Normal file
45
src/network/event_source_tests.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use tokio_util::bytes::BytesMut;
|
||||
|
||||
use super::*;
|
||||
|
||||
type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
#[test]
|
||||
fn decode_returns_each_event_already_in_the_buffer() -> Result<()> {
|
||||
let mut codec = ServerSentEventsCodec::new();
|
||||
let mut src = BytesMut::from("data: one\r\n\r\ndata: two\r\n\r\n");
|
||||
|
||||
let first = codec.decode(&mut src)?.ok_or("no first event")?;
|
||||
let second = codec.decode(&mut src)?.ok_or("no second event")?;
|
||||
|
||||
assert_eq!(first.data.as_deref(), Some("one"));
|
||||
assert_eq!(second.data.as_deref(), Some("two"));
|
||||
assert!(codec.decode(&mut src)?.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_keeps_a_partial_event_until_its_end_arrives() -> Result<()> {
|
||||
let mut codec = ServerSentEventsCodec::new();
|
||||
let mut src = BytesMut::from("event: delta\ndata: a\ndata: b\n");
|
||||
|
||||
assert!(codec.decode(&mut src)?.is_none());
|
||||
src.extend_from_slice(b"\n");
|
||||
let event = codec.decode(&mut src)?.ok_or("no event")?;
|
||||
|
||||
assert_eq!(event.event.as_deref(), Some("delta"));
|
||||
assert_eq!(event.data.as_deref(), Some("a\nb"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_skips_an_invalid_retry_and_finishes_the_event() -> Result<()> {
|
||||
let mut codec = ServerSentEventsCodec::new();
|
||||
let mut src = BytesMut::from("retry: soon\ndata: x\n\n");
|
||||
|
||||
let event = codec.decode(&mut src)?.ok_or("no event")?;
|
||||
|
||||
assert_eq!(event.retry, None);
|
||||
assert_eq!(event.data.as_deref(), Some("x"));
|
||||
Ok(())
|
||||
}
|
||||
@@ -5,7 +5,9 @@ use serde_json::Value;
|
||||
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
|
||||
pub struct Content {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub role: Option<Role>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub parts: Option<Vec<Part>>,
|
||||
}
|
||||
|
||||
@@ -22,6 +24,13 @@ impl Content {
|
||||
pub fn builder() -> ContentBuilder {
|
||||
ContentBuilder::default()
|
||||
}
|
||||
|
||||
pub fn system_prompt(prompt: impl Into<String>) -> Self {
|
||||
Content {
|
||||
parts: Some(vec![Part::text(prompt)]),
|
||||
role: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SystemPrompt {
|
||||
@@ -139,8 +148,28 @@ impl Part {
|
||||
pub fn function_call(name: impl Into<String>, args: Value) -> Self {
|
||||
Part {
|
||||
function_call: Some(FunctionCallData {
|
||||
id: None,
|
||||
name: name.into(),
|
||||
args,
|
||||
partial_args: None,
|
||||
will_continue: None,
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn function_call_with_id(
|
||||
id: impl Into<String>,
|
||||
name: impl Into<String>,
|
||||
args: Value,
|
||||
) -> Self {
|
||||
Part {
|
||||
function_call: Some(FunctionCallData {
|
||||
id: Some(id.into()),
|
||||
name: name.into(),
|
||||
args,
|
||||
partial_args: None,
|
||||
will_continue: None,
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
@@ -149,24 +178,119 @@ impl Part {
|
||||
pub fn function_response(name: impl Into<String>, response: Value) -> Self {
|
||||
Part {
|
||||
function_response: Some(FunctionResponseData {
|
||||
id: None,
|
||||
name: name.into(),
|
||||
response,
|
||||
parts: vec![],
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn function_response_with_id(
|
||||
id: impl Into<String>,
|
||||
name: impl Into<String>,
|
||||
response: Value,
|
||||
) -> Self {
|
||||
Part {
|
||||
function_response: Some(FunctionResponseData {
|
||||
id: Some(id.into()),
|
||||
name: name.into(),
|
||||
response,
|
||||
parts: vec![],
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_thought_signature(mut self, signature: impl Into<String>) -> Self {
|
||||
self.thought_signature = Some(signature.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_id(mut self, id: impl Into<String>) -> Self {
|
||||
let id = id.into();
|
||||
if let Some(ref mut call) = self.function_call {
|
||||
call.id = Some(id.clone());
|
||||
}
|
||||
if let Some(ref mut response) = self.function_response {
|
||||
response.id = Some(id);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_function_response_part(mut self, part: FunctionResponsePart) -> Self {
|
||||
if let Some(ref mut response) = self.function_response {
|
||||
response.parts.push(part);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_function_response_inline_data(
|
||||
self,
|
||||
mime_type: impl Into<String>,
|
||||
data: impl Into<String>,
|
||||
) -> Self {
|
||||
self.add_function_response_part(FunctionResponsePart::inline_data(mime_type, data))
|
||||
}
|
||||
|
||||
pub fn with_will_continue(mut self, will_continue: bool) -> Self {
|
||||
if let Some(ref mut call) = self.function_call {
|
||||
call.will_continue = Some(will_continue);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_partial_args(mut self, partial_args: Vec<Value>) -> Self {
|
||||
if let Some(ref mut call) = self.function_call {
|
||||
call.partial_args = Some(partial_args);
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FunctionCallData {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub name: String,
|
||||
#[serde(default, skip_serializing_if = "Value::is_null")]
|
||||
pub args: Value,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub partial_args: Option<Vec<Value>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub will_continue: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct FunctionResponseData {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<String>,
|
||||
pub name: String,
|
||||
pub response: Value,
|
||||
/// Media returned by the function (multimodal function responses), sent as
|
||||
/// `functionResponse.parts`. Omitted when empty.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub parts: Vec<FunctionResponsePart>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FunctionResponsePart {
|
||||
pub inline_data: InlineData,
|
||||
}
|
||||
|
||||
impl FunctionResponsePart {
|
||||
pub fn inline_data(mime_type: impl Into<String>, data: impl Into<String>) -> Self {
|
||||
Self {
|
||||
inline_data: InlineData {
|
||||
mime_type: mime_type.into(),
|
||||
data: data.into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
@@ -182,3 +306,210 @@ pub struct FileData {
|
||||
pub mime_type: String,
|
||||
pub file_uri: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::{Content, FunctionResponsePart, InlineData, Part, Role};
|
||||
|
||||
#[test]
|
||||
fn content_omits_unset_role_and_parts() {
|
||||
let system = Content::system_prompt("You are a helpful assistant.");
|
||||
assert_eq!(
|
||||
serde_json::to_value(&system).unwrap(),
|
||||
json!({
|
||||
"parts": [{"text": "You are a helpful assistant."}]
|
||||
})
|
||||
);
|
||||
|
||||
let role_only = Content {
|
||||
role: Some(Role::User),
|
||||
parts: None,
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_value(&role_only).unwrap(),
|
||||
json!({"role": "user"})
|
||||
);
|
||||
|
||||
let empty = Content::default();
|
||||
assert_eq!(serde_json::to_value(&empty).unwrap(), json!({}));
|
||||
|
||||
let roundtrip: Content = serde_json::from_str(r#"{"parts": [{"text": "Hello"}]}"#).unwrap();
|
||||
assert!(roundtrip.role.is_none());
|
||||
assert_eq!(roundtrip.get_text(), Some("Hello".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_call_id_handling() {
|
||||
let without_id = Part::function_call("lookup", json!({"q": "test"}));
|
||||
assert_eq!(
|
||||
serde_json::to_value(&without_id).unwrap(),
|
||||
json!({"functionCall": {"name": "lookup", "args": {"q": "test"}}})
|
||||
);
|
||||
|
||||
let with_id = Part::function_call("lookup", json!({"q": "test"})).with_id("call-1");
|
||||
assert_eq!(
|
||||
serde_json::to_value(&with_id).unwrap(),
|
||||
json!({"functionCall": {"id": "call-1", "name": "lookup", "args": {"q": "test"}}})
|
||||
);
|
||||
|
||||
let with_id_ctor = Part::function_call_with_id("call-2", "lookup", json!({"q": "test"}));
|
||||
assert_eq!(
|
||||
serde_json::to_value(&with_id_ctor).unwrap(),
|
||||
json!({"functionCall": {"id": "call-2", "name": "lookup", "args": {"q": "test"}}})
|
||||
);
|
||||
|
||||
let parsed: Part = serde_json::from_value(json!({
|
||||
"functionCall": {"id": "call-3", "name": "lookup", "args": {}}
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
parsed.function_call.as_ref().unwrap().id.as_deref(),
|
||||
Some("call-3")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_call_omits_unset_name_and_args_and_parses_missing_fields() {
|
||||
// Deserializing without args (e.g. zero-argument function call)
|
||||
let without_args: Part =
|
||||
serde_json::from_value(json!({"functionCall": {"name": "f"}})).unwrap();
|
||||
let fc = without_args.function_call.unwrap();
|
||||
assert_eq!(fc.name, "f");
|
||||
assert!(fc.args.is_null());
|
||||
assert!(fc.partial_args.is_none());
|
||||
assert!(fc.will_continue.is_none());
|
||||
|
||||
// Serializing when args is null omits args
|
||||
assert_eq!(
|
||||
serde_json::to_value(&Part {
|
||||
function_call: Some(fc),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap(),
|
||||
json!({"functionCall": {"name": "f"}})
|
||||
);
|
||||
|
||||
// Deserializing partial chunk without name and args
|
||||
let partial_chunk: Part = serde_json::from_value(json!({
|
||||
"functionCall": {
|
||||
"partialArgs": [{"key": "val"}],
|
||||
"willContinue": true
|
||||
}
|
||||
}))
|
||||
.unwrap();
|
||||
let fc_partial = partial_chunk.function_call.unwrap();
|
||||
assert_eq!(fc_partial.name, "");
|
||||
assert!(fc_partial.args.is_null());
|
||||
assert_eq!(fc_partial.partial_args, Some(vec![json!({"key": "val"})]));
|
||||
assert_eq!(fc_partial.will_continue, Some(true));
|
||||
|
||||
// Serializing partial chunk omits empty name and null args
|
||||
assert_eq!(
|
||||
serde_json::to_value(&Part {
|
||||
function_call: Some(fc_partial),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap(),
|
||||
json!({
|
||||
"functionCall": {
|
||||
"partialArgs": [{"key": "val"}],
|
||||
"willContinue": true
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_response_id_handling() {
|
||||
let without_id = Part::function_response("lookup", json!({"output": "ok"}));
|
||||
assert_eq!(
|
||||
serde_json::to_value(&without_id).unwrap(),
|
||||
json!({"functionResponse": {"name": "lookup", "response": {"output": "ok"}}})
|
||||
);
|
||||
|
||||
let with_id = Part::function_response("lookup", json!({"output": "ok"})).with_id("call-1");
|
||||
assert_eq!(
|
||||
serde_json::to_value(&with_id).unwrap(),
|
||||
json!({"functionResponse": {"id": "call-1", "name": "lookup", "response": {"output": "ok"}}})
|
||||
);
|
||||
|
||||
let with_id_ctor =
|
||||
Part::function_response_with_id("call-2", "lookup", json!({"output": "ok"}));
|
||||
assert_eq!(
|
||||
serde_json::to_value(&with_id_ctor).unwrap(),
|
||||
json!({"functionResponse": {"id": "call-2", "name": "lookup", "response": {"output": "ok"}}})
|
||||
);
|
||||
|
||||
let parsed: Part = serde_json::from_value(json!({
|
||||
"functionResponse": {"id": "call-3", "name": "lookup", "response": {}}
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
parsed.function_response.as_ref().unwrap().id.as_deref(),
|
||||
Some("call-3")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part_builder_helpers() {
|
||||
let part_sig = Part::function_call("fetch", json!({})).with_thought_signature("sig-abc");
|
||||
assert_eq!(
|
||||
serde_json::to_value(&part_sig).unwrap(),
|
||||
json!({
|
||||
"functionCall": {"name": "fetch", "args": {}},
|
||||
"thoughtSignature": "sig-abc"
|
||||
})
|
||||
);
|
||||
|
||||
let part_media = Part::function_response("capture", json!({}))
|
||||
.add_function_response_inline_data("image/jpeg", "base64data");
|
||||
assert_eq!(
|
||||
serde_json::to_value(&part_media).unwrap(),
|
||||
json!({
|
||||
"functionResponse": {
|
||||
"name": "capture",
|
||||
"response": {},
|
||||
"parts": [{"inlineData": {"mimeType": "image/jpeg", "data": "base64data"}}]
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_response_omits_empty_parts() {
|
||||
let part = Part::function_response("lookup", json!({"output": "ok"}));
|
||||
assert_eq!(
|
||||
serde_json::to_value(&part).unwrap(),
|
||||
json!({"functionResponse": {"name": "lookup", "response": {"output": "ok"}}})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_response_serializes_inline_data_parts() {
|
||||
let mut part = Part::function_response("screenshot", json!({}));
|
||||
part.function_response.as_mut().unwrap().parts = vec![FunctionResponsePart {
|
||||
inline_data: InlineData {
|
||||
mime_type: "image/png".to_string(),
|
||||
data: "aGVsbG8=".to_string(),
|
||||
},
|
||||
}];
|
||||
assert_eq!(
|
||||
serde_json::to_value(&part).unwrap(),
|
||||
json!({"functionResponse": {
|
||||
"name": "screenshot",
|
||||
"response": {},
|
||||
"parts": [{"inlineData": {"mimeType": "image/png", "data": "aGVsbG8="}}]
|
||||
}})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_response_without_parts_deserializes() {
|
||||
let part: Part =
|
||||
serde_json::from_value(json!({"functionResponse": {"name": "lookup", "response": {}}}))
|
||||
.unwrap();
|
||||
assert!(part.function_response.unwrap().parts.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
use std::fmt::Formatter;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct VertexApiError {
|
||||
pub code: i32,
|
||||
pub message: String,
|
||||
pub status: String,
|
||||
pub details: Option<Vec<ErrorType>>,
|
||||
/// Raw `google.rpc.*` detail entries, each tagged with an `@type` field. Kept as
|
||||
/// untyped JSON so that unknown detail types never break deserialization.
|
||||
pub details: Option<Vec<serde_json::Value>>,
|
||||
/// The delay from the HTTP response's `Retry-After` header, if present. Not part of
|
||||
/// the JSON error body; filled in by the client.
|
||||
#[serde(skip)]
|
||||
pub retry_after: Option<Duration>,
|
||||
}
|
||||
|
||||
impl core::fmt::Display for VertexApiError {
|
||||
@@ -19,36 +26,270 @@ impl core::fmt::Display for VertexApiError {
|
||||
|
||||
impl std::error::Error for VertexApiError {}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Link {
|
||||
pub description: String,
|
||||
pub url: String,
|
||||
impl VertexApiError {
|
||||
/// Returns the server-recommended retry delay, if any.
|
||||
///
|
||||
/// When Gemini rejects a request due to quota limits (`429 RESOURCE_EXHAUSTED`),
|
||||
/// its error details usually include a `google.rpc.RetryInfo` entry specifying
|
||||
/// how long the client should wait before retrying (e.g. `"37s"` or `"1.5s"`).
|
||||
/// That entry takes precedence; otherwise this falls back to
|
||||
/// [`retry_after`](Self::retry_after), taken from the `Retry-After` header.
|
||||
///
|
||||
/// Returns `None` if neither source provides a parseable delay.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use std::time::Duration;
|
||||
/// use gemini_rs::prelude::VertexApiError;
|
||||
/// use serde_json::json;
|
||||
///
|
||||
/// let err = VertexApiError {
|
||||
/// code: 429,
|
||||
/// message: "Resource exhausted".into(),
|
||||
/// status: "RESOURCE_EXHAUSTED".into(),
|
||||
/// details: Some(vec![json!({
|
||||
/// "@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
/// "retryDelay": "37s"
|
||||
/// })]),
|
||||
/// retry_after: None,
|
||||
/// };
|
||||
///
|
||||
/// assert_eq!(err.retry_delay(), Some(Duration::from_secs(37)));
|
||||
/// ```
|
||||
pub fn retry_delay(&self) -> Option<Duration> {
|
||||
self.retry_info_delay().or(self.retry_after)
|
||||
}
|
||||
|
||||
fn retry_info_delay(&self) -> Option<Duration> {
|
||||
self.details.as_deref()?.iter().find_map(|detail| {
|
||||
let is_retry_info = detail
|
||||
.get("@type")
|
||||
.and_then(|t| t.as_str())
|
||||
.is_some_and(is_retry_info_type);
|
||||
if !is_retry_info {
|
||||
return None;
|
||||
}
|
||||
detail
|
||||
.get("retryDelay")
|
||||
.or_else(|| detail.get("retry_delay"))
|
||||
.and_then(|d| d.as_str())
|
||||
.and_then(parse_duration)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "@type")]
|
||||
pub enum ErrorType {
|
||||
#[serde(rename = "type.googleapis.com/google.rpc.ErrorInfo")]
|
||||
ErrorInfo { metadata: ErrorInfoMetadata },
|
||||
|
||||
#[serde(rename = "type.googleapis.com/google.rpc.Help")]
|
||||
Help { links: Vec<Link> },
|
||||
|
||||
#[serde(rename = "type.googleapis.com/google.rpc.BadRequest")]
|
||||
BadRequest {
|
||||
#[serde(rename = "fieldViolations")]
|
||||
field_violations: Vec<FieldViolation>,
|
||||
},
|
||||
fn is_retry_info_type(type_url: &str) -> bool {
|
||||
type_url == "google.rpc.RetryInfo" || type_url.ends_with("/google.rpc.RetryInfo")
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct ErrorInfoMetadata {
|
||||
pub service: String,
|
||||
pub consumer: String,
|
||||
/// Parses a protobuf JSON `Duration` string (`"<secs>s"` or `"<secs>.<frac>s"`).
|
||||
fn parse_duration(s: &str) -> Option<Duration> {
|
||||
let s = s.strip_suffix('s')?;
|
||||
let (secs_str, frac_str) = match s.split_once('.') {
|
||||
Some((secs, frac)) => (secs, Some(frac)),
|
||||
None => (s, None),
|
||||
};
|
||||
|
||||
if secs_str.is_empty() || !secs_str.chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let secs: u64 = secs_str.parse().ok()?;
|
||||
|
||||
let nanos = match frac_str {
|
||||
Some(frac) => {
|
||||
if frac.is_empty() || frac.len() > 9 || !frac.chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let parsed: u32 = frac.parse().ok()?;
|
||||
parsed * 10u32.pow(9 - frac.len() as u32)
|
||||
}
|
||||
None => 0,
|
||||
};
|
||||
|
||||
Some(Duration::new(secs, nanos))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct FieldViolation {
|
||||
pub field: String,
|
||||
pub description: String,
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn retry_info_error(details: Vec<serde_json::Value>) -> VertexApiError {
|
||||
VertexApiError {
|
||||
code: 429,
|
||||
message: "Quota exceeded".into(),
|
||||
status: "RESOURCE_EXHAUSTED".into(),
|
||||
details: Some(details),
|
||||
retry_after: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserializes_unknown_detail_types() -> Result<(), serde_json::Error> {
|
||||
let body = r#"{
|
||||
"code": 429,
|
||||
"message": "Resource exhausted",
|
||||
"status": "RESOURCE_EXHAUSTED",
|
||||
"details": [
|
||||
{
|
||||
"@type": "type.googleapis.com/google.rpc.QuotaFailure",
|
||||
"violations": [{ "quotaMetric": "generate_content_requests" }]
|
||||
},
|
||||
{
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "37s"
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
let err: VertexApiError = serde_json::from_str(body)?;
|
||||
assert_eq!(err.details.as_ref().map(Vec::len), Some(2));
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(37)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_whole_seconds() {
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "37s"
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(37)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_fractional_seconds() {
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "1.5s"
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_millis(1500)));
|
||||
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "0.005s"
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_millis(5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_without_details() {
|
||||
let err = VertexApiError {
|
||||
details: None,
|
||||
..retry_info_error(vec![])
|
||||
};
|
||||
assert_eq!(err.retry_delay(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_falls_back_to_retry_after() {
|
||||
let err = VertexApiError {
|
||||
retry_after: Some(Duration::from_secs(30)),
|
||||
..retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.ErrorInfo"
|
||||
})])
|
||||
};
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(30)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_prefers_retry_info_over_retry_after() {
|
||||
let err = VertexApiError {
|
||||
retry_after: Some(Duration::from_secs(30)),
|
||||
..retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "37s"
|
||||
})])
|
||||
};
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(37)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_without_retry_info() {
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.BadRequest"
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), None);
|
||||
|
||||
assert_eq!(retry_info_error(vec![]).retry_delay(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_with_unparsable_or_missing_retry_delay() {
|
||||
let cases = [
|
||||
"invalid",
|
||||
"37", // missing 's' suffix
|
||||
"-1s", // negative
|
||||
"-1.5s", // negative fractional
|
||||
"1.5.0s", // multiple decimals
|
||||
".5s", // missing leading digits
|
||||
"1.s", // missing fractional digits
|
||||
"", // empty
|
||||
"s", // only suffix
|
||||
" 37s", // leading space
|
||||
"37s ", // trailing space
|
||||
"NaNs", // non-digit
|
||||
"1e3s", // scientific notation
|
||||
"1.1234567890s", // more than 9 fractional digits
|
||||
];
|
||||
|
||||
for case in cases {
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": case
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), None, "expected None for: {case:?}");
|
||||
}
|
||||
|
||||
let missing = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo"
|
||||
})]);
|
||||
assert_eq!(missing.retry_delay(), None);
|
||||
|
||||
let non_string = retry_info_error(vec![json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": 37
|
||||
})]);
|
||||
assert_eq!(non_string.retry_delay(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_with_multiple_details_entries() {
|
||||
let err = retry_info_error(vec![
|
||||
json!({
|
||||
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
|
||||
"reason": "RATE_LIMIT_EXCEEDED"
|
||||
}),
|
||||
json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "42s"
|
||||
}),
|
||||
]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(42)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_with_multiple_retry_info_entries_skips_malformed() {
|
||||
let err = retry_info_error(vec![
|
||||
json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "malformed"
|
||||
}),
|
||||
json!({
|
||||
"@type": "type.googleapis.com/google.rpc.RetryInfo",
|
||||
"retryDelay": "20s"
|
||||
}),
|
||||
]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(20)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_delay_snake_case_and_short_type() {
|
||||
let err = retry_info_error(vec![json!({
|
||||
"@type": "google.rpc.RetryInfo",
|
||||
"retry_delay": "10s"
|
||||
})]);
|
||||
assert_eq!(err.retry_delay(), Some(Duration::from_secs(10)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,11 +315,20 @@ pub struct SafetyRating {
|
||||
pub severity_score: Option<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UsageMetadata {
|
||||
pub candidates_token_count: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub prompt_token_count: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cached_content_token_count: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub candidates_token_count: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tool_use_prompt_token_count: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thoughts_token_count: Option<u32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub total_token_count: Option<u32>,
|
||||
}
|
||||
|
||||
@@ -328,7 +337,14 @@ pub struct UsageMetadata {
|
||||
pub struct FunctionDeclaration {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub parameters: Value,
|
||||
/// Parameters in Vertex's OpenAPI schema subset. Don't set both this and
|
||||
/// `parameters_json_schema`: Vertex rejects the request.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub parameters: Option<Value>,
|
||||
/// Parameters as a JSON Schema, which accepts keywords the OpenAPI subset doesn't
|
||||
/// (`$schema`, `$ref`/`$defs`, `const`, type arrays, ...).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub parameters_json_schema: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -370,7 +386,36 @@ impl GenerateContentResponse {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{GenerateContentResponse, GenerateContentResponseResult};
|
||||
use serde_json::json;
|
||||
|
||||
use super::{
|
||||
FunctionDeclaration, GenerateContentResponse, GenerateContentResponseResult, UsageMetadata,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn serializes_function_declaration_with_only_the_set_schema_field() {
|
||||
let schema = json!({"type": "object", "properties": {"q": {"type": "string"}}});
|
||||
let json_schema = FunctionDeclaration {
|
||||
name: "probe".to_string(),
|
||||
description: "Probe".to_string(),
|
||||
parameters: None,
|
||||
parameters_json_schema: Some(schema.clone()),
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_value(&json_schema).unwrap(),
|
||||
json!({"name": "probe", "description": "Probe", "parametersJsonSchema": schema})
|
||||
);
|
||||
|
||||
let openapi = FunctionDeclaration {
|
||||
parameters: Some(schema.clone()),
|
||||
parameters_json_schema: None,
|
||||
..json_schema
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_value(&openapi).unwrap(),
|
||||
json!({"name": "probe", "description": "Probe", "parameters": schema})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn parses_empty_metadata_response() {
|
||||
@@ -378,6 +423,47 @@ mod tests {
|
||||
serde_json::from_str::<GenerateContentResponseResult>(input).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_usage_metadata_with_all_token_counts() {
|
||||
let input = r#"{
|
||||
"promptTokenCount": 100,
|
||||
"cachedContentTokenCount": 50,
|
||||
"candidatesTokenCount": 200,
|
||||
"toolUsePromptTokenCount": 25,
|
||||
"thoughtsTokenCount": 75,
|
||||
"totalTokenCount": 375
|
||||
}"#;
|
||||
let metadata: UsageMetadata = serde_json::from_str(input).unwrap();
|
||||
assert_eq!(
|
||||
metadata,
|
||||
UsageMetadata {
|
||||
prompt_token_count: Some(100),
|
||||
cached_content_token_count: Some(50),
|
||||
candidates_token_count: Some(200),
|
||||
tool_use_prompt_token_count: Some(25),
|
||||
thoughts_token_count: Some(75),
|
||||
total_token_count: Some(375),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serializes_usage_metadata_skipping_none_fields() {
|
||||
let metadata = UsageMetadata {
|
||||
prompt_token_count: Some(10),
|
||||
total_token_count: Some(10),
|
||||
..Default::default()
|
||||
};
|
||||
let val = serde_json::to_value(&metadata).unwrap();
|
||||
assert_eq!(
|
||||
val,
|
||||
json!({
|
||||
"promptTokenCount": 10,
|
||||
"totalTokenCount": 10
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn parses_max_tokens_response() {
|
||||
let input = r#"{
|
||||
|
||||
Reference in New Issue
Block a user