Skip to main content

graphrt_llm/nodes/
common.rs

1//! Configuration and prompt assembly shared by the model-calling nodes.
2
3use std::sync::{Arc, LazyLock};
4
5use graphrt_core::event::Usage;
6use graphrt_core::template::{Part, Template};
7use graphrt_core::value::{FileKind, Value};
8use graphrt_core::{NodeContext, NodeError, Selector, VariablePool};
9use serde::Deserialize;
10use serde_json::Value as Json;
11
12use crate::registry::ModelRegistry;
13use crate::types::{
14    ChatDelta, ChatModel, ChatRequest, ChatResponse, ContentPart, FinishReason, Message, RESERVED_EXTRA_KEYS, Role,
15    collect,
16};
17
18/// Literal placeholder replaced by the configured context value.
19pub const CONTEXT_PLACEHOLDER: &str = "{{#context#}}";
20
21/// `model: {provider, name, completion_params}`.
22#[derive(Clone, Debug, Deserialize)]
23pub struct ModelConfig {
24    pub provider: String,
25    pub name: String,
26    #[serde(default)]
27    pub completion_params: serde_json::Map<String, Json>,
28}
29
30/// Parameters never forwarded to providers (UI-only settings).
31const IGNORED_PARAMS: &[&str] = &["mode"];
32
33/// A resolved completion parameter.
34enum Param {
35    /// Not set (explicit `null`, or an empty literal string).
36    Unset,
37    Value(Json),
38}
39
40impl ModelConfig {
41    /// Build a request for this model, applying completion parameters. Parameter
42    /// values that are templates (`"{{#start.temp#}}"`) are resolved per run;
43    /// the configuration itself is never modified.
44    ///
45    /// A parameter whose value has the wrong type (e.g. `temperature: "hot"`),
46    /// or a template that resolves to nothing, is an input error naming the
47    /// parameter instead of being dropped silently.
48    pub fn request(&self, messages: Vec<Message>, pool: &VariablePool) -> Result<ChatRequest, NodeError> {
49        let mut req = ChatRequest::new(self.name.clone(), messages);
50        for (key, raw) in &self.completion_params {
51            if IGNORED_PARAMS.contains(&key.as_str()) {
52                continue;
53            }
54            let value = match resolve_param(key, raw, pool)? {
55                Param::Unset => continue,
56                Param::Value(v) => v,
57            };
58            let bad = |expected: &str| {
59                NodeError::invalid_input(format!("completion parameter `{key}` must be {expected}, got {value}"))
60            };
61            match key.as_str() {
62                "temperature" => req.temperature = Some(value.as_f64().ok_or_else(|| bad("a number"))?),
63                "top_p" => req.top_p = Some(value.as_f64().ok_or_else(|| bad("a number"))?),
64                "max_tokens" | "max_completion_tokens" => {
65                    let n = value
66                        .as_u64()
67                        .and_then(|n| u32::try_from(n).ok())
68                        .ok_or_else(|| bad("a non-negative integer that fits in 32 bits"))?;
69                    req.max_tokens = Some(n);
70                }
71                "stop" => {
72                    req.stop = match &value {
73                        Json::String(s) => vec![s.clone()],
74                        Json::Array(items) => items
75                            .iter()
76                            .map(|i| i.as_str().map(str::to_owned))
77                            .collect::<Option<Vec<_>>>()
78                            .ok_or_else(|| bad("a string or a list of strings"))?,
79                        _ => return Err(bad("a string or a list of strings")),
80                    };
81                }
82                reserved if RESERVED_EXTRA_KEYS.contains(&reserved) => {
83                    return Err(NodeError::invalid_input(format!(
84                        "completion parameter `{key}` is managed by the node and cannot be set"
85                    )));
86                }
87                _ => {
88                    req.extra.insert(key.clone(), value);
89                }
90            }
91        }
92        Ok(req)
93    }
94
95    /// Selectors referenced by templated completion parameters.
96    pub fn selectors(&self) -> Vec<Selector> {
97        self.completion_params
98            .values()
99            .filter_map(Json::as_str)
100            .filter(|s| s.contains("{{#"))
101            .flat_map(|s| Template::parse(s).selectors().cloned().collect::<Vec<_>>())
102            .collect()
103    }
104}
105
106/// Resolve a completion parameter: templates are rendered, numeric/boolean strings coerced.
107fn resolve_param(key: &str, raw: &Json, pool: &VariablePool) -> Result<Param, NodeError> {
108    let text = match raw {
109        Json::Null => return Ok(Param::Unset),
110        Json::String(s) => s,
111        other => return Ok(Param::Value(other.clone())),
112    };
113    let is_template = text.contains("{{#");
114    let resolved = if is_template { Template::parse(text).resolve(pool) } else { Value::from(text.as_str()) };
115    match resolved {
116        Value::String(s) => {
117            let t = s.trim();
118            if t.is_empty() {
119                if is_template {
120                    return Err(NodeError::invalid_input(format!(
121                        "completion parameter `{key}` resolved to an empty value (`{text}`)"
122                    )));
123                }
124                return Ok(Param::Unset);
125            }
126            Ok(Param::Value(if let Ok(i) = t.parse::<i64>() {
127                Json::from(i)
128            } else if let Ok(f) = t.parse::<f64>() {
129                Json::from(f)
130            } else if t == "true" || t == "false" {
131                Json::Bool(t == "true")
132            } else {
133                Json::String(s.to_string())
134            }))
135        }
136        Value::Null => Err(NodeError::invalid_input(format!(
137            "completion parameter `{key}` references a missing variable (`{text}`)"
138        ))),
139        other => Ok(Param::Value(other.to_json())),
140    }
141}
142
143/// One prompt message template.
144#[derive(Clone, Debug, Deserialize)]
145pub struct PromptMessage {
146    #[serde(default = "user_role")]
147    pub role: Role,
148    #[serde(default)]
149    pub text: Template,
150}
151
152fn user_role() -> Role {
153    Role::User
154}
155
156/// `prompt_template`: a list of chat messages, or a single completion prompt.
157#[derive(Clone, Debug, Deserialize)]
158#[serde(untagged)]
159pub enum PromptTemplate {
160    Chat(Vec<PromptMessage>),
161    Completion(PromptMessage),
162}
163
164impl Default for PromptTemplate {
165    fn default() -> Self {
166        PromptTemplate::Chat(Vec::new())
167    }
168}
169
170impl PromptTemplate {
171    pub fn messages(&self) -> &[PromptMessage] {
172        match self {
173            PromptTemplate::Chat(m) => m,
174            PromptTemplate::Completion(m) => std::slice::from_ref(m),
175        }
176    }
177
178    /// Selectors referenced by the message templates.
179    pub fn selectors(&self) -> Vec<Selector> {
180        self.messages().iter().flat_map(|m| m.text.selectors().cloned()).collect()
181    }
182}
183
184/// `context: {enabled, variable_selector}`.
185#[derive(Clone, Debug, Default, Deserialize)]
186pub struct ContextConfig {
187    #[serde(default)]
188    pub enabled: bool,
189    #[serde(default)]
190    pub variable_selector: Option<Selector>,
191}
192
193impl ContextConfig {
194    /// Context text, if enabled and present.
195    pub fn resolve(&self, pool: &VariablePool) -> Option<String> {
196        if !self.enabled {
197            return None;
198        }
199        let value = pool.get(self.variable_selector.as_ref()?)?;
200        Some(context_text(&value))
201    }
202
203    pub fn selectors(&self) -> Vec<Selector> {
204        if !self.enabled {
205            return Vec::new();
206        }
207        self.variable_selector.iter().cloned().collect()
208    }
209}
210
211/// Retrieved-document lists render as their `content` fields; other values as text.
212fn context_text(value: &Value) -> String {
213    match value {
214        Value::Array(items) => items
215            .iter()
216            .map(|item| match item.as_object().and_then(|o| o.get("content")) {
217                Some(content) => content.to_text(),
218                None => item.to_text(),
219            })
220            .collect::<Vec<_>>()
221            .join("\n"),
222        other => other.to_text(),
223    }
224}
225
226#[derive(Clone, Debug, Default, Deserialize)]
227pub struct VisionDetail {
228    #[serde(default)]
229    pub variable_selector: Option<Selector>,
230    #[serde(default)]
231    pub detail: Option<String>,
232}
233
234/// `vision: {enabled, configs: {variable_selector, detail}}` (or the fields inline).
235#[derive(Clone, Debug, Default, Deserialize)]
236pub struct VisionConfig {
237    #[serde(default)]
238    pub enabled: bool,
239    #[serde(default)]
240    pub configs: Option<VisionDetail>,
241    #[serde(default)]
242    pub variable_selector: Option<Selector>,
243    #[serde(default)]
244    pub detail: Option<String>,
245}
246
247impl VisionConfig {
248    fn selector(&self) -> Selector {
249        self.configs
250            .as_ref()
251            .and_then(|c| c.variable_selector.clone())
252            .or_else(|| self.variable_selector.clone())
253            .unwrap_or_else(|| Selector::of("sys", "files"))
254    }
255
256    /// Image parts for the configured files (default selector `sys.files`).
257    ///
258    /// Non-image files are ignored. An image without a URL (e.g. a host
259    /// storage reference that was not resolved) is an input error rather than
260    /// being dropped silently.
261    pub fn image_parts(&self, pool: &VariablePool) -> Result<Vec<ContentPart>, NodeError> {
262        if !self.enabled {
263            return Ok(Vec::new());
264        }
265        let detail = self.configs.as_ref().and_then(|c| c.detail.clone()).or_else(|| self.detail.clone());
266        let files: Vec<Value> = match pool.get(&self.selector()) {
267            Some(Value::Array(items)) => items.iter().cloned().collect(),
268            Some(v @ Value::File(_)) => vec![v],
269            _ => Vec::new(),
270        };
271        let mut parts = Vec::new();
272        for file in files.iter().filter_map(Value::as_file) {
273            let is_image =
274                file.kind == FileKind::Image || file.mime_type.as_deref().is_some_and(|m| m.starts_with("image/"));
275            if !is_image {
276                continue;
277            }
278            let url = file.url.clone().filter(|u| !u.is_empty()).ok_or_else(|| {
279                NodeError::invalid_input(format!(
280                    "image `{}` has no URL; resolve host files to URLs before sending them to a model",
281                    file.name
282                ))
283            })?;
284            parts.push(ContentPart::Image { url, detail: detail.clone() });
285        }
286        Ok(parts)
287    }
288
289    pub fn selectors(&self) -> Vec<Selector> {
290        if self.enabled { vec![self.selector()] } else { Vec::new() }
291    }
292}
293
294#[derive(Clone, Debug, Default, Deserialize)]
295pub struct WindowConfig {
296    #[serde(default)]
297    pub enabled: bool,
298    #[serde(default)]
299    pub size: Option<usize>,
300}
301
302/// Conversation memory.
303///
304/// History is read from `variable_selector` (default `sys.history`): an array of
305/// `{role, content}` objects (or a JSON string encoding one), oldest first.
306/// Roles are `user`/`human`, `assistant`/`ai` and `system`. With
307/// `window.enabled`, only the last `window.size` turns (two messages per turn)
308/// are kept. The current query is appended as a user message, rendered from
309/// `query_prompt_template` (default `{{#sys.query#}}`). Without an explicit
310/// `query_prompt_template`, the query is not appended when a prompt template
311/// message already references `sys.query` (it would otherwise be sent twice).
312#[derive(Clone, Debug, Default, Deserialize)]
313pub struct MemoryConfig {
314    #[serde(default)]
315    pub window: Option<WindowConfig>,
316    #[serde(default)]
317    pub variable_selector: Option<Selector>,
318    #[serde(default)]
319    pub query_prompt_template: Option<Template>,
320}
321
322impl MemoryConfig {
323    fn history_selector(&self) -> Selector {
324        self.variable_selector.clone().unwrap_or_else(|| Selector::of("sys", "history"))
325    }
326
327    /// Conversation history. A missing history is empty; a history of the
328    /// wrong shape is an input error.
329    pub fn history(&self, pool: &VariablePool) -> Result<Vec<Message>, NodeError> {
330        let selector = self.history_selector();
331        let items: Vec<Value> = match pool.get(&selector) {
332            None | Some(Value::Null) => return Ok(Vec::new()),
333            Some(Value::Array(items)) => items.iter().cloned().collect(),
334            Some(Value::String(text)) if text.trim().is_empty() => return Ok(Vec::new()),
335            Some(Value::String(text)) => match serde_json::from_str::<Json>(&text) {
336                Ok(Json::Array(items)) => items.into_iter().map(Value::from_json).collect(),
337                _ => {
338                    return Err(NodeError::invalid_input(format!(
339                        "memory history `{selector}` is a string that is not a JSON array"
340                    )));
341                }
342            },
343            Some(other) => {
344                return Err(NodeError::invalid_input(format!(
345                    "memory history `{selector}` must be an array of {{role, content}} objects, got {}",
346                    other.type_name()
347                )));
348            }
349        };
350        let mut messages = Vec::with_capacity(items.len());
351        for (i, item) in items.iter().enumerate() {
352            let bad = |why: &str| NodeError::invalid_input(format!("memory history item #{i}: {why}"));
353            let obj = item.as_object().ok_or_else(|| bad("expected a {role, content} object"))?;
354            let role = match obj.get("role").and_then(Value::as_str) {
355                Some("user" | "human") => Role::User,
356                Some("assistant" | "ai") => Role::Assistant,
357                Some("system") => Role::System,
358                Some(other) => return Err(bad(&format!("unsupported role `{other}`"))),
359                None => return Err(bad("missing `role`")),
360            };
361            let content = obj.get("content").map(Value::to_text).unwrap_or_default();
362            messages.push(Message { role, ..Message::user(content) });
363        }
364        if let Some(window) = self.window.as_ref().filter(|w| w.enabled) {
365            let keep = window.size.unwrap_or(10).saturating_mul(2);
366            if messages.len() > keep {
367                messages.drain(..messages.len() - keep);
368            }
369        }
370        Ok(messages)
371    }
372
373    pub fn query(&self, pool: &VariablePool) -> Option<String> {
374        let text = match &self.query_prompt_template {
375            Some(t) => t.render(pool),
376            None => pool.get(&Selector::of("sys", "query"))?.to_text(),
377        };
378        if text.is_empty() { None } else { Some(text) }
379    }
380
381    /// Selectors read by the memory (history and query).
382    pub fn selectors(&self) -> Vec<Selector> {
383        let mut out = vec![self.history_selector()];
384        match &self.query_prompt_template {
385            Some(t) => out.extend(t.selectors().cloned()),
386            None => out.push(Selector::of("sys", "query")),
387        }
388        out
389    }
390}
391
392/// Render a template, substituting the literal context placeholder. Context and
393/// variable values are inserted as data and never parsed again, so content such
394/// as `{{#env.KEY#}}` inside retrieved text stays literal.
395pub fn render_with_context(template: &Template, pool: &VariablePool, context: Option<&str>) -> String {
396    let mut out = String::new();
397    for part in template.parts() {
398        match part {
399            Part::Text(t) => {
400                if t.contains(CONTEXT_PLACEHOLDER) {
401                    out.push_str(&t.replace(CONTEXT_PLACEHOLDER, context.unwrap_or_default()));
402                } else {
403                    out.push_str(t);
404                }
405            }
406            Part::Var(sel) => match pool.get(sel) {
407                // Strings (the common case) are copied once, straight into the prompt.
408                Some(Value::String(s)) => out.push_str(&s),
409                Some(v) => out.push_str(&v.to_text()),
410                None => {}
411            },
412        }
413    }
414    out
415}
416
417/// Assemble the message list: leading system messages, history, remaining
418/// template messages, the memory query, then vision images on the last user message.
419pub fn build_messages(
420    template: &PromptTemplate,
421    pool: &VariablePool,
422    context: Option<&str>,
423    memory: Option<&MemoryConfig>,
424    images: Vec<ContentPart>,
425) -> Result<Vec<Message>, NodeError> {
426    let prompts = template.messages();
427    let render =
428        |m: &PromptMessage| Message { role: m.role, ..Message::user(render_with_context(&m.text, pool, context)) };
429    let split = prompts.iter().take_while(|m| m.role == Role::System).count();
430    let (system, rest) = prompts.split_at(split);
431    let history = match memory {
432        Some(mem) => mem.history(pool)?,
433        None => Vec::new(),
434    };
435    // Room for the memory query and an images-only message.
436    let mut messages = Vec::with_capacity(prompts.len() + history.len() + 2);
437    messages.extend(system.iter().map(render));
438    messages.extend(history);
439    messages.extend(rest.iter().map(render));
440    // The current query is appended after the history unless the prompt template already
441    // contains it (a message referencing `sys.query`); otherwise it would be sent twice.
442    // An explicit `query_prompt_template` is always appended.
443    let template_has_query = template.messages().iter().any(|m| m.text.selectors().any(is_sys_query));
444    if let Some(mem) = memory
445        && (mem.query_prompt_template.is_some() || !template_has_query)
446        && let Some(query) = mem.query(pool)
447    {
448        messages.push(Message::user(query));
449    }
450    if !images.is_empty() {
451        match messages.iter_mut().rev().find(|m| m.role == Role::User) {
452            Some(last_user) => last_user.content.extend(images),
453            None => messages.push(Message { content: images, ..Message::user("") }),
454        }
455    }
456    Ok(messages)
457}
458
459fn is_sys_query(selector: &Selector) -> bool {
460    selector.namespace() == "sys" && selector.name() == "query"
461}
462
463/// Look up the configured provider.
464pub fn model_for(ctx: &NodeContext, config: &ModelConfig) -> Result<Arc<dyn ChatModel>, NodeError> {
465    let registry = ctx.require_service::<ModelRegistry>("model registry (graphrt_llm::ModelRegistry)")?;
466    Ok(registry.get(&config.provider)?)
467}
468
469/// What a model call streams to the run's event stream.
470#[derive(Clone, Copy, Debug, PartialEq, Eq)]
471pub enum StreamMode {
472    /// Nothing is streamed.
473    Off,
474    /// Answer text on field `text`, reasoning on field `reasoning`, as produced.
475    Raw,
476    /// Like [`StreamMode::Raw`], but `<think>...</think>` sections inside the
477    /// answer are routed to `reasoning`, so the streamed `text` matches the
478    /// node's separated `text` output.
479    SeparateThink,
480}
481
482/// Progress carrying a model node's rendered request messages.
483pub const MODEL_REQUEST_PROGRESS: &str = "model_request";
484
485/// Report the rendered request `messages` as [`MODEL_REQUEST_PROGRESS`]
486/// (`{"messages": [...]}`), for hosts that record content (callers check
487/// [`NodeContext::captures_content`] first, so this costs nothing otherwise).
488/// Prompts were rendered with secrets masked; inline image payloads are
489/// reduced to their `data:<mime>;base64` prefix.
490pub fn report_request_messages(ctx: &NodeContext, messages: &[Message]) {
491    let mut json = serde_json::to_value(messages).unwrap_or(Json::Null);
492    for message in json.as_array_mut().into_iter().flatten() {
493        let parts = message.get_mut("content").and_then(Json::as_array_mut);
494        for part in parts.into_iter().flatten() {
495            if let Some(Json::String(url)) = part.get_mut("url")
496                && url.starts_with("data:")
497                && let Some((prefix, _payload)) = url.split_once(',')
498            {
499                *url = prefix.to_owned();
500            }
501        }
502    }
503    ctx.progress(MODEL_REQUEST_PROGRESS, Value::from_json(serde_json::json!({ "messages": json })));
504}
505
506/// Run a request, streaming chunks according to `mode`.
507pub async fn invoke(
508    ctx: &NodeContext,
509    model: &dyn ChatModel,
510    request: ChatRequest,
511    mode: StreamMode,
512) -> Result<ChatResponse, NodeError> {
513    let stream = model.chat(request).await?;
514    let mut splitter = ThinkSplitter::default();
515    let response = collect(stream, |delta| match (mode, delta) {
516        (StreamMode::Off, _) => {}
517        (StreamMode::Raw, ChatDelta::Text(t)) if !t.is_empty() => ctx.chunk_shared(StreamField::Text.shared(), t),
518        (StreamMode::SeparateThink, ChatDelta::Text(t)) => {
519            for (field, piece) in splitter.push(&t) {
520                ctx.chunk_shared(field.shared(), piece);
521            }
522        }
523        (_, ChatDelta::Reasoning(t)) if !t.is_empty() => ctx.chunk_shared(StreamField::Reasoning.shared(), t),
524        _ => {}
525    })
526    .await?;
527    if mode == StreamMode::SeparateThink {
528        for (field, piece) in splitter.finish() {
529            ctx.chunk_shared(field.shared(), piece);
530        }
531    }
532    Ok(response)
533}
534
535/// Finish reasons that mean the model produced a broken turn (worth a retry).
536const MALFORMED_FINISH: &[&str] = &["malformed_function_call", "unexpected_tool_call", "too_many_tool_calls"];
537
538/// What a node should do with a response's finish reason.
539#[derive(Clone, Debug, PartialEq, Eq)]
540pub enum FinishCheck {
541    /// A normal end (stop, length, tool calls, or none reported).
542    Normal,
543    /// An unrecognized provider reason: keep the answer but report it.
544    Unknown(String),
545}
546
547/// Turn finish reasons that mean "no usable answer" into node errors: a content
548/// filter block is fatal (`content_filter`), a malformed turn is retryable
549/// (`model_decode`). Unknown reasons are returned for the caller to report.
550pub fn check_finish(response: &ChatResponse) -> Result<FinishCheck, NodeError> {
551    match &response.finish_reason {
552        None | Some(FinishReason::Stop | FinishReason::Length | FinishReason::ToolCalls) => Ok(FinishCheck::Normal),
553        Some(FinishReason::ContentFilter) => Err(NodeError::fatal(
554            "content_filter",
555            "the provider's safety filter blocked the response; no answer was produced",
556        )),
557        Some(FinishReason::Other(reason)) if MALFORMED_FINISH.contains(&reason.as_str()) => {
558            Err(NodeError::new("model_decode", format!("the model produced a malformed turn ({reason})")))
559        }
560        Some(FinishReason::Other(reason)) => Ok(FinishCheck::Unknown(reason.clone())),
561        #[allow(unreachable_patterns)]
562        Some(other) => Ok(FinishCheck::Unknown(other.as_str().to_owned())),
563    }
564}
565
566/// Output field a streamed piece belongs to.
567#[derive(Clone, Copy, Debug, PartialEq, Eq)]
568pub enum StreamField {
569    Text,
570    Reasoning,
571}
572
573static TEXT_FIELD: LazyLock<Arc<str>> = LazyLock::new(|| Arc::from("text"));
574static REASONING_FIELD: LazyLock<Arc<str>> = LazyLock::new(|| Arc::from("reasoning"));
575
576impl StreamField {
577    pub fn as_str(self) -> &'static str {
578        match self {
579            StreamField::Text => "text",
580            StreamField::Reasoning => "reasoning",
581        }
582    }
583
584    /// The field name as a shared string for [`NodeContext::chunk_shared`]:
585    /// one allocation per process instead of one per chunk.
586    pub fn shared(self) -> &'static Arc<str> {
587        match self {
588            StreamField::Text => &TEXT_FIELD,
589            StreamField::Reasoning => &REASONING_FIELD,
590        }
591    }
592}
593
594const THINK_OPEN: &str = "<think>";
595const THINK_CLOSE: &str = "</think>";
596
597/// Splits streamed answer text into answer and `<think>` reasoning pieces,
598/// handling tags split across chunks. Leading whitespace of the answer is
599/// dropped, matching [`split_think_tags`].
600#[derive(Debug, Default)]
601pub struct ThinkSplitter {
602    /// Text that may be the start of a tag and is held back until decided.
603    pending: String,
604    in_think: bool,
605    answer_started: bool,
606}
607
608impl ThinkSplitter {
609    /// Feed a chunk; returns the pieces that can be emitted now.
610    pub fn push(&mut self, chunk: &str) -> Vec<(StreamField, String)> {
611        self.pending.push_str(chunk);
612        let mut out = Vec::new();
613        loop {
614            let tag = if self.in_think { THINK_CLOSE } else { THINK_OPEN };
615            if let Some(pos) = self.pending.find(tag) {
616                let before: String = self.pending.drain(..pos).collect();
617                self.emit(&mut out, before);
618                self.pending.drain(..tag.len());
619                self.in_think = !self.in_think;
620                continue;
621            }
622            // Hold back the longest suffix that could still become `tag`.
623            let keep = longest_tag_prefix_suffix(&self.pending, tag);
624            let emit_len = self.pending.len() - keep;
625            let ready: String = self.pending.drain(..emit_len).collect();
626            self.emit(&mut out, ready);
627            break;
628        }
629        out
630    }
631
632    /// Flush held-back text at the end of the stream.
633    pub fn finish(&mut self) -> Vec<(StreamField, String)> {
634        let mut out = Vec::new();
635        let rest = std::mem::take(&mut self.pending);
636        self.emit(&mut out, rest);
637        out
638    }
639
640    fn emit(&mut self, out: &mut Vec<(StreamField, String)>, mut text: String) {
641        if self.in_think {
642            if !text.is_empty() {
643                out.push((StreamField::Reasoning, text));
644            }
645            return;
646        }
647        if !self.answer_started {
648            let trimmed = text.trim_start();
649            if trimmed.is_empty() {
650                return;
651            }
652            text = trimmed.to_owned();
653            self.answer_started = true;
654        }
655        if !text.is_empty() {
656            out.push((StreamField::Text, text));
657        }
658    }
659}
660
661/// Length of the longest suffix of `text` that is a proper prefix of `tag`.
662fn longest_tag_prefix_suffix(text: &str, tag: &str) -> usize {
663    (1..tag.len()).rev().find(|&n| tag.get(..n).is_some_and(|prefix| text.ends_with(prefix))).unwrap_or(0)
664}
665
666/// The `finish_reason` output: the reason's wire name, or `""` when none was
667/// reported. The standard reasons share one allocation per process.
668pub fn finish_reason_value(reason: Option<&FinishReason>) -> Value {
669    static STANDARD: LazyLock<[Value; 5]> =
670        LazyLock::new(|| ["", "stop", "length", "tool_calls", "content_filter"].map(Value::from));
671    let slot = match reason {
672        None => 0,
673        Some(FinishReason::Stop) => 1,
674        Some(FinishReason::Length) => 2,
675        Some(FinishReason::ToolCalls) => 3,
676        Some(FinishReason::ContentFilter) => 4,
677        Some(other) => return Value::from(other.as_str()),
678    };
679    STANDARD.get(slot).cloned().unwrap_or_default()
680}
681
682/// The `usage` output object.
683pub fn usage_value(usage: &Usage) -> Value {
684    // Built directly rather than through `serde_json::json!`, which allocated a
685    // second map (and its keys) only to convert it.
686    let count = |n: u64| i64::try_from(n).map_or_else(|_| Value::Float(n as f64), Value::Int);
687    let mut map = graphrt_core::value::Map::with_capacity(3);
688    map.insert("prompt_tokens".to_owned(), count(usage.prompt_tokens));
689    map.insert("completion_tokens".to_owned(), count(usage.completion_tokens));
690    map.insert("total_tokens".to_owned(), count(usage.total_tokens));
691    Value::Object(Arc::new(map))
692}
693
694/// Remove `<think>...</think>` sections, returning `(answer, reasoning)`.
695pub fn split_think_tags(text: &str) -> (String, String) {
696    let mut answer = String::new();
697    let mut reasoning = String::new();
698    let mut rest = text;
699    while let Some(start) = rest.find(THINK_OPEN) {
700        answer.push_str(&rest[..start]);
701        let after = &rest[start + THINK_OPEN.len()..];
702        match after.find(THINK_CLOSE) {
703            Some(end) => {
704                reasoning.push_str(after[..end].trim());
705                rest = &after[end + THINK_CLOSE.len()..];
706            }
707            None => {
708                reasoning.push_str(after.trim());
709                rest = "";
710            }
711        }
712    }
713    answer.push_str(rest);
714    (answer.trim_start().to_owned(), reasoning)
715}
716
717/// Maximum number of candidate positions [`extract_json`] tries. Each attempt
718/// scans at most the remaining text once, so total work is linear in the
719/// input size (times this constant).
720const MAX_JSON_CANDIDATES: usize = 32;
721
722/// Extract the first JSON object or array from model output, tolerating code
723/// fences, think tags and surrounding prose. Brace matching ignores braces
724/// inside string literals.
725pub fn extract_json(text: &str) -> Option<Json> {
726    extract_json_where(text, |v| v.is_object() || v.is_array())
727}
728
729/// Like [`extract_json`], returning the first candidate accepted by `accept`.
730pub fn extract_json_where(text: &str, accept: impl Fn(&Json) -> bool) -> Option<Json> {
731    let (answer, _) = split_think_tags(text);
732    let trimmed = answer.trim();
733    if let Ok(v) = serde_json::from_str::<Json>(trimmed)
734        && accept(&v)
735    {
736        return Some(v);
737    }
738    let bytes = trimmed.as_bytes();
739    let mut search_from = 0;
740    let mut attempts = 0;
741    while let Some(offset) = trimmed.get(search_from..)?.find(['{', '[']) {
742        attempts += 1;
743        if attempts > MAX_JSON_CANDIDATES {
744            return None;
745        }
746        let start = search_from + offset;
747        if let Some(candidate) = matching_close(bytes, start).and_then(|end| trimmed.get(start..=end))
748            && let Ok(v) = serde_json::from_str::<Json>(candidate)
749            && accept(&v)
750        {
751            return Some(v);
752        }
753        search_from = start + 1;
754    }
755    None
756}
757
758fn matching_close(bytes: &[u8], start: usize) -> Option<usize> {
759    let mut depth: usize = 0;
760    let mut in_string = false;
761    let mut escaped = false;
762    for (i, &b) in bytes.iter().enumerate().skip(start) {
763        if in_string {
764            match b {
765                _ if escaped => escaped = false,
766                b'\\' => escaped = true,
767                b'"' => in_string = false,
768                _ => {}
769            }
770            continue;
771        }
772        match b {
773            b'"' => in_string = true,
774            b'{' | b'[' => depth += 1,
775            b'}' | b']' => {
776                depth = depth.checked_sub(1)?;
777                if depth == 0 {
778                    return Some(i);
779                }
780            }
781            _ => {}
782        }
783    }
784    None
785}
786
787#[cfg(test)]
788mod tests {
789    use super::*;
790    use graphrt_core::value::File;
791
792    #[test]
793    fn json_extraction() {
794        assert_eq!(extract_json("```json\n{\"a\":1}\n```").unwrap()["a"], 1);
795        assert_eq!(extract_json("<think>{x}</think>Sure: {\"s\":\"}{\",\"b\":2} done").unwrap()["b"], 2);
796        assert!(extract_json("no json here").is_none());
797        let v = extract_json_where("see [1], then {\"a\": 2}", Json::is_object).unwrap();
798        assert_eq!(v["a"], 2);
799    }
800
801    #[test]
802    fn json_extraction_is_bounded_on_hostile_input() {
803        let hostile = "{".repeat(200_000);
804        let started = std::time::Instant::now();
805        assert!(extract_json(&hostile).is_none());
806        assert!(started.elapsed() < std::time::Duration::from_secs(2), "{:?}", started.elapsed());
807    }
808
809    #[test]
810    fn think_tags() {
811        let (a, r) = split_think_tags("<think>plan</think>\nanswer");
812        assert_eq!(a, "answer");
813        assert_eq!(r, "plan");
814    }
815
816    fn split_stream(chunks: &[&str]) -> (String, String) {
817        let mut s = ThinkSplitter::default();
818        let mut pieces = Vec::new();
819        for c in chunks {
820            pieces.extend(s.push(c));
821        }
822        pieces.extend(s.finish());
823        let mut text = String::new();
824        let mut reasoning = String::new();
825        for (field, piece) in pieces {
826            match field {
827                StreamField::Text => text.push_str(&piece),
828                StreamField::Reasoning => reasoning.push_str(&piece),
829            }
830        }
831        (text, reasoning)
832    }
833
834    #[test]
835    fn think_splitter_handles_tags_split_across_chunks() {
836        let (text, reasoning) = split_stream(&["<thi", "nk>pl", "an</th", "ink>\n", "Hel", "lo <", "b>"]);
837        assert_eq!(text, "Hello <b>");
838        assert_eq!(reasoning, "plan");
839        let whole = "<think>plan</think>\nHello <b>";
840        assert_eq!(text, split_think_tags(whole).0);
841        let (text, reasoning) = split_stream(&["no tags at all"]);
842        assert_eq!((text.as_str(), reasoning.as_str()), ("no tags at all", ""));
843        let (text, _) = split_stream(&["a <", "/think> b"]);
844        assert_eq!(text, "a </think> b");
845    }
846
847    #[test]
848    fn context_is_not_reparsed() {
849        let mut pool = VariablePool::new();
850        pool.insert("env", "KEY", Value::Secret(Arc::from("s3cret")));
851        pool.insert("sys", "query", Value::from("q"));
852        let t = Template::parse("ctx: {{#context#}} q: {{#sys.query#}}");
853        let out = render_with_context(&t, &pool, Some("evil {{#env.KEY#}}"));
854        assert_eq!(out, "ctx: evil {{#env.KEY#}} q: q");
855        let t = Template::parse("{{#env.KEY#}}");
856        assert!(!render_with_context(&t, &pool, None).contains("s3cret"));
857    }
858
859    fn model_config(params: Json) -> ModelConfig {
860        serde_json::from_value(serde_json::json!({"provider": "p", "name": "m", "completion_params": params})).unwrap()
861    }
862
863    #[test]
864    fn params_resolve_without_mutation() {
865        let mut pool = VariablePool::new();
866        pool.insert("start", "t", Value::from("0.3"));
867        let cfg = model_config(serde_json::json!(
868            {"temperature": "{{#start.t#}}", "max_tokens": 20, "stop": "x", "seed": "7", "mode": "chat", "top_p": null}
869        ));
870        let req = cfg.request(vec![], &pool).unwrap();
871        assert_eq!(req.temperature, Some(0.3));
872        assert_eq!(req.max_tokens, Some(20));
873        assert_eq!(req.top_p, None);
874        assert_eq!(req.stop, vec!["x".to_owned()]);
875        assert_eq!(req.extra.get("seed"), Some(&Json::from(7)));
876        assert!(!req.extra.contains_key("mode"));
877        assert_eq!(cfg.completion_params["temperature"], "{{#start.t#}}");
878        assert_eq!(cfg.selectors(), vec![Selector::of("start", "t")]);
879    }
880
881    #[test]
882    fn invalid_params_are_errors() {
883        let pool = VariablePool::new();
884        for params in [
885            serde_json::json!({"temperature": "hot"}),
886            serde_json::json!({"max_tokens": -1}),
887            serde_json::json!({"max_tokens": 1e12}),
888            serde_json::json!({"stop": [1, 2]}),
889            serde_json::json!({"temperature": "{{#start.missing#}}"}),
890            serde_json::json!({"stream": false}),
891        ] {
892            let err = model_config(params.clone()).request(vec![], &pool).unwrap_err();
893            assert_eq!(err.kind, "invalid_input", "{params}");
894            assert!(!err.retryable);
895        }
896    }
897
898    #[test]
899    fn messages_with_memory_and_vision() {
900        let mut pool = VariablePool::new();
901        pool.insert("sys", "query", Value::from("now"));
902        pool.insert(
903            "sys",
904            "history",
905            Value::from_json(serde_json::json!([
906                {"role": "user", "content": "old1"}, {"role": "assistant", "content": "old2"},
907                {"role": "user", "content": "old3"}, {"role": "assistant", "content": "old4"}
908            ])),
909        );
910        let image = File {
911            marker: true,
912            name: "a.png".into(),
913            kind: FileKind::Image,
914            url: Some("https://x/a.png".into()),
915            ..File::default()
916        };
917        pool.insert("sys", "files", Value::array([Value::from(image)]));
918        let template: PromptTemplate = serde_json::from_value(serde_json::json!([
919            {"role": "system", "text": "sys"}, {"role": "user", "text": "tmpl"}
920        ]))
921        .unwrap();
922        let memory: MemoryConfig =
923            serde_json::from_value(serde_json::json!({"window": {"enabled": true, "size": 1}})).unwrap();
924        let vision = VisionConfig { enabled: true, ..VisionConfig::default() };
925        let msgs = build_messages(&template, &pool, None, Some(&memory), vision.image_parts(&pool).unwrap()).unwrap();
926        let texts: Vec<String> = msgs.iter().map(Message::text).collect();
927        assert_eq!(texts, vec!["sys", "old3", "old4", "tmpl", "now"]);
928        assert!(matches!(msgs[4].content.last(), Some(ContentPart::Image { .. })));
929    }
930
931    #[test]
932    fn memory_does_not_duplicate_a_templated_query() {
933        let mut pool = VariablePool::new();
934        pool.insert("sys", "query", Value::from("now"));
935        pool.insert("sys", "history", Value::from_json(serde_json::json!([{"role": "user", "content": "old"}])));
936        let memory = MemoryConfig::default();
937        let with_query: PromptTemplate = serde_json::from_value(serde_json::json!([
938            {"role": "system", "text": "sys"}, {"role": "user", "text": "Q: {{#sys.query#}}"}
939        ]))
940        .unwrap();
941        let msgs = build_messages(&with_query, &pool, None, Some(&memory), Vec::new()).unwrap();
942        let texts: Vec<String> = msgs.iter().map(Message::text).collect();
943        assert_eq!(texts, vec!["sys", "old", "Q: now"], "the query is sent once, after the history");
944
945        let without_query: PromptTemplate =
946            serde_json::from_value(serde_json::json!([{"role": "system", "text": "sys"}])).unwrap();
947        let msgs = build_messages(&without_query, &pool, None, Some(&memory), Vec::new()).unwrap();
948        let texts: Vec<String> = msgs.iter().map(Message::text).collect();
949        assert_eq!(texts, vec!["sys", "old", "now"], "memory appends the query when the template lacks it");
950
951        let explicit: MemoryConfig =
952            serde_json::from_value(serde_json::json!({"query_prompt_template": "again: {{#sys.query#}}"})).unwrap();
953        let msgs = build_messages(&with_query, &pool, None, Some(&explicit), Vec::new()).unwrap();
954        assert_eq!(msgs.last().map(Message::text).as_deref(), Some("again: now"), "explicit query template wins");
955    }
956
957    #[test]
958    fn history_shapes() {
959        let memory = MemoryConfig::default();
960        let mut pool = VariablePool::new();
961        pool.insert("sys", "history", Value::from(r#"[{"role": "human", "content": "hi"}]"#));
962        assert_eq!(memory.history(&pool).unwrap().len(), 1, "JSON-string history is parsed");
963        pool.insert("sys", "history", Value::from_json(serde_json::json!([{"role": "tool", "content": "x"}])));
964        assert!(memory.history(&pool).is_err());
965        pool.insert("sys", "history", Value::Int(3));
966        assert!(memory.history(&pool).is_err());
967        assert!(memory.history(&VariablePool::new()).unwrap().is_empty());
968    }
969
970    #[test]
971    fn image_without_url_is_an_error() {
972        let mut pool = VariablePool::new();
973        let image = File { marker: true, name: "a.png".into(), kind: FileKind::Image, ..File::default() };
974        pool.insert("sys", "files", Value::array([Value::from(image)]));
975        let vision = VisionConfig { enabled: true, ..VisionConfig::default() };
976        assert!(vision.image_parts(&pool).is_err());
977    }
978}