-
Notifications
You must be signed in to change notification settings - Fork 83
Feat: Add Gemini Support to DataFlow (Rust) #360
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,110 @@ | ||
use async_trait::async_trait; | ||
use crate::llm::{LlmGenerationClient, LlmSpec, LlmGenerateRequest, LlmGenerateResponse, ToJsonSchemaOptions, OutputFormat}; | ||
use anyhow::{Result, bail, Context}; | ||
use serde_json::Value; | ||
use crate::api_bail; | ||
use urlencoding::encode; | ||
|
||
pub struct Client { | ||
model: String, | ||
api_key: String, | ||
client: reqwest::Client, | ||
} | ||
|
||
impl Client { | ||
pub async fn new(spec: LlmSpec) -> Result<Self> { | ||
let api_key = match std::env::var("GEMINI_API_KEY") { | ||
Ok(val) => val, | ||
Err(_) => api_bail!("GEMINI_API_KEY environment variable must be set"), | ||
}; | ||
Ok(Self { | ||
model: spec.model, | ||
api_key, | ||
client: reqwest::Client::new(), | ||
}) | ||
} | ||
} | ||
|
||
// Recursively remove all `additionalProperties` fields from a JSON value | ||
fn remove_additional_properties(value: &mut Value) { | ||
match value { | ||
Value::Object(map) => { | ||
map.remove("additionalProperties"); | ||
for v in map.values_mut() { | ||
remove_additional_properties(v); | ||
} | ||
} | ||
Value::Array(arr) => { | ||
for v in arr { | ||
remove_additional_properties(v); | ||
} | ||
} | ||
_ => {} | ||
} | ||
} | ||
|
||
#[async_trait] | ||
impl LlmGenerationClient for Client { | ||
async fn generate<'req>( | ||
&self, | ||
request: LlmGenerateRequest<'req>, | ||
) -> Result<LlmGenerateResponse> { | ||
// Compose the prompt/messages | ||
let contents = vec![serde_json::json!({ | ||
"role": "user", | ||
"parts": [{ "text": request.user_prompt }] | ||
})]; | ||
|
||
// Prepare payload | ||
let mut payload = serde_json::json!({ "contents": contents }); | ||
if let Some(system) = request.system_prompt { | ||
payload["systemInstruction"] = serde_json::json!({ | ||
"parts": [ { "text": system } ] | ||
}); | ||
} | ||
|
||
// If structured output is requested, add schema and responseMimeType | ||
if let Some(OutputFormat::JsonSchema { schema, .. }) = &request.output_format { | ||
let mut schema_json = serde_json::to_value(schema)?; | ||
remove_additional_properties(&mut schema_json); | ||
payload["generationConfig"] = serde_json::json!({ | ||
"responseMimeType": "application/json", | ||
"responseSchema": schema_json | ||
}); | ||
} | ||
|
||
let api_key = &self.api_key; | ||
let url = format!( | ||
"https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent?key={}", | ||
encode(&self.model), encode(api_key) | ||
); | ||
|
||
let resp = self.client.post(&url) | ||
.json(&payload) | ||
.send() | ||
.await | ||
.context("HTTP error")?; | ||
|
||
let resp_json: Value = resp.json().await.context("Invalid JSON")?; | ||
|
||
if let Some(error) = resp_json.get("error") { | ||
bail!("Gemini API error: {:?}", error); | ||
} | ||
let mut resp_json = resp_json; | ||
let text = match &mut resp_json["candidates"][0]["content"]["parts"][0]["text"] { | ||
Value::String(s) => std::mem::take(s), | ||
_ => bail!("No text in response"), | ||
}; | ||
|
||
Ok(LlmGenerateResponse { text }) | ||
} | ||
|
||
fn json_schema_options(&self) -> ToJsonSchemaOptions { | ||
ToJsonSchemaOptions { | ||
fields_always_required: false, | ||
supports_format: false, | ||
extract_descriptions: false, | ||
top_level_must_be_object: true, | ||
} | ||
} | ||
} |
This file contains hidden or 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
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.
Uh oh!
There was an error while loading. Please reload this page.