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/api/generate-content#generationconfig)
59    pub fn set_generation_config(&mut self) -> &mut Value {
60        self.generation_config = Some(json!({}));
61        self.generation_config.as_mut().unwrap()
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    /// To verify your schema visit [here](https://aistudio.google.com/prompts/new_chat):
73    /// - Under tools, toggle on Structured output
74    /// - Click Edit
75    /// - Here you can create schema with `Visual Editor` or `Code Editor` with error detection
76    pub fn set_json_mode(mut self, schema: Value) -> Self {
77        let config = self.set_generation_config();
78        config["response_mime_type"] = "application/json".into();
79        config["response_schema"] = schema.into();
80        self
81    }
82    pub fn unset_json_mode(mut self) -> Self {
83        if let Some(ref mut generation_config) = self.generation_config {
84            generation_config["response_schema"] = None::<Value>.into();
85            generation_config["response_mime_type"] = None::<Value>.into();
86        }
87        self
88    }
89    pub fn set_tools(mut self, tools: Vec<Tool>) -> Self {
90        self.tools = Some(tools);
91        self
92    }
93    pub fn unset_tools(mut self) -> Self {
94        self.tools = None;
95        self
96    }
97
98    pub async fn ask(&self, session: &mut Session) -> Result<GeminiResponse, GeminiResponseError> {
99        let req_url = format!(
100            "{BASE_URL}/{}:generateContent?key={}",
101            self.model, self.api_key
102        );
103
104        let response = self
105            .client
106            .post(req_url)
107            .json(&GeminiRequestBody::new(
108                self.sys_prompt.as_ref(),
109                self.tools.as_deref(),
110                &session.get_history().as_slice(),
111                self.generation_config.as_ref(),
112            ))
113            .send()
114            .await
115            .map_err(|e| GeminiResponseError::ReqwestError(e))?;
116
117        if !response.status().is_success() {
118            let text = response
119                .text()
120                .await
121                .map_err(|e| GeminiResponseError::ReqwestError(e))?;
122            return Err(GeminiResponseError::StatusNotOk(text));
123        }
124
125        let reply = GeminiResponse::new(response)
126            .await
127            .map_err(|e| GeminiResponseError::ReqwestError(e))?;
128        session.update(&reply);
129        Ok(reply)
130    }
131    /// # Warning
132    /// You must read the response stream to get reply stored context in `session`.
133    /// `data_extractor` is used to extract data that you get as a stream of futures.
134    /// # Example
135    ///```ignore
136    ///use futures::StreamExt
137    ///let mut response_stream = gemini.ask_as_stream_with_extractor(session,
138    ///|session, _gemini_response| session.get_last_message_text("").unwrap())
139    ///.await.unwrap(); // Use _gemini_response.get_text("") to just get the text received in every chunk
140    ///
141    ///while let Some(response) = response_stream.next().await {
142    ///    if let Ok(response) = response {
143    ///        println!("{}", response);
144    ///    }
145    ///}
146    ///```
147    pub async fn ask_as_stream_with_extractor<F, StreamType>(
148        &self,
149        session: Session,
150        data_extractor: F,
151    ) -> Result<ResponseStream<F, StreamType>, (Session, GeminiResponseError)>
152    where
153        F: FnMut(&Session, GeminiResponse) -> StreamType,
154    {
155        let req_url = format!(
156            "{BASE_URL}/{}:streamGenerateContent?key={}",
157            self.model, self.api_key
158        );
159
160        let request = self
161            .client
162            .post(req_url)
163            .json(&GeminiRequestBody::new(
164                self.sys_prompt.as_ref(),
165                self.tools.as_deref(),
166                session.get_history().as_slice(),
167                self.generation_config.as_ref(),
168            ))
169            .send()
170            .await;
171        let response = match request {
172            Ok(response) => response,
173            Err(e) => return Err((session, GeminiResponseError::ReqwestError(e))),
174        };
175
176        if !response.status().is_success() {
177            let text = match response.text().await {
178                Ok(response) => response,
179                Err(e) => return Err((session, GeminiResponseError::ReqwestError(e))),
180            };
181            return Err((session, GeminiResponseError::StatusNotOk(text.into())));
182        }
183
184        Ok(ResponseStream::new(
185            Box::new(response.bytes_stream()),
186            session,
187            data_extractor,
188        ))
189    }
190    /// # Warning
191    /// You must read the response stream to get reply stored context in `session`.
192    /// # Example
193    ///```ignore
194    ///use futures::StreamExt
195    ///let mut response_stream = gemini.ask_as_stream(session).await.unwrap();
196    ///
197    ///while let Some(response) = response_stream.next().await {
198    ///    if let Ok(response) = response {
199    ///        println!("{}", response.get_text(""));
200    ///    }
201    ///}
202    ///```
203    pub async fn ask_as_stream(
204        &self,
205        session: Session,
206    ) -> Result<GeminiResponseStream, (Session, GeminiResponseError)> {
207        self.ask_as_stream_with_extractor(
208            session,
209            (|_, gemini_response| gemini_response)
210                as fn(&Session, GeminiResponse) -> GeminiResponse,
211        )
212        .await
213    }
214}