Compare commits
5 Commits
feat/funct
...
fix/stream
| Author | SHA1 | Date | |
|---|---|---|---|
| 9bade7a1e6 | |||
| ba9870277c | |||
| 196d5a9f55 | |||
| 43cf7933fc | |||
| 69532ad110 |
@@ -45,7 +45,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
function_declarations: Some(vec![FunctionDeclaration {
|
function_declarations: Some(vec![FunctionDeclaration {
|
||||||
name: "take_snapshot".to_string(),
|
name: "take_snapshot".to_string(),
|
||||||
description: "Takes a snapshot of the camera and returns it as an image.".to_string(),
|
description: "Takes a snapshot of the camera and returns it as an image.".to_string(),
|
||||||
parameters: json!({"type": "object", "properties": {}}),
|
parameters: Some(json!({"type": "object", "properties": {}})),
|
||||||
|
parameters_json_schema: None,
|
||||||
}]),
|
}]),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
}];
|
}];
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ use crate::error::{Error, Result};
|
|||||||
use crate::network::event_source::{EventSource, ServerSentEvent};
|
use crate::network::event_source::{EventSource, ServerSentEvent};
|
||||||
use crate::prelude::{
|
use crate::prelude::{
|
||||||
Candidate, Content, CountTokensRequest, CountTokensResponse, GenerateContentRequest,
|
Candidate, Content, CountTokensRequest, CountTokensResponse, GenerateContentRequest,
|
||||||
GenerateContentResponse, GenerateContentResponseResult, TextEmbeddingRequest,
|
GenerateContentResponse, GenerateContentResponseError, GenerateContentResponseResult,
|
||||||
TextEmbeddingResponse,
|
TextEmbeddingRequest, TextEmbeddingResponse,
|
||||||
};
|
};
|
||||||
use crate::types::{PredictImageRequest, PredictImageResponse, Role};
|
use crate::types::{PredictImageRequest, PredictImageResponse, Role};
|
||||||
use crate::{prelude::Part, token_provider::TokenProvider};
|
use crate::{prelude::Part, token_provider::TokenProvider};
|
||||||
@@ -42,16 +42,27 @@ 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
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn generate_content(
|
pub async fn generate_content(
|
||||||
&self,
|
&self,
|
||||||
request: &GenerateContentRequest,
|
request: &GenerateContentRequest,
|
||||||
model: &str,
|
model: &str,
|
||||||
) -> Result<GenerateContentResponseResult> {
|
) -> Result<GenerateContentResponseResult> {
|
||||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||||
let endpoint_url: String = format!(
|
let endpoint_url = self.endpoint_url(ENDPOINT_VERSION, &format!("{model}:generateContent"));
|
||||||
"https://{}/{}/projects/{}/locations/{}/publishers/google/models/{}:generateContent",
|
|
||||||
self.api_endpoint, ENDPOINT_VERSION, self.project_id, self.location_id, model,
|
|
||||||
);
|
|
||||||
let resp = self
|
let resp = self
|
||||||
.client
|
.client
|
||||||
.post(&endpoint_url)
|
.post(&endpoint_url)
|
||||||
@@ -81,9 +92,9 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
model: &str,
|
model: &str,
|
||||||
) -> Result<impl Stream<Item = Result<GenerateContentResponseResult>> + use<'_, T>> {
|
) -> Result<impl Stream<Item = Result<GenerateContentResponseResult>> + use<'_, T>> {
|
||||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||||
let endpoint_url = format!(
|
let endpoint_url = self.endpoint_url(
|
||||||
"https://{}/{}/projects/{}/locations/{}/publishers/google/models/{}:streamGenerateContent?alt=sse",
|
ENDPOINT_VERSION,
|
||||||
self.api_endpoint, ENDPOINT_VERSION, self.project_id, self.location_id, model,
|
&format!("{model}:streamGenerateContent?alt=sse"),
|
||||||
);
|
);
|
||||||
let response = self
|
let response = self
|
||||||
.client
|
.client
|
||||||
@@ -92,6 +103,16 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
.json(request)
|
.json(request)
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.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 });
|
||||||
|
}
|
||||||
|
|
||||||
Ok(response.event_stream().filter_map(Self::parse_sse_event))
|
Ok(response.event_stream().filter_map(Self::parse_sse_event))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,10 +167,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
request: &TextEmbeddingRequest,
|
request: &TextEmbeddingRequest,
|
||||||
model: &str,
|
model: &str,
|
||||||
) -> Result<TextEmbeddingResponse> {
|
) -> Result<TextEmbeddingResponse> {
|
||||||
let endpoint_url = format!(
|
let endpoint_url = self.endpoint_url("v1", &format!("{model}:predict"));
|
||||||
"https://{}/v1/projects/{}/locations/{}/publishers/google/models/{}:predict",
|
|
||||||
self.api_endpoint, self.project_id, self.location_id, model,
|
|
||||||
);
|
|
||||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||||
let resp = self
|
let resp = self
|
||||||
.client
|
.client
|
||||||
@@ -168,10 +186,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
request: &CountTokensRequest,
|
request: &CountTokensRequest,
|
||||||
model: &str,
|
model: &str,
|
||||||
) -> Result<CountTokensResponse> {
|
) -> Result<CountTokensResponse> {
|
||||||
let endpoint_url = format!(
|
let endpoint_url = self.endpoint_url(ENDPOINT_VERSION, &format!("{model}:countTokens"));
|
||||||
"https://{}/{}/projects/{}/locations/{}/publishers/google/models/{}:countTokens",
|
|
||||||
self.api_endpoint, ENDPOINT_VERSION, self.project_id, self.location_id, model,
|
|
||||||
);
|
|
||||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||||
let resp = self
|
let resp = self
|
||||||
.client
|
.client
|
||||||
@@ -191,10 +206,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
request: &PredictImageRequest,
|
request: &PredictImageRequest,
|
||||||
model: &str,
|
model: &str,
|
||||||
) -> Result<PredictImageResponse> {
|
) -> Result<PredictImageResponse> {
|
||||||
let endpoint_url = format!(
|
let endpoint_url = self.endpoint_url("v1", &format!("{model}:predict"));
|
||||||
"https://{}/v1/projects/{}/locations/{}/publishers/google/models/{}:predict",
|
|
||||||
self.api_endpoint, self.project_id, self.location_id, model,
|
|
||||||
);
|
|
||||||
|
|
||||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||||
let resp = self
|
let resp = self
|
||||||
@@ -216,3 +228,8 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "client_tests.rs"]
|
||||||
|
mod tests;
|
||||||
|
|
||||||
|
|||||||
130
src/client_tests.rs
Normal file
130
src/client_tests.rs
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn stream_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 JSON payload received. Unknown name \"$schema\" at 'tools[0].function_declarations[0].parameters': Cannot find field.", "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.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 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 = 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 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 sse_body = "data: {\"candidates\": [{\"content\": {\"role\": \"model\", \"parts\": [{\"text\": \"Hello world\"}]}}]}\n\n";
|
||||||
|
let response = format!(
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||||
|
sse_body.len(),
|
||||||
|
sse_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 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(())
|
||||||
|
}
|
||||||
@@ -16,6 +16,11 @@ pub enum Error {
|
|||||||
NoCandidatesError,
|
NoCandidatesError,
|
||||||
/// An error occurred while decoding the SSE event stream.
|
/// An error occurred while decoding the SSE event stream.
|
||||||
EventSourceError(LinesCodecError),
|
EventSourceError(LinesCodecError),
|
||||||
|
/// An HTTP error status was returned by the server.
|
||||||
|
HttpStatus {
|
||||||
|
status: reqwest::StatusCode,
|
||||||
|
body: String,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for Error {
|
impl Display for Error {
|
||||||
@@ -28,6 +33,7 @@ impl Display for Error {
|
|||||||
Error::VertexError(e) => write!(f, "Vertex error: {e}"),
|
Error::VertexError(e) => write!(f, "Vertex error: {e}"),
|
||||||
Error::NoCandidatesError => write!(f, "No candidates returned for the prompt"),
|
Error::NoCandidatesError => write!(f, "No candidates returned for the prompt"),
|
||||||
Error::EventSourceError(e) => write!(f, "EventSource error: {e}"),
|
Error::EventSourceError(e) => write!(f, "EventSource error: {e}"),
|
||||||
|
Error::HttpStatus { status, body } => write!(f, "HTTP status {status}: {body}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use std::fmt::Formatter;
|
|||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct VertexApiError {
|
pub struct VertexApiError {
|
||||||
pub code: i32,
|
pub code: i32,
|
||||||
pub message: String,
|
pub message: String,
|
||||||
@@ -19,13 +19,13 @@ impl core::fmt::Display for VertexApiError {
|
|||||||
|
|
||||||
impl std::error::Error for VertexApiError {}
|
impl std::error::Error for VertexApiError {}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct Link {
|
pub struct Link {
|
||||||
pub description: String,
|
pub description: String,
|
||||||
pub url: String,
|
pub url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(tag = "@type")]
|
#[serde(tag = "@type")]
|
||||||
pub enum ErrorType {
|
pub enum ErrorType {
|
||||||
#[serde(rename = "type.googleapis.com/google.rpc.ErrorInfo")]
|
#[serde(rename = "type.googleapis.com/google.rpc.ErrorInfo")]
|
||||||
@@ -41,13 +41,13 @@ pub enum ErrorType {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct ErrorInfoMetadata {
|
pub struct ErrorInfoMetadata {
|
||||||
pub service: String,
|
pub service: String,
|
||||||
pub consumer: String,
|
pub consumer: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct FieldViolation {
|
pub struct FieldViolation {
|
||||||
pub field: String,
|
pub field: String,
|
||||||
pub description: String,
|
pub description: String,
|
||||||
|
|||||||
@@ -328,7 +328,14 @@ pub struct UsageMetadata {
|
|||||||
pub struct FunctionDeclaration {
|
pub struct FunctionDeclaration {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub description: 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)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
@@ -370,7 +377,34 @@ impl GenerateContentResponse {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{GenerateContentResponse, GenerateContentResponseResult};
|
use serde_json::json;
|
||||||
|
|
||||||
|
use super::{FunctionDeclaration, GenerateContentResponse, GenerateContentResponseResult};
|
||||||
|
|
||||||
|
#[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]
|
#[test]
|
||||||
pub fn parses_empty_metadata_response() {
|
pub fn parses_empty_metadata_response() {
|
||||||
|
|||||||
Reference in New Issue
Block a user