Files
hx/crates/hx-ai/src/lib.rs
T

369 lines
9.7 KiB
Rust

//! Provider-agnostic LLM types and the `Provider` trait.
pub mod anthropic;
pub mod auth;
pub mod claude_cli;
pub mod codex;
pub mod models;
pub mod openai_compat;
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,
}
/// Subscription limits reported by the provider with each response.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Quota {
/// Time-based windows (5h, 7d, …).
pub windows: Vec<QuotaWindow>,
/// Credit / extra-usage state for credit-based billing, human readable.
pub credits: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QuotaWindow {
pub label: String,
pub used_pct: f64,
/// Unix seconds when the window resets.
pub resets_at: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StopReason {
EndTurn,
ToolUse,
MaxTokens,
Other,
}
/// How hard the model thinks before answering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Effort {
Off,
Low,
#[default]
Medium,
High,
}
impl Effort {
pub const ALL: [Effort; 4] = [Effort::Off, Effort::Low, Effort::Medium, Effort::High];
/// Start level per provider: Claude thinks only when asked (token cost), Codex always reasons.
pub fn default_for(k: auth::Kind) -> Self {
match k {
auth::Kind::Claude => Effort::Off,
auth::Kind::Codex => Effort::Medium,
auth::Kind::Custom => Effort::Off,
}
}
/// Levels the provider supports (Codex models can't switch reasoning off).
pub fn levels(k: auth::Kind) -> &'static [Effort] {
match k {
auth::Kind::Claude | auth::Kind::Custom => &Self::ALL,
auth::Kind::Codex => &Self::ALL[1..],
}
}
/// Next level in `levels(k)`, wrapping; a level the provider lacks maps to its first.
pub fn next(self, k: auth::Kind) -> Self {
let l = Self::levels(k);
l.iter()
.position(|&e| e == self)
.map_or(l[0], |i| l[(i + 1) % l.len()])
}
pub fn name(self) -> &'static str {
match self {
Effort::Off => "off",
Effort::Low => "low",
Effort::Medium => "medium",
Effort::High => "high",
}
}
}
#[cfg(test)]
mod effort_tests {
use super::*;
use auth::Kind;
#[test]
fn cycle_wraps_and_codex_skips_off() {
let mut e = Effort::Off;
let seen: Vec<_> = (0..5)
.map(|_| {
e = e.next(Kind::Claude);
e
})
.collect();
assert_eq!(
seen,
[
Effort::Low,
Effort::Medium,
Effort::High,
Effort::Off,
Effort::Low
]
);
assert_eq!(Effort::High.next(Kind::Codex), Effort::Low);
assert_eq!(
Effort::Off.next(Kind::Codex),
Effort::Low,
"unsupported level"
);
assert_eq!("high".parse::<Effort>(), Ok(Effort::High));
assert!("max".parse::<Effort>().is_err());
}
}
impl std::str::FromStr for Effort {
type Err = String;
fn from_str(s: &str) -> std::result::Result<Self, String> {
Self::ALL
.into_iter()
.find(|e| e.name() == s)
.ok_or_else(|| format!("unknown level {s:?} (off, low, medium, high)"))
}
}
#[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,
pub effort: Effort,
}
/// 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,
},
/// A tool the provider ran itself (`claude_cli`): raw tool name and input plus its result.
/// The agent turns it into `ToolCall` / `ToolResult` events; it is not part of the message.
ToolRun {
id: String,
name: String,
input: serde_json::Value,
content: String,
is_error: bool,
},
/// Rate-limit / credit snapshot from the response headers (sent first, when present).
Quota(Quota),
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>>>;
/// Models this account can use. Empty = unknown (callers fall back to a static list).
async fn models(&self) -> Result<Vec<models::ModelInfo>> {
Ok(vec![])
}
}
/// `Quota` first (when the response carried one), then the body events.
pub(crate) fn with_quota(
q: Option<Quota>,
s: BoxStream<'static, Result<StreamEvent>>,
) -> BoxStream<'static, Result<StreamEvent>> {
use futures::StreamExt;
futures::stream::iter(q.map(|q| Ok(StreamEvent::Quota(q))))
.chain(s)
.boxed()
}
/// Header value as &str.
pub(crate) fn hdr<'a>(h: &'a reqwest::header::HeaderMap, k: &str) -> Option<&'a str> {
h.get(k)?
.to_str()
.ok()
.map(str::trim)
.filter(|v| !v.is_empty())
}
#[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::<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);
}
}