hx-ai: provider trait + shared types (#2)
This commit is contained in:
1 parent
275c00d900
commit
8d8bcfd315
3 files changed
+444
-5
No files matched your search
@@ -5,6 +5,11 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
async-trait = "0.1.92"
|
||||
futures = "0.3.34"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.151"
|
||||
thiserror = "2.0.21"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+205
-5
@@ -1,14 +1,214 @@
|
||||
pub fn add(left: u64, right: u64) -> u64 {
|
||||
left + right
|
||||
//! 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<String>,
|
||||
},
|
||||
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<ContentBlock>,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn user(text: impl Into<String>) -> 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<Message>,
|
||||
pub tools: Vec<ToolSpec>,
|
||||
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<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait Provider: Send + Sync {
|
||||
async fn stream(&self, req: Request) -> Result<BoxStream<'static, Result<StreamEvent>>>;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn it_works() {
|
||||
let result = add(2, 2);
|
||||
assert_eq!(result, 4);
|
||||
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::<Message>(&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::<StreamEvent>(&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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user