mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-27 07:46:25 +00:00
feat(ai): provider-agnostic AI crate (Anthropic, OpenAI, Gemini, compatible)
Streaming chat, embeddings (Embedder impl), key stores, retries/cancellation, and graph features: ask_graph, summarize_journal, suggest_links_and_tags, extract_tasks, consolidate_week. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fbcfcf678f
commit
6697924bf5
20 files changed
+4084
-6
No files matched your search
@@ -0,0 +1,129 @@
|
||||
//! Anthropic Messages API (streaming). Anthropic has no embeddings endpoint: use OpenAI,
|
||||
//! Gemini, Ollama or Voyage (via `OpenAiCompatible`) for embeddings.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use serde_json::{Value, json};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::config::ProviderConfig;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::http::{Http, for_each_sse};
|
||||
use crate::keys::Secret;
|
||||
use crate::provider::ChatProvider;
|
||||
use crate::types::{ChatRequest, ChatResponse, Role, TokenSink};
|
||||
|
||||
const API_VERSION: &str = "2023-06-01";
|
||||
|
||||
pub struct Anthropic {
|
||||
http: Http,
|
||||
url: String,
|
||||
key: Secret,
|
||||
model: String,
|
||||
max_tokens: u32,
|
||||
}
|
||||
|
||||
impl Anthropic {
|
||||
pub fn new(cfg: &ProviderConfig, key: Secret) -> Result<Self> {
|
||||
Ok(Self {
|
||||
http: Http::new(cfg)?,
|
||||
url: format!("{}/v1/messages", cfg.base_url()),
|
||||
key,
|
||||
model: cfg.model.clone(),
|
||||
max_tokens: cfg.max_tokens,
|
||||
})
|
||||
}
|
||||
|
||||
fn body(&self, req: &ChatRequest) -> Value {
|
||||
// No `temperature`: current Claude models reject non-default sampling parameters.
|
||||
let messages: Vec<Value> = req
|
||||
.messages
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let role = if m.role == Role::User {
|
||||
"user"
|
||||
} else {
|
||||
"assistant"
|
||||
};
|
||||
json!({"role": role, "content": m.content})
|
||||
})
|
||||
.collect();
|
||||
let mut body = json!({
|
||||
"model": self.model,
|
||||
"max_tokens": req.max_tokens.unwrap_or(self.max_tokens),
|
||||
"messages": messages,
|
||||
"stream": true,
|
||||
});
|
||||
if let Some(s) = &req.system {
|
||||
body["system"] = json!(s);
|
||||
}
|
||||
body
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ChatProvider for Anthropic {
|
||||
async fn chat(
|
||||
&self,
|
||||
req: &ChatRequest,
|
||||
mut sink: Option<TokenSink<'_>>,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<ChatResponse> {
|
||||
let headers = [
|
||||
("x-api-key", self.key.expose().to_string()),
|
||||
("anthropic-version", API_VERSION.to_string()),
|
||||
];
|
||||
let resp = self
|
||||
.http
|
||||
.post_json(&self.url, &headers, &self.body(req), cancel)
|
||||
.await?;
|
||||
let mut out = ChatResponse::default();
|
||||
for_each_sse(resp, cancel, |ev| {
|
||||
let v: Value =
|
||||
serde_json::from_str(&ev.data).map_err(|e| Error::Parse(e.to_string()))?;
|
||||
match v["type"].as_str().unwrap_or_default() {
|
||||
"message_start" => {
|
||||
out.usage.input_tokens =
|
||||
v["message"]["usage"]["input_tokens"].as_u64().unwrap_or(0);
|
||||
out.usage.output_tokens =
|
||||
v["message"]["usage"]["output_tokens"].as_u64().unwrap_or(0);
|
||||
}
|
||||
"content_block_delta" if v["delta"]["type"] == "text_delta" => {
|
||||
if let Some(t) = v["delta"]["text"].as_str() {
|
||||
out.text.push_str(t);
|
||||
if let Some(s) = sink.as_mut() {
|
||||
s(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
"message_delta" => {
|
||||
if let Some(n) = v["usage"]["output_tokens"].as_u64() {
|
||||
out.usage.output_tokens = n;
|
||||
}
|
||||
if let Some(n) = v["usage"]["input_tokens"].as_u64() {
|
||||
out.usage.input_tokens = n;
|
||||
}
|
||||
if let Some(r) = v["delta"]["stop_reason"].as_str() {
|
||||
out.stop_reason = Some(r.to_string());
|
||||
}
|
||||
}
|
||||
"error" => {
|
||||
let msg = v["error"]["message"].as_str().unwrap_or("stream error");
|
||||
return Err(Error::Api {
|
||||
status: 529,
|
||||
message: msg.to_string(),
|
||||
retry_after: None,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(true)
|
||||
})
|
||||
.await?;
|
||||
if out.stop_reason.as_deref() == Some("refusal") {
|
||||
return Err(Error::Refused(
|
||||
"the model's safety system declined this request".into(),
|
||||
));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Google Gemini (Generative Language API): streaming chat and batch embeddings.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use serde_json::{Value, json};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{EMBED_BATCH, known_embed_dims};
|
||||
use crate::config::ProviderConfig;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::http::{Http, for_each_sse};
|
||||
use crate::keys::Secret;
|
||||
use crate::provider::{ChatProvider, EmbeddingProvider};
|
||||
use crate::types::{ChatRequest, ChatResponse, EmbedResponse, Role, TokenSink, Usage};
|
||||
|
||||
pub struct Gemini {
|
||||
http: Http,
|
||||
base: String,
|
||||
key: Secret,
|
||||
model: String,
|
||||
embed_model: Option<String>,
|
||||
embed_dims: Option<usize>,
|
||||
max_tokens: u32,
|
||||
temperature: Option<f32>,
|
||||
}
|
||||
|
||||
impl Gemini {
|
||||
pub fn new(cfg: &ProviderConfig, key: Secret) -> Result<Self> {
|
||||
Ok(Self {
|
||||
http: Http::new(cfg)?,
|
||||
base: cfg.base_url(),
|
||||
key,
|
||||
model: cfg.model.clone(),
|
||||
embed_model: cfg.embed_model.clone(),
|
||||
embed_dims: cfg.embed_dims,
|
||||
max_tokens: cfg.max_tokens,
|
||||
temperature: cfg.temperature,
|
||||
})
|
||||
}
|
||||
|
||||
// The key travels in a header, never in the URL, so it cannot leak through logs or errors.
|
||||
fn headers(&self) -> [(&'static str, String); 1] {
|
||||
[("x-goog-api-key", self.key.expose().to_string())]
|
||||
}
|
||||
|
||||
fn body(&self, req: &ChatRequest) -> Value {
|
||||
let contents: Vec<Value> = req
|
||||
.messages
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let role = if m.role == Role::User {
|
||||
"user"
|
||||
} else {
|
||||
"model"
|
||||
};
|
||||
json!({"role": role, "parts": [{"text": m.content}]})
|
||||
})
|
||||
.collect();
|
||||
let mut gen_cfg = json!({"maxOutputTokens": req.max_tokens.unwrap_or(self.max_tokens)});
|
||||
if let Some(t) = self.temperature {
|
||||
gen_cfg["temperature"] = json!(t);
|
||||
}
|
||||
if req.json {
|
||||
gen_cfg["responseMimeType"] = json!("application/json");
|
||||
}
|
||||
let mut body = json!({"contents": contents, "generationConfig": gen_cfg});
|
||||
if let Some(s) = &req.system {
|
||||
body["systemInstruction"] = json!({"parts": [{"text": s}]});
|
||||
}
|
||||
body
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ChatProvider for Gemini {
|
||||
async fn chat(
|
||||
&self,
|
||||
req: &ChatRequest,
|
||||
mut sink: Option<TokenSink<'_>>,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<ChatResponse> {
|
||||
let url = format!(
|
||||
"{}/models/{}:streamGenerateContent?alt=sse",
|
||||
self.base, self.model
|
||||
);
|
||||
let resp = self
|
||||
.http
|
||||
.post_json(&url, &self.headers(), &self.body(req), cancel)
|
||||
.await?;
|
||||
let mut out = ChatResponse::default();
|
||||
for_each_sse(resp, cancel, |ev| {
|
||||
let v: Value =
|
||||
serde_json::from_str(&ev.data).map_err(|e| Error::Parse(e.to_string()))?;
|
||||
if let Some(reason) = v["promptFeedback"]["blockReason"].as_str() {
|
||||
return Err(Error::Refused(format!("prompt blocked: {reason}")));
|
||||
}
|
||||
if let Some(parts) = v["candidates"][0]["content"]["parts"].as_array() {
|
||||
for t in parts.iter().filter_map(|p| p["text"].as_str()) {
|
||||
out.text.push_str(t);
|
||||
if let Some(s) = sink.as_mut() {
|
||||
s(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(r) = v["candidates"][0]["finishReason"].as_str() {
|
||||
out.stop_reason = Some(r.to_string());
|
||||
}
|
||||
if let Some(u) = v.get("usageMetadata").filter(|u| u.is_object()) {
|
||||
out.usage = Usage {
|
||||
input_tokens: u["promptTokenCount"].as_u64().unwrap_or(0),
|
||||
output_tokens: u["candidatesTokenCount"].as_u64().unwrap_or(0)
|
||||
+ u["thoughtsTokenCount"].as_u64().unwrap_or(0),
|
||||
};
|
||||
}
|
||||
Ok(true)
|
||||
})
|
||||
.await?;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EmbeddingProvider for Gemini {
|
||||
fn model_id(&self) -> String {
|
||||
format!("gemini/{}", self.embed_model.as_deref().unwrap_or_default())
|
||||
}
|
||||
|
||||
fn known_dims(&self) -> Option<usize> {
|
||||
self.embed_dims
|
||||
.or_else(|| self.embed_model.as_deref().and_then(known_embed_dims))
|
||||
}
|
||||
|
||||
async fn embed(&self, texts: &[String], cancel: &CancellationToken) -> Result<EmbedResponse> {
|
||||
let model = self
|
||||
.embed_model
|
||||
.as_deref()
|
||||
.ok_or_else(|| Error::Config("no embed_model configured".into()))?;
|
||||
let url = format!("{}/models/{model}:batchEmbedContents", self.base);
|
||||
let mut out = EmbedResponse::default();
|
||||
for batch in texts.chunks(EMBED_BATCH) {
|
||||
let requests: Vec<Value> = batch
|
||||
.iter()
|
||||
.map(|t| json!({"model": format!("models/{model}"), "content": {"parts": [{"text": t}]}}))
|
||||
.collect();
|
||||
let body = json!({"requests": requests});
|
||||
let resp = self
|
||||
.http
|
||||
.post_json(&url, &self.headers(), &body, cancel)
|
||||
.await?;
|
||||
let v: Value = resp.json().await.map_err(|e| Error::Parse(e.to_string()))?;
|
||||
let rows = v["embeddings"]
|
||||
.as_array()
|
||||
.ok_or_else(|| Error::Parse("missing `embeddings` in response".into()))?;
|
||||
if rows.len() != batch.len() {
|
||||
return Err(Error::Parse(format!(
|
||||
"expected {} embeddings, got {}",
|
||||
batch.len(),
|
||||
rows.len()
|
||||
)));
|
||||
}
|
||||
for r in rows {
|
||||
out.vectors.push(
|
||||
r["values"]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_f64())
|
||||
.map(|x| x as f32)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
mod anthropic;
|
||||
mod gemini;
|
||||
mod openai;
|
||||
|
||||
pub use anthropic::Anthropic;
|
||||
pub use gemini::Gemini;
|
||||
pub use openai::OpenAi;
|
||||
|
||||
/// Embedding batch size per request.
|
||||
pub(crate) const EMBED_BATCH: usize = 96;
|
||||
|
||||
/// Vector sizes of well-known embedding models.
|
||||
pub(crate) fn known_embed_dims(model: &str) -> Option<usize> {
|
||||
Some(match model {
|
||||
"text-embedding-3-small" | "text-embedding-ada-002" => 1536,
|
||||
"text-embedding-3-large" | "gemini-embedding-001" => 3072,
|
||||
"text-embedding-004" | "nomic-embed-text" => 768,
|
||||
"mxbai-embed-large" | "bge-large" => 1024,
|
||||
"all-minilm" => 384,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
//! OpenAI Chat Completions + Embeddings; also serves any OpenAI-compatible endpoint
|
||||
//! (Ollama, LM Studio, OpenRouter, Mistral, Voyage…).
|
||||
|
||||
use async_trait::async_trait;
|
||||
use serde_json::{Value, json};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{EMBED_BATCH, known_embed_dims};
|
||||
use crate::config::{ProviderConfig, ProviderKind};
|
||||
use crate::error::{Error, Result};
|
||||
use crate::http::{Http, for_each_sse};
|
||||
use crate::keys::Secret;
|
||||
use crate::provider::{ChatProvider, EmbeddingProvider};
|
||||
use crate::types::{ChatRequest, ChatResponse, EmbedResponse, Role, TokenSink, Usage};
|
||||
|
||||
pub struct OpenAi {
|
||||
http: Http,
|
||||
base: String,
|
||||
key: Option<Secret>,
|
||||
kind: ProviderKind,
|
||||
model: String,
|
||||
embed_model: Option<String>,
|
||||
embed_dims: Option<usize>,
|
||||
max_tokens: u32,
|
||||
temperature: Option<f32>,
|
||||
}
|
||||
|
||||
impl OpenAi {
|
||||
pub fn new(cfg: &ProviderConfig, key: Option<Secret>) -> Result<Self> {
|
||||
Ok(Self {
|
||||
http: Http::new(cfg)?,
|
||||
base: cfg.base_url(),
|
||||
key,
|
||||
kind: cfg.kind,
|
||||
model: cfg.model.clone(),
|
||||
embed_model: cfg.embed_model.clone(),
|
||||
embed_dims: cfg.embed_dims,
|
||||
max_tokens: cfg.max_tokens,
|
||||
temperature: cfg.temperature,
|
||||
})
|
||||
}
|
||||
|
||||
fn headers(&self) -> Vec<(&'static str, String)> {
|
||||
self.key
|
||||
.iter()
|
||||
.map(|k| ("authorization", format!("Bearer {}", k.expose())))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn body(&self, req: &ChatRequest) -> Value {
|
||||
let mut messages = Vec::new();
|
||||
if let Some(s) = &req.system {
|
||||
messages.push(json!({"role": "system", "content": s}));
|
||||
}
|
||||
for m in &req.messages {
|
||||
let role = if m.role == Role::User {
|
||||
"user"
|
||||
} else {
|
||||
"assistant"
|
||||
};
|
||||
messages.push(json!({"role": role, "content": m.content}));
|
||||
}
|
||||
let max = req.max_tokens.unwrap_or(self.max_tokens);
|
||||
let mut body = json!({
|
||||
"model": self.model,
|
||||
"messages": messages,
|
||||
"stream": true,
|
||||
"stream_options": {"include_usage": true},
|
||||
});
|
||||
// OpenAI's newer models reject `max_tokens`; compatible servers only know that one.
|
||||
let key = if self.kind == ProviderKind::OpenAi {
|
||||
"max_completion_tokens"
|
||||
} else {
|
||||
"max_tokens"
|
||||
};
|
||||
body[key] = json!(max);
|
||||
if let Some(t) = self.temperature {
|
||||
body["temperature"] = json!(t);
|
||||
}
|
||||
if req.json {
|
||||
body["response_format"] = json!({"type": "json_object"});
|
||||
}
|
||||
body
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ChatProvider for OpenAi {
|
||||
async fn chat(
|
||||
&self,
|
||||
req: &ChatRequest,
|
||||
mut sink: Option<TokenSink<'_>>,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<ChatResponse> {
|
||||
let url = format!("{}/chat/completions", self.base);
|
||||
let resp = self
|
||||
.http
|
||||
.post_json(&url, &self.headers(), &self.body(req), cancel)
|
||||
.await?;
|
||||
let mut out = ChatResponse::default();
|
||||
for_each_sse(resp, cancel, |ev| {
|
||||
if ev.data.trim() == "[DONE]" {
|
||||
return Ok(false);
|
||||
}
|
||||
let v: Value =
|
||||
serde_json::from_str(&ev.data).map_err(|e| Error::Parse(e.to_string()))?;
|
||||
if let Some(msg) = v["error"]["message"].as_str() {
|
||||
return Err(Error::Api {
|
||||
status: 500,
|
||||
message: msg.to_string(),
|
||||
retry_after: None,
|
||||
});
|
||||
}
|
||||
if let Some(t) = v["choices"][0]["delta"]["content"]
|
||||
.as_str()
|
||||
.filter(|t| !t.is_empty())
|
||||
{
|
||||
out.text.push_str(t);
|
||||
if let Some(s) = sink.as_mut() {
|
||||
s(t);
|
||||
}
|
||||
}
|
||||
if let Some(r) = v["choices"][0]["finish_reason"].as_str() {
|
||||
out.stop_reason = Some(r.to_string());
|
||||
}
|
||||
if let Some(u) = v.get("usage").filter(|u| u.is_object()) {
|
||||
out.usage = Usage {
|
||||
input_tokens: u["prompt_tokens"].as_u64().unwrap_or(0),
|
||||
output_tokens: u["completion_tokens"].as_u64().unwrap_or(0),
|
||||
};
|
||||
}
|
||||
Ok(true)
|
||||
})
|
||||
.await?;
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EmbeddingProvider for OpenAi {
|
||||
fn model_id(&self) -> String {
|
||||
let p = match self.kind {
|
||||
ProviderKind::OpenAi => "openai",
|
||||
_ => "openai-compatible",
|
||||
};
|
||||
format!("{p}/{}", self.embed_model.as_deref().unwrap_or_default())
|
||||
}
|
||||
|
||||
fn known_dims(&self) -> Option<usize> {
|
||||
self.embed_dims
|
||||
.or_else(|| self.embed_model.as_deref().and_then(known_embed_dims))
|
||||
}
|
||||
|
||||
async fn embed(&self, texts: &[String], cancel: &CancellationToken) -> Result<EmbedResponse> {
|
||||
let model = self
|
||||
.embed_model
|
||||
.as_deref()
|
||||
.ok_or_else(|| Error::Config("no embed_model configured".into()))?;
|
||||
let url = format!("{}/embeddings", self.base);
|
||||
let mut out = EmbedResponse::default();
|
||||
for batch in texts.chunks(EMBED_BATCH) {
|
||||
let body = json!({"model": model, "input": batch});
|
||||
let resp = self
|
||||
.http
|
||||
.post_json(&url, &self.headers(), &body, cancel)
|
||||
.await?;
|
||||
let v: Value = resp.json().await.map_err(|e| Error::Parse(e.to_string()))?;
|
||||
let mut rows: Vec<(u64, Vec<f32>)> = v["data"]
|
||||
.as_array()
|
||||
.ok_or_else(|| Error::Parse("missing `data` in embeddings response".into()))?
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, d)| {
|
||||
let idx = d["index"].as_u64().unwrap_or(i as u64);
|
||||
let vec = d["embedding"]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.filter_map(|x| x.as_f64())
|
||||
.map(|x| x as f32)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
(idx, vec)
|
||||
})
|
||||
.collect();
|
||||
if rows.len() != batch.len() {
|
||||
return Err(Error::Parse(format!(
|
||||
"expected {} embeddings, got {}",
|
||||
batch.len(),
|
||||
rows.len()
|
||||
)));
|
||||
}
|
||||
rows.sort_by_key(|r| r.0);
|
||||
out.vectors.extend(rows.into_iter().map(|r| r.1));
|
||||
out.usage.input_tokens += v["usage"]["prompt_tokens"].as_u64().unwrap_or(0);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user