Compare commits
6 Commits
feat/usage
...
feat/funct
| Author | SHA1 | Date | |
|---|---|---|---|
| 2f15b5298d | |||
| 01a4300bb3 | |||
| a2cff20aff | |||
| 7d5c6e3e28 | |||
| 8d1c9c3bb6 | |||
| 7264276232 |
@@ -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(
|
||||
&self,
|
||||
request: &GenerateContentRequest,
|
||||
@@ -71,6 +84,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) {
|
||||
@@ -104,16 +118,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
let response = Self::error_for_status(response).await?;
|
||||
Ok(response.event_stream().filter_map(Self::parse_sse_event))
|
||||
}
|
||||
|
||||
@@ -182,6 +187,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)?)
|
||||
@@ -201,7 +207,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)?)
|
||||
@@ -222,7 +228,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) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use super::*;
|
||||
use crate::types::PredictImageRequestParameters;
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
#[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(())
|
||||
}
|
||||
|
||||
87
src/error.rs
87
src/error.rs
@@ -75,3 +75,90 @@ 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,6 +178,7 @@ 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![],
|
||||
@@ -156,16 +186,88 @@ impl Part {
|
||||
..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
|
||||
@@ -180,6 +282,17 @@ 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)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InlineData {
|
||||
@@ -198,7 +311,171 @@ pub struct FileData {
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::{FunctionResponsePart, InlineData, Part};
|
||||
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() {
|
||||
|
||||
Reference in New Issue
Block a user