Skip to content

Update Cargo.toml, add Gemini example, refine error handling #6

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 1 addition & 18 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 17 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,25 @@ name = "tosic-llm"
version = "0.1.0"
edition = "2024"

[package.metadata.docs.rs]
features = ["doc-utils"]
all-features = true
cargo-args = ["-Zunstable-options", "-Zrustdoc-scrape-examples"]

[lib]
test = true
doctest = true
Comment on lines +11 to +13
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider removing redundant library settings.

The test and doctest settings are enabled by default for libraries. These explicit settings are unnecessary unless you have a specific reason to include them.


[workspace.dependencies]
thiserror = "2.0.7"
tosic-utils = { version = "0.2.3", features = ["env", "dotenv", "tracing"], registry = "gitea" }
# tosic-utils = { version = "0.2.3", features = ["env", "dotenv", "tracing"], path = "../tosic-utils" }
tokio = { version = "1.42", features = ["full", "macros", "rt-multi-thread", "tracing"] }
tracing = { version = "0.1.41", features = ["log"] }
serde = { version = "1.0.216", features = ["derive", "alloc", "rc"] }
serde_json = "1.0.133"
futures = "0.3.31"
utoipa = { version = "5.2.0", features = ["actix_extras", "debug", "rc_schema", "non_strict_integers", "chrono", "uuid", "url"] }
validator ="0.19.0"

[dependencies]
derive_more = { version = "2.0.1", features = ["full"] }
reqwest = { version = "0.12.12", default-features = false, features = ["json", "stream", "rustls-tls", "charset", "http2"] }
tokio = { workspace = true, features = ["full"] }
serde = { version = "1.0.217", features = ["derive"] }
futures-util = "0.3.31"
tokio-stream = "0.1.17"
Expand All @@ -29,6 +32,12 @@ serde_json.workspace = true
thiserror.workspace = true
url = { version = "2.5.4", features = ["serde"] }
utoipa.workspace = true
validator.workspace = true
async-trait = "0.1.86"
base64 = "0.22.1"

[dev-dependencies]
tosic-llm = { path = ".", features = ["doc-utils"] }
tokio = { version = "1.43.0", features = ["full"] }
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider limiting tokio features in dev-dependencies.

Using features = ["full"] for tokio includes all features, which might be unnecessary for testing. Consider specifying only the features you need (e.g., "rt", "macros", "rt-multi-thread").

-tokio = { version = "1.43.0", features = ["full"] }
+tokio = { version = "1.43.0", features = ["rt", "macros", "rt-multi-thread"] }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
tokio = { version = "1.43.0", features = ["full"] }
tokio = { version = "1.43.0", features = ["rt", "macros", "rt-multi-thread"] }


[features]
default = []
doc-utils = []
110 changes: 110 additions & 0 deletions examples/gemini.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use std::io::Write;
use thiserror::Error;
use tokio_stream::StreamExt;
use tosic_llm::gemini::{GeminiClient, GeminiContent, GeminiModel};
use tosic_llm::{ensure, LlmProvider};
use tosic_llm::error::{LlmError, WithContext};
use tosic_llm::types::Role;

#[derive(Debug, Error)]
enum Error {
#[error(transparent)]
Llm(#[from] LlmError),
#[error("{0}")]
Generic(String),
}
Comment on lines +9 to +15
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider making the Error enum public if used across modules.
Currently, the Error enum is private to this file. If you anticipate needing it elsewhere, adding pub here can help maintain clarity and consistency across your project and keep your error types consolidated.


use serde_json::{Result as JsonResult, Value};

#[derive(Debug)]
pub struct GeminiResponseParser {
has_started: bool,
has_finished: bool,
}
Comment on lines +19 to +23
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider adding comments or docstrings.
GeminiResponseParser is self-explanatory, but docstrings can clarify the reasoning and usage patterns.


impl GeminiResponseParser {
pub fn new() -> Self {
Self {
has_started: false,
has_finished: false,
}
}

pub fn parse_chunk(&mut self, chunk: &[u8]) -> JsonResult<Option<String>> {
// Convert bytes to string
let chunk_str = String::from_utf8_lossy(chunk);

// Handle the start and end markers
if chunk_str == "[" {
self.has_started = true;
return Ok(None);
} else if chunk_str == "]" || chunk_str.is_empty() {
self.has_finished = true;
return Ok(None);
}

// Remove leading comma if present (subsequent chunks start with ,\r\n)
let cleaned_chunk = if chunk_str.starts_with(",") {
chunk_str.trim_start_matches(",").trim_start()
} else {
&chunk_str
};

// Parse the JSON object
let v: Value = serde_json::from_str(cleaned_chunk)?;

// Extract the text from the nested structure
let text = v
.get("candidates")
.and_then(|c| c.get(0))
.and_then(|c| c.get("content"))
.and_then(|c| c.get("parts"))
.and_then(|p| p.get(0))
.and_then(|p| p.get("text"))
.and_then(|t| t.as_str())
.map(String::from);

Ok(text)
}
}
Comment on lines +33 to +69
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Verify handling of chunked JSON.
Because the code handles [, ], and partial data, confirm you never receive a chunk that splits a JSON object across boundaries. Otherwise, serde_json::from_str will fail. If partial objects are possible, buffering logic might be necessary to reassemble JSON.

Could you confirm how GeminiClient streams JSON to ensure each chunk is a complete object (or bracket) for this parser?


async fn ask_ai() -> Result<(), Error> {
let client = GeminiClient::new(GeminiModel::Gemini2Flash).context("Failed to create the Gemini Client")?;
let provider = LlmProvider::new(client);

let req = GeminiContent::new(Some(Role::User), "Hi my name is Emil and i like to write complex rust libraries".to_string());

let res = provider.generate(vec![req], true).await.context("Failed to get response from LLM")?;

ensure!(res.is_stream(), Error::Generic("Response is not stream".into()));

let mut stream = res.unwrap_stream();

// Stream to STDOUT
let stdout = std::io::stdout();
let mut stdout = stdout.lock();

let mut parser = GeminiResponseParser::new();
let mut written_len = 0;

while let Some(chunk) = stream.next().await {
let chunk = chunk.context("Failed to read response from LLM")?;

if let Ok(Some(text)) = parser.parse_chunk(&chunk) {
let bytes = text.as_bytes();
written_len += bytes.len();
stdout.write_all(bytes).context("Failed to write to stdout")?;
stdout.flush().context("Failed to flush stdout")?;
}
}


println!("\nWrote {} bytes", written_len);

Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
ask_ai().await
}
Loading