Struct TypedModel

Source
pub struct TypedModel<'c, T> { /* private fields */ }
Expand description

Type-safe wrapper for GenerativeModel guaranteeing response type T.

This type enforces schema contracts through Rust’s type system while maintaining compatibility with Google’s Generative AI API. Use when:

  • You need structured output from the model
  • Response schema stability is critical
  • You want compile-time validation of response handling

§Example

use google_ai_rs::{Client, GenerativeModel, AsSchema};

#[derive(AsSchema)]
struct Recipe {
    name: String,
    ingredients: Vec<String>,
}

let client = Client::new(auth).await?;
let model = client.typed_model::<Recipe>("gemini-pro");

Implementations§

Source§

impl<'c, T> TypedModel<'c, T>
where T: AsSchema,

Source

pub fn new(client: &'c Client, name: &str) -> Self

Creates a new typed model with schema validation.

§Arguments
  • client: Authenticated API client
  • name: Model name (e.g., “gemini-pro”)
Source

pub async fn generate_typed_content<I>( &self, contents: I, ) -> Result<TypedResponse<T>, Error>

Generates content with full response metadata.

Returns both parsed content and raw API response.

§Example
let model = TypedModel::<StockAnalysis>::new(&client, "gemini-pro");
let analysis: TypedResponse<StockAnalysis> = model.generate_typed_content((
    "Analyze NVDA stock performance",
    "Consider PE ratio and recent earnings"
)).await?;
println!("Analysis: {:?}", analysis);
Source

pub async fn generate_content<I>(&self, contents: I) -> Result<T, Error>

Generates content and parses it directly into type T.

This is the primary method for most users wanting type-safe responses without dealing with raw API structures. For 90% of use cases where you just want structured data from the AI, this is what you need.

§Serde Integration

When the serde feature is enabled, any type implementing serde::Deserialize automatically works with this method. Just define your response structure and let the library handle parsing.

§Example: Simple JSON Response
#[derive(AsSchema, Deserialize)]
struct StoryResponse {
    title: String,
    length: usize,
    tags: Vec<String>,
}

let model = TypedModel::<StoryResponse>::new(&client, "gemini-pro");
let story = model.generate_content("Write a short story about a robot astronaut").await?;

println!("{} ({} words)", story.title, story.length);
§Example: Multi-part Input
#[derive(AsSchema, Deserialize)]
struct Analysis { safety_rating: u8 }

let model = TypedModel::<Analysis>::new(&client, "gemini-pro-vision");
let analysis = model.generate_content((
    "Analyze this scene safety:",
    Part::blob("image/jpeg", image_data),
    "Consider vehicles, pedestrians, and weather"
)).await?;
§Errors

Methods from Deref<Target = GenerativeModel<'c>>§

Source

pub fn start_chat(&self) -> Session<'_>

Starts a new chat session with empty history

Source

pub async fn generate_content<T>( &self, contents: T, ) -> Result<GenerateContentResponse, Error>
where T: TryIntoContents,

Generates content from flexible input types

§Example
use google_ai_rs::Part;

// Simple text generation
let response = model.generate_content("Hello world!").await?;

// Multi-part content
model.generate_content((
    "What's in this image?",
    Part::blob("image/jpeg", image_data)
)).await?;
§Errors

Returns Error::InvalidArgument for empty input or invalid combinations. Error::Service for model errors or Error::Net for transport failures

Source

pub async fn typed_generate_content<I, T>( &self, contents: I, ) -> Result<T, Error>

Source

pub async fn generate_typed_content<I, T>( &self, contents: I, ) -> Result<TypedResponse<T>, Error>

Source

pub async fn stream_generate_content<T>( &self, contents: T, ) -> Result<ResponseStream, Error>
where T: TryIntoContents,

Generates a streaming response from flexible input

§Example
let mut stream = model.stream_generate_content("Tell me a story.").await?;
while let Some(chunk) = stream.next().await? {
    // Process streaming response
}
§Errors

Returns Error::Service for model errors or Error::Net for transport failures

Source

pub async fn count_tokens<T>( &self, contents: T, ) -> Result<CountTokensResponse, Error>
where T: TryIntoContents,

Estimates token usage for given content

Useful for cost estimation and validation before full generation

§Arguments
  • parts - Content input that can be converted to parts
§Example
let token_count = model.count_tokens(content).await?;
println!("Estimated cost: ${}", token_count.total() * COST_PER_TOKEN);
§Errors

Returns Error::InvalidArgument for empty input

Source

pub fn full_name(&self) -> &str

Source

pub async fn info(&self) -> Result<Info, Error>

info returns information about the model.

Info::Tuned if the current model is a fine-tuned one, otherwise Info::Model.

Source

pub fn with_cloned_instruction<I: IntoContent>(&self, instruction: I) -> Self

Creates a copy with new system instructions

Trait Implementations§

Source§

impl<'c, T: Debug> Debug for TypedModel<'c, T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'c, T> Deref for TypedModel<'c, T>

Source§

type Target = GenerativeModel<'c>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<'c, T> From<GenerativeModel<'c>> for TypedModel<'c, T>
where T: AsSchema,

Source§

fn from(value: GenerativeModel<'c>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl<'c, T> Freeze for TypedModel<'c, T>

§

impl<'c, T> !RefUnwindSafe for TypedModel<'c, T>

§

impl<'c, T> Send for TypedModel<'c, T>
where T: Send,

§

impl<'c, T> Sync for TypedModel<'c, T>
where T: Sync,

§

impl<'c, T> Unpin for TypedModel<'c, T>
where T: Unpin,

§

impl<'c, T> !UnwindSafe for TypedModel<'c, T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more