1use std::collections::BTreeMap;
8use std::fmt;
9use std::pin::Pin;
10
11use futures::future::BoxFuture;
12use futures::{Stream, StreamExt};
13use graphrt_core::event::Usage;
14use graphrt_core::tool::ToolSpec;
15use serde::{Deserialize, Serialize};
16
17use crate::error::LlmError;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
21#[serde(rename_all = "lowercase")]
22#[non_exhaustive]
23pub enum Role {
24 System,
25 User,
26 Assistant,
27 Tool,
28}
29
30#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
32#[serde(tag = "type", rename_all = "snake_case")]
33#[non_exhaustive]
34pub enum ContentPart {
35 Text {
36 text: String,
37 },
38 Image {
40 url: String,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 detail: Option<String>,
43 },
44}
45
46#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48pub struct ToolCall {
49 pub id: String,
50 pub name: String,
51 pub arguments: String,
52}
53
54#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
56#[error("tool call `{name}` has invalid JSON arguments: {reason}")]
57pub struct InvalidToolArguments {
58 pub name: String,
60 pub reason: String,
61}
62
63impl ToolCall {
64 pub fn arguments_json(&self) -> Result<serde_json::Map<String, serde_json::Value>, InvalidToolArguments> {
68 if self.arguments.trim().is_empty() {
69 return Ok(serde_json::Map::new());
70 }
71 let invalid = |reason: String| InvalidToolArguments { name: self.name.clone(), reason };
72 match serde_json::from_str::<serde_json::Value>(&self.arguments) {
73 Ok(serde_json::Value::Object(map)) => Ok(map),
74 Ok(other) => Err(invalid(format!("expected a JSON object, got {}", json_kind(&other)))),
75 Err(e) => Err(invalid(e.to_string())),
76 }
77 }
78}
79
80fn json_kind(v: &serde_json::Value) -> &'static str {
81 match v {
82 serde_json::Value::Null => "null",
83 serde_json::Value::Bool(_) => "a boolean",
84 serde_json::Value::Number(_) => "a number",
85 serde_json::Value::String(_) => "a string",
86 serde_json::Value::Array(_) => "an array",
87 serde_json::Value::Object(_) => "an object",
88 }
89}
90
91#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
93pub struct Message {
94 pub role: Role,
95 #[serde(default)]
96 pub content: Vec<ContentPart>,
97 #[serde(default, skip_serializing_if = "Vec::is_empty")]
99 pub tool_calls: Vec<ToolCall>,
100 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub tool_call_id: Option<String>,
103 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub provider_state: Option<serde_json::Value>,
107}
108
109impl Message {
110 fn with_text(role: Role, text: impl Into<String>) -> Self {
111 Self {
112 role,
113 content: vec![ContentPart::Text { text: text.into() }],
114 tool_calls: Vec::new(),
115 tool_call_id: None,
116 provider_state: None,
117 }
118 }
119
120 pub fn system(text: impl Into<String>) -> Self {
121 Self::with_text(Role::System, text)
122 }
123
124 pub fn user(text: impl Into<String>) -> Self {
125 Self::with_text(Role::User, text)
126 }
127
128 pub fn assistant(text: impl Into<String>) -> Self {
129 Self::with_text(Role::Assistant, text)
130 }
131
132 pub fn tool(call_id: impl Into<String>, text: impl Into<String>) -> Self {
134 let mut m = Self::with_text(Role::Tool, text);
135 m.tool_call_id = Some(call_id.into());
136 m
137 }
138
139 pub fn tool_with_images(
143 call_id: impl Into<String>,
144 text: impl Into<String>,
145 image_urls: impl IntoIterator<Item = String>,
146 ) -> Self {
147 let mut m = Self::tool(call_id, text);
148 m.content.extend(image_urls.into_iter().map(|url| ContentPart::Image { url, detail: None }));
149 m
150 }
151
152 pub fn images(&self) -> impl Iterator<Item = &ContentPart> {
154 self.content.iter().filter(|p| matches!(p, ContentPart::Image { .. }))
155 }
156
157 pub fn text(&self) -> String {
159 let mut out = String::new();
160 for part in &self.content {
161 if let ContentPart::Text { text } = part {
162 out.push_str(text);
163 }
164 }
165 out
166 }
167}
168
169#[cfg(feature = "openai")]
172pub(crate) fn tool_text_with_image_note(m: &Message) -> String {
173 let text = m.text();
174 let count = m.images().count();
175 if count == 0 {
176 return text;
177 }
178 let note = if count == 1 {
179 "[1 image attached after the tool results]".to_owned()
180 } else {
181 format!("[{count} images attached after the tool results]")
182 };
183 if text.is_empty() { note } else { format!("{text}\n{note}") }
184}
185
186#[cfg(any(feature = "openai", feature = "gemini", feature = "bedrock"))]
188pub(crate) fn tool_images_intro(name: Option<&str>, call_id: &str) -> String {
189 match name {
190 Some(name) => format!("Images returned by tool `{name}` (call {call_id}):"),
191 None => format!("Images returned by tool call {call_id}:"),
192 }
193}
194
195#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(rename_all = "snake_case")]
198#[non_exhaustive]
199pub enum ToolChoice {
200 Auto,
201 None,
202 Required,
204 Tool(String),
206}
207
208#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
210#[serde(tag = "type", rename_all = "snake_case")]
211#[non_exhaustive]
212pub enum ResponseFormat {
213 Text,
214 JsonObject,
215 JsonSchema {
216 name: String,
217 schema: serde_json::Value,
218 #[serde(default)]
219 strict: bool,
220 },
221}
222
223#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
225pub struct ChatRequest {
226 pub model: String,
227 pub messages: Vec<Message>,
228 #[serde(default, skip_serializing_if = "Vec::is_empty")]
229 pub tools: Vec<ToolSpec>,
230 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub tool_choice: Option<ToolChoice>,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
233 pub temperature: Option<f64>,
234 #[serde(default, skip_serializing_if = "Option::is_none")]
235 pub top_p: Option<f64>,
236 #[serde(default, skip_serializing_if = "Option::is_none")]
237 pub max_tokens: Option<u32>,
238 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub budget_max_tokens: Option<u32>,
243 #[serde(default, skip_serializing_if = "Vec::is_empty")]
244 pub stop: Vec<String>,
245 #[serde(default, skip_serializing_if = "Option::is_none")]
246 pub response_format: Option<ResponseFormat>,
247 #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
249 pub extra: serde_json::Map<String, serde_json::Value>,
250}
251
252impl ChatRequest {
253 pub fn new(model: impl Into<String>, messages: Vec<Message>) -> Self {
254 Self { model: model.into(), messages, ..Self::default() }
255 }
256
257 pub fn output_limit(&self) -> Option<u32> {
259 match (self.max_tokens, self.budget_max_tokens) {
260 (Some(asked), Some(budget)) => Some(asked.min(budget)),
261 (asked, budget) => asked.or(budget),
262 }
263 }
264
265 pub fn with_tools(mut self, tools: Vec<ToolSpec>) -> Self {
267 self.tools = tools;
268 self
269 }
270
271 pub fn with_tool_choice(mut self, choice: ToolChoice) -> Self {
273 self.tool_choice = Some(choice);
274 self
275 }
276
277 pub fn with_temperature(mut self, temperature: f64) -> Self {
278 self.temperature = Some(temperature);
279 self
280 }
281
282 pub fn with_top_p(mut self, top_p: f64) -> Self {
283 self.top_p = Some(top_p);
284 self
285 }
286
287 pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
288 self.max_tokens = Some(max_tokens);
289 self
290 }
291
292 pub fn with_stop(mut self, stop: Vec<String>) -> Self {
293 self.stop = stop;
294 self
295 }
296
297 pub fn with_response_format(mut self, format: ResponseFormat) -> Self {
298 self.response_format = Some(format);
299 self
300 }
301
302 pub fn with_extra(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
304 self.extra.insert(key.into(), value);
305 self
306 }
307}
308
309pub const RESERVED_EXTRA_KEYS: &[&str] = &["model", "messages", "stream", "stream_options", "tools", "tool_choice"];
311
312pub fn check_extra(req: &ChatRequest) -> Result<(), LlmError> {
315 for key in req.extra.keys() {
316 if RESERVED_EXTRA_KEYS.contains(&key.as_str()) {
317 return Err(LlmError::Config(format!(
318 "parameter `{key}` cannot be set through extra parameters; use the dedicated request field"
319 )));
320 }
321 }
322 Ok(())
323}
324
325#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
327#[serde(rename_all = "snake_case")]
328#[non_exhaustive]
329pub enum FinishReason {
330 Stop,
331 Length,
332 ToolCalls,
333 ContentFilter,
334 Other(String),
335}
336
337impl FinishReason {
338 pub fn as_str(&self) -> &str {
340 match self {
341 FinishReason::Stop => "stop",
342 FinishReason::Length => "length",
343 FinishReason::ToolCalls => "tool_calls",
344 FinishReason::ContentFilter => "content_filter",
345 FinishReason::Other(s) => s,
346 }
347 }
348}
349
350#[derive(Clone, Debug, PartialEq)]
352#[non_exhaustive]
353pub enum ChatDelta {
354 Text(String),
356 Reasoning(String),
358 ToolCall {
361 index: usize,
362 id: Option<String>,
363 name: Option<String>,
364 arguments: String,
365 },
366 Usage(Usage),
368 Finish(FinishReason),
369 ProviderState(serde_json::Value),
371 Warning(String),
374}
375
376pub type ChatStream = Pin<Box<dyn Stream<Item = Result<ChatDelta, LlmError>> + Send>>;
378
379pub trait ChatModel: Send + Sync + fmt::Debug {
381 fn chat(&self, request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>>;
383
384 fn default_max_tokens(&self) -> Option<u32> {
388 None
389 }
390}
391
392#[derive(Clone, Debug, Default, PartialEq)]
394pub struct ChatResponse {
395 pub text: String,
396 pub reasoning: String,
397 pub tool_calls: Vec<ToolCall>,
398 pub usage: Usage,
399 pub finish_reason: Option<FinishReason>,
400 pub provider_state: Option<serde_json::Value>,
401 pub warnings: Vec<String>,
403}
404
405impl ChatResponse {
406 pub fn to_message(&self) -> Message {
408 let content =
409 if self.text.is_empty() { Vec::new() } else { vec![ContentPart::Text { text: self.text.clone() }] };
410 Message {
411 role: Role::Assistant,
412 content,
413 tool_calls: self.tool_calls.clone(),
414 tool_call_id: None,
415 provider_state: self.provider_state.clone(),
416 }
417 }
418}
419
420#[derive(Default)]
421struct PartialCall {
422 id: Option<String>,
423 name: String,
424 arguments: String,
425}
426
427pub async fn collect(mut stream: ChatStream, mut on_delta: impl FnMut(ChatDelta)) -> Result<ChatResponse, LlmError> {
458 let mut response = ChatResponse::default();
459 let mut calls: BTreeMap<usize, PartialCall> = BTreeMap::new();
460 while let Some(delta) = stream.next().await {
461 let delta = delta?;
462 match &delta {
465 ChatDelta::Text(t) => response.text.push_str(t),
466 ChatDelta::Reasoning(t) => response.reasoning.push_str(t),
467 ChatDelta::ToolCall { index, id, name, arguments } => {
468 let call = calls.entry(*index).or_default();
469 if let Some(id) = id.as_ref().filter(|s| !s.is_empty()) {
470 call.id = Some(id.clone());
471 }
472 if let Some(name) = name.as_ref().filter(|s| !s.is_empty()) {
473 call.name.clone_from(name);
474 }
475 call.arguments.push_str(arguments);
476 }
477 ChatDelta::Usage(u) => response.usage = *u,
478 ChatDelta::Finish(r) => response.finish_reason = Some(r.clone()),
479 ChatDelta::ProviderState(s) => response.provider_state = Some(s.clone()),
480 ChatDelta::Warning(w) => response.warnings.push(w.clone()),
481 }
482 on_delta(delta);
483 }
484 let mut tool_calls = Vec::with_capacity(calls.len());
485 for (index, call) in calls {
486 if call.name.is_empty() {
487 if call.id.is_none() && call.arguments.trim().is_empty() {
488 continue;
490 }
491 return Err(LlmError::Decode(format!("tool call #{index} has arguments or an id but no name")));
492 }
493 tool_calls.push(ToolCall {
494 id: call.id.unwrap_or_else(|| format!("call_{index}")),
495 name: call.name,
496 arguments: call.arguments,
497 });
498 }
499 response.tool_calls = tool_calls;
500 if response.usage.total_tokens == 0 {
501 response.usage.total_tokens = response.usage.prompt_tokens.saturating_add(response.usage.completion_tokens);
502 }
503 Ok(response)
504}
505
506#[cfg(test)]
507mod tests {
508 use super::*;
509
510 #[cfg(feature = "replay")]
511 #[test]
512 fn the_budget_left_never_changes_which_recording_is_replayed() {
513 let request = ChatRequest::new("m", vec![Message::user("hi")]);
514 let mut capped = request.clone();
515 capped.budget_max_tokens = Some(300);
516 assert_eq!(crate::replay::cassette_key(&request).ok(), crate::replay::cassette_key(&capped).ok());
517 }
518
519 #[test]
520 fn the_budget_lowers_an_output_limit_and_never_raises_one() {
521 let mut request = ChatRequest::new("m", Vec::new());
522 assert_eq!(request.output_limit(), None);
523 request.budget_max_tokens = Some(300);
524 assert_eq!(request.output_limit(), Some(300));
525 request.max_tokens = Some(100);
527 assert_eq!(request.output_limit(), Some(100));
528 request.max_tokens = Some(1024);
529 assert_eq!(request.output_limit(), Some(300));
530 }
531
532 fn stream(deltas: Vec<ChatDelta>) -> ChatStream {
533 Box::pin(futures::stream::iter(deltas.into_iter().map(Ok)))
534 }
535
536 #[tokio::test]
537 async fn interleaved_parallel_tool_calls_assemble_by_index() {
538 let deltas = vec![
539 ChatDelta::ToolCall {
540 index: 0,
541 id: Some("a".into()),
542 name: Some("search".into()),
543 arguments: "{\"q\":".into(),
544 },
545 ChatDelta::ToolCall {
546 index: 1,
547 id: Some("b".into()),
548 name: Some("fetch".into()),
549 arguments: "{\"url\":".into(),
550 },
551 ChatDelta::ToolCall { index: 0, id: None, name: None, arguments: "\"rust\"}".into() },
552 ChatDelta::ToolCall { index: 1, id: None, name: None, arguments: "\"x\"}".into() },
553 ChatDelta::Usage(Usage { prompt_tokens: 3, completion_tokens: 4, total_tokens: 0 }),
554 ChatDelta::Finish(FinishReason::ToolCalls),
555 ];
556 let r = collect(stream(deltas), |_| {}).await.unwrap();
557 assert_eq!(r.tool_calls.len(), 2);
558 assert_eq!(r.tool_calls[0].arguments, "{\"q\":\"rust\"}");
559 assert_eq!(r.tool_calls[1].id, "b");
560 assert_eq!(r.tool_calls[1].arguments_json().unwrap()["url"], "x");
561 assert_eq!(r.usage.total_tokens, 7);
562 assert_eq!(r.finish_reason, Some(FinishReason::ToolCalls));
563 }
564
565 #[tokio::test]
566 async fn nameless_tool_call_is_an_error() {
567 let deltas = vec![ChatDelta::ToolCall { index: 0, id: Some("a".into()), name: None, arguments: "{}".into() }];
568 let err = collect(stream(deltas), |_| {}).await.unwrap_err();
569 assert!(matches!(err, LlmError::Decode(_)), "{err:?}");
570 let deltas = vec![ChatDelta::ToolCall { index: 0, id: None, name: None, arguments: String::new() }];
572 assert!(collect(stream(deltas), |_| {}).await.unwrap().tool_calls.is_empty());
573 }
574
575 #[test]
576 fn arguments_json_rejects_malformed_input() {
577 let call = |args: &str| ToolCall { id: "1".into(), name: "t".into(), arguments: args.into() };
578 assert!(call("").arguments_json().unwrap().is_empty());
579 assert_eq!(call("{\"a\":1}").arguments_json().unwrap()["a"], 1);
580 assert!(call("{\"a\":").arguments_json().is_err());
581 let err = call("[1]").arguments_json().unwrap_err();
582 assert!(err.to_string().contains("an array"), "{err}");
583 }
584
585 #[test]
586 fn reserved_extra_keys_are_rejected() {
587 let req = ChatRequest::new("m", vec![]).with_extra("stream", serde_json::json!(false));
588 assert!(matches!(check_extra(&req), Err(LlmError::Config(_))));
589 let req = ChatRequest::new("m", vec![]).with_extra("seed", serde_json::json!(1)).with_temperature(0.1);
590 assert!(check_extra(&req).is_ok());
591 assert_eq!(req.temperature, Some(0.1));
592 }
593
594 #[cfg(feature = "openai")]
595 #[test]
596 fn tool_messages_with_images() {
597 let m = Message::tool_with_images("c1", "shot", ["data:image/png;base64,AAAA".to_owned()]);
598 assert_eq!(m.text(), "shot");
599 assert_eq!(m.images().count(), 1);
600 assert_eq!(tool_text_with_image_note(&m), "shot\n[1 image attached after the tool results]");
601 let m = Message::tool_with_images("c1", "", vec!["https://x/a.png".to_owned(); 2]);
602 assert_eq!(tool_text_with_image_note(&m), "[2 images attached after the tool results]");
603 assert_eq!(tool_text_with_image_note(&Message::tool("c1", "plain")), "plain");
604 assert_eq!(tool_images_intro(Some("screenshot"), "c1"), "Images returned by tool `screenshot` (call c1):");
605 }
606
607 #[tokio::test]
608 async fn text_and_reasoning_accumulate() {
609 let deltas =
610 vec![ChatDelta::Reasoning("hm".into()), ChatDelta::Text("he".into()), ChatDelta::Text("llo".into())];
611 let mut seen = 0;
612 let r = collect(stream(deltas), |_| seen += 1).await.unwrap();
613 assert_eq!(seen, 3);
614 assert_eq!(r.text, "hello");
615 assert_eq!(r.reasoning, "hm");
616 assert!(r.tool_calls.is_empty());
617 }
618}