//! Provider-agnostic LLM types and the `Provider` trait. use futures::stream::BoxStream; use serde::{Deserialize, Serialize}; use serde_json::Value; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Role { User, Assistant, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum ContentBlock { Text { text: String, }, Thinking { thinking: String, #[serde(default, skip_serializing_if = "Option::is_none")] signature: Option, }, Image { media_type: String, /// base64 data: String, }, ToolUse { id: String, name: String, input: Value, }, ToolResult { tool_use_id: String, content: String, #[serde(default)] is_error: bool, }, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Message { pub role: Role, pub content: Vec, } impl Message { pub fn user(text: impl Into) -> Self { Self { role: Role::User, content: vec![ContentBlock::Text { text: text.into() }], } } pub fn text(&self) -> String { self.content .iter() .filter_map(|b| match b { ContentBlock::Text { text } => Some(text.as_str()), _ => None, }) .collect() } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ToolSpec { pub name: String, pub description: String, /// JSON Schema object pub input_schema: Value, } #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] pub struct Usage { pub input_tokens: u64, pub output_tokens: u64, #[serde(default)] pub cache_read_tokens: u64, #[serde(default)] pub cache_write_tokens: u64, } impl Usage { pub fn add(&mut self, o: &Usage) { self.input_tokens += o.input_tokens; self.output_tokens += o.output_tokens; self.cache_read_tokens += o.cache_read_tokens; self.cache_write_tokens += o.cache_write_tokens; } /// Cost in USD given per-million-token prices. pub fn cost(&self, p: &Pricing) -> f64 { (self.input_tokens as f64 * p.input + self.output_tokens as f64 * p.output + self.cache_read_tokens as f64 * p.cache_read + self.cache_write_tokens as f64 * p.cache_write) / 1e6 } } #[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)] pub struct Pricing { pub input: f64, pub output: f64, pub cache_read: f64, pub cache_write: f64, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum StopReason { EndTurn, ToolUse, MaxTokens, Other, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Request { pub model: String, pub system: String, pub messages: Vec, pub tools: Vec, pub max_tokens: u32, } /// Incremental stream events. Providers must emit `Done` last with the full assembled message. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum StreamEvent { TextDelta { text: String, }, ThinkingDelta { text: String, }, ToolUseStart { id: String, name: String, }, Done { message: Message, stop: StopReason, usage: Usage, }, } #[derive(Debug, thiserror::Error)] pub enum Error { #[error("http: {0}")] Http(String), #[error("api {status}: {body}")] Api { status: u16, body: String }, #[error("decode: {0}")] Decode(String), } pub type Result = std::result::Result; #[async_trait::async_trait] pub trait Provider: Send + Sync { async fn stream(&self, req: Request) -> Result>>; } #[cfg(test)] mod tests { use super::*; use serde_json::json; #[test] fn round_trip() { let m = Message { role: Role::Assistant, content: vec![ ContentBlock::Text { text: "hi".into() }, ContentBlock::ToolUse { id: "t1".into(), name: "read".into(), input: json!({"path": "a"}), }, ContentBlock::ToolResult { tool_use_id: "t1".into(), content: "x".into(), is_error: false, }, ], }; let s = serde_json::to_string(&m).unwrap(); assert_eq!(serde_json::from_str::(&s).unwrap(), m); let e = StreamEvent::Done { message: m, stop: StopReason::ToolUse, usage: Usage::default(), }; let s = serde_json::to_string(&e).unwrap(); assert_eq!(serde_json::from_str::(&s).unwrap(), e); } #[test] fn cost() { let u = Usage { input_tokens: 1_000_000, output_tokens: 500_000, ..Default::default() }; let p = Pricing { input: 3.0, output: 15.0, ..Default::default() }; assert!((u.cost(&p) - 10.5).abs() < 1e-9); } }