gemini_client_api/gemini/
ask.rs

1use super::error::GeminiResponseError;
2use super::types::request::*;
3use super::types::response::*;
4use super::types::sessions::Session;
5use reqwest::Client;
6use serde_json::{Value, json};
7use std::time::Duration;
8
9const BASE_URL: &str = "https://generativelanguage.googleapis.com/v1beta/models";
10
11#[derive(Clone, Default, Debug)]
12pub struct Gemini {
13    client: Client,
14    api_key: String,
15    model: String,
16    sys_prompt: Option<SystemInstruction>,
17    generation_config: Option<Value>,
18    tools: Option<Vec<Tool>>,
19}
20impl Gemini {
21    /// # Arguments
22    /// `api_key` get one from [Google AI studio](https://aistudio.google.com/app/apikey)
23    /// `model` should be of those mentioned [here](https://ai.google.dev/gemini-api/docs/models#model-variations) in bold black color
24    /// `sys_prompt` should follow [gemini doc](https://ai.google.dev/gemini-api/docs/text-generation#image-input)
25    pub fn new(
26        api_key: impl Into<String>,
27        model: impl Into<String>,
28        sys_prompt: Option<SystemInstruction>,
29    ) -> Self {
30        Self {
31            client: Client::builder()
32                .timeout(Duration::from_secs(60))
33                .build()
34                .unwrap(),
35            api_key: api_key.into(),
36            model: model.into(),
37            sys_prompt,
38            generation_config: None,
39            tools: None,
40        }
41    }
42    /// `sys_prompt` should follow [gemini doc](https://ai.google.dev/gemini-api/docs/text-generation#image-input)
43    pub fn new_with_timeout(
44        api_key: impl Into<String>,
45        model: impl Into<String>,
46        sys_prompt: Option<SystemInstruction>,
47        api_timeout: Duration,
48    ) -> Self {
49        Self {
50            client: Client::builder().timeout(api_timeout).build().unwrap(),
51            api_key: api_key.into(),
52            model: model.into(),
53            sys_prompt,
54            generation_config: None,
55            tools: None,
56        }
57    }
58    /// The generation config Schema should follow [Gemini docs](https://ai.google.dev/gemini-api/docs/text-generation#configuration-parameters)
59    pub fn set_generation_config(mut self, generation_config: Value) -> Self {
60        self.generation_config = Some(generation_config);
61        self
62    }
63    pub fn set_model(mut self, model: impl Into<String>) -> Self {
64        self.model = model.into();
65        self
66    }
67    pub fn set_api_key(mut self, api_key: impl Into<String>) -> Self {
68        self.api_key = api_key.into();
69        self
70    }
71    /// `schema` should follow [Schema of gemini](https://ai.google.dev/api/caching#Schema)
72    pub fn set_json_mode(mut self, schema: Value) -> Self {
73        if let None = self.generation_config {
74            self.generation_config = Some(json!({
75                "response_mime_type": "application/json",
76                "response_schema":schema
77            }))
78        } else if let Some(config) = self.generation_config.as_mut() {
79            config["response_mime_type"] = "application/json".into();
80            config["response_schema"] = schema.into();
81        }
82        self
83    }
84    pub fn unset_json_mode(mut self) -> Self {
85        if let Some(ref mut generation_config) = self.generation_config {
86            generation_config["response_schema"] = None::<Value>.into();
87            generation_config["response_mime_type"] = None::<Value>.into();
88        }
89        self
90    }
91    pub fn set_tools(mut self, tools: Vec<Tool>) -> Self {
92        self.tools = Some(tools);
93        self
94    }
95    pub fn unset_tools(mut self) -> Self {
96        self.tools = None;
97        self
98    }
99
100    pub async fn ask(&self, session: &mut Session) -> Result<GeminiResponse, GeminiResponseError> {
101        let req_url = format!(
102            "{BASE_URL}/{}:generateContent?key={}",
103            self.model, self.api_key
104        );
105
106        let response = self
107            .client
108            .post(req_url)
109            .json(&GeminiRequestBody::new(
110                self.sys_prompt.as_ref(),
111                self.tools.as_deref(),
112                &session.get_history().as_slice(),
113                self.generation_config.as_ref(),
114            ))
115            .send()
116            .await?;
117
118        if !response.status().is_success() {
119            let text = response.text().await?;
120            return Err(text.into());
121        }
122
123        let reply = GeminiResponse::new(response).await?;
124        session.update(&reply);
125        Ok(reply)
126    }
127    /// # Warning
128    /// You must read the response stream to get reply stored context in `session`.
129    /// `data_extractor` is used to extract data that you get as a stream of futures.
130    /// # Example
131    ///```ignore
132    ///use futures::StreamExt
133    ///let mut response_stream = gemini.ask_as_stream_with_extractor(session,
134    ///|session, _gemini_response| session.get_last_message_text("").unwrap())
135    ///.await.unwrap(); // Use _gemini_response.get_text("") to just get the text received in every chunk
136    ///
137    ///while let Some(response) = response_stream.next().await {
138    ///    if let Ok(response) = response {
139    ///        println!("{}", response);
140    ///    }
141    ///}
142    ///```
143    pub async fn ask_as_stream_with_extractor<F, StreamType>(
144        &self,
145        session: Session,
146        data_extractor: F,
147    ) -> Result<ResponseStream<F, StreamType>, GeminiResponseError>
148    where
149        F: FnMut(&Session, GeminiResponse) -> StreamType,
150    {
151        let req_url = format!(
152            "{BASE_URL}/{}:streamGenerateContent?key={}",
153            self.model, self.api_key
154        );
155
156        let response = self
157            .client
158            .post(req_url)
159            .json(&GeminiRequestBody::new(
160                self.sys_prompt.as_ref(),
161                self.tools.as_deref(),
162                session.get_history().as_slice(),
163                self.generation_config.as_ref(),
164            ))
165            .send()
166            .await?;
167
168        if !response.status().is_success() {
169            let text = response.text().await?;
170            return Err(text.into());
171        }
172
173        Ok(ResponseStream::new(
174            Box::new(response.bytes_stream()),
175            session,
176            data_extractor,
177        ))
178    }
179    /// # Warning
180    /// You must read the response stream to get reply stored context in `session`.
181    /// # Example
182    ///```ignore
183    ///use futures::StreamExt
184    ///let mut response_stream = gemini.ask_as_stream(session).await.unwrap();
185    ///
186    ///while let Some(response) = response_stream.next().await {
187    ///    if let Ok(response) = response {
188    ///        println!("{}", response.get_text(""));
189    ///    }
190    ///}
191    ///```
192    pub async fn ask_as_stream(
193        &self,
194        session: Session,
195    ) -> Result<GeminiResponseStream, GeminiResponseError> {
196        self.ask_as_stream_with_extractor(
197            session,
198            (|_, gemini_response| gemini_response)
199                as fn(&Session, GeminiResponse) -> GeminiResponse,
200        )
201        .await
202    }
203}