Struct Content

Source
pub struct Content {
    pub parts: Vec<Part>,
    pub role: Option<Role>,
}
Expand description

Content of a message

Fields§

§parts: Vec<Part>

Parts of the content

§role: Option<Role>

Role of the content

Implementations§

Source§

impl Content

Source

pub fn text(text: impl Into<String>) -> Self

Create a new text content

Source

pub fn function_call(function_call: FunctionCall) -> Self

Create a new content with a function call

Source

pub fn function_response(function_response: FunctionResponse) -> Self

Create a new content with a function response

Source

pub fn function_response_json(name: impl Into<String>, response: Value) -> Self

Create a new content with a function response from name and JSON value

Source

pub fn with_role(self, role: Role) -> Self

Add a role to this content

Examples found in repository?
examples/advanced.rs (line 81)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    let api_key = env::var("GEMINI_API_KEY")?;
11    
12    // Create client
13    let client = Gemini::new(api_key);
14    
15    // Define a weather function
16    let get_weather = FunctionDeclaration::new(
17        "get_weather",
18        "Get the current weather for a location",
19        FunctionParameters::object()
20            .with_property(
21                "location",
22                PropertyDetails::string("The city and state, e.g., San Francisco, CA"),
23                true,
24            )
25            .with_property(
26                "unit",
27                PropertyDetails::enum_type(
28                    "The unit of temperature", 
29                    ["celsius", "fahrenheit"]
30                ),
31                false,
32            ),
33    );
34
35    // Create a request with function calling
36    println!("Sending function call request...");
37    let response = client
38        .generate_content()
39        .with_user_message("What's the weather like in Tokyo right now?")
40        .with_function(get_weather)
41        .with_function_calling_mode(FunctionCallingMode::Any)
42        .execute()
43        .await?;
44
45    // Check if there are function calls
46    if let Some(function_call) = response.function_calls().first() {
47        println!(
48            "Function call received: {} with args: {}",
49            function_call.name,
50            function_call.args
51        );
52
53        // Get parameters from the function call
54        let location: String = function_call.get("location")?;
55        let unit = function_call.get::<String>("unit").unwrap_or_else(|_| String::from("celsius"));
56        
57        println!("Location: {}, Unit: {}", location, unit);
58        
59        // Simulate function execution (in a real app, this would call a weather API)
60        // Create a JSON response object
61        let weather_response = serde_json::json!({
62            "temperature": 22,
63            "unit": unit,
64            "condition": "sunny",
65            "location": location
66        });
67
68        // Continue the conversation with the function result
69        // We need to replay the entire conversation with the function response
70        println!("Sending function response...");
71        
72        // First, need to recreate the original prompt and the model's response
73        let mut final_request = client.generate_content()
74            .with_user_message("What's the weather like in Tokyo right now?");
75        
76        // Add the function call from the model's response
77        let mut call_content = Content::default();
78        call_content.parts.push(Part::FunctionCall { 
79            function_call: (*function_call).clone()
80        });
81        let call_content = call_content.with_role(Role::Model);
82        final_request.contents.push(call_content);
83        
84        // Now add the function response using the JSON value
85        final_request = final_request.with_function_response("get_weather", weather_response);
86        
87        // Execute the request
88        let final_response = final_request.execute().await?;
89
90        println!("Final response: {}", final_response.text());
91    } else {
92        println!("No function calls in the response.");
93        println!("Response text: {}", response.text());
94    }
95
96    Ok(())
97}

Trait Implementations§

Source§

impl Clone for Content

Source§

fn clone(&self) -> Content

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Content

Source§

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

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

impl Default for Content

Source§

fn default() -> Content

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Content

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Content

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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<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
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T