feat(ai): add cloud providers and local model selection
Add OpenAI-compatible, Anthropic, and custom endpoint support while
keeping the local model path intact. The UI now lets users choose the
provider and local model, and staged diffs are prepared more carefully
so generated commit messages stay focused and usable.
- src-tauri/crates/commit_ai/*
- Add HTTP-based generators for OpenAI, Anthropic, and custom APIs.
- Introduce shared request/response handling and message sanitizing.
- Expand prompt building to require a body and trim long diffs safely.
- Expose selectable local model metadata and loading by model ID.
- src-tauri/src/git.rs
- Add commands for listing local models and loading them in background.
- Route generation by provider and include staged file lists in prompts.
- Exclude noisy lockfiles from detailed staged diffs.
- src-tauri/src/main.rs
- Wire the new AI commands into the Tauri app setup.
- src/lib/components/*
- Add an AI settings dialog and update the commit panel for provider
and model selection.
- src/lib/git.ts, src/lib/types.ts, src/App.svelte, src/app.css
- Extend frontend state, types, and styling for AI provider settings.
- src-tauri/Cargo.lock, src-tauri/crates/commit_ai/Cargo.toml
- Add reqwest and serde_json for cloud API requests.
This commit is contained in:
@@ -0,0 +1,203 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{build_messages, sanitize_message};
|
||||
|
||||
// Großzügig bemessen, damit ein ausführlicher Body mit Stichpunkten nicht abgeschnitten wird.
|
||||
const DEFAULT_MAX_TOKENS: u32 = 1500;
|
||||
// Ohne Timeout würde ein hängender Endpoint den "AI"-Button dauerhaft blockieren.
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
fn http_client() -> Result<reqwest::Client, String> {
|
||||
reqwest::Client::builder()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.build()
|
||||
.map_err(|err| format!("HTTP-Client konnte nicht erstellt werden: {err}"))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OpenAiMessage {
|
||||
role: &'static str,
|
||||
content: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct OpenAiRequest {
|
||||
model: String,
|
||||
messages: Vec<OpenAiMessage>,
|
||||
temperature: f32,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OpenAiResponseMessage {
|
||||
content: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OpenAiChoice {
|
||||
message: OpenAiResponseMessage,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OpenAiResponse {
|
||||
#[serde(default)]
|
||||
choices: Vec<OpenAiChoice>,
|
||||
}
|
||||
|
||||
async fn openai_compatible_request(
|
||||
url: String,
|
||||
bearer: Option<&str>,
|
||||
model: &str,
|
||||
diff: &str,
|
||||
notes: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
let (system, user) = build_messages(diff, notes)?;
|
||||
let body = OpenAiRequest {
|
||||
model: model.to_string(),
|
||||
messages: vec![
|
||||
OpenAiMessage { role: "system", content: system },
|
||||
OpenAiMessage { role: "user", content: user },
|
||||
],
|
||||
temperature: 0.3,
|
||||
};
|
||||
|
||||
let client = http_client()?;
|
||||
let mut request = client.post(url).json(&body);
|
||||
if let Some(key) = bearer.filter(|k| !k.trim().is_empty()) {
|
||||
request = request.bearer_auth(key);
|
||||
}
|
||||
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|err| format!("Anfrage an das KI-Modell fehlgeschlagen: {err}"))?;
|
||||
let status = response.status();
|
||||
let text = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|err| format!("Antwort konnte nicht gelesen werden: {err}"))?;
|
||||
|
||||
if !status.is_success() {
|
||||
return Err(format!("API-Fehler ({status}): {text}"));
|
||||
}
|
||||
|
||||
let parsed: OpenAiResponse = serde_json::from_str(&text)
|
||||
.map_err(|err| format!("Antwort konnte nicht verarbeitet werden: {err}"))?;
|
||||
|
||||
parsed
|
||||
.choices
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|choice| choice.message.content)
|
||||
.map(|content| sanitize_message(&content))
|
||||
.filter(|content| !content.is_empty())
|
||||
.ok_or_else(|| "Das Modell hat keine Antwort geliefert.".to_string())
|
||||
}
|
||||
|
||||
pub async fn generate_openai(
|
||||
api_key: &str,
|
||||
model: &str,
|
||||
diff: &str,
|
||||
notes: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
if api_key.trim().is_empty() {
|
||||
return Err("OpenAI-API-Key fehlt.".to_string());
|
||||
}
|
||||
openai_compatible_request(
|
||||
"https://api.openai.com/v1/chat/completions".to_string(),
|
||||
Some(api_key),
|
||||
model,
|
||||
diff,
|
||||
notes,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn generate_custom(
|
||||
base_url: &str,
|
||||
api_key: Option<&str>,
|
||||
model: &str,
|
||||
diff: &str,
|
||||
notes: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
if base_url.trim().is_empty() {
|
||||
return Err("Endpoint-URL fehlt.".to_string());
|
||||
}
|
||||
let url = format!("{}/chat/completions", base_url.trim_end_matches('/'));
|
||||
openai_compatible_request(url, api_key, model, diff, notes).await
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct AnthropicMessage {
|
||||
role: &'static str,
|
||||
content: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct AnthropicRequest {
|
||||
model: String,
|
||||
max_tokens: u32,
|
||||
system: String,
|
||||
messages: Vec<AnthropicMessage>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AnthropicContentBlock {
|
||||
#[serde(default)]
|
||||
text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AnthropicResponse {
|
||||
#[serde(default)]
|
||||
content: Vec<AnthropicContentBlock>,
|
||||
}
|
||||
|
||||
pub async fn generate_anthropic(
|
||||
api_key: &str,
|
||||
model: &str,
|
||||
diff: &str,
|
||||
notes: Option<&str>,
|
||||
) -> Result<String, String> {
|
||||
if api_key.trim().is_empty() {
|
||||
return Err("Anthropic-API-Key fehlt.".to_string());
|
||||
}
|
||||
let (system, user) = build_messages(diff, notes)?;
|
||||
let body = AnthropicRequest {
|
||||
model: model.to_string(),
|
||||
max_tokens: DEFAULT_MAX_TOKENS,
|
||||
system,
|
||||
messages: vec![AnthropicMessage { role: "user", content: user }],
|
||||
};
|
||||
|
||||
let client = http_client()?;
|
||||
let response = client
|
||||
.post("https://api.anthropic.com/v1/messages")
|
||||
.header("x-api-key", api_key)
|
||||
.header("anthropic-version", "2023-06-01")
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|err| format!("Anfrage an Anthropic fehlgeschlagen: {err}"))?;
|
||||
let status = response.status();
|
||||
let text = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|err| format!("Antwort konnte nicht gelesen werden: {err}"))?;
|
||||
|
||||
if !status.is_success() {
|
||||
return Err(format!("API-Fehler ({status}): {text}"));
|
||||
}
|
||||
|
||||
let parsed: AnthropicResponse = serde_json::from_str(&text)
|
||||
.map_err(|err| format!("Antwort konnte nicht verarbeitet werden: {err}"))?;
|
||||
|
||||
parsed
|
||||
.content
|
||||
.into_iter()
|
||||
.find_map(|block| block.text)
|
||||
.map(|text| sanitize_message(&text))
|
||||
.filter(|text| !text.is_empty())
|
||||
.ok_or_else(|| "Das Modell hat keine Antwort geliefert.".to_string())
|
||||
}
|
||||
Reference in New Issue
Block a user