use futures_util::Stream;
use std::collections::HashMap;
use std::pin::Pin;
use serde::{Deserialize, Serialize};
mod chat_request;
mod message;
mod schema;
mod tool_args;
pub use ante_protocol_shape::{
Effort, MISSING_TOOL_NAME, MalformedToolArgs, ModelSpec, ToolUse, Usage, WeightClass,
};
pub use chat_request::{CacheTtl, ChatRequest, ToolChoice};
pub use message::{Attachment, Content, ContentPart, Message, Role};
pub use schema::normalize_tool_schema;
pub(crate) use tool_args::{decode_tool_args, decoded_tool_use, replay_safe_tool_args};
pub(crate) fn supported_efforts_by_model(models: &[ModelSpec]) -> HashMap<String, Vec<Effort>> {
models
.iter()
.filter_map(|model| {
model.supported_efforts.as_ref().map(|supported_efforts| {
(model.id.clone(), crate::effort::normalize_levels(supported_efforts.clone()))
})
})
.collect()
}
pub const DEFAULT_STREAM_IDLE_TIMEOUT_SECS: u64 = 300;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ThinkingDisplay {
Off,
Concise,
Detailed,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolResult {
pub tool_use_id: String,
pub content: Content,
pub is_error: bool,
}
impl ToolResult {
pub fn ok(tool_use_id: String, content: Content) -> Self {
Self { tool_use_id, content, is_error: false }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
pub name: String,
pub description: Option<String>,
pub input_schema: serde_json::Value,
}
#[cfg(test)]
impl ToolDefinition {
pub(crate) fn stub(name: &str) -> Self {
Self {
name: name.to_string(),
description: None,
input_schema: serde_json::json!({ "type": "object" }),
}
}
}
#[derive(Debug, Clone)]
pub enum StreamEvent {
ThinkingDelta {
thinking: String,
signature: Option<String>,
},
TextDelta(String),
ContentPart(ContentPart),
ToolUse(ToolUse),
ContentStop,
Tag {
name: String,
value: String,
},
PrefillProgress {
total: u32,
cached: u32,
processed: u32,
},
MessageStop {
usage: Usage,
stop_reason: Option<StopReason>,
},
}
impl StreamEvent {
pub fn is_output(&self) -> bool {
match self {
StreamEvent::TextDelta(text)
| StreamEvent::ThinkingDelta { thinking: text, .. }
| StreamEvent::ContentPart(
ContentPart::Text(text) | ContentPart::Thinking { text, .. },
) => !text.is_empty(),
StreamEvent::ToolUse(tool) | StreamEvent::ContentPart(ContentPart::ToolUse(tool)) => {
tool.malformed_args.is_none()
}
_ => false,
}
}
}
pub type ChatResponseStream =
Pin<Box<dyn Stream<Item = Result<StreamEvent, crate::error::LlmError>> + Send>>;
#[derive(Debug, Clone)]
pub struct ChatResponse {
pub message: Message,
pub stop_reason: Option<StopReason>,
pub usage: Usage,
}
#[derive(Debug)]
pub struct WebSearchResult {
pub content: Content,
pub citations: Vec<WebCitation>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct WebCitation {
pub title: String,
pub uri: String,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub enum StopReason {
#[default]
EndTurn,
MaxTokens,
Refusal,
Other(String),
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn output_is_nonempty_text_or_reasoning_or_a_well_formed_tool_call() {
let tool = ToolUse::new("call", "Read", json!({}));
let mut malformed = tool.clone();
malformed.malformed_args = Some(MalformedToolArgs { raw: "{".into(), error: "EOF".into() });
for event in [
StreamEvent::TextDelta("answer".into()),
StreamEvent::ThinkingDelta { thinking: "reasoning".into(), signature: None },
StreamEvent::ToolUse(tool.clone()),
StreamEvent::ContentPart(ContentPart::Text("answer".into())),
StreamEvent::ContentPart(ContentPart::Thinking {
text: "reasoning".into(),
signature: None,
}),
StreamEvent::ContentPart(ContentPart::ToolUse(tool)),
] {
assert!(event.is_output(), "{event:?}");
}
for event in [
StreamEvent::TextDelta(String::new()),
StreamEvent::ThinkingDelta { thinking: String::new(), signature: Some("sig".into()) },
StreamEvent::ContentPart(ContentPart::RedactedThinking { data: "opaque".into() }),
StreamEvent::ToolUse(malformed),
StreamEvent::ContentStop,
StreamEvent::MessageStop { usage: Usage::default(), stop_reason: None },
] {
assert!(!event.is_output(), "{event:?}");
}
}
}