gemini_client_api/gemini/
ask.rs1use 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 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 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 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 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 .map_err(|e| GeminiResponseError::ReqwestError(e))?;
118
119 if !response.status().is_success() {
120 let text = response
121 .text()
122 .await
123 .map_err(|e| GeminiResponseError::ReqwestError(e))?;
124 return Err(GeminiResponseError::StatusNotOk(text));
125 }
126
127 let reply = GeminiResponse::new(response)
128 .await
129 .map_err(|e| GeminiResponseError::ReqwestError(e))?;
130 session.update(&reply);
131 Ok(reply)
132 }
133 pub async fn ask_as_stream_with_extractor<F, StreamType>(
150 &self,
151 session: Session,
152 data_extractor: F,
153 ) -> Result<ResponseStream<F, StreamType>, GeminiResponseError>
154 where
155 F: FnMut(&Session, GeminiResponse) -> StreamType,
156 {
157 let req_url = format!(
158 "{BASE_URL}/{}:streamGenerateContent?key={}",
159 self.model, self.api_key
160 );
161
162 let response = self
163 .client
164 .post(req_url)
165 .json(&GeminiRequestBody::new(
166 self.sys_prompt.as_ref(),
167 self.tools.as_deref(),
168 session.get_history().as_slice(),
169 self.generation_config.as_ref(),
170 ))
171 .send()
172 .await
173 .map_err(|e| GeminiResponseError::ReqwestError(e))?;
174
175 if !response.status().is_success() {
176 let text = response
177 .text()
178 .await
179 .map_err(|e| GeminiResponseError::ReqwestError(e))?;
180 return Err(GeminiResponseError::StatusNotOk(text.into()));
181 }
182
183 Ok(ResponseStream::new(
184 Box::new(response.bytes_stream()),
185 session,
186 data_extractor,
187 ))
188 }
189 pub async fn ask_as_stream(
203 &self,
204 session: Session,
205 ) -> Result<GeminiResponseStream, GeminiResponseError> {
206 self.ask_as_stream_with_extractor(
207 session,
208 (|_, gemini_response| gemini_response)
209 as fn(&Session, GeminiResponse) -> GeminiResponse,
210 )
211 .await
212 }
213}