Files
gemini-rs/src/types/common.rs
2026-10-26 19:57:09 +00:00

516 lines
16 KiB
Rust

use std::{fmt::Display, str::FromStr, vec};
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct Content {
#[serde(skip_serializing_if = "Option::is_none")]
pub role: Option<Role>,
#[serde(skip_serializing_if = "Option::is_none")]
pub parts: Option<Vec<Part>>,
}
impl Content {
pub fn get_text(&self) -> Option<String> {
self.parts.as_ref().map(|parts| {
parts
.iter()
.filter_map(|part| part.text.clone())
.collect::<String>()
})
}
pub fn builder() -> ContentBuilder {
ContentBuilder::default()
}
pub fn system_prompt(prompt: impl Into<String>) -> Self {
Content {
parts: Some(vec![Part::text(prompt)]),
role: None,
}
}
}
pub struct SystemPrompt {
content: Content,
}
impl<T: AsRef<str>> From<T> for SystemPrompt {
fn from(value: T) -> Self {
SystemPrompt {
content: Content {
parts: Some(vec![Part::text(value.as_ref())]),
role: None,
},
}
}
}
impl From<SystemPrompt> for Content {
fn from(value: SystemPrompt) -> Self {
value.content
}
}
#[derive(Default)]
pub struct ContentBuilder {
content: Content,
}
impl ContentBuilder {
pub fn add_text_part<T: Into<String>>(self, text: T) -> Self {
self.add_part(Part::text(text))
}
pub fn add_part(mut self, part: Part) -> Self {
match &mut self.content.parts {
Some(parts) => parts.push(part),
None => self.content.parts = Some(vec![part]),
}
self
}
pub fn role(mut self, role: Role) -> Self {
self.content.role = Some(role);
self
}
pub fn build(self) -> Content {
self.content
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
User,
Model,
}
impl Display for Role {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let role_str = match self {
Role::User => "user",
Role::Model => "model",
};
f.write_str(role_str)
}
}
impl FromStr for Role {
type Err = ();
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s {
"user" => Ok(Role::User),
"model" => Ok(Role::Model),
_ => Err(()),
}
}
}
#[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)]
#[serde(rename_all = "camelCase")]
pub struct FunctionResponsePart {
pub inline_data: InlineData,
}
impl FunctionResponsePart {
pub fn inline_data(mime_type: impl Into<String>, data: impl Into<String>) -> Self {
Self {
inline_data: InlineData {
mime_type: mime_type.into(),
data: data.into(),
},
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InlineData {
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());
}
}