4 Commits

Author SHA1 Message Date
8d1c9c3bb6 feat: check response status in all GeminiClient methods and add Error::is_retryable() (#10)
Some checks failed
Rust / build (pull_request) Failing after 3s
2026-10-26 19:24:49 +00:00
7264276232 Merge pull request 'feat: add thoughts, cached content, and tool use token counts to UsageMetadata (#9)' (#14) from feat/usage-metadata-token-counts into main
Some checks failed
Rust / build (push) Has been cancelled
Reviewed-on: #14
2026-10-26 19:07:08 +00:00
763a1a5da6 feat: add thoughts, cached content, and tool use token counts to UsageMetadata (#9)
Some checks failed
Rust / build (pull_request) Failing after 3s
2026-10-26 18:52:18 +00:00
f9e74ee171 Merge pull request 'fix: propagate LinesCodecError in parse_sse_event (#8)' (#13) from fix/propagate-sse-lines-codec-error into main
Some checks failed
Rust / build (push) Has been cancelled
Reviewed-on: #13
2026-10-26 18:44:14 +00:00
4 changed files with 361 additions and 15 deletions

View File

@@ -56,6 +56,19 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
) )
} }
async fn error_for_status(response: reqwest::Response) -> Result<reqwest::Response> {
if !response.status().is_success() {
let status = response.status();
let body = response.text().await?;
if let Ok(error_response) = serde_json::from_str::<GenerateContentResponseError>(&body)
{
return Err(error_response.error.into());
}
return Err(Error::HttpStatus { status, body });
}
Ok(response)
}
pub async fn generate_content( pub async fn generate_content(
&self, &self,
request: &GenerateContentRequest, request: &GenerateContentRequest,
@@ -71,6 +84,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
.send() .send()
.await?; .await?;
let resp = Self::error_for_status(resp).await?;
let txt_json = resp.text().await?; let txt_json = resp.text().await?;
tracing::debug!("generate_content response: {:?}", txt_json); tracing::debug!("generate_content response: {:?}", txt_json);
match serde_json::from_str::<GenerateContentResponse>(&txt_json) { match serde_json::from_str::<GenerateContentResponse>(&txt_json) {
@@ -104,16 +118,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
.send() .send()
.await?; .await?;
if !response.status().is_success() { let response = Self::error_for_status(response).await?;
let status = response.status();
let body = response.text().await?;
if let Ok(error_response) = serde_json::from_str::<GenerateContentResponseError>(&body)
{
return Err(error_response.error.into());
}
return Err(Error::HttpStatus { status, body });
}
Ok(response.event_stream().filter_map(Self::parse_sse_event)) Ok(response.event_stream().filter_map(Self::parse_sse_event))
} }
@@ -182,6 +187,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
.json(&request) .json(&request)
.send() .send()
.await?; .await?;
let resp = Self::error_for_status(resp).await?;
let txt_json = resp.text().await?; let txt_json = resp.text().await?;
tracing::debug!("text_embeddings response: {:?}", txt_json); tracing::debug!("text_embeddings response: {:?}", txt_json);
Ok(serde_json::from_str::<TextEmbeddingResponse>(&txt_json)?) Ok(serde_json::from_str::<TextEmbeddingResponse>(&txt_json)?)
@@ -201,7 +207,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
.json(&request) .json(&request)
.send() .send()
.await?; .await?;
let resp = Self::error_for_status(resp).await?;
let txt_json = resp.text().await?; let txt_json = resp.text().await?;
tracing::debug!("count_tokens response: {:?}", txt_json); tracing::debug!("count_tokens response: {:?}", txt_json);
Ok(serde_json::from_str(&txt_json)?) Ok(serde_json::from_str(&txt_json)?)
@@ -222,7 +228,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
.json(&request) .json(&request)
.send() .send()
.await?; .await?;
let resp = Self::error_for_status(resp).await?;
let txt_json = resp.text().await?; let txt_json = resp.text().await?;
match serde_json::from_str::<PredictImageResponse>(&txt_json) { match serde_json::from_str::<PredictImageResponse>(&txt_json) {

View File

@@ -1,6 +1,7 @@
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use super::*; use super::*;
use crate::types::PredictImageRequestParameters;
type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>; type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;
@@ -203,3 +204,203 @@ async fn stream_generate_content_yields_error_on_truncated_sse() -> Result<()> {
} }
Ok(()) Ok(())
} }
#[tokio::test]
async fn generate_content_returns_http_status_on_non_json_503() -> Result<()> {
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;
let body = "Service Unavailable";
let response = format!(
"HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
socket.write_all(response.as_bytes()).await.unwrap();
});
let client = GeminiClient::new(
MockTokenProvider,
format!("http://{addr}"),
"test-project".to_string(),
"test-location".to_string(),
);
let request = GenerateContentRequest::default();
let result = client.generate_content(&request, "gemini-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_returns_vertex_error_on_400_json() -> Result<()> {
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;
let body = r#"{"error": {"code": 400, "message": "Invalid request", "status": "INVALID_ARGUMENT"}}"#;
let response = format!(
"HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
socket.write_all(response.as_bytes()).await.unwrap();
});
let client = GeminiClient::new(
MockTokenProvider,
format!("http://{addr}"),
"test-project".to_string(),
"test-location".to_string(),
);
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");
}
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 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;
let body = "Bad Gateway";
let response = format!(
"HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
socket.write_all(response.as_bytes()).await.unwrap();
});
let client = GeminiClient::new(
MockTokenProvider,
format!("http://{addr}"),
"test-project".to_string(),
"test-location".to_string(),
);
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 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;
let body = "Internal Server Error";
let response = format!(
"HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
socket.write_all(response.as_bytes()).await.unwrap();
});
let client = GeminiClient::new(
MockTokenProvider,
format!("http://{addr}"),
"test-project".to_string(),
"test-location".to_string(),
);
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 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;
let body = "Service Unavailable";
let response = format!(
"HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
socket.write_all(response.as_bytes()).await.unwrap();
});
let client = GeminiClient::new(
MockTokenProvider,
format!("http://{addr}"),
"test-project".to_string(),
"test-location".to_string(),
);
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(())
}

View File

@@ -75,3 +75,90 @@ impl From<LinesCodecError> for Error {
Error::EventSourceError(e) 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,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vertex_error_retryable_classification() {
let make_err = |code: i32, status: &str| {
Error::VertexError(types::VertexApiError {
code,
message: "test".to_string(),
status: status.to_string(),
details: 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| Error::HttpStatus {
status,
body: "error".to_string(),
};
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 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());
}
}

View File

@@ -315,11 +315,20 @@ pub struct SafetyRating {
pub severity_score: Option<f32>, pub severity_score: Option<f32>,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct UsageMetadata { pub struct UsageMetadata {
pub candidates_token_count: Option<u32>, #[serde(skip_serializing_if = "Option::is_none")]
pub prompt_token_count: Option<u32>, 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>, pub total_token_count: Option<u32>,
} }
@@ -379,7 +388,9 @@ impl GenerateContentResponse {
mod tests { mod tests {
use serde_json::json; use serde_json::json;
use super::{FunctionDeclaration, GenerateContentResponse, GenerateContentResponseResult}; use super::{
FunctionDeclaration, GenerateContentResponse, GenerateContentResponseResult, UsageMetadata,
};
#[test] #[test]
fn serializes_function_declaration_with_only_the_set_schema_field() { fn serializes_function_declaration_with_only_the_set_schema_field() {
@@ -412,6 +423,47 @@ mod tests {
serde_json::from_str::<GenerateContentResponseResult>(input).unwrap(); 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] #[test]
pub fn parses_max_tokens_response() { pub fn parses_max_tokens_response() {
let input = r#"{ let input = r#"{