pub mod anthropic;
pub mod gemini;
pub mod openai;
use crate::request::{CompletionRequest, Delta};
use crate::sse::SseEvent;
use crate::status::{decode_error, kind_for_status};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use troupekit_core::error::{ProviderError, ProviderErrorKind};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Protocol {
#[serde(rename = "anthropic")]
Anthropic,
#[serde(rename = "openai")]
OpenAi,
#[serde(rename = "gemini")]
Gemini,
#[serde(rename = "openai_compatible")]
OpenAiCompatible,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuthStyle {
#[serde(rename = "bearer")]
Bearer,
#[serde(rename = "x-api-key")]
XApiKey,
#[serde(rename = "x-goog-api-key")]
XGoogApiKey,
#[serde(rename = "none")]
NoKey,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MaxTokensField {
#[default]
MaxTokens,
MaxCompletionTokens,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SchemaMode {
#[default]
#[serde(rename = "json_schema")]
JsonSchema,
#[serde(rename = "json_object")]
JsonObject,
#[serde(rename = "none")]
Unsupported,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Quirks {
pub max_tokens_field: MaxTokensField,
pub stream_usage: bool,
pub output_schema: SchemaMode,
pub temperature: bool,
}
impl Default for Quirks {
fn default() -> Self {
Self {
max_tokens_field: MaxTokensField::MaxTokens,
stream_usage: true,
output_schema: SchemaMode::JsonSchema,
temperature: true,
}
}
}
pub fn encode(
protocol: Protocol,
quirks: &Quirks,
model: &str,
req: &CompletionRequest,
stream: bool,
) -> Result<Value, ProviderError> {
let req = &req.sendable(protocol == Protocol::Anthropic)?;
match protocol {
Protocol::Anthropic => anthropic::encode(quirks, model, req, stream),
Protocol::OpenAi => {
let mut body = openai::encode(quirks, model, req, stream)?;
if !req.tools.is_empty() && matches!(model, "gpt-6-luna" | "gpt-6.1-terra") {
body["reasoning_effort"] = Value::from("none");
}
Ok(body)
}
Protocol::OpenAiCompatible => openai::encode(quirks, model, req, stream),
Protocol::Gemini => gemini::encode(quirks, model, req, stream),
}
}
pub fn decode_body(protocol: Protocol, body: &Value) -> Result<Vec<Delta>, ProviderError> {
match protocol {
Protocol::Anthropic => anthropic::decode_body(body),
Protocol::OpenAi | Protocol::OpenAiCompatible => openai::decode_body(body),
Protocol::Gemini => gemini::decode_body(body),
}
}
#[derive(Debug)]
pub enum Decoder {
Anthropic(anthropic::StreamDecoder),
OpenAi(openai::StreamDecoder),
Gemini(gemini::StreamDecoder),
}
impl Decoder {
pub fn new(protocol: Protocol) -> Self {
match protocol {
Protocol::Anthropic => Decoder::Anthropic(Default::default()),
Protocol::OpenAi | Protocol::OpenAiCompatible => Decoder::OpenAi(Default::default()),
Protocol::Gemini => Decoder::Gemini(Default::default()),
}
}
pub fn event(&mut self, data: &Value) -> Result<Vec<Delta>, ProviderError> {
match self {
Decoder::Anthropic(d) => d.event(data),
Decoder::OpenAi(d) => d.event(data),
Decoder::Gemini(d) => d.event(data),
}
}
pub fn sse(&mut self, event: &SseEvent) -> Result<Vec<Delta>, ProviderError> {
let data = event.data.trim();
if data.is_empty() || data == "[DONE]" {
return Ok(Vec::new());
}
let value: Value = serde_json::from_str(data)
.map_err(|e| decode_error(format!("event data is not JSON: {e}")))?;
self.event(&value)
}
}
pub(crate) fn push_turn(turns: &mut Vec<Value>, role: &str, key: &str, items: Vec<Value>) {
if items.is_empty() {
return;
}
if let Some(last) = turns.last_mut() {
if last["role"] == role {
if let Some(existing) = last[key].as_array_mut() {
existing.extend(items);
return;
}
}
}
let mut turn = Map::new();
turn.insert("role".into(), Value::from(role));
turn.insert(key.into(), Value::Array(items));
turns.push(Value::Object(turn));
}
pub(crate) fn str_at<'a>(value: &'a Value, pointer: &str) -> Option<&'a str> {
value.pointer(pointer).and_then(Value::as_str)
}
pub(crate) fn u64_at(value: &Value, pointer: &str) -> Option<u64> {
value.pointer(pointer).and_then(Value::as_u64)
}
pub(crate) fn index_at(value: &Value, pointer: &str) -> Result<u32, ProviderError> {
u64_at(value, pointer)
.and_then(|n| u32::try_from(n).ok())
.ok_or_else(|| decode_error(format!("missing or bad index at {pointer}")))
}
pub(crate) fn position(i: usize) -> Result<u32, ProviderError> {
u32::try_from(i).map_err(|_| decode_error("too many parts in one reply"))
}
pub(crate) fn text_delta(text: Option<&str>) -> Option<Delta> {
text.filter(|t| !t.is_empty())
.map(|t| Delta::TextDelta { text: t.to_owned() })
}
pub(crate) fn error_object(error: &Value) -> ProviderError {
let kind = u64_at(error, "/code")
.and_then(|c| u16::try_from(c).ok())
.map(kind_for_status)
.unwrap_or(ProviderErrorKind::Server);
ProviderError::new(
kind,
str_at(error, "/message")
.unwrap_or("provider error")
.to_owned(),
)
}