use std::{collections::VecDeque, sync::Arc};
use anyhow::{Result, bail};
use tracing::debug;
use super::{
Attachment, Content, ContentPart, Effort, Message, ModelSpec, ToolDefinition, ToolResult,
};
#[derive(Debug, Clone, Default)]
pub struct ChatRequest {
pub system: Arc<Vec<Arc<str>>>,
pub tools: Arc<Vec<ToolDefinition>>,
pub messages: Arc<Vec<Arc<Message>>>,
pub model: String,
pub temperature: Option<f32>,
pub max_tokens: Option<u32>,
pub stop_sequences: Option<Vec<String>>,
pub effort: Option<Effort>,
pub tool_choice: Option<ToolChoice>,
pub cache_ttl: Option<CacheTtl>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CacheTtl {
Short,
Long,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolChoice {
Required,
Tool(String),
Forbid,
}
impl ChatRequest {
pub fn new(model: impl Into<String>) -> Self {
Self { model: model.into(), ..Self::default() }
}
pub fn for_model(model: &ModelSpec) -> Self {
Self {
temperature: model.temperature,
max_tokens: model.max_tokens,
stop_sequences: model.stop_sequences.clone(),
effort: model.effort,
..Self::new(&model.id)
}
}
pub(crate) fn system_prompts(&self) -> impl Iterator<Item = &str> {
self.system.iter().map(AsRef::as_ref).filter(|s| !s.is_empty())
}
pub(crate) fn system_text(&self) -> String {
self.system_prompts().collect::<Vec<_>>().join("\n\n")
}
pub fn with_system(mut self, text: impl Into<Arc<str>>) -> Self {
Arc::make_mut(&mut self.system).push(text.into());
self
}
pub fn with_tools(mut self, tools: Vec<ToolDefinition>) -> Self {
self.tools = Arc::new(tools);
self
}
pub fn with_message(mut self, message: Message) -> Self {
Arc::make_mut(&mut self.messages).push(Arc::new(message));
self
}
pub fn with_user_text(self, text: impl Into<String>) -> Self {
self.with_message(Message::user_text(text.into()))
}
pub fn retain_newest_images(&mut self, limit: u32, reason: &str) {
let mut remaining = limit;
let mut replaced_images = 0;
for index in (0..self.messages.len()).rev() {
if let Some(content) = project_images(
&self.messages[index].content,
&mut remaining,
reason,
&mut replaced_images,
) {
let Message { role, tags, .. } = self.messages[index].as_ref();
let message = Message { role: role.clone(), content, tags: tags.clone() };
Arc::make_mut(&mut self.messages)[index] = Arc::new(message);
}
}
if replaced_images > 0 {
debug!(model = %self.model, limit, replaced_images, reason, "replaced images");
}
}
pub(crate) fn within_image_budget(mut self, max_request_images: Option<u32>) -> Self {
if let Some(limit) = max_request_images {
self.retain_newest_images(
limit,
&format!("omitted to fit provider image budget (max_request_images={limit})"),
);
}
self
}
pub(crate) fn resolved_tool_choice(&self) -> Result<Option<&ToolChoice>> {
let Some(choice) = &self.tool_choice else {
return Ok(None);
};
match choice {
ToolChoice::Forbid if self.tools.is_empty() => Ok(None),
ToolChoice::Forbid => Ok(Some(choice)),
ToolChoice::Required => {
if self.tools.is_empty() {
bail!("tool_choice requires a tool call but the request has no tools");
}
Ok(Some(choice))
}
ToolChoice::Tool(name) => {
if !self.tools.iter().any(|tool| tool.name == *name) {
bail!("tool_choice names `{name}`, which is not among the request's tools");
}
Ok(Some(choice))
}
}
}
}
fn project_images(
content: &Content,
remaining: &mut u32,
reason: &str,
replaced_images: &mut usize,
) -> Option<Content> {
let Content::Parts(parts) = content else { return None };
let mut replaced: Option<VecDeque<ContentPart>> = None;
for (index, part) in parts.iter().enumerate().rev() {
let replacement = match part {
ContentPart::Image(_) if *remaining > 0 => {
*remaining -= 1;
None
}
ContentPart::Image(image) => {
*replaced_images += 1;
let media_type = match image {
Attachment::Base64 { media_type, .. } => media_type.clone(),
Attachment::Url { url } => format!("url:{url}"),
};
Some(ContentPart::Text(format!("[Image content (type: {media_type}) {reason}]")))
}
ContentPart::ToolResult(result) => {
project_images(&result.content, remaining, reason, replaced_images).map(|content| {
ContentPart::ToolResult(ToolResult {
tool_use_id: result.tool_use_id.clone(),
content,
is_error: result.is_error,
})
})
}
_ => None,
};
if let Some(replacement) = replacement {
replaced
.get_or_insert_with(|| parts[index + 1..].iter().cloned().collect())
.push_front(replacement);
} else if let Some(replaced) = &mut replaced {
replaced.push_front(part.clone());
}
}
replaced.map(|parts| Content::Parts(parts.into()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn image_budget_preserves_nested_results_and_shares_unchanged_messages() {
let image = |data: &str| ContentPart::image("image/png".into(), data.into());
let omitted = |part: &ContentPart| matches!(part, ContentPart::Text(text) if text.contains("omitted by budget"));
let nested = ContentPart::ToolResult(ToolResult {
tool_use_id: "inner".into(),
is_error: true,
content: Content::Parts(vec![image("inner-old"), image("inner-new")]),
});
let original = ChatRequest {
messages: Arc::new(vec![
Arc::new(Message::user(Content::Parts(vec![image("oldest")]))),
Arc::new(Message::user(Content::Parts(vec![ContentPart::ToolResult(
ToolResult::ok(
"outer".into(),
Content::Parts(vec![
ContentPart::Text("before".into()),
nested,
image("last"),
]),
),
)]))),
Arc::new(Message::user_text("after".into())),
]),
..Default::default()
};
let mut request = original.clone();
request.retain_newest_images(2, "omitted by budget");
assert!(omitted(&request.messages[0].content.parts()[0]));
assert!(Arc::ptr_eq(&request.messages[2], &original.messages[2]));
let ContentPart::ToolResult(outer) = &request.messages[1].content.parts()[0] else {
panic!("outer result must survive");
};
assert_eq!(outer.tool_use_id, "outer");
assert!(!outer.is_error);
assert_eq!(outer.content.parts()[0], ContentPart::Text("before".into()));
assert_eq!(outer.content.parts()[2], image("last"));
let ContentPart::ToolResult(inner) = &outer.content.parts()[1] else {
panic!("inner result must survive");
};
assert_eq!(inner.tool_use_id, "inner");
assert!(inner.is_error);
assert!(omitted(&inner.content.parts()[0]));
assert_eq!(inner.content.parts()[1], image("inner-new"));
let already_projected = Arc::clone(&request.messages);
request.retain_newest_images(2, "omitted by budget");
assert!(Arc::ptr_eq(&request.messages, &already_projected));
let mut unlimited = original.clone();
unlimited.retain_newest_images(u32::MAX, "omitted by budget");
assert!(Arc::ptr_eq(&unlimited.messages, &original.messages));
}
fn with_tools(tools: Vec<ToolDefinition>, tool_choice: Option<ToolChoice>) -> ChatRequest {
ChatRequest { tools: Arc::new(tools), tool_choice, ..ChatRequest::default() }
}
#[test]
fn system_helpers_skip_blank_sections() {
let request = ChatRequest {
system: Arc::new(vec!["a".into(), "".into(), "b".into()]),
..ChatRequest::default()
};
assert_eq!(request.system_prompts().collect::<Vec<_>>(), ["a", "b"]);
assert_eq!(request.system_text(), "a\n\nb");
}
#[test]
fn forced_calls_need_matching_tools() {
let error =
with_tools(vec![], Some(ToolChoice::Required)).resolved_tool_choice().unwrap_err();
assert!(error.to_string().contains("no tools"), "{error}");
let error =
with_tools(vec![ToolDefinition::stub("grep")], Some(ToolChoice::Tool("read".into())))
.resolved_tool_choice()
.unwrap_err();
assert!(error.to_string().contains("`read`"), "{error}");
}
}