use crate::prompt::PromptBlock;
use crate::provider::ApiType;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::{Arc, Mutex};
use tokio_util::sync::CancellationToken;
mod metering;
pub use metering::OnSpent;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ThinkingMode {
Auto,
Off,
On,
OnBudget(u32),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Effort {
Low,
Medium,
High,
Xhigh,
Max,
}
#[async_trait]
pub trait Model: Send + Sync {
fn api_type(&self) -> ApiType;
fn provenance(&self) -> Option<String> {
None
}
async fn stream(
&self,
prompt_blocks: Vec<PromptBlock>,
tools: Vec<ToolDef>,
messages: Vec<ModelMessage>,
params: StreamParams,
cancel: CancellationToken,
) -> Result<ModelStream, ModelError>;
}
#[derive(Debug, Clone)]
pub struct StreamParams {
pub model: String,
pub max_tokens: u32,
pub thinking_mode: ThinkingMode,
pub effort: Option<Effort>,
pub cache_edits: Vec<String>,
pub origin: Option<CallOrigin>,
pub input_map: Option<InputMap>,
pub provider_search: Option<ProviderSearch>,
pub usage_tap: UsageTap,
}
#[derive(Clone, Default)]
pub struct UsageTap {
reported: Option<Arc<Mutex<Option<Usage>>>>,
charge: Option<Arc<crate::interface::budget_policy::SpendNode>>,
}
impl UsageTap {
pub fn new() -> Self {
Self {
reported: Some(Arc::default()),
charge: None,
}
}
pub fn charging(node: Arc<crate::interface::budget_policy::SpendNode>) -> Self {
Self {
reported: None,
charge: Some(node),
}
}
pub fn for_attempt(&self) -> Self {
Self {
charge: self.charge.clone(),
..Self::new()
}
}
pub fn charge(&self) -> Option<&Arc<crate::interface::budget_policy::SpendNode>> {
self.charge.as_ref()
}
pub fn report(&self, usage: Usage) {
if let Some(slot) = &self.reported {
*slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(usage);
}
}
pub fn reported(&self) -> Option<Usage> {
self.reported
.as_ref()
.and_then(|slot| *slot.lock().unwrap_or_else(|e| e.into_inner()))
}
}
impl std::fmt::Debug for UsageTap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UsageTap")
.field("reported", &self.reported())
.field("charged", &self.charge.is_some())
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProviderSearch {
pub max_uses: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SearchHit {
pub title: String,
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InputMap {
pub user_message: usize,
pub spans: Vec<InputSpan>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InputSpan {
pub source: String,
pub block: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub range: Option<(usize, usize)>,
}
pub mod input_source {
pub const USER_PROMPT: &str = "user_prompt";
pub const MCP_RESOURCE: &str = "mcp_resource";
pub const ATTACHMENT: &str = "attachment";
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallOrigin {
pub session_id: String,
pub parent_session_id: Option<String>,
pub agent_type: Option<String>,
pub turn_id: Option<String>,
pub kind: CallKind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CallKind {
Turn {
turn: u32,
step: u32,
},
Auxiliary { purpose: String },
}
impl CallOrigin {
pub fn turn(session_id: impl Into<String>, turn: u32, step: u32) -> Self {
Self {
session_id: session_id.into(),
parent_session_id: None,
agent_type: None,
turn_id: None,
kind: CallKind::Turn { turn, step },
}
}
pub fn auxiliary(session_id: impl Into<String>, purpose: impl Into<String>) -> Self {
Self {
session_id: session_id.into(),
parent_session_id: None,
agent_type: None,
turn_id: None,
kind: CallKind::Auxiliary {
purpose: purpose.into(),
},
}
}
pub fn with_lineage(
mut self,
parent_session_id: Option<String>,
agent_type: Option<String>,
) -> Self {
self.parent_session_id = parent_session_id;
self.agent_type = agent_type;
self
}
pub fn with_turn_id(mut self, turn_id: impl Into<String>) -> Self {
self.turn_id = Some(turn_id.into());
self
}
pub fn turn_step(&self) -> (u32, u32) {
match &self.kind {
CallKind::Turn { turn, step } => (*turn, *step),
CallKind::Auxiliary { .. } => (0, 0),
}
}
pub fn purpose(&self) -> Option<&str> {
match &self.kind {
CallKind::Turn { .. } => None,
CallKind::Auxiliary { purpose } => Some(purpose),
}
}
}
pub mod call_purpose {
pub const COMPACT: &str = "compact";
pub const MEMORY: &str = "memory";
pub const TITLE: &str = "title";
pub const HOOK: &str = "hook";
pub const TEAM_JUDGE: &str = "team_judge";
pub const WEB_SEARCH: &str = "web_search";
pub const WEB_FETCH: &str = "web_fetch";
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ToolDef {
pub name: String,
pub description: String,
pub input_schema: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
}
impl ToolDef {
pub fn new(
name: impl Into<String>,
description: impl Into<String>,
input_schema: Value,
) -> Self {
Self {
name: name.into(),
description: description.into(),
input_schema,
source: None,
}
}
pub fn with_source(mut self, source: impl Into<String>) -> Self {
self.source = Some(source.into());
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelMessage {
pub role: MessageRole,
pub content: Vec<ModelContentBlock>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageRole {
User,
Assistant,
System,
}
pub const IMAGE_TOKEN_ESTIMATE: usize = 1600;
pub fn document_token_estimate(base64_len: usize) -> usize {
(base64_len / 4 * 3 / 20).max(IMAGE_TOKEN_ESTIMATE)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ModelContentBlock {
Text {
text: String,
},
Image {
media_type: String,
data: String,
},
Document {
media_type: String,
data: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
title: Option<String>,
},
Thinking {
text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
signature: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
provider: Option<String>,
},
RedactedThinking {
data: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
provider: Option<String>,
},
ToolUse {
id: String,
name: String,
input: Value,
},
ToolResult {
tool_use_id: String,
content: String,
is_error: Option<bool>,
},
}
impl ModelContentBlock {
pub fn is_foreign_reasoning(&self, provenance: Option<&str>) -> bool {
let produced_by = match self {
ModelContentBlock::Thinking { provider, .. }
| ModelContentBlock::RedactedThinking { provider, .. } => provider.as_deref(),
_ => return false,
};
matches!((produced_by, provenance), (Some(a), Some(b)) if a != b)
}
}
pub type ModelStream =
Box<dyn futures::Stream<Item = Result<ModelEvent, ModelError>> + Send + Unpin>;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ModelEvent {
Served {
provider: String,
#[serde(default)]
model: String,
},
TextDelta {
text: String,
},
ThinkingDelta {
text: String,
},
ThinkingSignature {
signature: String,
},
RedactedThinking {
data: String,
},
ToolUseStart {
id: String,
name: String,
},
ToolUse {
id: String,
name: String,
input: Value,
},
MalformedToolUse {
id: String,
name: String,
raw_input: String,
},
ToolArgsDelta {
id: String,
partial_json: String,
},
ContentBlockStart {
index: usize,
block: ModelContentBlock,
},
ContentBlockStop {
index: usize,
},
SearchResults {
hits: Vec<SearchHit>,
},
Truncated,
EndTurn {
stop_reason: String,
usage: Usage,
},
}
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
)]
pub struct Usage {
pub input_tokens: u32,
pub output_tokens: u32,
#[serde(default)]
pub cache_creation_input_tokens: u32,
#[serde(default)]
pub cache_read_input_tokens: u32,
}
impl Usage {
pub fn plus(self, other: Usage) -> Usage {
Usage {
input_tokens: self.input_tokens.saturating_add(other.input_tokens),
output_tokens: self.output_tokens.saturating_add(other.output_tokens),
cache_creation_input_tokens: self
.cache_creation_input_tokens
.saturating_add(other.cache_creation_input_tokens),
cache_read_input_tokens: self
.cache_read_input_tokens
.saturating_add(other.cache_read_input_tokens),
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModelErrorKind {
RateLimited,
Overloaded,
Unavailable,
Transport,
Timeout,
StreamInterrupted,
ContextTooLong,
InvalidRequest,
NotFound,
Auth,
NoCredentials,
Billing,
Denied,
ServerError,
Protocol,
Cancelled,
Unsupported,
NotRecorded,
ProvidersUnavailable,
}
impl ModelErrorKind {
pub fn as_str(self) -> &'static str {
match self {
Self::RateLimited => "rate_limited",
Self::Overloaded => "overloaded",
Self::Unavailable => "unavailable",
Self::Transport => "transport",
Self::Timeout => "timeout",
Self::StreamInterrupted => "stream_interrupted",
Self::ContextTooLong => "context_too_long",
Self::InvalidRequest => "invalid_request",
Self::NotFound => "not_found",
Self::Auth => "auth",
Self::NoCredentials => "no_credentials",
Self::Billing => "billing",
Self::Denied => "denied",
Self::ServerError => "server_error",
Self::Protocol => "protocol",
Self::Cancelled => "cancelled",
Self::Unsupported => "unsupported",
Self::NotRecorded => "not_recorded",
Self::ProvidersUnavailable => "providers_unavailable",
}
}
pub fn request_failure(self) -> crate::interface::backoff::RequestFailure {
use crate::interface::backoff::RequestFailure;
match self {
Self::RateLimited => RequestFailure::RateLimited,
Self::Overloaded | Self::Unavailable => RequestFailure::Overloaded,
Self::Transport | Self::Timeout => RequestFailure::Transport,
_ => RequestFailure::Other,
}
}
pub fn transient(self) -> bool {
matches!(
self,
Self::RateLimited
| Self::Overloaded
| Self::Unavailable
| Self::Transport
| Self::Timeout
| Self::StreamInterrupted
)
}
}
impl std::fmt::Display for ModelErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelError {
pub kind: ModelErrorKind,
pub status: Option<u16>,
pub retry_after: Option<std::time::Duration>,
pub message: String,
}
impl ModelError {
pub fn new(kind: ModelErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
status: None,
retry_after: None,
message: message.into(),
}
}
pub fn with_status(mut self, status: u16) -> Self {
self.status = Some(status);
self
}
pub fn with_retry_after(mut self, retry_after: Option<std::time::Duration>) -> Self {
self.retry_after = retry_after;
self
}
pub fn cancelled() -> Self {
Self::new(ModelErrorKind::Cancelled, "")
}
pub fn rate_limited() -> Self {
Self::new(ModelErrorKind::RateLimited, "")
}
pub fn overloaded() -> Self {
Self::new(ModelErrorKind::Overloaded, "")
}
pub fn unaffordable(why: &str) -> Self {
Self::new(ModelErrorKind::InvalidRequest, format!("not sent: {why}"))
}
pub fn auth(message: impl Into<String>) -> Self {
Self::new(ModelErrorKind::Auth, message)
}
pub fn transport(message: impl Into<String>) -> Self {
Self::new(ModelErrorKind::Transport, message)
}
pub fn timeout(message: impl Into<String>) -> Self {
Self::new(ModelErrorKind::Timeout, message)
}
pub fn stream_interrupted(message: impl Into<String>) -> Self {
Self::new(ModelErrorKind::StreamInterrupted, message)
}
pub fn protocol(message: impl Into<String>) -> Self {
Self::new(ModelErrorKind::Protocol, message)
}
pub fn invalid_request(message: impl Into<String>) -> Self {
Self::new(ModelErrorKind::InvalidRequest, message)
}
pub fn unsupported(message: impl Into<String>) -> Self {
Self::new(ModelErrorKind::Unsupported, message)
}
pub fn not_recorded(message: impl Into<String>) -> Self {
Self::new(ModelErrorKind::NotRecorded, message)
}
}
impl std::fmt::Display for ModelError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.kind.as_str())?;
if let Some(status) = self.status {
write!(f, " (HTTP {status})")?;
}
if !self.message.is_empty() {
write!(f, ": {}", self.message)?;
}
Ok(())
}
}
impl std::error::Error for ModelError {}