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 Failover(crate::failover::FailoverReport),
377}
378
379pub type ChatStream = Pin<Box<dyn Stream<Item = Result<ChatDelta, LlmError>> + Send>>;
381
382pub trait ChatModel: Send + Sync + fmt::Debug {
384 fn chat(&self, request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>>;
386
387 fn default_max_tokens(&self) -> Option<u32> {
391 None
392 }
393}
394
395#[derive(Clone, Debug, Default, PartialEq)]
397pub struct ChatResponse {
398 pub text: String,
399 pub reasoning: String,
400 pub tool_calls: Vec<ToolCall>,
401 pub usage: Usage,
402 pub finish_reason: Option<FinishReason>,
403 pub provider_state: Option<serde_json::Value>,
404 pub warnings: Vec<String>,
406 pub failover: Option<crate::failover::FailoverReport>,
408}
409
410impl ChatResponse {
411 pub fn to_message(&self) -> Message {
413 let content =
414 if self.text.is_empty() { Vec::new() } else { vec![ContentPart::Text { text: self.text.clone() }] };
415 Message {
416 role: Role::Assistant,
417 content,
418 tool_calls: self.tool_calls.clone(),
419 tool_call_id: None,
420 provider_state: self.provider_state.clone(),
421 }
422 }
423}
424
425#[derive(Default)]
426struct PartialCall {
427 id: Option<String>,
428 name: String,
429 arguments: String,
430}
431
432pub async fn collect(mut stream: ChatStream, mut on_delta: impl FnMut(ChatDelta)) -> Result<ChatResponse, LlmError> {
463 let mut response = ChatResponse::default();
464 let mut calls: BTreeMap<usize, PartialCall> = BTreeMap::new();
465 while let Some(delta) = stream.next().await {
466 let delta = delta?;
467 match &delta {
470 ChatDelta::Text(t) => response.text.push_str(t),
471 ChatDelta::Reasoning(t) => response.reasoning.push_str(t),
472 ChatDelta::ToolCall { index, id, name, arguments } => {
473 let call = calls.entry(*index).or_default();
474 if let Some(id) = id.as_ref().filter(|s| !s.is_empty()) {
475 call.id = Some(id.clone());
476 }
477 if let Some(name) = name.as_ref().filter(|s| !s.is_empty()) {
478 call.name.clone_from(name);
479 }
480 call.arguments.push_str(arguments);
481 }
482 ChatDelta::Usage(u) => response.usage = *u,
483 ChatDelta::Finish(r) => response.finish_reason = Some(r.clone()),
484 ChatDelta::ProviderState(s) => response.provider_state = Some(s.clone()),
485 ChatDelta::Warning(w) => response.warnings.push(w.clone()),
486 ChatDelta::Failover(report) => response.failover = Some(report.clone()),
487 }
488 on_delta(delta);
489 }
490 let mut tool_calls = Vec::with_capacity(calls.len());
491 for (index, call) in calls {
492 if call.name.is_empty() {
493 if call.id.is_none() && call.arguments.trim().is_empty() {
494 continue;
496 }
497 return Err(LlmError::Decode(format!("tool call #{index} has arguments or an id but no name")));
498 }
499 tool_calls.push(ToolCall {
500 id: call.id.unwrap_or_else(|| format!("call_{index}")),
501 name: call.name,
502 arguments: call.arguments,
503 });
504 }
505 response.tool_calls = tool_calls;
506 if response.usage.total_tokens == 0 {
507 response.usage.total_tokens = response.usage.prompt_tokens.saturating_add(response.usage.completion_tokens);
508 }
509 Ok(response)
510}
511
512#[cfg(test)]
513mod tests {
514 use super::*;
515
516 #[cfg(feature = "replay")]
517 #[test]
518 fn the_budget_left_never_changes_which_recording_is_replayed() {
519 let request = ChatRequest::new("m", vec![Message::user("hi")]);
520 let mut capped = request.clone();
521 capped.budget_max_tokens = Some(300);
522 assert_eq!(crate::replay::cassette_key(&request).ok(), crate::replay::cassette_key(&capped).ok());
523 }
524
525 #[test]
526 fn the_budget_lowers_an_output_limit_and_never_raises_one() {
527 let mut request = ChatRequest::new("m", Vec::new());
528 assert_eq!(request.output_limit(), None);
529 request.budget_max_tokens = Some(300);
530 assert_eq!(request.output_limit(), Some(300));
531 request.max_tokens = Some(100);
533 assert_eq!(request.output_limit(), Some(100));
534 request.max_tokens = Some(1024);
535 assert_eq!(request.output_limit(), Some(300));
536 }
537
538 fn stream(deltas: Vec<ChatDelta>) -> ChatStream {
539 Box::pin(futures::stream::iter(deltas.into_iter().map(Ok)))
540 }
541
542 #[tokio::test]
543 async fn interleaved_parallel_tool_calls_assemble_by_index() {
544 let deltas = vec![
545 ChatDelta::ToolCall {
546 index: 0,
547 id: Some("a".into()),
548 name: Some("search".into()),
549 arguments: "{\"q\":".into(),
550 },
551 ChatDelta::ToolCall {
552 index: 1,
553 id: Some("b".into()),
554 name: Some("fetch".into()),
555 arguments: "{\"url\":".into(),
556 },
557 ChatDelta::ToolCall { index: 0, id: None, name: None, arguments: "\"rust\"}".into() },
558 ChatDelta::ToolCall { index: 1, id: None, name: None, arguments: "\"x\"}".into() },
559 ChatDelta::Usage(Usage { prompt_tokens: 3, completion_tokens: 4, total_tokens: 0 }),
560 ChatDelta::Finish(FinishReason::ToolCalls),
561 ];
562 let r = collect(stream(deltas), |_| {}).await.unwrap();
563 assert_eq!(r.tool_calls.len(), 2);
564 assert_eq!(r.tool_calls[0].arguments, "{\"q\":\"rust\"}");
565 assert_eq!(r.tool_calls[1].id, "b");
566 assert_eq!(r.tool_calls[1].arguments_json().unwrap()["url"], "x");
567 assert_eq!(r.usage.total_tokens, 7);
568 assert_eq!(r.finish_reason, Some(FinishReason::ToolCalls));
569 }
570
571 #[tokio::test]
572 async fn nameless_tool_call_is_an_error() {
573 let deltas = vec![ChatDelta::ToolCall { index: 0, id: Some("a".into()), name: None, arguments: "{}".into() }];
574 let err = collect(stream(deltas), |_| {}).await.unwrap_err();
575 assert!(matches!(err, LlmError::Decode(_)), "{err:?}");
576 let deltas = vec![ChatDelta::ToolCall { index: 0, id: None, name: None, arguments: String::new() }];
578 assert!(collect(stream(deltas), |_| {}).await.unwrap().tool_calls.is_empty());
579 }
580
581 #[test]
582 fn arguments_json_rejects_malformed_input() {
583 let call = |args: &str| ToolCall { id: "1".into(), name: "t".into(), arguments: args.into() };
584 assert!(call("").arguments_json().unwrap().is_empty());
585 assert_eq!(call("{\"a\":1}").arguments_json().unwrap()["a"], 1);
586 assert!(call("{\"a\":").arguments_json().is_err());
587 let err = call("[1]").arguments_json().unwrap_err();
588 assert!(err.to_string().contains("an array"), "{err}");
589 }
590
591 #[test]
592 fn reserved_extra_keys_are_rejected() {
593 let req = ChatRequest::new("m", vec![]).with_extra("stream", serde_json::json!(false));
594 assert!(matches!(check_extra(&req), Err(LlmError::Config(_))));
595 let req = ChatRequest::new("m", vec![]).with_extra("seed", serde_json::json!(1)).with_temperature(0.1);
596 assert!(check_extra(&req).is_ok());
597 assert_eq!(req.temperature, Some(0.1));
598 }
599
600 #[cfg(feature = "openai")]
601 #[test]
602 fn tool_messages_with_images() {
603 let m = Message::tool_with_images("c1", "shot", ["data:image/png;base64,AAAA".to_owned()]);
604 assert_eq!(m.text(), "shot");
605 assert_eq!(m.images().count(), 1);
606 assert_eq!(tool_text_with_image_note(&m), "shot\n[1 image attached after the tool results]");
607 let m = Message::tool_with_images("c1", "", vec!["https://x/a.png".to_owned(); 2]);
608 assert_eq!(tool_text_with_image_note(&m), "[2 images attached after the tool results]");
609 assert_eq!(tool_text_with_image_note(&Message::tool("c1", "plain")), "plain");
610 assert_eq!(tool_images_intro(Some("screenshot"), "c1"), "Images returned by tool `screenshot` (call c1):");
611 }
612
613 #[tokio::test]
614 async fn text_and_reasoning_accumulate() {
615 let deltas =
616 vec![ChatDelta::Reasoning("hm".into()), ChatDelta::Text("he".into()), ChatDelta::Text("llo".into())];
617 let mut seen = 0;
618 let r = collect(stream(deltas), |_| seen += 1).await.unwrap();
619 assert_eq!(seen, 3);
620 assert_eq!(r.text, "hello");
621 assert_eq!(r.reasoning, "hm");
622 assert!(r.tool_calls.is_empty());
623 }
624}