gemini_genai/lib.rs
1//! **Unofficial.** An independent Rust port of the
2//! [Google Gen AI Python SDK](https://github.com/googleapis/python-genai)
3//! (`google-genai` 2.28.0) for the **Gemini Developer API**. Not affiliated
4//! with, endorsed by, or sponsored by Google. Portions of this crate are
5//! derived from `google-genai`, Copyright 2025 Google LLC, licensed under the
6//! Apache License, Version 2.0; see the `NOTICE` file at the repository root
7//! for what is derived and what was changed.
8//!
9//! The package is named `gemini-genai` but its library name is
10//! `gemini_genai`: depend on the former (`cargo add gemini-genai`) and
11//! `use gemini_genai::...`.
12//!
13//! Vertex AI is out of scope: asking for it (via
14//! [`ClientBuilder::vertexai`], `project`/`location`, or the
15//! `GOOGLE_GENAI_USE_VERTEXAI` environment variable) fails fast with
16//! [`Error::UnsupportedBackend`].
17//!
18//! # Quickstart
19//!
20//! ```no_run
21//! # async fn run() -> gemini_genai::Result<()> {
22//! use gemini_genai::Client;
23//!
24//! let client = Client::new()?;
25//! let response = client
26//! .models()
27//! .generate_content("gemini-flash-latest", "Why is the sky blue?", None)
28//! .await?;
29//! println!("{}", response.text().unwrap_or_default());
30//! # Ok(())
31//! # }
32//! ```
33//!
34//! [`Client::new`] reads the API key from `GOOGLE_API_KEY`, falling back to
35//! `GEMINI_API_KEY`; [`Client::builder`] sets it (and
36//! [`HttpOptions`](types::HttpOptions)) explicitly. `GOOGLE_GEMINI_BASE_URL`
37//! overrides the API base URL when it is not set on the builder.
38//!
39//! # Streaming
40//!
41//! ```no_run
42//! # async fn run() -> gemini_genai::Result<()> {
43//! use futures_util::StreamExt;
44//! use gemini_genai::Client;
45//!
46//! let client = Client::new()?;
47//! let stream = client
48//! .models()
49//! .generate_content_stream("gemini-flash-latest", "Write a haiku.", None)
50//! .await?;
51//!
52//! let mut stream = Box::pin(stream);
53//! while let Some(chunk) = stream.next().await {
54//! print!("{}", chunk?.text().unwrap_or_default());
55//! }
56//! # Ok(())
57//! # }
58//! ```
59//!
60//! # Structured output
61//!
62//! [`GenerateContentConfig::with_json_schema_of`](types::GenerateContentConfig::with_json_schema_of)
63//! derives the response schema from a plain Rust type via
64//! [`schemars`], so the reply parses straight back into it.
65//!
66//! ```no_run
67//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
68//! use gemini_genai::Client;
69//! use gemini_genai::types::GenerateContentConfig;
70//!
71//! #[derive(serde::Deserialize, schemars::JsonSchema)]
72//! struct Capital {
73//! country: String,
74//! capital: String,
75//! }
76//!
77//! let client = Client::new()?;
78//! let config = GenerateContentConfig::default().with_json_schema_of::<Capital>();
79//! let response = client
80//! .models()
81//! .generate_content("gemini-flash-latest", "What is the capital of Japan?", Some(config))
82//! .await?;
83//!
84//! let capital: Capital = serde_json::from_str(&response.text().unwrap_or_default())?;
85//! println!("{} -> {}", capital.country, capital.capital);
86//! # Ok(())
87//! # }
88//! ```
89//!
90//! # Automatic function calling
91//!
92//! [`function_tool`] wraps an async Rust function as a model-callable
93//! tool; [`Tool::from_function`](types::Tool::from_function) declares it in
94//! [`GenerateContentConfig`](types::GenerateContentConfig), and
95//! `generate_content` then drives the call/response loop itself. See
96//! [`automatic_function_calling_util`] for the loop's limits and for the process-wide registry caveat
97//! (callables are keyed by function name).
98//!
99//! ```no_run
100//! # async fn run() -> gemini_genai::Result<()> {
101//! use gemini_genai::function_tool;
102//! use gemini_genai::types::{GenerateContentConfig, Tool};
103//! use gemini_genai::Client;
104//!
105//! #[derive(serde::Deserialize, schemars::JsonSchema)]
106//! struct WeatherArgs {
107//! /// The city to look up.
108//! city: String,
109//! }
110//!
111//! let tool = Tool::from_function(function_tool(
112//! "get_weather",
113//! "Returns the current weather for a city.",
114//! |args: WeatherArgs| async move {
115//! Ok(serde_json::json!({ "city": args.city, "temperature_c": 21 }))
116//! },
117//! ));
118//!
119//! let client = Client::new()?;
120//! let response = client
121//! .models()
122//! .generate_content(
123//! "gemini-flash-latest",
124//! "What is the weather in Kyoto?",
125//! Some(GenerateContentConfig { tools: Some(vec![tool]), ..Default::default() }),
126//! )
127//! .await?;
128//! println!("{}", response.text().unwrap_or_default());
129//! # Ok(())
130//! # }
131//! ```
132//!
133//! # Modules
134//!
135//! Every API surface hangs off [`Client`], one accessor per Python SDK
136//! module: [`models`], [`chats`], [`files`], [`caches`], [`tunings`],
137//! [`batches`], [`operations`], [`file_search_stores`] (plus
138//! [`documents`]), [`tokens`], and [`live`]. Request/response types
139//! live in [`types`], errors in [`errors`], and list endpoints return a
140//! [`Pager<T>`](Pager) with `page()`, `next_page().await`, and
141//! `into_stream()`.
142//!
143//! # Cargo features
144//!
145//! | Feature | Default | Enables |
146//! |---|---|---|
147//! | `rustls-tls` | yes | TLS via `rustls` + `webpki-roots` (no system OpenSSL) |
148//! | `native-tls` | no | TLS via the platform's native stack instead |
149//! | `live` | yes | [`live`]: the bidirectional realtime (WebSocket) API |
150//! | `blocking` | no | `gemini_genai::blocking`: a synchronous mirror of this API |
151//! | `mcp` | no | `gemini_genai::mcp`: exposes MCP server tools to the model |
152//!
153//! # Errors
154//!
155//! Every fallible call returns [`Result<T>`](Result), whose error is the
156//! [`Error`] enum: [`Error::Api`] (boxed [`ApiError`] with `code`,
157//! `status`, `message`), [`Error::Http`], [`Error::Json`],
158//! [`Error::Io`], [`Error::Validation`], [`Error::UnsupportedByBackend`],
159//! [`Error::UnsupportedBackend`], [`Error::FunctionCall`],
160//! [`Error::WebSocket`] (with the `live` feature), [`Error::Stream`],
161//! [`Error::Upload`], [`Error::NoMorePages`], and
162//! [`Error::BlockingInsideRuntime`].
163//!
164//! ```
165//! use gemini_genai::{ApiError, Error};
166//!
167//! fn describe(error: &Error) -> String {
168//! match error {
169//! Error::Api(api) if api.code == 429 => "rate limited; back off".to_owned(),
170//! Error::Api(api) => format!("API error {}: {}", api.code, api.message),
171//! Error::Validation(message) => format!("bad request: {message}"),
172//! other => other.to_string(),
173//! }
174//! }
175//!
176//! let error = Error::Api(Box::new(ApiError {
177//! code: 429,
178//! status: Some("RESOURCE_EXHAUSTED".to_owned()),
179//! message: "quota exceeded".to_owned(),
180//! details: Vec::new(),
181//! response_headers: std::collections::HashMap::new(),
182//! }));
183//! assert_eq!(describe(&error), "rate limited; back off");
184//! ```
185//!
186//! # Further reading
187//!
188//! - `docs/parity.md` (generated): the full Python-to-Rust method and type
189//! mapping, including what is deliberately not ported.
190//! - `docs/migrating-from-python.md`: a migration guide for people coming
191//! from the Python SDK.
192
193pub mod agents;
194pub(crate) mod api_client;
195pub mod automatic_function_calling_util;
196pub(crate) mod base_transformers;
197pub mod base_url;
198pub mod batches;
199pub mod caches;
200pub mod chats;
201pub(crate) mod client;
202pub(crate) mod common;
203pub mod converters;
204pub mod credentials;
205pub mod documents;
206pub mod environments;
207pub mod errors;
208pub(crate) mod extra_utils;
209pub mod file_search_stores;
210pub mod files;
211pub(crate) mod gaos;
212pub mod interactions;
213#[cfg(feature = "live")]
214pub mod live;
215#[cfg(feature = "live")]
216pub mod live_music;
217#[cfg(feature = "mcp")]
218pub mod mcp_utils;
219pub mod models;
220pub mod operations;
221pub mod pagers;
222pub mod tokens;
223pub(crate) mod transformers;
224pub mod triggers;
225pub mod tunings;
226pub mod types;
227pub mod voices;
228pub mod webhooks;
229
230#[cfg(feature = "blocking")]
231pub mod blocking;
232
233/// The `google-genai` (Python SDK) release this crate's generated types and
234/// wire converters were produced from, and verified against.
235///
236/// `google-genai` ships frequently. This crate's type surface and
237/// request/response converters are a 1:1 mechanical port of one exact
238/// upstream release, so this constant is the answer to "which upstream
239/// behaviour does this build actually match?" -- useful when diagnosing a
240/// field the API now returns that this crate doesn't yet know about.
241///
242/// The same value is stamped into every generated file's header, pinned in
243/// `tools/codegen/requirements.txt`, and recorded under
244/// `[package.metadata.upstream]` in `Cargo.toml`;
245/// `tools/codegen/upstream.py` is the single source of truth that keeps
246/// them in sync and documents the upgrade procedure.
247pub const UPSTREAM_GENAI_VERSION: &str = "2.28.0";
248
249pub use automatic_function_calling_util::{FunctionTool, function_tool};
250pub use client::{Backend, Client, ClientBuilder};
251pub use errors::{ApiError, Error, Result};
252pub use pagers::Pager;
253
254/// Crate-internal items re-exported for the integration tests under
255/// `tests/`. Not part of the public API: it may change in any release.
256#[doc(hidden)]
257pub mod __test_support {
258 /// `crate::extra_utils` helpers, for the AFC tests under `tests/afc/`.
259 pub mod extra_utils {
260 pub use crate::extra_utils::{
261 append_chunk_contents, convert_number_values_for_dict_function_call_args,
262 convert_number_values_for_function_call_args, find_afc_incompatible_tool_indexes,
263 get_function_map, get_function_response_parts, get_max_remote_calls_afc,
264 get_usage_header, invoke_function_from_dict_args, log_afc_incompatible_tools_warning,
265 raise_error_for_afc_incompatible_config, should_append_afc_history, should_disable_afc,
266 };
267 }
268
269 /// `crate::api_client` helpers, for the `common/` upstream tests under
270 /// `tests/common_upstream/`.
271 pub mod api_client {
272 pub use crate::api_client::recursive_body_update;
273 }
274
275 /// `crate::transformers` (`_transformers.py`), for `tests/transformers/`.
276 pub mod transformers {
277 pub use crate::transformers::*;
278 }
279
280 /// `crate::base_transformers` (`_base_transformers.py`), for
281 /// `tests/transformers/`.
282 pub mod base_transformers {
283 pub use crate::base_transformers::*;
284 }
285}