8 Commits

Author SHA1 Message Date
4791125943 Merge pull request 'ci: run fmt, clippy and tests on the Gitea runner' (#18) from ci/gitea-actions into main
All checks were successful
Rust / check (push) Successful in 2m39s
Reviewed-on: #18
2026-10-26 20:42:05 +00:00
6d49f9939c ci: install Rust on the Gitea runner and check fmt and clippy
All checks were successful
Rust / check (pull_request) Successful in 5m14s
The Gitea runner image doesn't include Rust, so every job failed at
'cargo: command not found'. Install the stable toolchain, cache the
build, and run cargo fmt --check and clippy alongside the tests.
2026-10-26 20:34:40 +00:00
c911fc382e style: run cargo fmt on examples 2026-10-26 20:34:40 +00:00
a8961b12e3 Merge pull request 'feat: allow missing name/args in FunctionCallData and add streamed argument fields (#12)' (#17) from feat/function-call-optional-fields into main
Some checks failed
Rust / build (push) Failing after 3s
Reviewed-on: #17
2026-10-26 19:59:46 +00:00
2f15b5298d feat: allow missing name/args in FunctionCallData and add streamed argument fields (#12)
Some checks failed
Rust / build (pull_request) Failing after 4s
2026-10-26 19:57:09 +00:00
01a4300bb3 Merge pull request 'feat: omit None fields on Content, add optional id to function call/response, and add Part helpers (#11)' (#16) from feat/content-none-and-part-helpers into main
Some checks failed
Rust / build (push) Has been cancelled
Reviewed-on: #16
2026-10-26 19:45:55 +00:00
a2cff20aff feat: omit None fields on Content, add optional id to function call/response, and add Part helpers (#11)
Some checks failed
Rust / build (pull_request) Failing after 4s
2026-10-26 19:39:36 +00:00
7d5c6e3e28 Merge pull request 'feat: check response status in all GeminiClient methods and add Error::is_retryable() (#10)' (#15) from feat/error-status-and-retryable into main
Some checks failed
Rust / build (push) Has been cancelled
Reviewed-on: #15
2026-10-26 19:26:46 +00:00
6 changed files with 363 additions and 74 deletions

View File

@@ -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

View File

@@ -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;

View File

@@ -19,10 +19,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.add_text_part("Answer as if you were Yoda") .add_text_part("Answer as if you were Yoda")
.build(); .build();
let user_prompt = vec![Content::builder() let user_prompt = vec![
.role(Role::User) Content::builder()
.add_text_part("What is the airspeed of an unladen swallow?") .role(Role::User)
.build()]; .add_text_part("What is the airspeed of an unladen swallow?")
.build(),
];
let request = GenerateContentRequest::builder() let request = GenerateContentRequest::builder()
.contents(user_prompt) .contents(user_prompt)

View File

@@ -1,34 +1,36 @@
use gemini_rs::prelude::*; use gemini_rs::prelude::*;
use tokio_stream::StreamExt; 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>> {
let authentication_manager = gcp_auth::provider().await?; let authentication_manager = gcp_auth::provider().await?;
let api_endpoint = std::env::var("API_ENDPOINT")?; let api_endpoint = std::env::var("API_ENDPOINT")?;
let project_id = std::env::var("PROJECT_ID")?; let project_id = std::env::var("PROJECT_ID")?;
let location_id = std::env::var("LOCATION_ID")?; let location_id = std::env::var("LOCATION_ID")?;
let gemini = GeminiClient::new( let gemini = GeminiClient::new(
authentication_manager, authentication_manager,
api_endpoint, api_endpoint,
project_id, project_id,
location_id, location_id,
); );
let prompt = vec![Content::builder() let prompt = vec![
.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_text_part("Tell me the story of the genesis of the universe as a bedtime story.")
.build(),
let request = GenerateContentRequest::builder().contents(prompt).build(); ];
let mut queue = gemini let request = GenerateContentRequest::builder().contents(prompt).build();
.stream_generate_content(&request, "gemini-2.0-flash-001")
.await?; let mut queue = gemini
.stream_generate_content(&request, "gemini-2.0-flash-001")
while let Some(response) = queue.next().await { .await?;
println!("Response: {:?}", response?);
} while let Some(response) = queue.next().await {
println!("Response: {:?}", response?);
Ok(()) }
}
Ok(())
}

View File

@@ -1,27 +1,29 @@
use gemini_rs::prelude::*; use gemini_rs::prelude::*;
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> { async fn main() -> Result<(), Box<dyn std::error::Error>> {
let authentication_manager = gcp_auth::provider().await?; let authentication_manager = gcp_auth::provider().await?;
let api_endpoint = std::env::var("API_ENDPOINT")?; let api_endpoint = std::env::var("API_ENDPOINT")?;
let project_id = std::env::var("PROJECT_ID")?; let project_id = std::env::var("PROJECT_ID")?;
let location_id = std::env::var("LOCATION_ID")?; let location_id = std::env::var("LOCATION_ID")?;
let gemini = GeminiClient::new( let gemini = GeminiClient::new(
authentication_manager, authentication_manager,
api_endpoint, api_endpoint,
project_id, project_id,
location_id, location_id,
); );
let prompt = vec![Content::builder() let prompt = vec![
.role(Role::User) Content::builder()
.add_text_part("What is the airspeed of an unladen swallow?") .role(Role::User)
.build()]; .add_text_part("What is the airspeed of an unladen swallow?")
.build(),
let request = GenerateContentRequest::builder().contents(prompt).build(); ];
let response = gemini.generate_content(&request, "gemini-pro").await?;
println!("Response: {:?}", response.candidates[0].get_text().unwrap()); let request = GenerateContentRequest::builder().contents(prompt).build();
let response = gemini.generate_content(&request, "gemini-pro").await?;
Ok(()) println!("Response: {:?}", response.candidates[0].get_text().unwrap());
}
Ok(())
}

View File

@@ -5,7 +5,9 @@ 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>>,
} }
@@ -22,6 +24,13 @@ impl Content {
pub fn builder() -> ContentBuilder { pub fn builder() -> ContentBuilder {
ContentBuilder::default() ContentBuilder::default()
} }
pub fn system_prompt(prompt: impl Into<String>) -> Self {
Content {
parts: Some(vec![Part::text(prompt)]),
role: None,
}
}
} }
pub struct SystemPrompt { pub struct SystemPrompt {
@@ -139,8 +148,28 @@ impl Part {
pub fn function_call(name: impl Into<String>, args: Value) -> Self { pub fn function_call(name: impl Into<String>, args: Value) -> Self {
Part { Part {
function_call: Some(FunctionCallData { function_call: Some(FunctionCallData {
id: None,
name: name.into(), name: name.into(),
args, 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() ..Default::default()
} }
@@ -149,6 +178,7 @@ impl Part {
pub fn function_response(name: impl Into<String>, response: Value) -> Self { pub fn function_response(name: impl Into<String>, response: Value) -> Self {
Part { Part {
function_response: Some(FunctionResponseData { function_response: Some(FunctionResponseData {
id: None,
name: name.into(), name: name.into(),
response, response,
parts: vec![], parts: vec![],
@@ -156,16 +186,88 @@ impl Part {
..Default::default() ..Default::default()
} }
} }
pub fn function_response_with_id(
id: impl Into<String>,
name: impl Into<String>,
response: Value,
) -> Self {
Part {
function_response: Some(FunctionResponseData {
id: Some(id.into()),
name: name.into(),
response,
parts: vec![],
}),
..Default::default()
}
}
pub fn with_thought_signature(mut self, signature: impl Into<String>) -> Self {
self.thought_signature = Some(signature.into());
self
}
pub fn with_id(mut self, id: impl Into<String>) -> Self {
let id = id.into();
if let Some(ref mut call) = self.function_call {
call.id = Some(id.clone());
}
if let Some(ref mut response) = self.function_response {
response.id = Some(id);
}
self
}
pub fn add_function_response_part(mut self, part: FunctionResponsePart) -> Self {
if let Some(ref mut response) = self.function_response {
response.parts.push(part);
}
self
}
pub fn add_function_response_inline_data(
self,
mime_type: impl Into<String>,
data: impl Into<String>,
) -> Self {
self.add_function_response_part(FunctionResponsePart::inline_data(mime_type, data))
}
pub fn with_will_continue(mut self, will_continue: bool) -> Self {
if let Some(ref mut call) = self.function_call {
call.will_continue = Some(will_continue);
}
self
}
pub fn with_partial_args(mut self, partial_args: Vec<Value>) -> Self {
if let Some(ref mut call) = self.function_call {
call.partial_args = Some(partial_args);
}
self
}
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FunctionCallData { 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, pub name: String,
#[serde(default, skip_serializing_if = "Value::is_null")]
pub args: Value, 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)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FunctionResponseData { pub struct FunctionResponseData {
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
pub name: String, pub name: String,
pub response: Value, pub response: Value,
/// Media returned by the function (multimodal function responses), sent as /// Media returned by the function (multimodal function responses), sent as
@@ -180,6 +282,17 @@ pub struct FunctionResponsePart {
pub inline_data: InlineData, pub inline_data: InlineData,
} }
impl FunctionResponsePart {
pub fn inline_data(mime_type: impl Into<String>, data: impl Into<String>) -> Self {
Self {
inline_data: InlineData {
mime_type: mime_type.into(),
data: data.into(),
},
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct InlineData { pub struct InlineData {
@@ -198,7 +311,171 @@ pub struct FileData {
mod tests { mod tests {
use serde_json::json; use serde_json::json;
use super::{FunctionResponsePart, InlineData, Part}; use super::{Content, FunctionResponsePart, InlineData, Part, Role};
#[test]
fn content_omits_unset_role_and_parts() {
let system = Content::system_prompt("You are a helpful assistant.");
assert_eq!(
serde_json::to_value(&system).unwrap(),
json!({
"parts": [{"text": "You are a helpful assistant."}]
})
);
let role_only = Content {
role: Some(Role::User),
parts: None,
};
assert_eq!(
serde_json::to_value(&role_only).unwrap(),
json!({"role": "user"})
);
let empty = Content::default();
assert_eq!(serde_json::to_value(&empty).unwrap(), json!({}));
let roundtrip: Content = serde_json::from_str(r#"{"parts": [{"text": "Hello"}]}"#).unwrap();
assert!(roundtrip.role.is_none());
assert_eq!(roundtrip.get_text(), Some("Hello".to_string()));
}
#[test]
fn function_call_id_handling() {
let without_id = Part::function_call("lookup", json!({"q": "test"}));
assert_eq!(
serde_json::to_value(&without_id).unwrap(),
json!({"functionCall": {"name": "lookup", "args": {"q": "test"}}})
);
let with_id = Part::function_call("lookup", json!({"q": "test"})).with_id("call-1");
assert_eq!(
serde_json::to_value(&with_id).unwrap(),
json!({"functionCall": {"id": "call-1", "name": "lookup", "args": {"q": "test"}}})
);
let with_id_ctor = Part::function_call_with_id("call-2", "lookup", json!({"q": "test"}));
assert_eq!(
serde_json::to_value(&with_id_ctor).unwrap(),
json!({"functionCall": {"id": "call-2", "name": "lookup", "args": {"q": "test"}}})
);
let parsed: Part = serde_json::from_value(json!({
"functionCall": {"id": "call-3", "name": "lookup", "args": {}}
}))
.unwrap();
assert_eq!(
parsed.function_call.as_ref().unwrap().id.as_deref(),
Some("call-3")
);
}
#[test]
fn function_call_omits_unset_name_and_args_and_parses_missing_fields() {
// Deserializing without args (e.g. zero-argument function call)
let without_args: Part =
serde_json::from_value(json!({"functionCall": {"name": "f"}})).unwrap();
let fc = without_args.function_call.unwrap();
assert_eq!(fc.name, "f");
assert!(fc.args.is_null());
assert!(fc.partial_args.is_none());
assert!(fc.will_continue.is_none());
// Serializing when args is null omits args
assert_eq!(
serde_json::to_value(&Part {
function_call: Some(fc),
..Default::default()
})
.unwrap(),
json!({"functionCall": {"name": "f"}})
);
// Deserializing partial chunk without name and args
let partial_chunk: Part = serde_json::from_value(json!({
"functionCall": {
"partialArgs": [{"key": "val"}],
"willContinue": true
}
}))
.unwrap();
let fc_partial = partial_chunk.function_call.unwrap();
assert_eq!(fc_partial.name, "");
assert!(fc_partial.args.is_null());
assert_eq!(fc_partial.partial_args, Some(vec![json!({"key": "val"})]));
assert_eq!(fc_partial.will_continue, Some(true));
// Serializing partial chunk omits empty name and null args
assert_eq!(
serde_json::to_value(&Part {
function_call: Some(fc_partial),
..Default::default()
})
.unwrap(),
json!({
"functionCall": {
"partialArgs": [{"key": "val"}],
"willContinue": true
}
})
);
}
#[test]
fn function_response_id_handling() {
let without_id = Part::function_response("lookup", json!({"output": "ok"}));
assert_eq!(
serde_json::to_value(&without_id).unwrap(),
json!({"functionResponse": {"name": "lookup", "response": {"output": "ok"}}})
);
let with_id = Part::function_response("lookup", json!({"output": "ok"})).with_id("call-1");
assert_eq!(
serde_json::to_value(&with_id).unwrap(),
json!({"functionResponse": {"id": "call-1", "name": "lookup", "response": {"output": "ok"}}})
);
let with_id_ctor =
Part::function_response_with_id("call-2", "lookup", json!({"output": "ok"}));
assert_eq!(
serde_json::to_value(&with_id_ctor).unwrap(),
json!({"functionResponse": {"id": "call-2", "name": "lookup", "response": {"output": "ok"}}})
);
let parsed: Part = serde_json::from_value(json!({
"functionResponse": {"id": "call-3", "name": "lookup", "response": {}}
}))
.unwrap();
assert_eq!(
parsed.function_response.as_ref().unwrap().id.as_deref(),
Some("call-3")
);
}
#[test]
fn part_builder_helpers() {
let part_sig = Part::function_call("fetch", json!({})).with_thought_signature("sig-abc");
assert_eq!(
serde_json::to_value(&part_sig).unwrap(),
json!({
"functionCall": {"name": "fetch", "args": {}},
"thoughtSignature": "sig-abc"
})
);
let part_media = Part::function_response("capture", json!({}))
.add_function_response_inline_data("image/jpeg", "base64data");
assert_eq!(
serde_json::to_value(&part_media).unwrap(),
json!({
"functionResponse": {
"name": "capture",
"response": {},
"parts": [{"inlineData": {"mimeType": "image/jpeg", "data": "base64data"}}]
}
})
);
}
#[test] #[test]
fn function_response_omits_empty_parts() { fn function_response_omits_empty_parts() {