Compare commits
26 Commits
db5a01afef
...
feat/usage
| Author | SHA1 | Date | |
|---|---|---|---|
| 763a1a5da6 | |||
| f9e74ee171 | |||
| 20f7a4a34c | |||
| e64a748d5c | |||
| 166bdefa89 | |||
| ebb49eb929 | |||
| 9bade7a1e6 | |||
| ba9870277c | |||
| 196d5a9f55 | |||
| 43cf7933fc | |||
| 69532ad110 | |||
| e120780006 | |||
| f4f275f2f9 | |||
| 494aab6d14 | |||
| ad82fc712b | |||
| f9c50a3f45 | |||
| 1d467138ed | |||
| 9a8732f609 | |||
| 6e64b8fd72 | |||
| d1678bdc37 | |||
| 8ff379d040 | |||
| 51d6a27017 | |||
| de9b14b984 | |||
| 83663680c9 | |||
| fd1223da59 | |||
| 56d6b95c53 |
25
Cargo.toml
25
Cargo.toml
@@ -1,26 +1,27 @@
|
||||
[package]
|
||||
name = "gemini-rs"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
edition = "2024"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
deadqueue = "0.2"
|
||||
futures-util = "0.3"
|
||||
gcp_auth = "0.12"
|
||||
reqwest = { version = "0.12", features = ["json", "gzip"] }
|
||||
reqwest-eventsource = "0.6"
|
||||
reqwest = { version = "0.13", features = ["json", "gzip", "stream"] }
|
||||
tokio-util = "0.7"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = { version = "1"}
|
||||
serde_with = { version = "3.9", features = ["base64"]}
|
||||
serde_json = { version = "1" }
|
||||
serde_with = { version = "3.21", features = ["base64"] }
|
||||
tracing = "0.1"
|
||||
tokio = { version = "1" }
|
||||
tokio-stream = "0.1.18"
|
||||
|
||||
[dev-dependencies]
|
||||
console = "0.15.8"
|
||||
dialoguer = "0.11.0"
|
||||
image = "0.25.2"
|
||||
indicatif = "0.17.8"
|
||||
tokio = { version = "1.37.0", features = ["full"] }
|
||||
tracing-subscriber = "0.3.18"
|
||||
base64 = "0.23.1"
|
||||
console = "0.16.4"
|
||||
dialoguer = "0.12.0"
|
||||
image = "0.25.10"
|
||||
indicatif = "0.18.6"
|
||||
tokio = { version = "1.52.3", features = ["full"] }
|
||||
tracing-subscriber = "0.3.23"
|
||||
|
||||
132
README.md
132
README.md
@@ -1,2 +1,132 @@
|
||||
# gemini-rs [](https://github.com/andreban/gemini-rs/actions/workflows/rust.yml)
|
||||
A Rust wrapper for the Google Cloud Gemini REST API
|
||||
|
||||
A Rust wrapper for the Google Cloud Gemini REST API (Vertex AI).
|
||||
|
||||
## Features
|
||||
|
||||
- **Text Generation**: Generate text responses from Gemini models
|
||||
- **Streaming**: Stream responses in real-time using SSE
|
||||
- **Text Embeddings**: Generate text embeddings for ML pipelines
|
||||
- **Token Counting**: Count tokens before making API calls
|
||||
- **Image Generation**: Generate and predict images
|
||||
- **Conversations**: Maintain multi-turn dialogue context
|
||||
- **Safety Settings**: Configure content safety thresholds
|
||||
- **Function Calling**: Declare and use tools/functions
|
||||
- **Google Search Retrieval**: Enable dynamic search-backed responses
|
||||
- **JSON Schema Responses**: Get structured JSON output
|
||||
|
||||
## Installation
|
||||
|
||||
Add this to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
gemini-rs = { path = "path/to/gemini-rs" }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```rust
|
||||
use gemini_rs::prelude::*;
|
||||
use gcp_auth::AuthenticationManager;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Authenticate with GCP
|
||||
let provider = AuthenticationManager::new();
|
||||
|
||||
// Create client
|
||||
let client = GeminiClient::new(
|
||||
provider,
|
||||
"us-central1-aiplatform.googleapis.com".to_string(),
|
||||
"your-project-id".to_string(),
|
||||
"us-central1".to_string(),
|
||||
);
|
||||
|
||||
// Generate content
|
||||
let request = GenerateContentRequest::builder()
|
||||
.contents(vec![Content {
|
||||
role: Some(Role::User),
|
||||
parts: Some(vec![Part::Text("Hello, Gemini!".to_string())]),
|
||||
}])
|
||||
.build();
|
||||
|
||||
let response = client.generate_content(&request, "gemini-2.0-flash").await?;
|
||||
|
||||
for candidate in &response.candidates {
|
||||
if let Some(text) = candidate.get_text() {
|
||||
println!("{}", text);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
Run the examples in the `examples/` directory:
|
||||
|
||||
```bash
|
||||
# Generate text
|
||||
cargo run --example text-from-text
|
||||
|
||||
# Streaming text generation
|
||||
cargo run --example text-from-text-streaming
|
||||
|
||||
# Multi-turn conversation
|
||||
cargo run --example conversation
|
||||
|
||||
# Count tokens
|
||||
cargo run --example count-tokens
|
||||
|
||||
# Generate images
|
||||
cargo run --example generate_image
|
||||
|
||||
# Text embeddings
|
||||
cargo run --example text-embedding
|
||||
|
||||
# JSON schema responses
|
||||
cargo run --example json-schema
|
||||
|
||||
# Safety settings
|
||||
cargo run --example safety-setting
|
||||
|
||||
# System instructions
|
||||
cargo run --example system_instruction
|
||||
|
||||
# Google Search Retrieval
|
||||
cargo run --example google-search-retrieval
|
||||
|
||||
# Google Search tool
|
||||
cargo run --example google-search
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### Client Methods
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `generate_content()` | Generate content from a model |
|
||||
| `generate_content_stream()` | Stream content generation responses |
|
||||
| `stream_generate_content()` | Stream content using a queue-based approach |
|
||||
| `prompt_conversation()` | Send a conversation prompt and get response |
|
||||
| `text_embeddings()` | Generate text embeddings |
|
||||
| `count_tokens()` | Count tokens in a request |
|
||||
| `predict_image()` | Generate/predict images |
|
||||
|
||||
### Supported Models
|
||||
|
||||
The library works with all Vertex AI Gemini models, including:
|
||||
- `gemini-2.0-flash`
|
||||
- `gemini-2.0-flash-lite`
|
||||
- `gemini-1.5-pro`
|
||||
- `gemini-1.5-flash`
|
||||
- `text-embedding-004`
|
||||
- `imagen-3.0-generate-002`
|
||||
|
||||
## License
|
||||
|
||||
See [LICENSE](LICENSE) for details.
|
||||
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -34,9 +34,14 @@ pub async fn main() -> Result<(), Box<dyn Error>> {
|
||||
mime_type: Some("image/jpeg".to_string()),
|
||||
compression_quality: Some(75),
|
||||
}),
|
||||
person_generation: Some("allow_all".to_string()),
|
||||
safety_setting: Some("block_only_high".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
println!("Request: {:#?}", serde_json::to_string(&request).unwrap());
|
||||
|
||||
let mut result = gemini
|
||||
.predict_image(&request, "imagen-3.0-fast-generate-001")
|
||||
.await?;
|
||||
|
||||
@@ -20,7 +20,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let request = GenerateContentRequest {
|
||||
contents: vec![Content {
|
||||
role: Some(Role::User),
|
||||
parts: Some(vec![Part::Text(prompt.to_string())]),
|
||||
parts: Some(vec![Part::text(prompt)]),
|
||||
}],
|
||||
tools: Some(vec![Tools {
|
||||
google_search_retrieval: Some(GoogleSearchRetrieval::default()),
|
||||
@@ -29,8 +29,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
println!(
|
||||
"Request: {}",
|
||||
serde_json::to_string_pretty(&request).unwrap()
|
||||
);
|
||||
|
||||
let result = gemini
|
||||
.generate_content(&request, "gemini-1.0-pro-002")
|
||||
.generate_content(&request, "gemini-1.5-flash-002")
|
||||
.await?;
|
||||
|
||||
println!("Response: {:?}", result.candidates[0].get_text().unwrap());
|
||||
|
||||
44
examples/google-search.rs
Normal file
44
examples/google-search.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use gemini_rs::prelude::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
tracing_subscriber::fmt().init();
|
||||
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 gemini = GeminiClient::new(
|
||||
authentication_manager,
|
||||
api_endpoint,
|
||||
project_id,
|
||||
location_id,
|
||||
);
|
||||
|
||||
let prompt = "What day is today?";
|
||||
|
||||
let request = GenerateContentRequest {
|
||||
contents: vec![Content {
|
||||
role: Some(Role::User),
|
||||
parts: Some(vec![Part::text(prompt)]),
|
||||
}],
|
||||
tools: Some(vec![Tools {
|
||||
google_search: Some(GoogleSearch::default()),
|
||||
..Default::default()
|
||||
}]),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
println!(
|
||||
"Request: {}",
|
||||
serde_json::to_string_pretty(&request).unwrap()
|
||||
);
|
||||
|
||||
let result = gemini
|
||||
.generate_content(&request, "gemini-2.0-flash-001")
|
||||
.await?;
|
||||
|
||||
println!("Response: {:?}", result.candidates[0].get_text().unwrap());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -19,7 +19,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let request = GenerateContentRequest {
|
||||
contents: vec![Content {
|
||||
role: Some(Role::User),
|
||||
parts: Some(vec![Part::Text(prompt.to_string())]),
|
||||
parts: Some(vec![Part::text(prompt)]),
|
||||
}],
|
||||
generation_config: Some(GenerationConfig {
|
||||
response_mime_type: Some("application/json".to_string()),
|
||||
|
||||
@@ -21,7 +21,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let request = GenerateContentRequest {
|
||||
contents: vec![Content {
|
||||
role: Some(Role::User),
|
||||
parts: Some(vec![Part::Text(prompt.to_string())]),
|
||||
parts: Some(vec![Part::text(prompt)]),
|
||||
}],
|
||||
safety_settings: Some(vec![SafetySetting {
|
||||
category: HarmCategory::HateSpeech,
|
||||
|
||||
@@ -15,20 +15,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
location_id,
|
||||
);
|
||||
|
||||
let system_instruction = "Answer as if you were Yoda";
|
||||
let prompt = "What is the airspeed of an unladen swallow?";
|
||||
let system_instruction = Content::builder()
|
||||
.add_text_part("Answer as if you were Yoda")
|
||||
.build();
|
||||
|
||||
let request = GenerateContentRequest {
|
||||
contents: vec![Content {
|
||||
role: Some(Role::User),
|
||||
parts: Some(vec![Part::Text(prompt.to_string())]),
|
||||
}],
|
||||
system_instruction: Some(Content {
|
||||
role: None,
|
||||
parts: Some(vec![Part::Text(system_instruction.to_string())]),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
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)
|
||||
.system_instruction(system_instruction)
|
||||
.build();
|
||||
|
||||
let result = gemini
|
||||
.generate_content(&request, "gemini-1.0-pro-002")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use gemini_rs::prelude::*;
|
||||
use tokio_stream::StreamExt;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
@@ -14,32 +15,19 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
location_id,
|
||||
);
|
||||
|
||||
let prompt = "Tell me the story of the genesis of the universe as a bedtime story.";
|
||||
let request = GenerateContentRequest::builder()
|
||||
.add_content(
|
||||
Content::builder()
|
||||
.role(Role::User)
|
||||
.add_part(Part::Text(prompt.to_string()))
|
||||
.build(),
|
||||
)
|
||||
.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 queue = gemini.stream_generate_content(&request, "gemini-pro").await;
|
||||
let request = GenerateContentRequest::builder().contents(prompt).build();
|
||||
|
||||
while let Some(response) = queue.pop().await {
|
||||
match response {
|
||||
Ok(result) => {
|
||||
let text = result
|
||||
.candidates
|
||||
.iter()
|
||||
.filter_map(|c| c.get_text())
|
||||
.collect::<String>();
|
||||
print!("{}", text);
|
||||
}
|
||||
Err(error) => {
|
||||
println!("{error}");
|
||||
}
|
||||
}
|
||||
let mut queue = gemini
|
||||
.stream_generate_content(&request, "gemini-2.0-flash-001")
|
||||
.await?;
|
||||
|
||||
while let Some(response) = queue.next().await {
|
||||
println!("Response: {:?}", response?);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -14,15 +14,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
location_id,
|
||||
);
|
||||
|
||||
let prompt = "What is the airspeed of an unladen swallow?";
|
||||
let request = GenerateContentRequest::builder()
|
||||
.add_content(
|
||||
Content::builder()
|
||||
.role(Role::User)
|
||||
.add_part(Part::Text(prompt.to_string()))
|
||||
.build(),
|
||||
)
|
||||
.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?;
|
||||
println!("Response: {:?}", response.candidates[0].get_text().unwrap());
|
||||
|
||||
|
||||
528
src/client.rs
528
src/client.rs
@@ -1,288 +1,240 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use deadqueue::unlimited::Queue;
|
||||
use futures_util::stream::StreamExt;
|
||||
use reqwest_eventsource::{Event, EventSource};
|
||||
use tracing::error;
|
||||
|
||||
use crate::dialogue::Message;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::prelude::{
|
||||
Candidate, Content, CountTokensRequest, CountTokensResponse, GenerateContentRequest,
|
||||
GenerateContentResponse, GenerateContentResponseResult, GenerationConfig, TextEmbeddingRequest,
|
||||
TextEmbeddingResponse,
|
||||
};
|
||||
use crate::types::{PredictImageRequest, PredictImageResponse, Role};
|
||||
use crate::{prelude::Part, token_provider::TokenProvider};
|
||||
|
||||
pub static AUTH_SCOPE: &[&str] = &["https://www.googleapis.com/auth/cloud-platform"];
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GeminiClient<T: TokenProvider + Clone> {
|
||||
token_provider: T,
|
||||
client: reqwest::Client,
|
||||
api_endpoint: String,
|
||||
project_id: String,
|
||||
location_id: String,
|
||||
}
|
||||
|
||||
unsafe impl<T: TokenProvider + Clone> Send for GeminiClient<T> {}
|
||||
unsafe impl<T: TokenProvider + Clone> Sync for GeminiClient<T> {}
|
||||
|
||||
impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
pub fn new(
|
||||
token_provider: T,
|
||||
api_endpoint: String,
|
||||
project_id: String,
|
||||
location_id: String,
|
||||
) -> Self {
|
||||
GeminiClient {
|
||||
token_provider,
|
||||
client: reqwest::Client::new(),
|
||||
api_endpoint,
|
||||
project_id,
|
||||
location_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn stream_generate_content(
|
||||
&self,
|
||||
request: &GenerateContentRequest,
|
||||
model: &str,
|
||||
) -> Arc<Queue<Option<Result<GenerateContentResponseResult>>>> {
|
||||
let queue = Arc::new(Queue::<Option<Result<GenerateContentResponseResult>>>::new());
|
||||
let access_token = match self.token_provider.get_token(AUTH_SCOPE).await {
|
||||
Ok(access_token) => access_token,
|
||||
Err(e) => {
|
||||
queue.push(Some(Err(e)));
|
||||
return queue;
|
||||
}
|
||||
};
|
||||
|
||||
// Clone the queue and other necessary data to move into the async block.
|
||||
let cloned_queue = queue.clone();
|
||||
let endpoint_url: String = format!(
|
||||
"https://{}/v1beta1/projects/{}/locations/{}/publishers/google/models/{}:streamGenerateContent?alt=sse", self.api_endpoint, self.project_id, self.location_id, model,
|
||||
);
|
||||
let client = self.client.clone();
|
||||
let request = request.clone();
|
||||
|
||||
// Start a thread to run the request in the background.
|
||||
tokio::spawn(async move {
|
||||
let req = client
|
||||
.post(&endpoint_url)
|
||||
.bearer_auth(access_token)
|
||||
.json(&request);
|
||||
|
||||
let mut event_source = match EventSource::new(req) {
|
||||
Ok(event_source) => event_source,
|
||||
Err(e) => {
|
||||
cloned_queue.push(Some(Err(e.into())));
|
||||
return;
|
||||
}
|
||||
};
|
||||
while let Some(event) = event_source.next().await {
|
||||
match event {
|
||||
Ok(event) => {
|
||||
if let Event::Message(event) = event {
|
||||
let response: serde_json::error::Result<GenerateContentResponse> =
|
||||
serde_json::from_str(&event.data);
|
||||
|
||||
match response {
|
||||
Ok(response) => {
|
||||
let result = response.into_result();
|
||||
let finished = match &result {
|
||||
Ok(result) => result.candidates[0].finish_reason.is_some(),
|
||||
Err(_) => true,
|
||||
};
|
||||
cloned_queue.push(Some(result));
|
||||
if finished {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::error!("Error parsing message: {}", event.data);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Error in event source: {:?}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
cloned_queue.push(None);
|
||||
});
|
||||
|
||||
// Return the queue that will receive the responses.
|
||||
queue
|
||||
}
|
||||
|
||||
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://{}/v1beta1/projects/{}/locations/{}/publishers/google/models/{}:generateContent", self.api_endpoint, self.project_id, self.location_id, model,
|
||||
);
|
||||
let resp = self
|
||||
.client
|
||||
.post(&endpoint_url)
|
||||
.bearer_auth(access_token)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let txt_json = resp.text().await?;
|
||||
tracing::debug!("generate_content response: {:?}", txt_json);
|
||||
match serde_json::from_str::<GenerateContentResponse>(&txt_json) {
|
||||
Ok(response) => Ok(response.into_result()?),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to parse response: {} with error {}", txt_json, e);
|
||||
Err(e.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompts a conversation to the model.
|
||||
pub async fn prompt_conversation(&self, messages: &[Message], model: &str) -> Result<Message> {
|
||||
let request = GenerateContentRequest {
|
||||
contents: messages
|
||||
.iter()
|
||||
.map(|m| Content {
|
||||
role: Some(m.role),
|
||||
parts: Some(vec![Part::Text(m.text.clone())]),
|
||||
})
|
||||
.collect(),
|
||||
generation_config: None,
|
||||
tools: None,
|
||||
system_instruction: None,
|
||||
safety_settings: None,
|
||||
};
|
||||
|
||||
let response = self.generate_content(&request, model).await?;
|
||||
|
||||
// Check for errors in the response.
|
||||
let mut candidates = GeminiClient::<T>::collect_text_from_response(&response);
|
||||
|
||||
match candidates.pop() {
|
||||
Some(text) => Ok(Message::new(Role::Model, &text)),
|
||||
None => Err(Error::NoCandidatesError),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends a text prompt to the Vertex API using the Gemini Pro model and extracts the text
|
||||
/// from the response.
|
||||
#[deprecated(note = "Use `generate_content` instead")]
|
||||
pub async fn prompt_text(
|
||||
&self,
|
||||
prompt: &str,
|
||||
generation_config: Option<&GenerationConfig>,
|
||||
) -> Result<String> {
|
||||
let request = GenerateContentRequest {
|
||||
contents: vec![Content {
|
||||
role: Some(Role::User),
|
||||
parts: Some(vec![Part::Text(prompt.to_string())]),
|
||||
}],
|
||||
generation_config: generation_config.cloned(),
|
||||
tools: None,
|
||||
system_instruction: None,
|
||||
safety_settings: None,
|
||||
};
|
||||
|
||||
let response = self.generate_content(&request, "gemini-pro").await?;
|
||||
let mut candidates = GeminiClient::<T>::collect_text_from_response(&response);
|
||||
|
||||
match candidates.pop() {
|
||||
Some(candidate) => Ok(candidate),
|
||||
None => Err(Error::NoCandidatesError),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_text_from_response(response: &GenerateContentResponseResult) -> Vec<String> {
|
||||
response
|
||||
.candidates
|
||||
.iter()
|
||||
.filter_map(Candidate::get_text)
|
||||
.collect::<Vec<String>>()
|
||||
}
|
||||
|
||||
pub async fn text_embeddings(
|
||||
&self,
|
||||
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 access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||
let resp = self
|
||||
.client
|
||||
.post(&endpoint_url)
|
||||
.bearer_auth(access_token)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
let txt_json = resp.text().await?;
|
||||
tracing::debug!("text_embeddings response: {:?}", txt_json);
|
||||
Ok(serde_json::from_str::<TextEmbeddingResponse>(&txt_json)?)
|
||||
}
|
||||
|
||||
pub async fn count_tokens(
|
||||
&self,
|
||||
request: &CountTokensRequest,
|
||||
model: &str,
|
||||
) -> Result<CountTokensResponse> {
|
||||
let endpoint_url = format!(
|
||||
"https://{}/v1beta1/projects/{}/locations/{}/publishers/google/models/{}:countTokens",
|
||||
self.api_endpoint, self.project_id, self.location_id, model,
|
||||
);
|
||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||
let resp = self
|
||||
.client
|
||||
.post(&endpoint_url)
|
||||
.bearer_auth(access_token)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let txt_json = resp.text().await?;
|
||||
tracing::debug!("count_tokens response: {:?}", txt_json);
|
||||
Ok(serde_json::from_str(&txt_json)?)
|
||||
}
|
||||
|
||||
pub async fn predict_image(
|
||||
&self,
|
||||
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 access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||
let resp = self
|
||||
.client
|
||||
.post(&endpoint_url)
|
||||
.bearer_auth(access_token)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let txt_json = resp.text().await?;
|
||||
|
||||
match serde_json::from_str::<PredictImageResponse>(&txt_json) {
|
||||
Ok(response) => return Ok(response),
|
||||
Err(e) => {
|
||||
error!(response = txt_json, error = ?e, "Failed to parse response");
|
||||
return Err(e.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
use std::vec;
|
||||
use tracing::error;
|
||||
|
||||
use tokio_stream::{Stream, StreamExt};
|
||||
|
||||
use crate::dialogue::Message;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::network::event_source::{EventSource, ServerSentEvent};
|
||||
use crate::prelude::{
|
||||
Candidate, Content, CountTokensRequest, CountTokensResponse, GenerateContentRequest,
|
||||
GenerateContentResponse, GenerateContentResponseError, GenerateContentResponseResult,
|
||||
TextEmbeddingRequest, TextEmbeddingResponse,
|
||||
};
|
||||
use crate::types::{PredictImageRequest, PredictImageResponse, Role};
|
||||
use crate::{prelude::Part, token_provider::TokenProvider};
|
||||
|
||||
pub const AUTH_SCOPE: &[&str] = &["https://www.googleapis.com/auth/cloud-platform"];
|
||||
const ENDPOINT_VERSION: &str = "v1beta1";
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GeminiClient<T: TokenProvider + Clone> {
|
||||
token_provider: T,
|
||||
client: reqwest::Client,
|
||||
api_endpoint: String,
|
||||
project_id: String,
|
||||
location_id: String,
|
||||
}
|
||||
|
||||
impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||
pub fn new(
|
||||
token_provider: T,
|
||||
api_endpoint: String,
|
||||
project_id: String,
|
||||
location_id: String,
|
||||
) -> Self {
|
||||
GeminiClient {
|
||||
token_provider,
|
||||
client: reqwest::Client::new(),
|
||||
api_endpoint,
|
||||
project_id,
|
||||
location_id,
|
||||
}
|
||||
}
|
||||
|
||||
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(
|
||||
&self,
|
||||
request: &GenerateContentRequest,
|
||||
model: &str,
|
||||
) -> Result<GenerateContentResponseResult> {
|
||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||
let endpoint_url = self.endpoint_url(ENDPOINT_VERSION, &format!("{model}:generateContent"));
|
||||
let resp = self
|
||||
.client
|
||||
.post(&endpoint_url)
|
||||
.bearer_auth(access_token)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let txt_json = resp.text().await?;
|
||||
tracing::debug!("generate_content response: {:?}", txt_json);
|
||||
match serde_json::from_str::<GenerateContentResponse>(&txt_json) {
|
||||
Ok(response) => Ok(response.into_result()?),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to parse response: {} with error {}", txt_json, e);
|
||||
Err(e.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends a content generation request and returns a stream of response chunks via SSE.
|
||||
///
|
||||
/// Each item in the stream is a [`GenerateContentResponseResult`] containing one or more
|
||||
/// candidates. Useful for displaying incremental output as it is generated.
|
||||
pub async fn stream_generate_content(
|
||||
&self,
|
||||
request: &GenerateContentRequest,
|
||||
model: &str,
|
||||
) -> Result<impl Stream<Item = Result<GenerateContentResponseResult>> + use<'_, T>> {
|
||||
let access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||
let endpoint_url = self.endpoint_url(
|
||||
ENDPOINT_VERSION,
|
||||
&format!("{model}:streamGenerateContent?alt=sse"),
|
||||
);
|
||||
let response = self
|
||||
.client
|
||||
.post(&endpoint_url)
|
||||
.bearer_auth(access_token)
|
||||
.json(request)
|
||||
.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 });
|
||||
}
|
||||
|
||||
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>> {
|
||||
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.
|
||||
pub async fn prompt_conversation(&self, messages: &[Message], model: &str) -> Result<Message> {
|
||||
let request = GenerateContentRequest {
|
||||
contents: messages
|
||||
.iter()
|
||||
.map(|m| Content {
|
||||
role: Some(m.role),
|
||||
parts: Some(vec![Part::text(m.text.clone())]),
|
||||
})
|
||||
.collect(),
|
||||
generation_config: None,
|
||||
tools: None,
|
||||
system_instruction: None,
|
||||
safety_settings: None,
|
||||
};
|
||||
|
||||
let response = self.generate_content(&request, model).await?;
|
||||
|
||||
// Check for errors in the response.
|
||||
let mut candidates = GeminiClient::<T>::collect_text_from_response(&response);
|
||||
|
||||
match candidates.pop() {
|
||||
Some(text) => Ok(Message::new(Role::Model, &text)),
|
||||
None => Err(Error::NoCandidatesError),
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_text_from_response(response: &GenerateContentResponseResult) -> Vec<String> {
|
||||
response
|
||||
.candidates
|
||||
.iter()
|
||||
.filter_map(Candidate::get_text)
|
||||
.collect::<Vec<String>>()
|
||||
}
|
||||
|
||||
pub async fn text_embeddings(
|
||||
&self,
|
||||
request: &TextEmbeddingRequest,
|
||||
model: &str,
|
||||
) -> Result<TextEmbeddingResponse> {
|
||||
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
|
||||
.post(&endpoint_url)
|
||||
.bearer_auth(access_token)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
let txt_json = resp.text().await?;
|
||||
tracing::debug!("text_embeddings response: {:?}", txt_json);
|
||||
Ok(serde_json::from_str::<TextEmbeddingResponse>(&txt_json)?)
|
||||
}
|
||||
|
||||
pub async fn count_tokens(
|
||||
&self,
|
||||
request: &CountTokensRequest,
|
||||
model: &str,
|
||||
) -> Result<CountTokensResponse> {
|
||||
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
|
||||
.post(&endpoint_url)
|
||||
.bearer_auth(access_token)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let txt_json = resp.text().await?;
|
||||
tracing::debug!("count_tokens response: {:?}", txt_json);
|
||||
Ok(serde_json::from_str(&txt_json)?)
|
||||
}
|
||||
|
||||
pub async fn predict_image(
|
||||
&self,
|
||||
request: &PredictImageRequest,
|
||||
model: &str,
|
||||
) -> Result<PredictImageResponse> {
|
||||
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
|
||||
.post(&endpoint_url)
|
||||
.bearer_auth(access_token)
|
||||
.json(&request)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let txt_json = resp.text().await?;
|
||||
|
||||
match serde_json::from_str::<PredictImageResponse>(&txt_json) {
|
||||
Ok(response) => Ok(response),
|
||||
Err(e) => {
|
||||
error!(response = txt_json, error = ?e, "Failed to parse response");
|
||||
Err(e.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "client_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
205
src/client_tests.rs
Normal file
205
src/client_tests.rs
Normal file
@@ -0,0 +1,205 @@
|
||||
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(())
|
||||
}
|
||||
|
||||
#[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<()> {
|
||||
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;
|
||||
// Incomplete event without trailing newline before EOF
|
||||
let partial_sse = "data: {\"candidates\": [";
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{}",
|
||||
partial_sse
|
||||
);
|
||||
socket.write_all(response.as_bytes()).await.unwrap();
|
||||
let _ = socket.shutdown().await;
|
||||
});
|
||||
|
||||
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 item_res = stream.next().await;
|
||||
|
||||
match item_res {
|
||||
Some(Err(Error::EventSourceError(_))) => {}
|
||||
other => panic!("Expected Some(Err(Error::EventSourceError)), got: {other:?}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,46 +1,46 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{client::GeminiClient, error::Result, prelude::TokenProvider, types::Role};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Message {
|
||||
pub role: Role,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn new(role: Role, text: &str) -> Self {
|
||||
Message {
|
||||
role,
|
||||
text: text.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Dialogue {
|
||||
model: String,
|
||||
messages: Vec<Message>,
|
||||
}
|
||||
|
||||
impl Dialogue {
|
||||
pub fn new(model: &str) -> Self {
|
||||
Dialogue {
|
||||
model: model.to_string(),
|
||||
messages: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn do_turn<T: TokenProvider + Clone>(
|
||||
&mut self,
|
||||
gemini: &GeminiClient<T>,
|
||||
message: &str,
|
||||
) -> Result<Message> {
|
||||
self.messages.push(Message::new(Role::User, message));
|
||||
let response = gemini
|
||||
.prompt_conversation(&self.messages, &self.model)
|
||||
.await?;
|
||||
self.messages.push(response.clone());
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{client::GeminiClient, error::Result, prelude::TokenProvider, types::Role};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Message {
|
||||
pub role: Role,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn new(role: Role, text: &str) -> Self {
|
||||
Message {
|
||||
role,
|
||||
text: text.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Dialogue {
|
||||
model: String,
|
||||
messages: Vec<Message>,
|
||||
}
|
||||
|
||||
impl Dialogue {
|
||||
pub fn new(model: &str) -> Self {
|
||||
Dialogue {
|
||||
model: model.to_string(),
|
||||
messages: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn do_turn<T: TokenProvider + Clone>(
|
||||
&mut self,
|
||||
gemini: &GeminiClient<T>,
|
||||
message: &str,
|
||||
) -> Result<Message> {
|
||||
self.messages.push(Message::new(Role::User, message));
|
||||
let response = gemini
|
||||
.prompt_conversation(&self.messages, &self.model)
|
||||
.await?;
|
||||
self.messages.push(response.clone());
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
153
src/error.rs
153
src/error.rs
@@ -1,76 +1,77 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use reqwest_eventsource::CannotCloneRequestError;
|
||||
|
||||
use crate::types;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
Env(std::env::VarError),
|
||||
HttpClient(reqwest::Error),
|
||||
Token(gcp_auth::Error),
|
||||
Serde(serde_json::Error),
|
||||
VertexError(types::VertexApiError),
|
||||
NoCandidatesError,
|
||||
EventSourceError(CannotCloneRequestError),
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match &self {
|
||||
Error::Env(e) => write!(f, "Environment variable error: {}", e),
|
||||
Error::HttpClient(e) => write!(f, "HTTP Client error: {}", e),
|
||||
Error::Token(e) => write!(f, "Token error: {}", e),
|
||||
Error::Serde(e) => write!(f, "Serde error: {}", e),
|
||||
Error::VertexError(e) => {
|
||||
write!(f, "Vertex error: {}", e)
|
||||
}
|
||||
Error::NoCandidatesError => {
|
||||
write!(f, "No candidates returned for the prompt")
|
||||
}
|
||||
Error::EventSourceError(e) => {
|
||||
write!(f, "EventSourrce Error: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
impl From<reqwest::Error> for Error {
|
||||
fn from(e: reqwest::Error) -> Self {
|
||||
Error::HttpClient(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::env::VarError> for Error {
|
||||
fn from(e: std::env::VarError) -> Self {
|
||||
Error::Env(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<gcp_auth::Error> for Error {
|
||||
fn from(e: gcp_auth::Error) -> Self {
|
||||
Error::Token(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for Error {
|
||||
fn from(e: serde_json::Error) -> Self {
|
||||
Error::Serde(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<types::VertexApiError> for Error {
|
||||
fn from(e: types::VertexApiError) -> Self {
|
||||
Error::VertexError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CannotCloneRequestError> for Error {
|
||||
fn from(e: CannotCloneRequestError) -> Self {
|
||||
Error::EventSourceError(e)
|
||||
}
|
||||
}
|
||||
use std::fmt::Display;
|
||||
|
||||
use tokio_util::codec::LinesCodecError;
|
||||
|
||||
use crate::types;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
Env(std::env::VarError),
|
||||
HttpClient(reqwest::Error),
|
||||
Token(gcp_auth::Error),
|
||||
Serde(serde_json::Error),
|
||||
VertexError(types::VertexApiError),
|
||||
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,
|
||||
},
|
||||
}
|
||||
|
||||
impl Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match &self {
|
||||
Error::Env(e) => write!(f, "Environment variable error: {e}"),
|
||||
Error::HttpClient(e) => write!(f, "HTTP Client error: {e}"),
|
||||
Error::Token(e) => write!(f, "Token error: {e}"),
|
||||
Error::Serde(e) => write!(f, "Serde error: {e}"),
|
||||
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}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
impl From<reqwest::Error> for Error {
|
||||
fn from(e: reqwest::Error) -> Self {
|
||||
Error::HttpClient(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::env::VarError> for Error {
|
||||
fn from(e: std::env::VarError) -> Self {
|
||||
Error::Env(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for Error {
|
||||
fn from(e: serde_json::Error) -> Self {
|
||||
Error::Serde(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<gcp_auth::Error> for Error {
|
||||
fn from(e: gcp_auth::Error) -> Self {
|
||||
Error::Token(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<types::VertexApiError> for Error {
|
||||
fn from(e: types::VertexApiError) -> Self {
|
||||
Error::VertexError(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<LinesCodecError> for Error {
|
||||
fn from(e: LinesCodecError) -> Self {
|
||||
Error::EventSourceError(e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod client;
|
||||
mod dialogue;
|
||||
pub mod error;
|
||||
pub(crate) mod network;
|
||||
mod token_provider;
|
||||
mod types;
|
||||
|
||||
|
||||
113
src/network/event_source.rs
Normal file
113
src/network/event_source.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use reqwest::Response;
|
||||
use std::mem;
|
||||
use tokio_stream::{Stream, StreamExt};
|
||||
use tokio_util::{
|
||||
codec::{Decoder, FramedRead, LinesCodec, LinesCodecError},
|
||||
io::StreamReader,
|
||||
};
|
||||
use tracing::warn;
|
||||
|
||||
static EVENT: &str = "event: ";
|
||||
static DATA: &str = "data: ";
|
||||
static ID: &str = "id: ";
|
||||
static RETRY: &str = "retry: ";
|
||||
|
||||
/// Extension trait for converting an HTTP response into a stream of [`ServerSentEvent`]s.
|
||||
pub trait EventSource {
|
||||
/// Consumes the response and returns a stream of parsed SSE events.
|
||||
fn event_stream(self) -> impl Stream<Item = Result<ServerSentEvent, LinesCodecError>>;
|
||||
}
|
||||
|
||||
impl EventSource for Response {
|
||||
fn event_stream(self) -> impl Stream<Item = Result<ServerSentEvent, LinesCodecError>> {
|
||||
stream_response(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// A parsed Server-Sent Event.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct ServerSentEvent {
|
||||
pub event: Option<String>,
|
||||
/// The event payload (from one or more `data:` fields, joined by `\n`).
|
||||
pub data: Option<String>,
|
||||
pub id: Option<String>,
|
||||
pub retry: Option<usize>,
|
||||
}
|
||||
|
||||
/// [`Decoder`] that parses a byte stream of SSE-formatted data into [`ServerSentEvent`]s.
|
||||
pub struct ServerSentEventsCodec {
|
||||
lines_codec: LinesCodec,
|
||||
next: ServerSentEvent,
|
||||
}
|
||||
|
||||
impl Default for ServerSentEventsCodec {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerSentEventsCodec {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
lines_codec: LinesCodec::new(),
|
||||
next: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for ServerSentEventsCodec {
|
||||
type Item = ServerSentEvent;
|
||||
type Error = LinesCodecError;
|
||||
|
||||
fn decode(
|
||||
&mut self,
|
||||
src: &mut tokio_util::bytes::BytesMut,
|
||||
) -> Result<Option<Self::Item>, Self::Error> {
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a [`Response`] into a stream of [`ServerSentEvent`]s.
|
||||
pub fn stream_response(
|
||||
response: Response,
|
||||
) -> impl Stream<Item = Result<ServerSentEvent, LinesCodecError>> {
|
||||
let bytes_stream = response.bytes_stream();
|
||||
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(())
|
||||
}
|
||||
1
src/network/mod.rs
Normal file
1
src/network/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod event_source;
|
||||
@@ -1,18 +1,18 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::error::Result;
|
||||
|
||||
pub trait TokenProvider {
|
||||
fn get_token(&self, scope: &[&str])
|
||||
-> impl std::future::Future<Output = Result<String>> + Send;
|
||||
}
|
||||
|
||||
impl<'a> TokenProvider for Arc<dyn gcp_auth::TokenProvider + 'a> {
|
||||
async fn get_token(&self, scope: &[&str]) -> Result<String> {
|
||||
let token = self.token(scope).await;
|
||||
match token {
|
||||
Ok(token) => Ok(token.as_str().to_string()),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::error::Result;
|
||||
|
||||
pub trait TokenProvider {
|
||||
fn get_token(&self, scope: &[&str])
|
||||
-> impl std::future::Future<Output = Result<String>> + Send;
|
||||
}
|
||||
|
||||
impl TokenProvider for Arc<dyn gcp_auth::TokenProvider + '_> {
|
||||
async fn get_token(&self, scope: &[&str]) -> Result<String> {
|
||||
let token = self.token(scope).await;
|
||||
match token {
|
||||
Ok(token) => Ok(token.as_str().to_string()),
|
||||
Err(e) => Err(e.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::{collections::HashMap, str::FromStr, vec};
|
||||
use std::{fmt::Display, str::FromStr, vec};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
|
||||
pub struct Content {
|
||||
@@ -13,28 +14,45 @@ impl Content {
|
||||
self.parts.as_ref().map(|parts| {
|
||||
parts
|
||||
.iter()
|
||||
.filter_map(|part| match part {
|
||||
Part::Text(text) => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.filter_map(|part| part.text.clone())
|
||||
.collect::<String>()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn builder() -> ContentBuilder {
|
||||
ContentBuilder::new()
|
||||
ContentBuilder::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SystemPrompt {
|
||||
content: Content,
|
||||
}
|
||||
|
||||
impl<T: AsRef<str>> From<T> for SystemPrompt {
|
||||
fn from(value: T) -> Self {
|
||||
SystemPrompt {
|
||||
content: Content {
|
||||
parts: Some(vec![Part::text(value.as_ref())]),
|
||||
role: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SystemPrompt> for Content {
|
||||
fn from(value: SystemPrompt) -> Self {
|
||||
value.content
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ContentBuilder {
|
||||
content: Content,
|
||||
}
|
||||
|
||||
impl ContentBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
content: Default::default(),
|
||||
}
|
||||
pub fn add_text_part<T: Into<String>>(self, text: T) -> Self {
|
||||
self.add_part(Part::text(text))
|
||||
}
|
||||
|
||||
pub fn add_part(mut self, part: Part) -> Self {
|
||||
@@ -55,19 +73,20 @@ impl ContentBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Role {
|
||||
User,
|
||||
Model,
|
||||
}
|
||||
|
||||
impl ToString for Role {
|
||||
fn to_string(&self) -> String {
|
||||
match self {
|
||||
Role::User => "user".to_string(),
|
||||
Role::Model => "model".to_string(),
|
||||
}
|
||||
impl Display for Role {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let role_str = match self {
|
||||
Role::User => "user",
|
||||
Role::Model => "model",
|
||||
};
|
||||
f.write_str(role_str)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,20 +102,137 @@ impl FromStr for Role {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Part {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub text: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub inline_data: Option<InlineData>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub file_data: Option<FileData>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub function_call: Option<FunctionCallData>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub function_response: Option<FunctionResponseData>,
|
||||
/// Opaque signature emitted by Gemini 2.5+ thinking models on function-call
|
||||
/// parts. Must be echoed back on the same part — and on the corresponding
|
||||
/// `functionResponse` part — in subsequent turns, otherwise Vertex rejects
|
||||
/// the request with "function call X is missing a thought_signature".
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thought_signature: Option<String>,
|
||||
/// `Some(true)` on a response part marks it as a reasoning/thinking token
|
||||
/// (only emitted when `thinkingConfig.includeThoughts` is set on the
|
||||
/// request). Absent on regular text and on outgoing requests.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thought: Option<bool>,
|
||||
}
|
||||
|
||||
impl Part {
|
||||
pub fn text(text: impl Into<String>) -> Self {
|
||||
Part {
|
||||
text: Some(text.into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn function_call(name: impl Into<String>, args: Value) -> Self {
|
||||
Part {
|
||||
function_call: Some(FunctionCallData {
|
||||
name: name.into(),
|
||||
args,
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn function_response(name: impl Into<String>, response: Value) -> Self {
|
||||
Part {
|
||||
function_response: Some(FunctionResponseData {
|
||||
name: name.into(),
|
||||
response,
|
||||
parts: vec![],
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct FunctionCallData {
|
||||
pub name: String,
|
||||
pub args: Value,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct FunctionResponseData {
|
||||
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 enum Part {
|
||||
Text(String),
|
||||
InlineData {
|
||||
mime_type: String,
|
||||
data: String,
|
||||
},
|
||||
FileData {
|
||||
mime_type: String,
|
||||
file_uri: String,
|
||||
},
|
||||
FunctionCall {
|
||||
name: String,
|
||||
args: HashMap<String, String>,
|
||||
},
|
||||
pub struct FunctionResponsePart {
|
||||
pub inline_data: InlineData,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InlineData {
|
||||
pub mime_type: String,
|
||||
pub data: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileData {
|
||||
pub mime_type: String,
|
||||
pub file_uri: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::{FunctionResponsePart, InlineData, Part};
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,25 +9,20 @@ pub struct CountTokensRequest {
|
||||
|
||||
impl CountTokensRequest {
|
||||
pub fn builder() -> CountTokensRequestBuilder {
|
||||
CountTokensRequestBuilder::new()
|
||||
CountTokensRequestBuilder::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct CountTokensRequestBuilder {
|
||||
contents: Content,
|
||||
}
|
||||
|
||||
impl CountTokensRequestBuilder {
|
||||
pub fn new() -> Self {
|
||||
CountTokensRequestBuilder {
|
||||
contents: Content::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_prompt(prompt: &str) -> Self {
|
||||
CountTokensRequestBuilder {
|
||||
contents: Content {
|
||||
parts: Some(vec![super::Part::Text(prompt.to_string())]),
|
||||
parts: Some(vec![super::Part::text(prompt)]),
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::fmt::Formatter;
|
||||
|
||||
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,
|
||||
@@ -19,13 +19,13 @@ impl core::fmt::Display for VertexApiError {
|
||||
|
||||
impl std::error::Error for VertexApiError {}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Link {
|
||||
pub description: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "@type")]
|
||||
pub enum ErrorType {
|
||||
#[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 service: String,
|
||||
pub consumer: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct FieldViolation {
|
||||
pub field: String,
|
||||
pub description: String,
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
@@ -37,8 +35,8 @@ impl GenerateContentRequestBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_content(mut self, content: Content) -> Self {
|
||||
self.request.contents.push(content);
|
||||
pub fn contents(mut self, contents: Vec<Content>) -> Self {
|
||||
self.request.contents = contents;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -71,15 +69,39 @@ impl GenerateContentRequestBuilder {
|
||||
pub struct Tools {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub function_declarations: Option<Vec<FunctionDeclaration>>,
|
||||
|
||||
#[serde(rename = "googleSearchRetrieval")]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub google_search_retrieval: Option<GoogleSearchRetrieval>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub google_search: Option<GoogleSearch>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
pub struct GoogleSearch {}
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DynamicRetrievalConfig {
|
||||
pub mode: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub dynamic_threshold: Option<f32>,
|
||||
}
|
||||
|
||||
impl Default for DynamicRetrievalConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mode: "MODE_DYNAMIC".to_string(),
|
||||
dynamic_threshold: Some(0.7),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GoogleSearchRetrieval {
|
||||
pub disable_attribution: bool,
|
||||
pub dynamic_retrieval_config: DynamicRetrievalConfig,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
|
||||
@@ -101,6 +123,37 @@ pub struct GenerationConfig {
|
||||
pub response_mime_type: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub response_schema: Option<Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thinking_config: Option<ThinkingConfig>,
|
||||
}
|
||||
|
||||
/// Configures Gemini 2.5+ thinking models. See
|
||||
/// <https://docs.cloud.google.com/vertex-ai/generative-ai/docs/thinking>.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ThinkingConfig {
|
||||
/// When `true`, the response includes parts with `thought: true` carrying
|
||||
/// the model's reasoning tokens.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub include_thoughts: Option<bool>,
|
||||
/// Maximum tokens the model may spend thinking. `Some(0)` disables
|
||||
/// thinking entirely on models that support it.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thinking_budget: Option<i32>,
|
||||
/// Coarse-grained thinking effort. Mutually-exclusive shorthand for
|
||||
/// `thinking_budget` on supported models.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thinking_level: Option<ThinkingLevel>,
|
||||
}
|
||||
|
||||
/// Coarse-grained thinking effort. Serialized as `SCREAMING_SNAKE_CASE` to
|
||||
/// match the Vertex API enum.
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum ThinkingLevel {
|
||||
ThinkingLevelUnspecified,
|
||||
Low,
|
||||
High,
|
||||
}
|
||||
|
||||
impl GenerationConfig {
|
||||
@@ -160,6 +213,11 @@ impl GenerationConfigBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn thinking_config(mut self, thinking_config: ThinkingConfig) -> Self {
|
||||
self.generation_config.thinking_config = Some(thinking_config);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn build(self) -> GenerationConfig {
|
||||
self.generation_config
|
||||
}
|
||||
@@ -257,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>,
|
||||
}
|
||||
|
||||
@@ -270,22 +337,14 @@ pub struct UsageMetadata {
|
||||
pub struct FunctionDeclaration {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub parameters: FunctionParameters,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FunctionParameters {
|
||||
pub r#type: String,
|
||||
pub properties: HashMap<String, FunctionParametersProperty>,
|
||||
pub required: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FunctionParametersProperty {
|
||||
pub r#type: String,
|
||||
pub description: String,
|
||||
/// 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)]
|
||||
@@ -327,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() {
|
||||
@@ -335,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#"{
|
||||
@@ -461,6 +590,47 @@ mod tests {
|
||||
serde_json::from_str::<GenerateContentResponse>(input).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_function_call_with_thought_signature() {
|
||||
let input = r#"{
|
||||
"candidates": [
|
||||
{
|
||||
"content": {
|
||||
"role": "model",
|
||||
"parts": [
|
||||
{
|
||||
"functionCall": {
|
||||
"name": "delegate_to_agent",
|
||||
"args": { "agent_name": "general", "task": "Say hello." }
|
||||
},
|
||||
"thoughtSignature": "CsYCAY89a18IQwmp"
|
||||
}
|
||||
]
|
||||
},
|
||||
"finishReason": "STOP"
|
||||
}
|
||||
],
|
||||
"usageMetadata": { "promptTokenCount": 112, "totalTokenCount": 196 }
|
||||
}"#;
|
||||
let resp = serde_json::from_str::<GenerateContentResponse>(input).unwrap();
|
||||
if let GenerateContentResponse::Ok(r) = resp {
|
||||
let part = &r.candidates[0]
|
||||
.content
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.parts
|
||||
.as_ref()
|
||||
.unwrap()[0];
|
||||
assert_eq!(
|
||||
part.function_call.as_ref().unwrap().name,
|
||||
"delegate_to_agent"
|
||||
);
|
||||
assert_eq!(part.thought_signature.as_deref(), Some("CsYCAY89a18IQwmp"));
|
||||
} else {
|
||||
panic!("expected Ok response");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_safety_rating_without_scores() {
|
||||
let input = r#"{
|
||||
|
||||
@@ -12,6 +12,10 @@ pub struct PredictImageRequest {
|
||||
pub struct PredictImageRequestPrompt {
|
||||
/// The text prompt for the image.
|
||||
/// The following models support different values for this parameter:
|
||||
/// - `imagen-4.0-generate-001`: up to 480 tokens.
|
||||
/// - `imagen-4.0-fast-generate-001`: up to 480 tokens.
|
||||
/// - `imagen-4.0-ultra-generate-001`: up to 480 tokens.
|
||||
/// - `imagen-3.0-generate-002`: up to 480 tokens.
|
||||
/// - `imagen-3.0-generate-001`: up to 480 tokens.
|
||||
/// - `imagen-3.0-fast-generate-001`: up to 480 tokens.
|
||||
/// - `imagegeneration@006`: up to 128 tokens.
|
||||
@@ -24,21 +28,20 @@ pub struct PredictImageRequestPrompt {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PredictImageRequestParameters {
|
||||
/// The number of images to generate. The default value is 4.
|
||||
/// The following models support different values for this parameter:
|
||||
/// - `imagen-3.0-generate-001`: 1 to 4.
|
||||
/// - `imagen-3.0-fast-generate-001`: 1 to 4.
|
||||
/// - `imagegeneration@006`: 1 to 4.
|
||||
/// - `imagegeneration@005`: 1 to 4.
|
||||
/// - `imagegeneration@002`: 1 to 8.
|
||||
/// Supported range: 1 to 4 for all current models.
|
||||
pub sample_count: i32,
|
||||
|
||||
/// The random seed for image generation. This is not available when addWatermark is set to
|
||||
/// true.
|
||||
/// The random seed for image generation. This is not available when `add_watermark` is set to
|
||||
/// `true`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub seed: Option<u32>,
|
||||
|
||||
/// A description of what to discourage in the generated images.
|
||||
/// The following models support this parameter:
|
||||
/// - `imagen-4.0-generate-001`: up to 480 tokens.
|
||||
/// - `imagen-4.0-fast-generate-001`: up to 480 tokens.
|
||||
/// - `imagen-4.0-ultra-generate-001`: up to 480 tokens.
|
||||
/// - `imagen-3.0-generate-002`: up to 480 tokens.
|
||||
/// - `imagen-3.0-generate-001`: up to 480 tokens.
|
||||
/// - `imagen-3.0-fast-generate-001`: up to 480 tokens.
|
||||
/// - `imagegeneration@006`: up to 128 tokens.
|
||||
@@ -47,13 +50,8 @@ pub struct PredictImageRequestParameters {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub negative_prompt: Option<String>,
|
||||
|
||||
/// The aspect ratio for the image. The default value is "1:1".
|
||||
/// The following models support different values for this parameter:
|
||||
/// - `imagen-3.0-generate-001`: "1:1", "9:16", "16:9", "3:4", or "4:3".
|
||||
/// - `imagen-3.0-fast-generate-001`: "1:1", "9:16", "16:9", "3:4", or "4:3".
|
||||
/// - `imagegeneration@006`: "1:1", "9:16", "16:9", "3:4", or "4:3".
|
||||
/// - `imagegeneration@005`: "1:1" or "9:16".
|
||||
/// - `imagegeneration@002`: "1:1".
|
||||
/// The aspect ratio for the image. The default value is `"1:1"`.
|
||||
/// Supported values: `"1:1"`, `"9:16"`, `"16:9"`, `"3:4"`, `"4:3"`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub aspect_ratio: Option<String>,
|
||||
|
||||
@@ -70,7 +68,8 @@ pub struct PredictImageRequestParameters {
|
||||
/// - "watercolor"
|
||||
/// - "cyberpunk"
|
||||
/// - "pop_art"
|
||||
/// Pre-defined styles is only supported for model imagegeneration@002
|
||||
///
|
||||
/// **Deprecated**: only supported by the legacy `imagegeneration@002` model.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sample_image_style: Option<String>,
|
||||
|
||||
@@ -80,36 +79,41 @@ pub struct PredictImageRequestParameters {
|
||||
/// - `"allow_all"`: Allow generation of people of all ages.
|
||||
///
|
||||
/// The default value is `"allow_adult"`.
|
||||
///
|
||||
/// Supported by the models `imagen-3.0-generate-001`, `imagen-3.0-fast-generate-001`, and
|
||||
/// `imagegeneration@006` only.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub person_generation: Option<String>,
|
||||
|
||||
/// Adds a filter level to safety filtering. The following values are supported:
|
||||
/// - `"block_most"`: Strongest filtering level, most strict blocking.
|
||||
/// - `"block_some"`: Block some problematic prompts and responses.
|
||||
/// - `"block_few"`: Reduces the number of requests blocked due to safety filters. May
|
||||
/// increase objectionable content generated by Imagen.
|
||||
/// - `"block_fewest"`: Block very few problematic prompts and responses. Access to this
|
||||
/// feature is restricted.
|
||||
///
|
||||
/// The default value is `"block_some"`.
|
||||
///
|
||||
/// Supported by the models `imagen-3.0-generate-001`, `imagen-3.0-fast-generate-001`, and
|
||||
/// `imagegeneration@006` only.
|
||||
/// - `"block_low_and_above"`: Strongest filtering, most strict blocking.
|
||||
/// - `"block_medium_and_above"`: Block medium and high severity content. Default.
|
||||
/// - `"block_only_high"`: Only block high severity content.
|
||||
/// - `"block_none"`: No blocking.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub safety_setting: Option<String>,
|
||||
|
||||
/// Add an invisible watermark to the generated images. The default value is `false` for the
|
||||
/// `imagegeneration@002` and `imagegeneration@005` models, and `true` for the
|
||||
/// `imagen-3.0-fast-generate-001`, `imagegeneration@006`, and imagegeneration@006 models.
|
||||
/// Add an invisible SynthID watermark to the generated images. Defaults to `true` for
|
||||
/// Imagen 3 and 4 models. Not available when `seed` is set.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub add_watermark: Option<bool>,
|
||||
|
||||
/// Cloud Storage URI to store the generated images.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub storage_uri: Option<String>,
|
||||
|
||||
/// Enables LLM-based prompt rewriting to improve image quality. Default: `true`.
|
||||
/// Recommended to set to `false` for `imagen-4.0-fast-generate-001` when the prompt is
|
||||
/// complex.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub enhance_prompt: Option<bool>,
|
||||
|
||||
/// Language of the prompt. Default: `"auto"`.
|
||||
/// Supported values: `"auto"`, `"en"`, `"zh"`, `"zh-CN"`, `"zh-TW"`, `"hi"`, `"ja"`,
|
||||
/// `"ko"`, `"pt"`, `"es"`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub language: Option<String>,
|
||||
|
||||
/// Output image resolution. `"1K"` (default) or `"2K"`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sample_image_size: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -117,10 +121,9 @@ pub struct PredictImageRequestParameters {
|
||||
pub struct PredictImageRequestParametersOutputOptions {
|
||||
/// The image format that the output should be saved as. The following values are supported:
|
||||
///
|
||||
/// - "image/png": Save as a PNG image
|
||||
/// - "image/jpeg": Save as a JPEG image
|
||||
///
|
||||
/// The default value is "image/png".v
|
||||
/// - `"image/png"`: Save as a PNG image (default)
|
||||
/// - `"image/jpeg"`: Save as a JPEG image
|
||||
/// - `"image/webp"`: Save as a WebP image
|
||||
pub mime_type: Option<String>,
|
||||
|
||||
/// The level of compression if the output type is "image/jpeg".
|
||||
|
||||
@@ -51,7 +51,7 @@ pub struct TextEmbeddingPrediction {
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TextEmbeddingResult {
|
||||
pub statistics: TextEmbeddingStatistics,
|
||||
pub values: Vec<f32>,
|
||||
pub values: Vec<f64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
|
||||
Reference in New Issue
Block a user