-
Notifications
You must be signed in to change notification settings - Fork 30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feature: Add gemini backend #52
Merged
dustinblackman
merged 18 commits into
dustinblackman:main
from
aislasq:feature/backend-gemini
Mar 12, 2024
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
a847974
feat: Add gemini enums
aislasq 2053e05
feat: Add cli arguments for gemini
aislasq 132064b
feat: Add first version gemini
aislasq f3aa847
fix: Add break on empty text
aislasq aa96b1a
feat: Added tests and snapshots
aislasq da32605
feat: Update readme
aislasq 356ccc8
fix: Commented out unused model attributes
aislasq 8e23fd4
fix: Config URL for Gemini cannot be different
aislasq b805eb2
docs: Removed gemini-url from docs
aislasq 07a42fe
test: Removed unused vars in model from tests
aislasq 98914f8
Merge branch 'dustinblackman:main' into feature/backend-gemini
aislasq 5f4fd4f
refactor: Clean imports in test
aislasq 0666955
Merge branch 'dustinblackman:main' into feature/backend-gemini
aislasq 5912905
docs: Fix config example, removed unused variables
aislasq c2e5540
fix: Add config set to gemini tests
aislasq 1b63550
fix: Added config set to gemini test completions
aislasq bd82547
refactor: Change completion test body to raw string
aislasq a2b3a83
chore: Run fmt lint
aislasq File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,6 +19,7 @@ pub enum BackendName { | |
LangChain, | ||
Ollama, | ||
OpenAI, | ||
Gemini, | ||
} | ||
|
||
impl BackendName { | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,249 @@ | ||
#[cfg(test)] | ||
#[path = "gemini_test.rs"] | ||
mod tests; | ||
|
||
use std::time::Duration; | ||
|
||
use anyhow::bail; | ||
use anyhow::Result; | ||
use async_trait::async_trait; | ||
use futures::stream::TryStreamExt; | ||
use serde::Deserialize; | ||
use serde::Serialize; | ||
use tokio::io::AsyncBufReadExt; | ||
use tokio::sync::mpsc; | ||
use tokio_util::io::StreamReader; | ||
|
||
use crate::configuration::Config; | ||
use crate::configuration::ConfigKey; | ||
use crate::domain::models::Author; | ||
use crate::domain::models::Backend; | ||
use crate::domain::models::BackendName; | ||
use crate::domain::models::BackendPrompt; | ||
use crate::domain::models::BackendResponse; | ||
use crate::domain::models::Event; | ||
|
||
fn convert_err(err: reqwest::Error) -> std::io::Error { | ||
let err_msg = err.to_string(); | ||
return std::io::Error::new(std::io::ErrorKind::Interrupted, err_msg); | ||
} | ||
|
||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
#[serde(rename_all = "camelCase")] | ||
struct Model { | ||
name: String, | ||
supported_generation_methods: Vec<String>, | ||
} | ||
|
||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
struct ModelListResponse { | ||
models: Vec<Model>, | ||
} | ||
|
||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
#[serde(rename_all = "camelCase")] | ||
struct ContentPartsBlob { | ||
mime_type: String, | ||
data: String, | ||
} | ||
|
||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
#[serde(rename_all = "camelCase")] | ||
enum ContentParts { | ||
Text(String), | ||
InlineData(ContentPartsBlob), | ||
} | ||
|
||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
struct Content { | ||
role: String, | ||
parts: Vec<ContentParts>, | ||
} | ||
|
||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
struct CompletionRequest { | ||
contents: Vec<Content>, | ||
} | ||
|
||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | ||
#[serde(rename_all = "camelCase")] | ||
struct GenerateContentResponse { | ||
text: String, | ||
} | ||
|
||
pub struct Gemini { | ||
url: String, | ||
token: String, | ||
timeout: String, | ||
} | ||
|
||
impl Default for Gemini { | ||
fn default() -> Gemini { | ||
return Gemini { | ||
url: "https://generativelanguage.googleapis.com".to_string(), | ||
token: Config::get(ConfigKey::GeminiToken), | ||
timeout: Config::get(ConfigKey::BackendHealthCheckTimeout), | ||
}; | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl Backend for Gemini { | ||
fn name(&self) -> BackendName { | ||
return BackendName::Gemini; | ||
} | ||
|
||
#[allow(clippy::implicit_return)] | ||
async fn health_check(&self) -> Result<()> { | ||
if self.url.is_empty() { | ||
bail!("Gemini URL is not defined"); | ||
} | ||
if self.token.is_empty() { | ||
bail!("Gemini token is not defined"); | ||
} | ||
|
||
let url = format!( | ||
"{url}/v1beta/{model}?key={key}", | ||
url = self.url, | ||
model = Config::get(ConfigKey::Model), | ||
key = self.token | ||
); | ||
|
||
let res = reqwest::Client::new() | ||
.get(&url) | ||
.timeout(Duration::from_millis(self.timeout.parse::<u64>()?)) | ||
.send() | ||
.await; | ||
|
||
if res.is_err() { | ||
tracing::error!(error = ?res.unwrap_err(), "Gemini is not reachable"); | ||
bail!("Gemini is not reachable"); | ||
} | ||
|
||
let status = res.unwrap().status().as_u16(); | ||
if status >= 400 { | ||
tracing::error!(status = status, "Gemini health check failed"); | ||
bail!("Gemini health check failed"); | ||
} | ||
|
||
return Ok(()); | ||
} | ||
|
||
#[allow(clippy::implicit_return)] | ||
async fn list_models(&self) -> Result<Vec<String>> { | ||
let res = reqwest::Client::new() | ||
.get(format!( | ||
"{url}/v1beta/models?key={key}", | ||
url = self.url, | ||
key = self.token | ||
)) | ||
.send() | ||
.await? | ||
.json::<ModelListResponse>() | ||
.await?; | ||
|
||
let mut models: Vec<String> = res | ||
.models | ||
.iter() | ||
.filter(|model| { | ||
model | ||
.supported_generation_methods | ||
.contains(&"generateContent".to_string()) | ||
}) | ||
.map(|model| { | ||
return model.name.to_string(); | ||
}) | ||
.collect(); | ||
|
||
models.sort(); | ||
|
||
return Ok(models); | ||
} | ||
|
||
#[allow(clippy::implicit_return)] | ||
async fn get_completion<'a>( | ||
&self, | ||
prompt: BackendPrompt, | ||
tx: &'a mpsc::UnboundedSender<Event>, | ||
) -> Result<()> { | ||
let mut contents: Vec<Content> = vec![]; | ||
if !prompt.backend_context.is_empty() { | ||
contents = serde_json::from_str(&prompt.backend_context)?; | ||
} | ||
contents.push(Content { | ||
role: "user".to_string(), | ||
parts: vec![ContentParts::Text(prompt.text)], | ||
}); | ||
|
||
let req = CompletionRequest { | ||
contents: contents.clone(), | ||
}; | ||
|
||
let res = reqwest::Client::new() | ||
.post(format!( | ||
"{url}/v1beta/{model}:streamGenerateContent?key={key}", | ||
url = self.url, | ||
model = Config::get(ConfigKey::Model), | ||
key = self.token, | ||
)) | ||
.json(&req) | ||
.send() | ||
.await?; | ||
|
||
if !res.status().is_success() { | ||
tracing::error!( | ||
status = res.status().as_u16(), | ||
"Failed to make completion request to Gemini" | ||
); | ||
bail!(format!( | ||
"Failed to make completion request to Gemini, {}", | ||
res.status().as_u16() | ||
)); | ||
} | ||
let stream = res.bytes_stream().map_err(convert_err); | ||
let mut lines_reader = StreamReader::new(stream).lines(); | ||
|
||
let mut last_message = "".to_string(); | ||
while let Ok(line) = lines_reader.next_line().await { | ||
if line.is_none() { | ||
break; | ||
} | ||
|
||
let cleaned_line = line.unwrap().trim().to_string(); | ||
if !cleaned_line.starts_with("\"text\":") { | ||
continue; | ||
} | ||
|
||
let ores: GenerateContentResponse = | ||
serde_json::from_str(&format!("{{ {text} }}", text = cleaned_line)).unwrap(); | ||
|
||
if ores.text.is_empty() || ores.text.is_empty() || ores.text == "\n" { | ||
break; | ||
} | ||
|
||
last_message += &ores.text; | ||
let msg = BackendResponse { | ||
author: Author::Model, | ||
text: ores.text, | ||
done: false, | ||
context: None, | ||
}; | ||
tx.send(Event::BackendPromptResponse(msg))?; | ||
} | ||
|
||
contents.push(Content { | ||
role: "model".to_string(), | ||
parts: vec![ContentParts::Text(last_message.clone())], | ||
}); | ||
|
||
let msg = BackendResponse { | ||
author: Author::Model, | ||
text: "".to_string(), | ||
done: true, | ||
context: Some(serde_json::to_string(&contents)?), | ||
}; | ||
tx.send(Event::BackendPromptResponse(msg))?; | ||
|
||
return Ok(()); | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🚓 Health checks are failing due to this. I admit configuration should be injected in the backend interface rather than pulled in from a global repository, but I haven't gotten around to doing it. As this is a health check, you could hardcode the default model here and that'd be enough.
Alternatively, you could call
Config::set
right before calling the healthcheck function in your test and set it tomodel-1
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there a possibility to get more info on the test? I am doing the Config::set in the test exactly as you mentioned:
https://github.com/aislasq/oatmeal/blob/5f4fd4f89b0634060e456ef9b3e4144167ddfeee/src/infrastructure/backends/gemini_test.rs#L54
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The github actions test suite is using
nextest
, this runs tests in parallel process' where memory will be different for each test. You haveConfig:set
being used in one test, but it's gotta be use in all your healthcheck tests.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done, let me check the linter so you can re-run the tests. Thanks!