Compare commits
35 Commits
db5a01afef
...
ci/gitea-a
| Author | SHA1 | Date | |
|---|---|---|---|
| 6d49f9939c | |||
| c911fc382e | |||
| a8961b12e3 | |||
| 2f15b5298d | |||
| 01a4300bb3 | |||
| a2cff20aff | |||
| 7d5c6e3e28 | |||
| 8d1c9c3bb6 | |||
| 7264276232 | |||
| 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 |
18
.github/workflows/rust.yml
vendored
18
.github/workflows/rust.yml
vendored
@@ -10,13 +10,19 @@ env:
|
|||||||
CARGO_TERM_COLOR: always
|
CARGO_TERM_COLOR: always
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
check:
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Build
|
# The Gitea runner image doesn't ship with Rust, unlike GitHub's.
|
||||||
run: cargo build --verbose
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
- name: Run tests
|
with:
|
||||||
run: cargo test --verbose
|
components: clippy, rustfmt
|
||||||
|
- uses: Swatinem/rust-cache@v2
|
||||||
|
- name: Format
|
||||||
|
run: cargo fmt --check
|
||||||
|
- name: Clippy
|
||||||
|
run: cargo clippy --all-targets -- -D warnings
|
||||||
|
- name: Test
|
||||||
|
run: cargo test
|
||||||
|
|||||||
25
Cargo.toml
25
Cargo.toml
@@ -1,26 +1,27 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "gemini-rs"
|
name = "gemini-rs"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2024"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
deadqueue = "0.2"
|
deadqueue = "0.2"
|
||||||
futures-util = "0.3"
|
|
||||||
gcp_auth = "0.12"
|
gcp_auth = "0.12"
|
||||||
reqwest = { version = "0.12", features = ["json", "gzip"] }
|
reqwest = { version = "0.13", features = ["json", "gzip", "stream"] }
|
||||||
reqwest-eventsource = "0.6"
|
tokio-util = "0.7"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = { version = "1"}
|
serde_json = { version = "1" }
|
||||||
serde_with = { version = "3.9", features = ["base64"]}
|
serde_with = { version = "3.21", features = ["base64"] }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tokio = { version = "1" }
|
tokio = { version = "1" }
|
||||||
|
tokio-stream = "0.1.18"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
console = "0.15.8"
|
base64 = "0.23.1"
|
||||||
dialoguer = "0.11.0"
|
console = "0.16.4"
|
||||||
image = "0.25.2"
|
dialoguer = "0.12.0"
|
||||||
indicatif = "0.17.8"
|
image = "0.25.10"
|
||||||
tokio = { version = "1.37.0", features = ["full"] }
|
indicatif = "0.18.6"
|
||||||
tracing-subscriber = "0.3.18"
|
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)
|
# 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.
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use console::style;
|
use console::style;
|
||||||
use dialoguer::{theme::ColorfulTheme, Input};
|
use dialoguer::{Input, theme::ColorfulTheme};
|
||||||
use gemini_rs::prelude::*;
|
use gemini_rs::prelude::*;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
|||||||
135
examples/function-response-image.rs
Normal file
135
examples/function-response-image.rs
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
//! Returns an image from a function call as a multimodal function response
|
||||||
|
//! (`functionResponse.parts` with `inlineData`) and asks the model what it sees.
|
||||||
|
//!
|
||||||
|
//! The image is a solid square in a color picked at random, so a correct answer
|
||||||
|
//! shows the model actually received the image.
|
||||||
|
|
||||||
|
use std::io::Cursor;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use base64::Engine;
|
||||||
|
use gemini_rs::prelude::*;
|
||||||
|
use image::{ImageFormat, Rgb, RgbImage};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
const COLORS: [(&str, [u8; 3]); 4] = [
|
||||||
|
("red", [220, 20, 20]),
|
||||||
|
("green", [20, 180, 20]),
|
||||||
|
("blue", [20, 40, 220]),
|
||||||
|
("yellow", [240, 220, 20]),
|
||||||
|
];
|
||||||
|
|
||||||
|
fn square_png(rgb: [u8; 3]) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
let image = RgbImage::from_pixel(64, 64, Rgb(rgb));
|
||||||
|
let mut bytes = Cursor::new(Vec::new());
|
||||||
|
image.write_to(&mut bytes, ImageFormat::Png)?;
|
||||||
|
Ok(base64::engine::general_purpose::STANDARD.encode(bytes.into_inner()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let authentication_manager = gcp_auth::provider().await?;
|
||||||
|
let api_endpoint = std::env::var("API_ENDPOINT")?;
|
||||||
|
let project_id = std::env::var("PROJECT_ID")?;
|
||||||
|
let location_id = std::env::var("LOCATION_ID")?;
|
||||||
|
let model = std::env::var("MODEL").unwrap_or_else(|_| "gemini-3.8-flash".to_string());
|
||||||
|
|
||||||
|
let gemini = GeminiClient::new(
|
||||||
|
authentication_manager,
|
||||||
|
api_endpoint,
|
||||||
|
project_id,
|
||||||
|
location_id,
|
||||||
|
);
|
||||||
|
|
||||||
|
let tools = vec![Tools {
|
||||||
|
function_declarations: Some(vec![FunctionDeclaration {
|
||||||
|
name: "take_snapshot".to_string(),
|
||||||
|
description: "Takes a snapshot of the camera and returns it as an image.".to_string(),
|
||||||
|
parameters: Some(json!({"type": "object", "properties": {}})),
|
||||||
|
parameters_json_schema: None,
|
||||||
|
}]),
|
||||||
|
..Default::default()
|
||||||
|
}];
|
||||||
|
let mut contents = vec![
|
||||||
|
Content::builder()
|
||||||
|
.role(Role::User)
|
||||||
|
.add_text_part(
|
||||||
|
"Take a snapshot with the camera and tell me, in one word, the color it shows.",
|
||||||
|
)
|
||||||
|
.build(),
|
||||||
|
];
|
||||||
|
|
||||||
|
let first = gemini
|
||||||
|
.generate_content(
|
||||||
|
&GenerateContentRequest::builder()
|
||||||
|
.contents(contents.clone())
|
||||||
|
.tools(tools.clone())
|
||||||
|
.build(),
|
||||||
|
&model,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let model_turn = first.candidates[0]
|
||||||
|
.content
|
||||||
|
.clone()
|
||||||
|
.ok_or("first response has no content")?;
|
||||||
|
let call = model_turn
|
||||||
|
.parts
|
||||||
|
.iter()
|
||||||
|
.flatten()
|
||||||
|
.find(|p| p.function_call.is_some())
|
||||||
|
.ok_or("model did not call take_snapshot")?
|
||||||
|
.clone();
|
||||||
|
println!(
|
||||||
|
"Model called: {}",
|
||||||
|
call.function_call.as_ref().unwrap().name
|
||||||
|
);
|
||||||
|
|
||||||
|
// `COLOR` picks one explicitly; otherwise pick by time (in microseconds, since
|
||||||
|
// some platforms' clocks have 100ns resolution).
|
||||||
|
let (color, rgb) = match std::env::var("COLOR") {
|
||||||
|
Ok(name) => *COLORS
|
||||||
|
.iter()
|
||||||
|
.find(|(c, _)| *c == name)
|
||||||
|
.ok_or_else(|| format!("unknown COLOR {name}"))?,
|
||||||
|
Err(_) => {
|
||||||
|
let micros = SystemTime::now().duration_since(UNIX_EPOCH)?.as_micros();
|
||||||
|
COLORS[(micros % COLORS.len() as u128) as usize]
|
||||||
|
}
|
||||||
|
};
|
||||||
|
println!("Returning a {color} image");
|
||||||
|
|
||||||
|
let mut response = Part::function_response("take_snapshot", json!({"status": "ok"}));
|
||||||
|
response.thought_signature = call.thought_signature.clone();
|
||||||
|
response.function_response.as_mut().unwrap().parts = vec![FunctionResponsePart {
|
||||||
|
inline_data: InlineData {
|
||||||
|
mime_type: "image/png".to_string(),
|
||||||
|
data: square_png(rgb)?,
|
||||||
|
},
|
||||||
|
}];
|
||||||
|
contents.push(model_turn);
|
||||||
|
contents.push(
|
||||||
|
Content::builder()
|
||||||
|
.role(Role::User)
|
||||||
|
.add_part(response)
|
||||||
|
.build(),
|
||||||
|
);
|
||||||
|
|
||||||
|
let second = gemini
|
||||||
|
.generate_content(
|
||||||
|
&GenerateContentRequest::builder()
|
||||||
|
.contents(contents)
|
||||||
|
.tools(tools)
|
||||||
|
.build(),
|
||||||
|
&model,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let answer = second.candidates[0].get_text().unwrap_or_default();
|
||||||
|
println!("Model answered: {answer}");
|
||||||
|
|
||||||
|
if answer.to_lowercase().contains(color) {
|
||||||
|
println!("OK: the model saw the {color} image");
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(format!("expected the answer to mention {color}").into())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,9 +34,14 @@ pub async fn main() -> Result<(), Box<dyn Error>> {
|
|||||||
mime_type: Some("image/jpeg".to_string()),
|
mime_type: Some("image/jpeg".to_string()),
|
||||||
compression_quality: Some(75),
|
compression_quality: Some(75),
|
||||||
}),
|
}),
|
||||||
|
person_generation: Some("allow_all".to_string()),
|
||||||
|
safety_setting: Some("block_only_high".to_string()),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
println!("Request: {:#?}", serde_json::to_string(&request).unwrap());
|
||||||
|
|
||||||
let mut result = gemini
|
let mut result = gemini
|
||||||
.predict_image(&request, "imagen-3.0-fast-generate-001")
|
.predict_image(&request, "imagen-3.0-fast-generate-001")
|
||||||
.await?;
|
.await?;
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let request = GenerateContentRequest {
|
let request = GenerateContentRequest {
|
||||||
contents: vec![Content {
|
contents: vec![Content {
|
||||||
role: Some(Role::User),
|
role: Some(Role::User),
|
||||||
parts: Some(vec![Part::Text(prompt.to_string())]),
|
parts: Some(vec![Part::text(prompt)]),
|
||||||
}],
|
}],
|
||||||
tools: Some(vec![Tools {
|
tools: Some(vec![Tools {
|
||||||
google_search_retrieval: Some(GoogleSearchRetrieval::default()),
|
google_search_retrieval: Some(GoogleSearchRetrieval::default()),
|
||||||
@@ -29,8 +29,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
println!(
|
||||||
|
"Request: {}",
|
||||||
|
serde_json::to_string_pretty(&request).unwrap()
|
||||||
|
);
|
||||||
|
|
||||||
let result = gemini
|
let result = gemini
|
||||||
.generate_content(&request, "gemini-1.0-pro-002")
|
.generate_content(&request, "gemini-1.5-flash-002")
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
println!("Response: {:?}", result.candidates[0].get_text().unwrap());
|
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 {
|
let request = GenerateContentRequest {
|
||||||
contents: vec![Content {
|
contents: vec![Content {
|
||||||
role: Some(Role::User),
|
role: Some(Role::User),
|
||||||
parts: Some(vec![Part::Text(prompt.to_string())]),
|
parts: Some(vec![Part::text(prompt)]),
|
||||||
}],
|
}],
|
||||||
generation_config: Some(GenerationConfig {
|
generation_config: Some(GenerationConfig {
|
||||||
response_mime_type: Some("application/json".to_string()),
|
response_mime_type: Some("application/json".to_string()),
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let request = GenerateContentRequest {
|
let request = GenerateContentRequest {
|
||||||
contents: vec![Content {
|
contents: vec![Content {
|
||||||
role: Some(Role::User),
|
role: Some(Role::User),
|
||||||
parts: Some(vec![Part::Text(prompt.to_string())]),
|
parts: Some(vec![Part::text(prompt)]),
|
||||||
}],
|
}],
|
||||||
safety_settings: Some(vec![SafetySetting {
|
safety_settings: Some(vec![SafetySetting {
|
||||||
category: HarmCategory::HateSpeech,
|
category: HarmCategory::HateSpeech,
|
||||||
|
|||||||
@@ -15,20 +15,21 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
location_id,
|
location_id,
|
||||||
);
|
);
|
||||||
|
|
||||||
let system_instruction = "Answer as if you were Yoda";
|
let system_instruction = Content::builder()
|
||||||
let prompt = "What is the airspeed of an unladen swallow?";
|
.add_text_part("Answer as if you were Yoda")
|
||||||
|
.build();
|
||||||
|
|
||||||
let request = GenerateContentRequest {
|
let user_prompt = vec![
|
||||||
contents: vec![Content {
|
Content::builder()
|
||||||
role: Some(Role::User),
|
.role(Role::User)
|
||||||
parts: Some(vec![Part::Text(prompt.to_string())]),
|
.add_text_part("What is the airspeed of an unladen swallow?")
|
||||||
}],
|
.build(),
|
||||||
system_instruction: Some(Content {
|
];
|
||||||
role: None,
|
|
||||||
parts: Some(vec![Part::Text(system_instruction.to_string())]),
|
let request = GenerateContentRequest::builder()
|
||||||
}),
|
.contents(user_prompt)
|
||||||
..Default::default()
|
.system_instruction(system_instruction)
|
||||||
};
|
.build();
|
||||||
|
|
||||||
let result = gemini
|
let result = gemini
|
||||||
.generate_content(&request, "gemini-1.0-pro-002")
|
.generate_content(&request, "gemini-1.0-pro-002")
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use gemini_rs::prelude::*;
|
use gemini_rs::prelude::*;
|
||||||
|
use tokio_stream::StreamExt;
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
@@ -14,32 +15,21 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
location_id,
|
location_id,
|
||||||
);
|
);
|
||||||
|
|
||||||
let prompt = "Tell me the story of the genesis of the universe as a bedtime story.";
|
let prompt = vec![
|
||||||
let request = GenerateContentRequest::builder()
|
Content::builder()
|
||||||
.add_content(
|
.role(Role::User)
|
||||||
Content::builder()
|
.add_text_part("Tell me the story of the genesis of the universe as a bedtime story.")
|
||||||
.role(Role::User)
|
.build(),
|
||||||
.add_part(Part::Text(prompt.to_string()))
|
];
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
.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 {
|
let mut queue = gemini
|
||||||
match response {
|
.stream_generate_content(&request, "gemini-2.0-flash-001")
|
||||||
Ok(result) => {
|
.await?;
|
||||||
let text = result
|
|
||||||
.candidates
|
while let Some(response) = queue.next().await {
|
||||||
.iter()
|
println!("Response: {:?}", response?);
|
||||||
.filter_map(|c| c.get_text())
|
|
||||||
.collect::<String>();
|
|
||||||
print!("{}", text);
|
|
||||||
}
|
|
||||||
Err(error) => {
|
|
||||||
println!("{error}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -14,15 +14,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
location_id,
|
location_id,
|
||||||
);
|
);
|
||||||
|
|
||||||
let prompt = "What is the airspeed of an unladen swallow?";
|
let prompt = vec![
|
||||||
let request = GenerateContentRequest::builder()
|
Content::builder()
|
||||||
.add_content(
|
.role(Role::User)
|
||||||
Content::builder()
|
.add_text_part("What is the airspeed of an unladen swallow?")
|
||||||
.role(Role::User)
|
.build(),
|
||||||
.add_part(Part::Text(prompt.to_string()))
|
];
|
||||||
.build(),
|
|
||||||
)
|
let request = GenerateContentRequest::builder().contents(prompt).build();
|
||||||
.build();
|
|
||||||
let response = gemini.generate_content(&request, "gemini-pro").await?;
|
let response = gemini.generate_content(&request, "gemini-pro").await?;
|
||||||
println!("Response: {:?}", response.candidates[0].get_text().unwrap());
|
println!("Response: {:?}", response.candidates[0].get_text().unwrap());
|
||||||
|
|
||||||
|
|||||||
216
src/client.rs
216
src/client.rs
@@ -1,21 +1,21 @@
|
|||||||
use std::sync::Arc;
|
use std::vec;
|
||||||
|
|
||||||
use deadqueue::unlimited::Queue;
|
|
||||||
use futures_util::stream::StreamExt;
|
|
||||||
use reqwest_eventsource::{Event, EventSource};
|
|
||||||
use tracing::error;
|
use tracing::error;
|
||||||
|
|
||||||
|
use tokio_stream::{Stream, StreamExt};
|
||||||
|
|
||||||
use crate::dialogue::Message;
|
use crate::dialogue::Message;
|
||||||
use crate::error::{Error, Result};
|
use crate::error::{Error, Result};
|
||||||
|
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, GenerationConfig, 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};
|
||||||
|
|
||||||
pub static AUTH_SCOPE: &[&str] = &["https://www.googleapis.com/auth/cloud-platform"];
|
pub const AUTH_SCOPE: &[&str] = &["https://www.googleapis.com/auth/cloud-platform"];
|
||||||
|
const ENDPOINT_VERSION: &str = "v1beta1";
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct GeminiClient<T: TokenProvider + Clone> {
|
pub struct GeminiClient<T: TokenProvider + Clone> {
|
||||||
@@ -26,9 +26,6 @@ pub struct GeminiClient<T: TokenProvider + Clone> {
|
|||||||
location_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> {
|
impl<T: TokenProvider + Clone> GeminiClient<T> {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
token_provider: T,
|
token_provider: T,
|
||||||
@@ -45,79 +42,31 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn stream_generate_content(
|
fn endpoint_url(&self, version: &str, action: &str) -> String {
|
||||||
&self,
|
let scheme = if self.api_endpoint.starts_with("http://")
|
||||||
request: &GenerateContentRequest,
|
|| self.api_endpoint.starts_with("https://")
|
||||||
model: &str,
|
{
|
||||||
) -> Arc<Queue<Option<Result<GenerateContentResponseResult>>>> {
|
""
|
||||||
let queue = Arc::new(Queue::<Option<Result<GenerateContentResponseResult>>>::new());
|
} else {
|
||||||
let access_token = match self.token_provider.get_token(AUTH_SCOPE).await {
|
"https://"
|
||||||
Ok(access_token) => access_token,
|
|
||||||
Err(e) => {
|
|
||||||
queue.push(Some(Err(e)));
|
|
||||||
return queue;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
format!(
|
||||||
|
"{scheme}{}/{version}/projects/{}/locations/{}/publishers/google/models/{action}",
|
||||||
|
self.api_endpoint, self.project_id, self.location_id
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// Clone the queue and other necessary data to move into the async block.
|
async fn error_for_status(response: reqwest::Response) -> Result<reqwest::Response> {
|
||||||
let cloned_queue = queue.clone();
|
if !response.status().is_success() {
|
||||||
let endpoint_url: String = format!(
|
let status = response.status();
|
||||||
"https://{}/v1beta1/projects/{}/locations/{}/publishers/google/models/{}:streamGenerateContent?alt=sse", self.api_endpoint, self.project_id, self.location_id, model,
|
let body = response.text().await?;
|
||||||
);
|
if let Ok(error_response) = serde_json::from_str::<GenerateContentResponseError>(&body)
|
||||||
let client = self.client.clone();
|
{
|
||||||
let request = request.clone();
|
return Err(error_response.error.into());
|
||||||
|
|
||||||
// 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 Err(Error::HttpStatus { status, body });
|
||||||
});
|
}
|
||||||
|
Ok(response)
|
||||||
// Return the queue that will receive the responses.
|
|
||||||
queue
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn generate_content(
|
pub async fn generate_content(
|
||||||
@@ -126,9 +75,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
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://{}/v1beta1/projects/{}/locations/{}/publishers/google/models/{}:generateContent", self.api_endpoint, self.project_id, self.location_id, model,
|
|
||||||
);
|
|
||||||
let resp = self
|
let resp = self
|
||||||
.client
|
.client
|
||||||
.post(&endpoint_url)
|
.post(&endpoint_url)
|
||||||
@@ -137,6 +84,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
let resp = Self::error_for_status(resp).await?;
|
||||||
let txt_json = resp.text().await?;
|
let txt_json = resp.text().await?;
|
||||||
tracing::debug!("generate_content response: {:?}", txt_json);
|
tracing::debug!("generate_content response: {:?}", txt_json);
|
||||||
match serde_json::from_str::<GenerateContentResponse>(&txt_json) {
|
match serde_json::from_str::<GenerateContentResponse>(&txt_json) {
|
||||||
@@ -148,6 +96,48 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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?;
|
||||||
|
|
||||||
|
let response = Self::error_for_status(response).await?;
|
||||||
|
Ok(response.event_stream().filter_map(Self::parse_sse_event))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_sse_event(
|
||||||
|
event_result: std::result::Result<ServerSentEvent, tokio_util::codec::LinesCodecError>,
|
||||||
|
) -> Option<Result<GenerateContentResponseResult>> {
|
||||||
|
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.
|
/// Prompts a conversation to the model.
|
||||||
pub async fn prompt_conversation(&self, messages: &[Message], model: &str) -> Result<Message> {
|
pub async fn prompt_conversation(&self, messages: &[Message], model: &str) -> Result<Message> {
|
||||||
let request = GenerateContentRequest {
|
let request = GenerateContentRequest {
|
||||||
@@ -155,7 +145,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
.iter()
|
.iter()
|
||||||
.map(|m| Content {
|
.map(|m| Content {
|
||||||
role: Some(m.role),
|
role: Some(m.role),
|
||||||
parts: Some(vec![Part::Text(m.text.clone())]),
|
parts: Some(vec![Part::text(m.text.clone())]),
|
||||||
})
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
generation_config: None,
|
generation_config: None,
|
||||||
@@ -175,34 +165,6 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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> {
|
fn collect_text_from_response(response: &GenerateContentResponseResult) -> Vec<String> {
|
||||||
response
|
response
|
||||||
.candidates
|
.candidates
|
||||||
@@ -216,10 +178,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
|
||||||
@@ -228,6 +187,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
.json(&request)
|
.json(&request)
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
|
let resp = Self::error_for_status(resp).await?;
|
||||||
let txt_json = resp.text().await?;
|
let txt_json = resp.text().await?;
|
||||||
tracing::debug!("text_embeddings response: {:?}", txt_json);
|
tracing::debug!("text_embeddings response: {:?}", txt_json);
|
||||||
Ok(serde_json::from_str::<TextEmbeddingResponse>(&txt_json)?)
|
Ok(serde_json::from_str::<TextEmbeddingResponse>(&txt_json)?)
|
||||||
@@ -238,10 +198,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://{}/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 access_token = self.token_provider.get_token(AUTH_SCOPE).await?;
|
||||||
let resp = self
|
let resp = self
|
||||||
.client
|
.client
|
||||||
@@ -250,7 +207,7 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
.json(&request)
|
.json(&request)
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
|
let resp = Self::error_for_status(resp).await?;
|
||||||
let txt_json = resp.text().await?;
|
let txt_json = resp.text().await?;
|
||||||
tracing::debug!("count_tokens response: {:?}", txt_json);
|
tracing::debug!("count_tokens response: {:?}", txt_json);
|
||||||
Ok(serde_json::from_str(&txt_json)?)
|
Ok(serde_json::from_str(&txt_json)?)
|
||||||
@@ -261,10 +218,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
|
||||||
@@ -274,15 +228,19 @@ impl<T: TokenProvider + Clone> GeminiClient<T> {
|
|||||||
.json(&request)
|
.json(&request)
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
|
let resp = Self::error_for_status(resp).await?;
|
||||||
let txt_json = resp.text().await?;
|
let txt_json = resp.text().await?;
|
||||||
|
|
||||||
match serde_json::from_str::<PredictImageResponse>(&txt_json) {
|
match serde_json::from_str::<PredictImageResponse>(&txt_json) {
|
||||||
Ok(response) => return Ok(response),
|
Ok(response) => Ok(response),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!(response = txt_json, error = ?e, "Failed to parse response");
|
error!(response = txt_json, error = ?e, "Failed to parse response");
|
||||||
return Err(e.into());
|
Err(e.into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "client_tests.rs"]
|
||||||
|
mod tests;
|
||||||
|
|||||||
406
src/client_tests.rs
Normal file
406
src/client_tests.rs
Normal file
@@ -0,0 +1,406 @@
|
|||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
use crate::types::PredictImageRequestParameters;
|
||||||
|
|
||||||
|
type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct MockTokenProvider;
|
||||||
|
|
||||||
|
impl TokenProvider for MockTokenProvider {
|
||||||
|
async fn get_token(&self, _scope: &[&str]) -> crate::error::Result<String> {
|
||||||
|
Ok("test-token".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn generate_content_returns_http_status_on_non_json_503() -> Result<()> {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||||
|
let addr = listener.local_addr()?;
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let (mut socket, _) = listener.accept().await.unwrap();
|
||||||
|
let mut buf = [0u8; 4096];
|
||||||
|
let _ = socket.read(&mut buf).await;
|
||||||
|
let body = "Service Unavailable";
|
||||||
|
let response = format!(
|
||||||
|
"HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||||
|
body.len(),
|
||||||
|
body
|
||||||
|
);
|
||||||
|
socket.write_all(response.as_bytes()).await.unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let client = GeminiClient::new(
|
||||||
|
MockTokenProvider,
|
||||||
|
format!("http://{addr}"),
|
||||||
|
"test-project".to_string(),
|
||||||
|
"test-location".to_string(),
|
||||||
|
);
|
||||||
|
let request = GenerateContentRequest::default();
|
||||||
|
|
||||||
|
let result = client.generate_content(&request, "gemini-test").await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Err(Error::HttpStatus { status, body }) => {
|
||||||
|
assert_eq!(status, reqwest::StatusCode::SERVICE_UNAVAILABLE);
|
||||||
|
assert_eq!(body, "Service Unavailable");
|
||||||
|
}
|
||||||
|
Err(other) => panic!("Expected Error::HttpStatus, got: {other:?}"),
|
||||||
|
Ok(_) => panic!("Expected error response, got Ok"),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn generate_content_returns_vertex_error_on_400_json() -> Result<()> {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||||
|
let addr = listener.local_addr()?;
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let (mut socket, _) = listener.accept().await.unwrap();
|
||||||
|
let mut buf = [0u8; 4096];
|
||||||
|
let _ = socket.read(&mut buf).await;
|
||||||
|
let body = r#"{"error": {"code": 400, "message": "Invalid request", "status": "INVALID_ARGUMENT"}}"#;
|
||||||
|
let response = format!(
|
||||||
|
"HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||||
|
body.len(),
|
||||||
|
body
|
||||||
|
);
|
||||||
|
socket.write_all(response.as_bytes()).await.unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let client = GeminiClient::new(
|
||||||
|
MockTokenProvider,
|
||||||
|
format!("http://{addr}"),
|
||||||
|
"test-project".to_string(),
|
||||||
|
"test-location".to_string(),
|
||||||
|
);
|
||||||
|
let request = GenerateContentRequest::default();
|
||||||
|
|
||||||
|
let result = client.generate_content(&request, "gemini-test").await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Err(Error::VertexError(err)) => {
|
||||||
|
assert_eq!(err.code, 400);
|
||||||
|
assert_eq!(err.status, "INVALID_ARGUMENT");
|
||||||
|
}
|
||||||
|
Err(other) => panic!("Expected Error::VertexError, got: {other:?}"),
|
||||||
|
Ok(_) => panic!("Expected error response, got Ok"),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn count_tokens_returns_http_status_on_non_json_error() -> Result<()> {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||||
|
let addr = listener.local_addr()?;
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let (mut socket, _) = listener.accept().await.unwrap();
|
||||||
|
let mut buf = [0u8; 4096];
|
||||||
|
let _ = socket.read(&mut buf).await;
|
||||||
|
let body = "Bad Gateway";
|
||||||
|
let response = format!(
|
||||||
|
"HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||||
|
body.len(),
|
||||||
|
body
|
||||||
|
);
|
||||||
|
socket.write_all(response.as_bytes()).await.unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let client = GeminiClient::new(
|
||||||
|
MockTokenProvider,
|
||||||
|
format!("http://{addr}"),
|
||||||
|
"test-project".to_string(),
|
||||||
|
"test-location".to_string(),
|
||||||
|
);
|
||||||
|
let request = CountTokensRequest {
|
||||||
|
contents: Content::default(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = client.count_tokens(&request, "gemini-test").await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Err(Error::HttpStatus { status, body }) => {
|
||||||
|
assert_eq!(status, reqwest::StatusCode::BAD_GATEWAY);
|
||||||
|
assert_eq!(body, "Bad Gateway");
|
||||||
|
}
|
||||||
|
Err(other) => panic!("Expected Error::HttpStatus, got: {other:?}"),
|
||||||
|
Ok(_) => panic!("Expected error response, got Ok"),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn text_embeddings_returns_http_status_on_non_json_error() -> Result<()> {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||||
|
let addr = listener.local_addr()?;
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let (mut socket, _) = listener.accept().await.unwrap();
|
||||||
|
let mut buf = [0u8; 4096];
|
||||||
|
let _ = socket.read(&mut buf).await;
|
||||||
|
let body = "Internal Server Error";
|
||||||
|
let response = format!(
|
||||||
|
"HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||||
|
body.len(),
|
||||||
|
body
|
||||||
|
);
|
||||||
|
socket.write_all(response.as_bytes()).await.unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let client = GeminiClient::new(
|
||||||
|
MockTokenProvider,
|
||||||
|
format!("http://{addr}"),
|
||||||
|
"test-project".to_string(),
|
||||||
|
"test-location".to_string(),
|
||||||
|
);
|
||||||
|
let request = TextEmbeddingRequest { instances: vec![] };
|
||||||
|
|
||||||
|
let result = client.text_embeddings(&request, "gemini-test").await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Err(Error::HttpStatus { status, body }) => {
|
||||||
|
assert_eq!(status, reqwest::StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
assert_eq!(body, "Internal Server Error");
|
||||||
|
}
|
||||||
|
Err(other) => panic!("Expected Error::HttpStatus, got: {other:?}"),
|
||||||
|
Ok(_) => panic!("Expected error response, got Ok"),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn predict_image_returns_http_status_on_non_json_error() -> Result<()> {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||||
|
let addr = listener.local_addr()?;
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let (mut socket, _) = listener.accept().await.unwrap();
|
||||||
|
let mut buf = [0u8; 4096];
|
||||||
|
let _ = socket.read(&mut buf).await;
|
||||||
|
let body = "Service Unavailable";
|
||||||
|
let response = format!(
|
||||||
|
"HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||||
|
body.len(),
|
||||||
|
body
|
||||||
|
);
|
||||||
|
socket.write_all(response.as_bytes()).await.unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let client = GeminiClient::new(
|
||||||
|
MockTokenProvider,
|
||||||
|
format!("http://{addr}"),
|
||||||
|
"test-project".to_string(),
|
||||||
|
"test-location".to_string(),
|
||||||
|
);
|
||||||
|
let request = PredictImageRequest {
|
||||||
|
instances: vec![],
|
||||||
|
parameters: PredictImageRequestParameters::default(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = client.predict_image(&request, "imagen-test").await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Err(Error::HttpStatus { status, body }) => {
|
||||||
|
assert_eq!(status, reqwest::StatusCode::SERVICE_UNAVAILABLE);
|
||||||
|
assert_eq!(body, "Service Unavailable");
|
||||||
|
}
|
||||||
|
Err(other) => panic!("Expected Error::HttpStatus, got: {other:?}"),
|
||||||
|
Ok(_) => panic!("Expected error response, got Ok"),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
134
src/error.rs
134
src/error.rs
@@ -1,6 +1,6 @@
|
|||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
use reqwest_eventsource::CannotCloneRequestError;
|
use tokio_util::codec::LinesCodecError;
|
||||||
|
|
||||||
use crate::types;
|
use crate::types;
|
||||||
|
|
||||||
@@ -14,25 +14,26 @@ pub enum Error {
|
|||||||
Serde(serde_json::Error),
|
Serde(serde_json::Error),
|
||||||
VertexError(types::VertexApiError),
|
VertexError(types::VertexApiError),
|
||||||
NoCandidatesError,
|
NoCandidatesError,
|
||||||
EventSourceError(CannotCloneRequestError),
|
/// 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 {
|
impl Display for Error {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match &self {
|
match &self {
|
||||||
Error::Env(e) => write!(f, "Environment variable error: {}", e),
|
Error::Env(e) => write!(f, "Environment variable error: {e}"),
|
||||||
Error::HttpClient(e) => write!(f, "HTTP Client error: {}", e),
|
Error::HttpClient(e) => write!(f, "HTTP Client error: {e}"),
|
||||||
Error::Token(e) => write!(f, "Token error: {}", e),
|
Error::Token(e) => write!(f, "Token error: {e}"),
|
||||||
Error::Serde(e) => write!(f, "Serde error: {}", e),
|
Error::Serde(e) => write!(f, "Serde error: {e}"),
|
||||||
Error::VertexError(e) => {
|
Error::VertexError(e) => write!(f, "Vertex error: {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::NoCandidatesError => {
|
Error::HttpStatus { status, body } => write!(f, "HTTP status {status}: {body}"),
|
||||||
write!(f, "No candidates returned for the prompt")
|
|
||||||
}
|
|
||||||
Error::EventSourceError(e) => {
|
|
||||||
write!(f, "EventSourrce Error: {}", e)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -51,26 +52,113 @@ impl From<std::env::VarError> for Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<gcp_auth::Error> for Error {
|
|
||||||
fn from(e: gcp_auth::Error) -> Self {
|
|
||||||
Error::Token(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<serde_json::Error> for Error {
|
impl From<serde_json::Error> for Error {
|
||||||
fn from(e: serde_json::Error) -> Self {
|
fn from(e: serde_json::Error) -> Self {
|
||||||
Error::Serde(e)
|
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 {
|
impl From<types::VertexApiError> for Error {
|
||||||
fn from(e: types::VertexApiError) -> Self {
|
fn from(e: types::VertexApiError) -> Self {
|
||||||
Error::VertexError(e)
|
Error::VertexError(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<CannotCloneRequestError> for Error {
|
impl From<LinesCodecError> for Error {
|
||||||
fn from(e: CannotCloneRequestError) -> Self {
|
fn from(e: LinesCodecError) -> Self {
|
||||||
Error::EventSourceError(e)
|
Error::EventSourceError(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Error {
|
||||||
|
/// Returns whether this error is considered retryable per Vertex AI error guidance.
|
||||||
|
///
|
||||||
|
/// The following errors are treated as retryable:
|
||||||
|
/// - `VertexError` with HTTP status code 429, 500, or 503, or status string
|
||||||
|
/// `RESOURCE_EXHAUSTED`, `INTERNAL`, `UNKNOWN`, or `UNAVAILABLE`.
|
||||||
|
/// - `HttpStatus` with status code 429, 500, 502, or 503.
|
||||||
|
/// - `HttpClient` transport errors that are timeouts or connection failures.
|
||||||
|
pub fn is_retryable(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Error::VertexError(err) => {
|
||||||
|
matches!(err.code, 429 | 500 | 503)
|
||||||
|
|| matches!(
|
||||||
|
err.status.as_str(),
|
||||||
|
"RESOURCE_EXHAUSTED" | "INTERNAL" | "UNKNOWN" | "UNAVAILABLE"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Error::HttpStatus { status, .. } => {
|
||||||
|
matches!(status.as_u16(), 429 | 500 | 502 | 503)
|
||||||
|
}
|
||||||
|
Error::HttpClient(err) => err.is_timeout() || err.is_connect(),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vertex_error_retryable_classification() {
|
||||||
|
let make_err = |code: i32, status: &str| {
|
||||||
|
Error::VertexError(types::VertexApiError {
|
||||||
|
code,
|
||||||
|
message: "test".to_string(),
|
||||||
|
status: status.to_string(),
|
||||||
|
details: None,
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
// Retryable codes
|
||||||
|
assert!(make_err(429, "TOO_MANY_REQUESTS").is_retryable());
|
||||||
|
assert!(make_err(500, "INTERNAL").is_retryable());
|
||||||
|
assert!(make_err(500, "UNKNOWN").is_retryable());
|
||||||
|
assert!(make_err(503, "UNAVAILABLE").is_retryable());
|
||||||
|
|
||||||
|
// Retryable status strings regardless of code
|
||||||
|
assert!(make_err(400, "RESOURCE_EXHAUSTED").is_retryable());
|
||||||
|
assert!(make_err(400, "INTERNAL").is_retryable());
|
||||||
|
assert!(make_err(400, "UNKNOWN").is_retryable());
|
||||||
|
assert!(make_err(400, "UNAVAILABLE").is_retryable());
|
||||||
|
|
||||||
|
// Non-retryable
|
||||||
|
assert!(!make_err(400, "INVALID_ARGUMENT").is_retryable());
|
||||||
|
assert!(!make_err(403, "PERMISSION_DENIED").is_retryable());
|
||||||
|
assert!(!make_err(404, "NOT_FOUND").is_retryable());
|
||||||
|
assert!(!make_err(504, "DEADLINE_EXCEEDED").is_retryable());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn http_status_retryable_classification() {
|
||||||
|
let make_err = |status: reqwest::StatusCode| Error::HttpStatus {
|
||||||
|
status,
|
||||||
|
body: "error".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(make_err(reqwest::StatusCode::TOO_MANY_REQUESTS).is_retryable());
|
||||||
|
assert!(make_err(reqwest::StatusCode::INTERNAL_SERVER_ERROR).is_retryable());
|
||||||
|
assert!(make_err(reqwest::StatusCode::BAD_GATEWAY).is_retryable());
|
||||||
|
assert!(make_err(reqwest::StatusCode::SERVICE_UNAVAILABLE).is_retryable());
|
||||||
|
|
||||||
|
assert!(!make_err(reqwest::StatusCode::BAD_REQUEST).is_retryable());
|
||||||
|
assert!(!make_err(reqwest::StatusCode::UNAUTHORIZED).is_retryable());
|
||||||
|
assert!(!make_err(reqwest::StatusCode::FORBIDDEN).is_retryable());
|
||||||
|
assert!(!make_err(reqwest::StatusCode::NOT_FOUND).is_retryable());
|
||||||
|
assert!(!make_err(reqwest::StatusCode::GATEWAY_TIMEOUT).is_retryable());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn other_errors_not_retryable() {
|
||||||
|
assert!(!Error::NoCandidatesError.is_retryable());
|
||||||
|
let serde_err = serde_json::from_str::<String>("invalid").unwrap_err();
|
||||||
|
assert!(!Error::Serde(serde_err).is_retryable());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
mod client;
|
mod client;
|
||||||
mod dialogue;
|
mod dialogue;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
pub(crate) mod network;
|
||||||
mod token_provider;
|
mod token_provider;
|
||||||
mod types;
|
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;
|
||||||
@@ -4,10 +4,10 @@ use crate::error::Result;
|
|||||||
|
|
||||||
pub trait TokenProvider {
|
pub trait TokenProvider {
|
||||||
fn get_token(&self, scope: &[&str])
|
fn get_token(&self, scope: &[&str])
|
||||||
-> impl std::future::Future<Output = Result<String>> + Send;
|
-> impl std::future::Future<Output = Result<String>> + Send;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TokenProvider for Arc<dyn gcp_auth::TokenProvider + 'a> {
|
impl TokenProvider for Arc<dyn gcp_auth::TokenProvider + '_> {
|
||||||
async fn get_token(&self, scope: &[&str]) -> Result<String> {
|
async fn get_token(&self, scope: &[&str]) -> Result<String> {
|
||||||
let token = self.token(scope).await;
|
let token = self.token(scope).await;
|
||||||
match token {
|
match token {
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
use std::{collections::HashMap, str::FromStr, vec};
|
use std::{fmt::Display, str::FromStr, vec};
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
|
||||||
pub struct Content {
|
pub struct Content {
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub role: Option<Role>,
|
pub role: Option<Role>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub parts: Option<Vec<Part>>,
|
pub parts: Option<Vec<Part>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -13,28 +16,52 @@ impl Content {
|
|||||||
self.parts.as_ref().map(|parts| {
|
self.parts.as_ref().map(|parts| {
|
||||||
parts
|
parts
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|part| match part {
|
.filter_map(|part| part.text.clone())
|
||||||
Part::Text(text) => Some(text.clone()),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect::<String>()
|
.collect::<String>()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn builder() -> ContentBuilder {
|
pub fn builder() -> ContentBuilder {
|
||||||
ContentBuilder::new()
|
ContentBuilder::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn system_prompt(prompt: impl Into<String>) -> Self {
|
||||||
|
Content {
|
||||||
|
parts: Some(vec![Part::text(prompt)]),
|
||||||
|
role: None,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 {
|
pub struct ContentBuilder {
|
||||||
content: Content,
|
content: Content,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ContentBuilder {
|
impl ContentBuilder {
|
||||||
pub fn new() -> Self {
|
pub fn add_text_part<T: Into<String>>(self, text: T) -> Self {
|
||||||
Self {
|
self.add_part(Part::text(text))
|
||||||
content: Default::default(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_part(mut self, part: Part) -> Self {
|
pub fn add_part(mut self, part: Part) -> Self {
|
||||||
@@ -55,19 +82,20 @@ impl ContentBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "lowercase")]
|
||||||
pub enum Role {
|
pub enum Role {
|
||||||
User,
|
User,
|
||||||
Model,
|
Model,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ToString for Role {
|
impl Display for Role {
|
||||||
fn to_string(&self) -> String {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
let role_str = match self {
|
||||||
Role::User => "user".to_string(),
|
Role::User => "user",
|
||||||
Role::Model => "model".to_string(),
|
Role::Model => "model",
|
||||||
}
|
};
|
||||||
|
f.write_str(role_str)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,20 +111,405 @@ 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 {
|
||||||
|
id: None,
|
||||||
|
name: name.into(),
|
||||||
|
args,
|
||||||
|
partial_args: None,
|
||||||
|
will_continue: None,
|
||||||
|
}),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn function_call_with_id(
|
||||||
|
id: impl Into<String>,
|
||||||
|
name: impl Into<String>,
|
||||||
|
args: Value,
|
||||||
|
) -> Self {
|
||||||
|
Part {
|
||||||
|
function_call: Some(FunctionCallData {
|
||||||
|
id: Some(id.into()),
|
||||||
|
name: name.into(),
|
||||||
|
args,
|
||||||
|
partial_args: None,
|
||||||
|
will_continue: None,
|
||||||
|
}),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn function_response(name: impl Into<String>, response: Value) -> Self {
|
||||||
|
Part {
|
||||||
|
function_response: Some(FunctionResponseData {
|
||||||
|
id: None,
|
||||||
|
name: name.into(),
|
||||||
|
response,
|
||||||
|
parts: vec![],
|
||||||
|
}),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn function_response_with_id(
|
||||||
|
id: impl Into<String>,
|
||||||
|
name: impl Into<String>,
|
||||||
|
response: Value,
|
||||||
|
) -> Self {
|
||||||
|
Part {
|
||||||
|
function_response: Some(FunctionResponseData {
|
||||||
|
id: Some(id.into()),
|
||||||
|
name: name.into(),
|
||||||
|
response,
|
||||||
|
parts: vec![],
|
||||||
|
}),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_thought_signature(mut self, signature: impl Into<String>) -> Self {
|
||||||
|
self.thought_signature = Some(signature.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_id(mut self, id: impl Into<String>) -> Self {
|
||||||
|
let id = id.into();
|
||||||
|
if let Some(ref mut call) = self.function_call {
|
||||||
|
call.id = Some(id.clone());
|
||||||
|
}
|
||||||
|
if let Some(ref mut response) = self.function_response {
|
||||||
|
response.id = Some(id);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_function_response_part(mut self, part: FunctionResponsePart) -> Self {
|
||||||
|
if let Some(ref mut response) = self.function_response {
|
||||||
|
response.parts.push(part);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_function_response_inline_data(
|
||||||
|
self,
|
||||||
|
mime_type: impl Into<String>,
|
||||||
|
data: impl Into<String>,
|
||||||
|
) -> Self {
|
||||||
|
self.add_function_response_part(FunctionResponsePart::inline_data(mime_type, data))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_will_continue(mut self, will_continue: bool) -> Self {
|
||||||
|
if let Some(ref mut call) = self.function_call {
|
||||||
|
call.will_continue = Some(will_continue);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_partial_args(mut self, partial_args: Vec<Value>) -> Self {
|
||||||
|
if let Some(ref mut call) = self.function_call {
|
||||||
|
call.partial_args = Some(partial_args);
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct FunctionCallData {
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub id: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Value::is_null")]
|
||||||
|
pub args: Value,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub partial_args: Option<Vec<Value>>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub will_continue: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
pub struct FunctionResponseData {
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub id: Option<String>,
|
||||||
|
pub name: String,
|
||||||
|
pub response: Value,
|
||||||
|
/// Media returned by the function (multimodal function responses), sent as
|
||||||
|
/// `functionResponse.parts`. Omitted when empty.
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub parts: Vec<FunctionResponsePart>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub enum Part {
|
pub struct FunctionResponsePart {
|
||||||
Text(String),
|
pub inline_data: InlineData,
|
||||||
InlineData {
|
}
|
||||||
mime_type: String,
|
|
||||||
data: String,
|
impl FunctionResponsePart {
|
||||||
},
|
pub fn inline_data(mime_type: impl Into<String>, data: impl Into<String>) -> Self {
|
||||||
FileData {
|
Self {
|
||||||
mime_type: String,
|
inline_data: InlineData {
|
||||||
file_uri: String,
|
mime_type: mime_type.into(),
|
||||||
},
|
data: data.into(),
|
||||||
FunctionCall {
|
},
|
||||||
name: String,
|
}
|
||||||
args: HashMap<String, String>,
|
}
|
||||||
},
|
}
|
||||||
|
|
||||||
|
#[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::{Content, FunctionResponsePart, InlineData, Part, Role};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_omits_unset_role_and_parts() {
|
||||||
|
let system = Content::system_prompt("You are a helpful assistant.");
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&system).unwrap(),
|
||||||
|
json!({
|
||||||
|
"parts": [{"text": "You are a helpful assistant."}]
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
let role_only = Content {
|
||||||
|
role: Some(Role::User),
|
||||||
|
parts: None,
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&role_only).unwrap(),
|
||||||
|
json!({"role": "user"})
|
||||||
|
);
|
||||||
|
|
||||||
|
let empty = Content::default();
|
||||||
|
assert_eq!(serde_json::to_value(&empty).unwrap(), json!({}));
|
||||||
|
|
||||||
|
let roundtrip: Content = serde_json::from_str(r#"{"parts": [{"text": "Hello"}]}"#).unwrap();
|
||||||
|
assert!(roundtrip.role.is_none());
|
||||||
|
assert_eq!(roundtrip.get_text(), Some("Hello".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn function_call_id_handling() {
|
||||||
|
let without_id = Part::function_call("lookup", json!({"q": "test"}));
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&without_id).unwrap(),
|
||||||
|
json!({"functionCall": {"name": "lookup", "args": {"q": "test"}}})
|
||||||
|
);
|
||||||
|
|
||||||
|
let with_id = Part::function_call("lookup", json!({"q": "test"})).with_id("call-1");
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&with_id).unwrap(),
|
||||||
|
json!({"functionCall": {"id": "call-1", "name": "lookup", "args": {"q": "test"}}})
|
||||||
|
);
|
||||||
|
|
||||||
|
let with_id_ctor = Part::function_call_with_id("call-2", "lookup", json!({"q": "test"}));
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&with_id_ctor).unwrap(),
|
||||||
|
json!({"functionCall": {"id": "call-2", "name": "lookup", "args": {"q": "test"}}})
|
||||||
|
);
|
||||||
|
|
||||||
|
let parsed: Part = serde_json::from_value(json!({
|
||||||
|
"functionCall": {"id": "call-3", "name": "lookup", "args": {}}
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
parsed.function_call.as_ref().unwrap().id.as_deref(),
|
||||||
|
Some("call-3")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn function_call_omits_unset_name_and_args_and_parses_missing_fields() {
|
||||||
|
// Deserializing without args (e.g. zero-argument function call)
|
||||||
|
let without_args: Part =
|
||||||
|
serde_json::from_value(json!({"functionCall": {"name": "f"}})).unwrap();
|
||||||
|
let fc = without_args.function_call.unwrap();
|
||||||
|
assert_eq!(fc.name, "f");
|
||||||
|
assert!(fc.args.is_null());
|
||||||
|
assert!(fc.partial_args.is_none());
|
||||||
|
assert!(fc.will_continue.is_none());
|
||||||
|
|
||||||
|
// Serializing when args is null omits args
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&Part {
|
||||||
|
function_call: Some(fc),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.unwrap(),
|
||||||
|
json!({"functionCall": {"name": "f"}})
|
||||||
|
);
|
||||||
|
|
||||||
|
// Deserializing partial chunk without name and args
|
||||||
|
let partial_chunk: Part = serde_json::from_value(json!({
|
||||||
|
"functionCall": {
|
||||||
|
"partialArgs": [{"key": "val"}],
|
||||||
|
"willContinue": true
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let fc_partial = partial_chunk.function_call.unwrap();
|
||||||
|
assert_eq!(fc_partial.name, "");
|
||||||
|
assert!(fc_partial.args.is_null());
|
||||||
|
assert_eq!(fc_partial.partial_args, Some(vec![json!({"key": "val"})]));
|
||||||
|
assert_eq!(fc_partial.will_continue, Some(true));
|
||||||
|
|
||||||
|
// Serializing partial chunk omits empty name and null args
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&Part {
|
||||||
|
function_call: Some(fc_partial),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.unwrap(),
|
||||||
|
json!({
|
||||||
|
"functionCall": {
|
||||||
|
"partialArgs": [{"key": "val"}],
|
||||||
|
"willContinue": true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn function_response_id_handling() {
|
||||||
|
let without_id = Part::function_response("lookup", json!({"output": "ok"}));
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&without_id).unwrap(),
|
||||||
|
json!({"functionResponse": {"name": "lookup", "response": {"output": "ok"}}})
|
||||||
|
);
|
||||||
|
|
||||||
|
let with_id = Part::function_response("lookup", json!({"output": "ok"})).with_id("call-1");
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&with_id).unwrap(),
|
||||||
|
json!({"functionResponse": {"id": "call-1", "name": "lookup", "response": {"output": "ok"}}})
|
||||||
|
);
|
||||||
|
|
||||||
|
let with_id_ctor =
|
||||||
|
Part::function_response_with_id("call-2", "lookup", json!({"output": "ok"}));
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&with_id_ctor).unwrap(),
|
||||||
|
json!({"functionResponse": {"id": "call-2", "name": "lookup", "response": {"output": "ok"}}})
|
||||||
|
);
|
||||||
|
|
||||||
|
let parsed: Part = serde_json::from_value(json!({
|
||||||
|
"functionResponse": {"id": "call-3", "name": "lookup", "response": {}}
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
parsed.function_response.as_ref().unwrap().id.as_deref(),
|
||||||
|
Some("call-3")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn part_builder_helpers() {
|
||||||
|
let part_sig = Part::function_call("fetch", json!({})).with_thought_signature("sig-abc");
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&part_sig).unwrap(),
|
||||||
|
json!({
|
||||||
|
"functionCall": {"name": "fetch", "args": {}},
|
||||||
|
"thoughtSignature": "sig-abc"
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
let part_media = Part::function_response("capture", json!({}))
|
||||||
|
.add_function_response_inline_data("image/jpeg", "base64data");
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&part_media).unwrap(),
|
||||||
|
json!({
|
||||||
|
"functionResponse": {
|
||||||
|
"name": "capture",
|
||||||
|
"response": {},
|
||||||
|
"parts": [{"inlineData": {"mimeType": "image/jpeg", "data": "base64data"}}]
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn function_response_omits_empty_parts() {
|
||||||
|
let part = Part::function_response("lookup", json!({"output": "ok"}));
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&part).unwrap(),
|
||||||
|
json!({"functionResponse": {"name": "lookup", "response": {"output": "ok"}}})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn function_response_serializes_inline_data_parts() {
|
||||||
|
let mut part = Part::function_response("screenshot", json!({}));
|
||||||
|
part.function_response.as_mut().unwrap().parts = vec![FunctionResponsePart {
|
||||||
|
inline_data: InlineData {
|
||||||
|
mime_type: "image/png".to_string(),
|
||||||
|
data: "aGVsbG8=".to_string(),
|
||||||
|
},
|
||||||
|
}];
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_value(&part).unwrap(),
|
||||||
|
json!({"functionResponse": {
|
||||||
|
"name": "screenshot",
|
||||||
|
"response": {},
|
||||||
|
"parts": [{"inlineData": {"mimeType": "image/png", "data": "aGVsbG8="}}]
|
||||||
|
}})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn function_response_without_parts_deserializes() {
|
||||||
|
let part: Part =
|
||||||
|
serde_json::from_value(json!({"functionResponse": {"name": "lookup", "response": {}}}))
|
||||||
|
.unwrap();
|
||||||
|
assert!(part.function_response.unwrap().parts.is_empty());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,25 +9,20 @@ pub struct CountTokensRequest {
|
|||||||
|
|
||||||
impl CountTokensRequest {
|
impl CountTokensRequest {
|
||||||
pub fn builder() -> CountTokensRequestBuilder {
|
pub fn builder() -> CountTokensRequestBuilder {
|
||||||
CountTokensRequestBuilder::new()
|
CountTokensRequestBuilder::default()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
pub struct CountTokensRequestBuilder {
|
pub struct CountTokensRequestBuilder {
|
||||||
contents: Content,
|
contents: Content,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CountTokensRequestBuilder {
|
impl CountTokensRequestBuilder {
|
||||||
pub fn new() -> Self {
|
|
||||||
CountTokensRequestBuilder {
|
|
||||||
contents: Content::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn from_prompt(prompt: &str) -> Self {
|
pub fn from_prompt(prompt: &str) -> Self {
|
||||||
CountTokensRequestBuilder {
|
CountTokensRequestBuilder {
|
||||||
contents: Content {
|
contents: Content {
|
||||||
parts: Some(vec![super::Part::Text(prompt.to_string())]),
|
parts: Some(vec![super::Part::text(prompt)]),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
@@ -37,8 +35,8 @@ impl GenerateContentRequestBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_content(mut self, content: Content) -> Self {
|
pub fn contents(mut self, contents: Vec<Content>) -> Self {
|
||||||
self.request.contents.push(content);
|
self.request.contents = contents;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,15 +69,39 @@ impl GenerateContentRequestBuilder {
|
|||||||
pub struct Tools {
|
pub struct Tools {
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub function_declarations: Option<Vec<FunctionDeclaration>>,
|
pub function_declarations: Option<Vec<FunctionDeclaration>>,
|
||||||
|
|
||||||
#[serde(rename = "googleSearchRetrieval")]
|
#[serde(rename = "googleSearchRetrieval")]
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub google_search_retrieval: Option<GoogleSearchRetrieval>,
|
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)]
|
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct GoogleSearchRetrieval {
|
pub struct GoogleSearchRetrieval {
|
||||||
pub disable_attribution: bool,
|
pub dynamic_retrieval_config: DynamicRetrievalConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
|
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
|
||||||
@@ -101,6 +123,37 @@ pub struct GenerationConfig {
|
|||||||
pub response_mime_type: Option<String>,
|
pub response_mime_type: Option<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub response_schema: Option<Value>,
|
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 {
|
impl GenerationConfig {
|
||||||
@@ -160,6 +213,11 @@ impl GenerationConfigBuilder {
|
|||||||
self
|
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 {
|
pub fn build(self) -> GenerationConfig {
|
||||||
self.generation_config
|
self.generation_config
|
||||||
}
|
}
|
||||||
@@ -257,11 +315,20 @@ pub struct SafetyRating {
|
|||||||
pub severity_score: Option<f32>,
|
pub severity_score: Option<f32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct UsageMetadata {
|
pub struct UsageMetadata {
|
||||||
pub candidates_token_count: Option<u32>,
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub prompt_token_count: Option<u32>,
|
pub prompt_token_count: Option<u32>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub cached_content_token_count: Option<u32>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub candidates_token_count: Option<u32>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub tool_use_prompt_token_count: Option<u32>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub thoughts_token_count: Option<u32>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub total_token_count: Option<u32>,
|
pub total_token_count: Option<u32>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -270,22 +337,14 @@ pub struct UsageMetadata {
|
|||||||
pub struct FunctionDeclaration {
|
pub struct FunctionDeclaration {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub description: String,
|
pub description: String,
|
||||||
pub parameters: FunctionParameters,
|
/// 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")]
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
pub parameters: Option<Value>,
|
||||||
#[serde(rename_all = "camelCase")]
|
/// Parameters as a JSON Schema, which accepts keywords the OpenAPI subset doesn't
|
||||||
pub struct FunctionParameters {
|
/// (`$schema`, `$ref`/`$defs`, `const`, type arrays, ...).
|
||||||
pub r#type: String,
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub properties: HashMap<String, FunctionParametersProperty>,
|
pub parameters_json_schema: Option<Value>,
|
||||||
pub required: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct FunctionParametersProperty {
|
|
||||||
pub r#type: String,
|
|
||||||
pub description: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
@@ -327,7 +386,36 @@ impl GenerateContentResponse {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
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]
|
#[test]
|
||||||
pub fn parses_empty_metadata_response() {
|
pub fn parses_empty_metadata_response() {
|
||||||
@@ -335,6 +423,47 @@ mod tests {
|
|||||||
serde_json::from_str::<GenerateContentResponseResult>(input).unwrap();
|
serde_json::from_str::<GenerateContentResponseResult>(input).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_usage_metadata_with_all_token_counts() {
|
||||||
|
let input = r#"{
|
||||||
|
"promptTokenCount": 100,
|
||||||
|
"cachedContentTokenCount": 50,
|
||||||
|
"candidatesTokenCount": 200,
|
||||||
|
"toolUsePromptTokenCount": 25,
|
||||||
|
"thoughtsTokenCount": 75,
|
||||||
|
"totalTokenCount": 375
|
||||||
|
}"#;
|
||||||
|
let metadata: UsageMetadata = serde_json::from_str(input).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
metadata,
|
||||||
|
UsageMetadata {
|
||||||
|
prompt_token_count: Some(100),
|
||||||
|
cached_content_token_count: Some(50),
|
||||||
|
candidates_token_count: Some(200),
|
||||||
|
tool_use_prompt_token_count: Some(25),
|
||||||
|
thoughts_token_count: Some(75),
|
||||||
|
total_token_count: Some(375),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serializes_usage_metadata_skipping_none_fields() {
|
||||||
|
let metadata = UsageMetadata {
|
||||||
|
prompt_token_count: Some(10),
|
||||||
|
total_token_count: Some(10),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let val = serde_json::to_value(&metadata).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
val,
|
||||||
|
json!({
|
||||||
|
"promptTokenCount": 10,
|
||||||
|
"totalTokenCount": 10
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
pub fn parses_max_tokens_response() {
|
pub fn parses_max_tokens_response() {
|
||||||
let input = r#"{
|
let input = r#"{
|
||||||
@@ -461,6 +590,47 @@ mod tests {
|
|||||||
serde_json::from_str::<GenerateContentResponse>(input).unwrap();
|
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]
|
#[test]
|
||||||
fn parses_safety_rating_without_scores() {
|
fn parses_safety_rating_without_scores() {
|
||||||
let input = r#"{
|
let input = r#"{
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ pub struct PredictImageRequest {
|
|||||||
pub struct PredictImageRequestPrompt {
|
pub struct PredictImageRequestPrompt {
|
||||||
/// The text prompt for the image.
|
/// The text prompt for the image.
|
||||||
/// The following models support different values for this parameter:
|
/// 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-generate-001`: up to 480 tokens.
|
||||||
/// - `imagen-3.0-fast-generate-001`: up to 480 tokens.
|
/// - `imagen-3.0-fast-generate-001`: up to 480 tokens.
|
||||||
/// - `imagegeneration@006`: up to 128 tokens.
|
/// - `imagegeneration@006`: up to 128 tokens.
|
||||||
@@ -24,21 +28,20 @@ pub struct PredictImageRequestPrompt {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct PredictImageRequestParameters {
|
pub struct PredictImageRequestParameters {
|
||||||
/// The number of images to generate. The default value is 4.
|
/// The number of images to generate. The default value is 4.
|
||||||
/// The following models support different values for this parameter:
|
/// Supported range: 1 to 4 for all current models.
|
||||||
/// - `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.
|
|
||||||
pub sample_count: i32,
|
pub sample_count: i32,
|
||||||
|
|
||||||
/// The random seed for image generation. This is not available when addWatermark is set to
|
/// The random seed for image generation. This is not available when `add_watermark` is set to
|
||||||
/// true.
|
/// `true`.
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub seed: Option<u32>,
|
pub seed: Option<u32>,
|
||||||
|
|
||||||
/// A description of what to discourage in the generated images.
|
/// A description of what to discourage in the generated images.
|
||||||
/// The following models support this parameter:
|
/// 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-generate-001`: up to 480 tokens.
|
||||||
/// - `imagen-3.0-fast-generate-001`: up to 480 tokens.
|
/// - `imagen-3.0-fast-generate-001`: up to 480 tokens.
|
||||||
/// - `imagegeneration@006`: up to 128 tokens.
|
/// - `imagegeneration@006`: up to 128 tokens.
|
||||||
@@ -47,13 +50,8 @@ pub struct PredictImageRequestParameters {
|
|||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub negative_prompt: Option<String>,
|
pub negative_prompt: Option<String>,
|
||||||
|
|
||||||
/// The aspect ratio for the image. The default value is "1:1".
|
/// The aspect ratio for the image. The default value is `"1:1"`.
|
||||||
/// The following models support different values for this parameter:
|
/// Supported values: `"1:1"`, `"9:16"`, `"16:9"`, `"3:4"`, `"4:3"`.
|
||||||
/// - `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".
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub aspect_ratio: Option<String>,
|
pub aspect_ratio: Option<String>,
|
||||||
|
|
||||||
@@ -70,7 +68,8 @@ pub struct PredictImageRequestParameters {
|
|||||||
/// - "watercolor"
|
/// - "watercolor"
|
||||||
/// - "cyberpunk"
|
/// - "cyberpunk"
|
||||||
/// - "pop_art"
|
/// - "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")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub sample_image_style: Option<String>,
|
pub sample_image_style: Option<String>,
|
||||||
|
|
||||||
@@ -80,36 +79,41 @@ pub struct PredictImageRequestParameters {
|
|||||||
/// - `"allow_all"`: Allow generation of people of all ages.
|
/// - `"allow_all"`: Allow generation of people of all ages.
|
||||||
///
|
///
|
||||||
/// The default value is `"allow_adult"`.
|
/// 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")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub person_generation: Option<String>,
|
pub person_generation: Option<String>,
|
||||||
|
|
||||||
/// Adds a filter level to safety filtering. The following values are supported:
|
/// Adds a filter level to safety filtering. The following values are supported:
|
||||||
/// - `"block_most"`: Strongest filtering level, most strict blocking.
|
/// - `"block_low_and_above"`: Strongest filtering, most strict blocking.
|
||||||
/// - `"block_some"`: Block some problematic prompts and responses.
|
/// - `"block_medium_and_above"`: Block medium and high severity content. Default.
|
||||||
/// - `"block_few"`: Reduces the number of requests blocked due to safety filters. May
|
/// - `"block_only_high"`: Only block high severity content.
|
||||||
/// increase objectionable content generated by Imagen.
|
/// - `"block_none"`: No blocking.
|
||||||
/// - `"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.
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub safety_setting: Option<String>,
|
pub safety_setting: Option<String>,
|
||||||
|
|
||||||
/// Add an invisible watermark to the generated images. The default value is `false` for the
|
/// Add an invisible SynthID watermark to the generated images. Defaults to `true` for
|
||||||
/// `imagegeneration@002` and `imagegeneration@005` models, and `true` for the
|
/// Imagen 3 and 4 models. Not available when `seed` is set.
|
||||||
/// `imagen-3.0-fast-generate-001`, `imagegeneration@006`, and imagegeneration@006 models.
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub add_watermark: Option<bool>,
|
pub add_watermark: Option<bool>,
|
||||||
|
|
||||||
/// Cloud Storage URI to store the generated images.
|
/// Cloud Storage URI to store the generated images.
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub storage_uri: Option<String>,
|
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)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
@@ -117,10 +121,9 @@ pub struct PredictImageRequestParameters {
|
|||||||
pub struct PredictImageRequestParametersOutputOptions {
|
pub struct PredictImageRequestParametersOutputOptions {
|
||||||
/// The image format that the output should be saved as. The following values are supported:
|
/// The image format that the output should be saved as. The following values are supported:
|
||||||
///
|
///
|
||||||
/// - "image/png": Save as a PNG image
|
/// - `"image/png"`: Save as a PNG image (default)
|
||||||
/// - "image/jpeg": Save as a JPEG image
|
/// - `"image/jpeg"`: Save as a JPEG image
|
||||||
///
|
/// - `"image/webp"`: Save as a WebP image
|
||||||
/// The default value is "image/png".v
|
|
||||||
pub mime_type: Option<String>,
|
pub mime_type: Option<String>,
|
||||||
|
|
||||||
/// The level of compression if the output type is "image/jpeg".
|
/// The level of compression if the output type is "image/jpeg".
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ pub struct TextEmbeddingPrediction {
|
|||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
pub struct TextEmbeddingResult {
|
pub struct TextEmbeddingResult {
|
||||||
pub statistics: TextEmbeddingStatistics,
|
pub statistics: TextEmbeddingStatistics,
|
||||||
pub values: Vec<f32>,
|
pub values: Vec<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
|
|||||||
Reference in New Issue
Block a user