1use crate::http::{HttpClient, HttpError, HttpRequest};
11use crate::{base64, mime};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18#[non_exhaustive]
19pub enum Role {
20 User,
22 Assistant,
24 Tool,
26}
27
28#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33#[non_exhaustive]
34pub struct Message {
35 pub role: Role,
37 pub parts: Vec<Part>,
39}
40
41impl Message {
42 pub fn new(role: Role, parts: Vec<Part>) -> Self {
44 Self { role, parts }
45 }
46
47 pub fn user(text: impl Into<String>) -> Self {
49 Self::new(Role::User, vec![Part::Text(text.into())])
50 }
51
52 pub fn assistant(text: impl Into<String>) -> Self {
54 Self::new(Role::Assistant, vec![Part::Text(text.into())])
55 }
56
57 pub fn tool_response(response: ToolResponse) -> Self {
59 Self::new(Role::Tool, vec![Part::ToolResponse(response)])
60 }
61
62 pub fn deferred_task_notifications(
66 notifications: impl IntoIterator<Item = String>,
67 ) -> Option<Self> {
68 let mut text = String::new();
69 for notification in notifications {
70 if !text.is_empty() {
71 text.push('\n');
72 }
73 text.push_str(¬ification);
74 }
75 (!text.is_empty()).then(|| Self::user(text))
76 }
77
78 pub fn text(&self) -> Option<String> {
80 joined_text(&self.parts)
81 }
82
83 pub fn tool_calls(&self) -> Vec<&ToolCall> {
85 self.parts
86 .iter()
87 .filter_map(|part| match part {
88 Part::ToolCall(call) => Some(call),
89 _ => None,
90 })
91 .collect()
92 }
93}
94
95#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[serde(tag = "type", content = "value", rename_all = "snake_case")]
98#[non_exhaustive]
99pub enum Part {
100 Text(String),
102 ToolCall(ToolCall),
104 ToolResponse(ToolResponse),
106 Reasoning(String),
108 ReasoningSignature(String),
111 Media(Media),
113 ProviderData(ProviderData),
116}
117
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120#[non_exhaustive]
121pub struct ToolCall {
122 pub id: String,
124 pub name: String,
126 pub arguments: Value,
128 #[serde(default, skip_serializing_if = "Vec::is_empty")]
130 pub(crate) signatures: Vec<String>,
131}
132
133impl ToolCall {
134 pub fn new(id: impl Into<String>, name: impl Into<String>, arguments: Value) -> Self {
136 Self {
137 id: id.into(),
138 name: name.into(),
139 arguments,
140 signatures: Vec::new(),
141 }
142 }
143
144 pub fn signatures(&self) -> &[String] {
147 &self.signatures
148 }
149
150 pub fn with_signatures(mut self, signatures: Vec<String>) -> Self {
152 self.signatures = signatures;
153 self
154 }
155}
156
157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159#[non_exhaustive]
160pub struct ToolResponse {
161 pub call_id: String,
163 pub name: String,
165 #[serde(deserialize_with = "deserialize_tool_content")]
169 pub content: Vec<Part>,
170}
171
172impl ToolResponse {
173 pub fn new(call: &ToolCall, content: impl Into<ToolOutput>) -> Self {
175 Self {
176 call_id: call.id.clone(),
177 name: call.name.clone(),
178 content: content.into().parts,
179 }
180 }
181
182 pub fn text(&self) -> Option<String> {
184 joined_text(&self.content)
185 }
186}
187
188fn deserialize_tool_content<'de, D>(deserializer: D) -> Result<Vec<Part>, D::Error>
190where
191 D: serde::Deserializer<'de>,
192{
193 #[derive(Deserialize)]
194 #[serde(untagged)]
195 enum Content {
196 Text(String),
197 Parts(Vec<Part>),
198 }
199 Ok(match Content::deserialize(deserializer)? {
200 Content::Text(text) => vec![Part::Text(text)],
201 Content::Parts(parts) => parts,
202 })
203}
204
205fn joined_text(parts: &[Part]) -> Option<String> {
207 let texts: Vec<&str> = parts
208 .iter()
209 .filter_map(|part| match part {
210 Part::Text(text) => Some(text.as_str()),
211 _ => None,
212 })
213 .collect();
214 (!texts.is_empty()).then(|| texts.concat())
215}
216
217#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
219#[non_exhaustive]
220pub struct Media {
221 pub content_type: String,
223 pub source: MediaSource,
225 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub name: Option<String>,
228}
229
230impl Media {
231 pub fn new(content_type: impl Into<String>, source: MediaSource) -> Self {
233 Self {
234 content_type: content_type.into(),
235 source,
236 name: None,
237 }
238 }
239
240 pub fn from_url(content_type: impl Into<String>, url: impl Into<String>) -> Self {
243 Self::new(content_type, MediaSource::Url(url.into()))
244 }
245
246 pub fn image_url(url: impl Into<String>) -> Self {
250 let url = url.into();
251 let content_type = mime::from_path(&url)
252 .filter(|content_type| content_type.starts_with("image/"))
253 .unwrap_or("image/jpeg");
254 Self::from_url(content_type, url)
255 }
256
257 pub fn from_bytes(content_type: impl Into<String>, bytes: impl AsRef<[u8]>) -> Self {
260 Self::from_base64(content_type, base64::encode(bytes))
261 }
262
263 pub fn from_base64(content_type: impl Into<String>, data: impl Into<String>) -> Self {
265 Self::new(content_type, MediaSource::Base64(data.into()))
266 }
267
268 pub fn with_name(mut self, name: impl Into<String>) -> Self {
270 self.name = Some(name.into());
271 self
272 }
273
274 pub fn is_image(&self) -> bool {
276 self.content_type.starts_with("image/")
277 }
278
279 pub fn extension(&self) -> &str {
281 mime::extension(&self.content_type)
282 }
283
284 pub fn file_name(&self, stem: &str) -> String {
294 mime::with_extension(self.name.as_deref().unwrap_or(stem), &self.content_type)
295 }
296
297 pub fn to_url(&self) -> String {
299 match &self.source {
300 MediaSource::Url(url) => url.clone(),
301 MediaSource::Base64(data) => format!("data:{};base64,{data}", self.content_type),
302 }
303 }
304
305 pub fn byte_len(&self) -> Option<usize> {
307 match &self.source {
308 MediaSource::Base64(data) => base64::decode(data).ok().map(|bytes| bytes.len()),
309 MediaSource::Url(_) => None,
310 }
311 }
312
313 pub async fn bytes(&self, client: &dyn HttpClient) -> Result<Vec<u8>, HttpError> {
316 match &self.source {
317 MediaSource::Base64(data) => base64::decode(data),
318 MediaSource::Url(url) => Ok(client
319 .send(HttpRequest::get(url))
320 .await?
321 .error_for_status()?
322 .body),
323 }
324 }
325}
326
327#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
329#[serde(rename_all = "snake_case")]
330pub enum MediaSource {
331 Url(String),
333 Base64(String),
335}
336
337#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
339#[non_exhaustive]
340pub struct ProviderData {
341 #[serde(default, skip_serializing_if = "Option::is_none")]
343 pub provider: Option<String>,
344 #[serde(default, skip_serializing_if = "Option::is_none")]
346 pub model: Option<String>,
347 pub data: Value,
349}
350
351impl ProviderData {
352 pub fn new(data: Value) -> Self {
354 Self {
355 provider: None,
356 model: None,
357 data,
358 }
359 }
360
361 pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
363 self.provider = Some(provider.into());
364 self
365 }
366
367 pub fn with_model(mut self, model: impl Into<String>) -> Self {
369 self.model = Some(model.into());
370 self
371 }
372}
373
374#[derive(Debug, Clone, Default, PartialEq)]
393#[non_exhaustive]
394pub struct ToolOutput {
395 pub parts: Vec<Part>,
397}
398
399impl ToolOutput {
400 pub fn from_text(text: impl Into<String>) -> Self {
402 Self::default().with_text(text)
403 }
404
405 pub fn from_media(media: Media) -> Self {
407 Self::default().with_media(media)
408 }
409
410 pub fn with_text(mut self, text: impl Into<String>) -> Self {
412 self.parts.push(Part::Text(text.into()));
413 self
414 }
415
416 pub fn with_media(mut self, media: Media) -> Self {
418 self.parts.push(Part::Media(media));
419 self
420 }
421
422 pub fn text(&self) -> Option<String> {
424 joined_text(&self.parts)
425 }
426
427 pub fn media(&self) -> Vec<&Media> {
429 self.parts
430 .iter()
431 .filter_map(|part| match part {
432 Part::Media(media) => Some(media),
433 _ => None,
434 })
435 .collect()
436 }
437}
438
439impl std::fmt::Display for ToolOutput {
441 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
442 for part in &self.parts {
443 match part {
444 Part::Text(text) => f.write_str(text)?,
445 Part::Media(media) => write!(f, "[{}]", media.content_type)?,
446 _ => {}
447 }
448 }
449 Ok(())
450 }
451}
452
453impl From<String> for ToolOutput {
454 fn from(text: String) -> Self {
455 Self::from_text(text)
456 }
457}
458
459impl From<&str> for ToolOutput {
460 fn from(text: &str) -> Self {
461 Self::from_text(text)
462 }
463}
464
465impl From<Media> for ToolOutput {
466 fn from(media: Media) -> Self {
467 Self::from_media(media)
468 }
469}
470
471#[cfg(test)]
472mod tests {
473 use super::*;
474 use serde_json::json;
475
476 fn every_part() -> Message {
477 let mut call = ToolCall::new("call_1", "echo", json!({"text": "hi"}));
478 call.signatures = vec!["sig".to_string()];
479 Message::new(
480 Role::Assistant,
481 vec![
482 Part::ReasoningSignature("signature".into()),
483 Part::Reasoning("thinking".into()),
484 Part::Text("hello".into()),
485 Part::ToolCall(call.clone()),
486 Part::ToolResponse(ToolResponse::new(&call, "result")),
487 Part::ToolResponse(ToolResponse::new(
488 &call,
489 ToolOutput::from_text("an image")
490 .with_media(Media::new("image/png", MediaSource::Base64("aGk=".into()))),
491 )),
492 Part::Media(Media::new("image/png", MediaSource::Base64("aGk=".into()))),
493 Part::Media(Media::new(
494 "image/png",
495 MediaSource::Url("https://example.com/a.png".into()),
496 )),
497 Part::ProviderData(ProviderData {
498 provider: Some("OpenRouter".into()),
499 model: Some("m".into()),
500 data: json!({"type": "reasoning.encrypted"}),
501 }),
502 ],
503 )
504 }
505
506 #[test]
507 fn messages_round_trip_through_json() {
508 let message = every_part();
509 let json = serde_json::to_string(&message).unwrap();
510 assert_eq!(serde_json::from_str::<Message>(&json).unwrap(), message);
511 }
512
513 #[test]
514 fn tool_responses_stored_before_0_5_still_load() {
515 let json = r#"{"role":"tool","parts":[{"type":"tool_response",
516 "value":{"call_id":"call_1","name":"echo","content":"result"}}]}"#;
517 let message: Message = serde_json::from_str(json).unwrap();
518 let call = ToolCall::new("call_1", "echo", json!({}));
519 assert_eq!(
520 message,
521 Message::tool_response(ToolResponse::new(&call, "result"))
522 );
523 }
524
525 #[test]
526 fn image_url_guesses_the_type_from_the_extension() {
527 let types: Vec<String> = [
528 "https://example.com/a.png",
529 "https://example.com/a.PNG?size=2#top",
530 "https://example.com/a.webp",
531 "https://example.com/a.gif",
532 "https://example.com/a.jpeg",
533 "https://example.com/image",
534 ]
535 .into_iter()
536 .map(|url| Media::image_url(url).content_type)
537 .collect();
538 assert_eq!(
539 types,
540 [
541 "image/png",
542 "image/png",
543 "image/webp",
544 "image/gif",
545 "image/jpeg",
546 "image/jpeg"
547 ]
548 );
549 assert_eq!(
550 Media::image_url("https://example.com/a.png").source,
551 MediaSource::Url("https://example.com/a.png".into())
552 );
553 }
554
555 #[test]
556 fn file_name_prefers_the_name_over_the_stem() {
557 let video = Media::from_bytes("video/mp4", b"MP4");
558 assert_eq!(video.file_name("first_frame"), "first_frame.mp4");
559 assert_eq!(video.clone().with_name("clip").file_name("x"), "clip.mp4");
560 assert_eq!(video.with_name("clip.mov").file_name("x"), "clip.mov");
561 }
562
563 #[test]
564 fn to_url_gives_the_url_or_a_data_url() {
565 assert_eq!(
566 Media::from_base64("image/png", "aGk=").to_url(),
567 "data:image/png;base64,aGk="
568 );
569 assert_eq!(
570 Media::image_url("https://example.com/a.png").to_url(),
571 "https://example.com/a.png"
572 );
573 }
574
575 #[test]
576 fn json_format_is_stable() {
577 let message = Message::user("hi");
578 assert_eq!(
579 serde_json::to_value(&message).unwrap(),
580 json!({"role": "user", "parts": [{"type": "text", "value": "hi"}]})
581 );
582 }
583}