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