STRA-338 size-fn2: leleka-gateway-text lines within 120 columns (wide 67 -> 0: prod 61 -> 0, test 6 -> 0; comments re-filled, test strings continued after a newline escape with the same bytes); test ids unchanged
This commit is contained in:
@@ -11,12 +11,13 @@
|
||||
//! ([`ChatInput`]); [`pinned`] is the compiled default.
|
||||
//! * [`render`] / [`render_with_tools`] are the typed entry points the Responses path uses.
|
||||
//!
|
||||
//! Object key order matters to the model: `tojson` prints keys in the order they were given (the Python server's `tojson`
|
||||
//! is `json.dumps(..., sort_keys=False)`). [`Json`] keeps that order when it is deserialized directly from request text,
|
||||
//! whatever features `serde_json` is built with. A `serde_json::Value` keeps it only with the `preserve_order` feature,
|
||||
//! which this crate declares in its `Cargo.toml` (see `json_order.rs`, whose test fails if it is off); without it the map
|
||||
//! is sorted and [`Json::from_value`] yields sorted keys. The tool schema heuristic in [`schema_order`] still orders the
|
||||
//! keys of every schema object that has a `"type"` the conventional way, whatever order the client wrote them in.
|
||||
//! Object key order matters to the model: `tojson` prints keys in the order they were given (the Python server's
|
||||
//! `tojson` is `json.dumps(..., sort_keys=False)`). [`Json`] keeps that order when it is deserialized directly from
|
||||
//! request text, whatever features `serde_json` is built with. A `serde_json::Value` keeps it only with the
|
||||
//! `preserve_order` feature, which this crate declares in its `Cargo.toml` (see `json_order.rs`, whose test fails if it
|
||||
//! is off); without it the map is sorted and [`Json::from_value`] yields sorted keys. The tool schema heuristic in
|
||||
//! [`schema_order`] still orders the keys of every schema object that has a `"type"` the conventional way, whatever
|
||||
//! order the client wrote them in.
|
||||
use std::{collections::BTreeMap, fmt, sync::OnceLock};
|
||||
|
||||
use minijinja::{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: impl Json, fn schema_order, impl Serialize_for_Json, impl Deserialize_for_Json, fn py_space, fn trim ....
|
||||
//! Moved out of the parent module by STRA-338: impl Json, fn schema_order, impl Serialize_for_Json, impl
|
||||
//! Deserialize_for_Json, fn py_space, fn trim ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -19,8 +20,8 @@ impl Json {
|
||||
}
|
||||
}
|
||||
|
||||
/// From a `serde_json::Value`: keys come out in the order the value holds them (insertion order with `preserve_order`,
|
||||
/// which this crate declares; sorted otherwise).
|
||||
/// From a `serde_json::Value`: keys come out in the order the value holds them (insertion order with
|
||||
/// `preserve_order`, which this crate declares; sorted otherwise).
|
||||
pub fn from_value(value: &Plain) -> Self {
|
||||
match value {
|
||||
Plain::Null => Self::Null,
|
||||
@@ -35,10 +36,10 @@ impl Json {
|
||||
}
|
||||
|
||||
/// Like [`Json::from_value`], but every object that has a `"type"` key is ordered the way JSON Schema is
|
||||
/// conventionally written (see [`schema_order`]). It was written for a `serde_json::Value` that had sorted the client's
|
||||
/// keys away; the value now keeps them, so this only differs from the client's order for a schema object that was not
|
||||
/// written in that convention (none of the 281 schemas in the repository's fixtures: Codex, Claude Code and the tool
|
||||
/// corpus). Objects without a `"type"` (`properties`, `definitions`) keep the client's order.
|
||||
/// conventionally written (see [`schema_order`]). It was written for a `serde_json::Value` that had sorted the
|
||||
/// client's keys away; the value now keeps them, so this only differs from the client's order for a schema object
|
||||
/// that was not written in that convention (none of the 281 schemas in the repository's fixtures: Codex, Claude
|
||||
/// Code and the tool corpus). Objects without a `"type"` (`properties`, `definitions`) keep the client's order.
|
||||
pub fn from_schema_value(value: &Plain) -> Self {
|
||||
match value {
|
||||
Plain::Array(items) => Self::Array(items.iter().map(Self::from_schema_value).collect()),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: impl Renderer, fn pinned, impl Role, impl Message, impl Effort, fn render ....
|
||||
//! Moved out of the parent module by STRA-338: impl Renderer, fn pinned, impl Role, impl Message, impl Effort, fn
|
||||
//! render ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -57,8 +58,8 @@ impl Role {
|
||||
}
|
||||
|
||||
impl<'a> Message<'a> {
|
||||
/// A completed empty assistant turn (see [`without_empty_assistant_turns`]): no text after `str.strip`, no picture, and (the
|
||||
/// typed messages carry none) no tool calls.
|
||||
/// A completed empty assistant turn (see [`without_empty_assistant_turns`]): no text after `str.strip`, no picture,
|
||||
/// and (the typed messages carry none) no tool calls.
|
||||
pub(super) fn is_empty_assistant_turn(&self) -> bool {
|
||||
if self.role != Role::Assistant {
|
||||
return false;
|
||||
@@ -123,18 +124,19 @@ pub(super) fn reference_render() -> bool {
|
||||
|
||||
/// The prompt of a text-only conversation without running the Jinja template over the history.
|
||||
///
|
||||
/// For the pinned template a message after the leading system/developer ones renders to text that depends on that message
|
||||
/// alone, because `preserve_thinking` is never set (an assistant turn always keeps its `<think>` block):
|
||||
/// For the pinned template a message after the leading system/developer ones renders to text that depends on that
|
||||
/// message alone, because `preserve_thinking` is never set (an assistant turn always keeps its `<think>` block):
|
||||
///
|
||||
/// ```text
|
||||
/// user: <|im_start|>user\n{content|trim}<|im_end|>\n
|
||||
/// assistant: <|im_start|>assistant\n<think>\n{reasoning|trim}\n</think>\n\n{content|trim}<|im_end|>\n
|
||||
/// ```
|
||||
///
|
||||
/// and what comes before them (the tools, the reasoning instruction, the merged system text) depends only on the leading
|
||||
/// system messages, the tools and the effort, so the template renders just that part, with the history left out. The
|
||||
/// generation prompt is the template's own closing lines. The result is the template's output byte for byte
|
||||
/// (`native_render_equals_the_template` renders thousands of random conversations both ways); pictures take the template.
|
||||
/// and what comes before them (the tools, the reasoning instruction, the merged system text) depends only on the
|
||||
/// leading system messages, the tools and the effort, so the template renders just that part, with the history left
|
||||
/// out. The generation prompt is the template's own closing lines. The result is the template's output byte for byte
|
||||
/// (`native_render_equals_the_template` renders thousands of random conversations both ways); pictures take the
|
||||
/// template.
|
||||
pub(super) fn render_native(messages: &[Message<'_>], effort: Effort, tools: &[Json]) -> Result<String, String> {
|
||||
let leading = messages.iter().take_while(|message| matches!(message.role, Role::System | Role::Developer)).count();
|
||||
let mut prompt = render_head(&messages[..leading], effort, tools)?;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: fn json_string, fn write_json, fn tojson, fn keep_empty_turns, fn content_text, fn content_has_image ....
|
||||
//! Moved out of the parent module by STRA-338: fn json_string, fn write_json, fn tojson, fn keep_empty_turns, fn
|
||||
//! content_text, fn content_has_image ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -140,9 +141,10 @@ pub(super) fn keep_empty_turns() -> bool {
|
||||
std::env::var_os("STRATA_KEEP_EMPTY_TURNS").is_some_and(|v| v == "1")
|
||||
}
|
||||
|
||||
/// `serve/frontend.py` `_text_of`, as far as the emptiness test needs it: the text of a message's content, or the `TypeError`
|
||||
/// Python raises for a content it cannot iterate (a number or a boolean). A string is itself, a list joins the `text` of its text
|
||||
/// parts (type `text`, `input_text` or no type), an object is iterated by key (no part is a dict, so its text is empty).
|
||||
/// `serve/frontend.py` `_text_of`, as far as the emptiness test needs it: the text of a message's content, or the
|
||||
/// `TypeError` Python raises for a content it cannot iterate (a number or a boolean). A string is itself, a list joins
|
||||
/// the `text` of its text parts (type `text`, `input_text` or no type), an object is iterated by key (no part is a
|
||||
/// dict, so its text is empty).
|
||||
pub(super) fn content_text(content: Option<&Json>) -> Result<String, String> {
|
||||
match content {
|
||||
None | Some(Json::Null) | Some(Json::Object(_)) => Ok(String::new()),
|
||||
@@ -199,8 +201,8 @@ pub(super) fn truthy(value: Option<&Json>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// A completed empty assistant turn: an assistant message with no text (after `str.strip`), no picture and no tool calls.
|
||||
/// A reasoning content does not keep it.
|
||||
/// A completed empty assistant turn: an assistant message with no text (after `str.strip`), no picture and no tool
|
||||
/// calls. A reasoning content does not keep it.
|
||||
pub(super) fn is_empty_assistant_turn(message: &Json) -> Result<bool, String> {
|
||||
if !matches!(message.get("role"), Some(Json::String(role)) if role == "assistant") {
|
||||
return Ok(false);
|
||||
@@ -211,8 +213,9 @@ pub(super) fn is_empty_assistant_turn(message: &Json) -> Result<bool, String> {
|
||||
&& !truthy(message.get("tool_calls")))
|
||||
}
|
||||
|
||||
/// `ChatTemplate.render` (serve/frontend.py, Strata 0.1.50, #843): "Do not use completed empty assistant turns as examples
|
||||
/// for the next reply. Keep the final message." The template sees the list without them; `STRATA_KEEP_EMPTY_TURNS=1` keeps them.
|
||||
/// `ChatTemplate.render` (serve/frontend.py, Strata 0.1.50, #843): "Do not use completed empty assistant turns as
|
||||
/// examples for the next reply. Keep the final message." The template sees the list without them;
|
||||
/// `STRATA_KEEP_EMPTY_TURNS=1` keeps them.
|
||||
pub(super) fn without_empty_assistant_turns(messages: &[Json]) -> Result<Vec<Json>, String> {
|
||||
let mut kept = Vec::with_capacity(messages.len());
|
||||
for (index, message) in messages.iter().enumerate() {
|
||||
|
||||
@@ -192,7 +192,8 @@ fn flattened_tool_continuation_matches_the_golden_bytes() {
|
||||
user("Weather in Oslo?"),
|
||||
Message {
|
||||
role: Role::Assistant,
|
||||
content: "<tool_call>\n<function=get_weather>\n<parameter=city>\nOslo\n</parameter>\n</function>\n</tool_call>",
|
||||
content: "<tool_call>\n<function=get_weather>\n<parameter=city>\nOslo\n</parameter>\n</function>\n\
|
||||
</tool_call>",
|
||||
reasoning: None,
|
||||
parts: None,
|
||||
},
|
||||
|
||||
@@ -24,8 +24,8 @@ pub fn render_with_images(
|
||||
if messages.is_empty() {
|
||||
return Err("prompt needs a message".into());
|
||||
}
|
||||
// The template never sees a completed empty assistant turn (`without_empty_assistant_turns`); the checks below and the native
|
||||
// renderer work on the same list.
|
||||
// The template never sees a completed empty assistant turn (`without_empty_assistant_turns`); the checks below and
|
||||
// the native renderer work on the same list.
|
||||
let kept = without_empty_turns(messages);
|
||||
let messages = kept.as_slice();
|
||||
let first_non_system = messages
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! Complete Qwen tool-call parsing for the pinned Strata chat-template format.
|
||||
//! A call is publishable only after its function and outer call delimiters close. Three delimiters may be missing where
|
||||
//! something else shows that the call is whole: the `</tool_call>` after a `</function>` that ends the generation or is
|
||||
//! followed by the next call's opener, and the `</function>` before a `</tool_call>` that follows the last `</parameter>`
|
||||
//! (see `docs/api-contract.md`, "Tool-call parsing"). A call for a tool the request did not declare is an error: it is
|
||||
//! Complete Qwen tool-call parsing for the pinned Strata chat-template format. A call is publishable only after its
|
||||
//! function and outer call delimiters close. Three delimiters may be missing where something else shows that the call
|
||||
//! is whole: the `</tool_call>` after a `</function>` that ends the generation or is followed by the next call's
|
||||
//! opener, and the `</function>` before a `</tool_call>` that follows the last `</parameter>` (see
|
||||
//! `docs/api-contract.md`, "Tool-call parsing"). A call for a tool the request did not declare is an error: it is
|
||||
//! neither run nor shown as text.
|
||||
//!
|
||||
//! `Options::recovery` (the experimental `tool_call_recovery` setting, off by default) also reads the forms a model drifts
|
||||
//! into: see [`Options`].
|
||||
//! `Options::recovery` (the experimental `tool_call_recovery` setting, off by default) also reads the forms a model
|
||||
//! drifts into: see [`Options`].
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
@@ -21,21 +21,24 @@ pub enum Segment {
|
||||
pub struct Options {
|
||||
/// The generation ended on its own and not at the token limit: a call whose text ends on `</function>` is whole.
|
||||
pub natural_stop: bool,
|
||||
/// EXPERIMENTAL, off by default (`tool_call_recovery`): a declared tool's call written next to the template form is the
|
||||
/// call. These forms: `<parameter=NAME>` where `<function=NAME>` belongs; `<=NAME>`, `<function:NAME>`, `<function =NAME>` or
|
||||
/// `<NAME>` after `<tool_call>`; a JSON object `{"name": ..., "arguments": {...}}` inside `<tool_call>` (also in a Markdown
|
||||
/// fence); a bare `<function=NAME>...</function>` at the start of a line outside code, with no `<tool_call>`; a second call
|
||||
/// in the same `<tool_call>`. Also damaged JSON arguments that need a guess: brackets left open at the end and a bare string
|
||||
/// where an object member belongs (dropped). Only for declared tools; anything else is read as without the option.
|
||||
/// EXPERIMENTAL, off by default (`tool_call_recovery`): a declared tool's call written next to the template form is
|
||||
/// the call. These forms: `<parameter=NAME>` where `<function=NAME>` belongs; `<=NAME>`, `<function:NAME>`,
|
||||
/// `<function =NAME>` or `<NAME>` after `<tool_call>`; a JSON object `{"name": ..., "arguments": {...}}` inside
|
||||
/// `<tool_call>` (also in a Markdown fence); a bare `<function=NAME>...</function>` at the start of a line outside
|
||||
/// code, with no `<tool_call>`; a second call in the same `<tool_call>`. Also damaged JSON arguments that need a
|
||||
/// guess: brackets left open at the end and a bare string where an object member belongs (dropped). Only for
|
||||
/// declared tools; anything else is read as without the option.
|
||||
pub recovery: bool,
|
||||
}
|
||||
|
||||
/// What was accepted although the template form was not followed. The caller logs it; nothing is silent.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Notes {
|
||||
/// Calls whose `</function>` or `</tool_call>` was left out and which the next token or the end of the generation confirmed.
|
||||
/// Calls whose `</function>` or `</tool_call>` was left out and which the next token or the end of the generation
|
||||
/// confirmed.
|
||||
pub closers_supplied: usize,
|
||||
/// Array or object arguments that were damaged JSON (or JSON written inside a JSON string) and were read as written.
|
||||
/// Array or object arguments that were damaged JSON (or JSON written inside a JSON string) and were read as
|
||||
/// written.
|
||||
pub repaired_arguments: usize,
|
||||
/// Calls read in a drifted form (`Options::recovery` only).
|
||||
pub recovered_forms: usize,
|
||||
@@ -46,8 +49,9 @@ pub struct Parsed {
|
||||
pub notes: Notes,
|
||||
}
|
||||
|
||||
/// The reading of Markdown code in the text so far: the open fence, the backticks of the current paragraph and the current line.
|
||||
/// A bare `<function=` counts as a call only at the start of a line outside a fence and outside inline code.
|
||||
/// The reading of Markdown code in the text so far: the open fence, the backticks of the current paragraph and the
|
||||
/// current line. A bare `<function=` counts as a call only at the start of a line outside a fence and outside inline
|
||||
/// code.
|
||||
#[derive(Clone, Default)]
|
||||
struct CodeState {
|
||||
fence: Option<char>,
|
||||
@@ -64,14 +68,15 @@ pub struct Incremental<'a> {
|
||||
/// The call being read has no `<tool_call>` around it (`Options::recovery`); it ends at its `</function>`.
|
||||
bare: bool,
|
||||
after_call: bool,
|
||||
/// Candidate call ends before this offset of the buffer were tried and are not the end of the call; the text before a
|
||||
/// candidate does not change when more arrives, so they are not tried again.
|
||||
/// Candidate call ends before this offset of the buffer were tried and are not the end of the call; the text before
|
||||
/// a candidate does not change when more arrives, so they are not tried again.
|
||||
tried: usize,
|
||||
/// The Markdown code state of the text that has left the buffer (`Options::recovery` only).
|
||||
code: CodeState,
|
||||
}
|
||||
|
||||
/// A call without `<tool_call>` (`Options::recovery`): where `<function=NAME>` of a declared tool starts a line outside code.
|
||||
/// A call without `<tool_call>` (`Options::recovery`): where `<function=NAME>` of a declared tool starts a line outside
|
||||
/// code.
|
||||
enum Bare {
|
||||
None,
|
||||
/// A call starts here.
|
||||
@@ -83,7 +88,8 @@ enum Bare {
|
||||
/// How to run a shell command through the shell tool the agent declared.
|
||||
struct PatchShell {
|
||||
tool: String,
|
||||
/// The argument that carries the command, and whether it is an argv array (`["bash","-lc",script]`) or the script text.
|
||||
/// The argument that carries the command, and whether it is an argv array (`["bash","-lc",script]`) or the script
|
||||
/// text.
|
||||
argument: &'static str,
|
||||
argv: bool,
|
||||
}
|
||||
@@ -102,9 +108,9 @@ struct Lenient {
|
||||
lossy: bool,
|
||||
}
|
||||
|
||||
/// Counts, for increasing positions, the calls a value quotes: openers `<function=NAME>` that are followed by `<parameter=` or
|
||||
/// `</function>` (a bare `<function=` in prose or code is not one), and the `</function>` closers. Both cursors only move
|
||||
/// forward, so walking every `</parameter>` candidate of a value costs one pass over it.
|
||||
/// Counts, for increasing positions, the calls a value quotes: openers `<function=NAME>` that are followed by
|
||||
/// `<parameter=` or `</function>` (a bare `<function=` in prose or code is not one), and the `</function>` closers.
|
||||
/// Both cursors only move forward, so walking every `</parameter>` candidate of a value costs one pass over it.
|
||||
struct QuoteBalance<'a> {
|
||||
text: &'a str,
|
||||
opener_at: usize,
|
||||
|
||||
@@ -3,15 +3,15 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// Where a parameter value in `text` (which starts at the value) ends, and whether the call's `</function>` was left out.
|
||||
/// The value ends at the first `</parameter>` that is followed, after whitespace, by the next `<parameter=` or
|
||||
/// `</function>`. The same text inside a value (a file that documents the call format) is part of the value, and so is a close
|
||||
/// that belongs to a call the value itself quotes (upstream #4078): a `</parameter>` counts only when the quoted openers
|
||||
/// (`<function=NAME>` followed by `<parameter=` or `</function>`) before it are no more than the `</function>` closers before
|
||||
/// it. (A value that reopens its own parameter, `</parameter><parameter=NAME>` of the same name, still ends at the first close:
|
||||
/// it is indistinguishable from a parameter written twice, which is refused as `duplicate tool parameter`, not merged.)
|
||||
/// Only when no such close exists, and `closes_call` is set, a `</parameter>` followed by `</tool_call>` ends the value and the
|
||||
/// call (the `</function>` was left out).
|
||||
/// Where a parameter value in `text` (which starts at the value) ends, and whether the call's `</function>` was left
|
||||
/// out. The value ends at the first `</parameter>` that is followed, after whitespace, by the next `<parameter=` or
|
||||
/// `</function>`. The same text inside a value (a file that documents the call format) is part of the value, and so is
|
||||
/// a close that belongs to a call the value itself quotes (upstream #4078): a `</parameter>` counts only when the
|
||||
/// quoted openers (`<function=NAME>` followed by `<parameter=` or `</function>`) before it are no more than the
|
||||
/// `</function>` closers before it. (A value that reopens its own parameter, `</parameter><parameter=NAME>` of the same
|
||||
/// name, still ends at the first close: it is indistinguishable from a parameter written twice, which is refused as
|
||||
/// `duplicate tool parameter`, not merged.) Only when no such close exists, and `closes_call` is set, a `</parameter>`
|
||||
/// followed by `</tool_call>` ends the value and the call (the `</function>` was left out).
|
||||
pub(super) fn find_parameter_end(text: &str, closes_call: bool) -> Option<(usize, bool)> {
|
||||
scan_parameter_end(text, false)
|
||||
.map(|at| (at, false))
|
||||
|
||||
@@ -47,14 +47,15 @@ impl<'a> Incremental<'a> {
|
||||
self.bare = bare;
|
||||
}
|
||||
|
||||
/// A wrapped call that is whole in the buffer: its calls, how much of the buffer they used, what was accepted beyond the form.
|
||||
/// A wrapped call that is whole in the buffer: its calls, how much of the buffer they used, what was accepted
|
||||
/// beyond the form.
|
||||
pub(super) fn complete_wrapped(&mut self) -> Option<(Vec<Segment>, usize, Notes)> {
|
||||
let mut search = self.tried;
|
||||
while let Some(relative) = self.buffer[search..].find("</tool_call>") {
|
||||
let end = search + relative + "</tool_call>".len();
|
||||
let mut found = Notes::default();
|
||||
// A `</function>` left out is not accepted while streaming: the `</tool_call>` found may be text inside a value, and
|
||||
// only the end of the generation can tell (see `finish_after`).
|
||||
// A `</function>` left out is not accepted while streaming: the `</tool_call>` found may be text inside a
|
||||
// value, and only the end of the generation can tell (see `finish_after`).
|
||||
if let Ok((calls, used)) = read_wrapped(
|
||||
&self.buffer[..end],
|
||||
self.tools,
|
||||
@@ -70,7 +71,8 @@ impl<'a> Incremental<'a> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The same for a call with no `<tool_call>`: it ends at its `</function>`, and a `</tool_call>` after it is dropped.
|
||||
/// The same for a call with no `<tool_call>`: it ends at its `</function>`, and a `</tool_call>` after it is
|
||||
/// dropped.
|
||||
pub(super) fn complete_bare(&mut self) -> Option<(Vec<Segment>, usize, Notes)> {
|
||||
let mut search = self.tried;
|
||||
while let Some(relative) = self.buffer[search..].find("</function>") {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: impl Notes, impl std_fmt_Display, impl CodeState, fn stands_outside_code.
|
||||
//! Moved out of the parent module by STRA-338: impl Notes, impl std_fmt_Display, impl CodeState, fn
|
||||
//! stands_outside_code.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -79,11 +79,12 @@ fn declares_kind(kind: &Value, parsed: &Value) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// A reader for the mechanical slips a model makes inside an array or object argument: a trailing or doubled comma, single
|
||||
/// quotes, Python's `True`/`False`/`None`, and extra closing brackets at the end. It is only asked about text that is not valid
|
||||
/// JSON. It never guesses a value and never drops or invents one: a string cut short, an unknown word, a bare string where a
|
||||
/// member belongs, a missing colon: anything else is not repaired. With `lossy` (`Options::recovery`) it also closes brackets
|
||||
/// left open at the end of the text and drops a bare string where an object member belongs.
|
||||
/// A reader for the mechanical slips a model makes inside an array or object argument: a trailing or doubled comma,
|
||||
/// single quotes, Python's `True`/`False`/`None`, and extra closing brackets at the end. It is only asked about text
|
||||
/// that is not valid JSON. It never guesses a value and never drops or invents one: a string cut short, an unknown
|
||||
/// word, a bare string where a member belongs, a missing colon: anything else is not repaired. With `lossy`
|
||||
/// (`Options::recovery`) it also closes brackets left open at the end of the text and drops a bare string where an
|
||||
/// object member belongs.
|
||||
pub(super) fn repair_json(raw: &str, lossy: bool) -> Option<Value> {
|
||||
let text = raw.trim();
|
||||
if !text.starts_with(['[', '{']) || text.len() > 1 << 20 {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: fn parse_text, fn calls_at_end, fn find_bare, fn is_declared, fn is_tool_name, fn read_wrapped ....
|
||||
//! Moved out of the parent module by STRA-338: fn parse_text, fn calls_at_end, fn find_bare, fn is_declared, fn
|
||||
//! is_tool_name, fn read_wrapped ....
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -71,10 +72,10 @@ fn read_call(
|
||||
read_wrapped(body, tools, options, true, notes)
|
||||
}
|
||||
|
||||
/// A generation that stopped by itself without ever closing its reasoning (`</think>`) and ended on tool calls: the offset
|
||||
/// where the calls start. The calls count only when every one of them is a whole call of a declared tool, they are the last
|
||||
/// thing in the text (whitespace aside), and the first one stands at the start of a line outside a code fence and outside
|
||||
/// inline code, so a call the reasoning only quotes is not one.
|
||||
/// A generation that stopped by itself without ever closing its reasoning (`</think>`) and ended on tool calls: the
|
||||
/// offset where the calls start. The calls count only when every one of them is a whole call of a declared tool, they
|
||||
/// are the last thing in the text (whitespace aside), and the first one stands at the start of a line outside a code
|
||||
/// fence and outside inline code, so a call the reasoning only quotes is not one.
|
||||
pub fn calls_at_end(text: &str, tools: &[Value], options: Options) -> Option<usize> {
|
||||
let options = Options {
|
||||
natural_stop: true,
|
||||
@@ -139,8 +140,8 @@ pub(super) fn is_tool_name(name: &str) -> bool {
|
||||
!name.is_empty() && !name.contains(|c: char| c == '<' || c == '>' || c.is_whitespace())
|
||||
}
|
||||
|
||||
/// The calls of a wrapped body (the text after `<tool_call>`) up to and including its `</tool_call>`, and how much it used. With
|
||||
/// `Options::recovery` the body may be a JSON call, and may hold several calls.
|
||||
/// The calls of a wrapped body (the text after `<tool_call>`) up to and including its `</tool_call>`, and how much it
|
||||
/// used. With `Options::recovery` the body may be a JSON call, and may hold several calls.
|
||||
pub(super) fn read_wrapped(
|
||||
text: &str,
|
||||
tools: &[Value],
|
||||
@@ -168,8 +169,8 @@ pub(super) fn read_wrapped(
|
||||
}
|
||||
}
|
||||
|
||||
/// `{"name": NAME, "arguments": {...}}` (or `"parameters"`, or the arguments as a JSON string) of a declared tool inside the
|
||||
/// wrapper, up to its `</tool_call>`; also inside a Markdown fence.
|
||||
/// `{"name": NAME, "arguments": {...}}` (or `"parameters"`, or the arguments as a JSON string) of a declared tool
|
||||
/// inside the wrapper, up to its `</tool_call>`; also inside a Markdown fence.
|
||||
pub(super) fn json_call(text: &str, tools: &[Value]) -> Option<(Segment, usize)> {
|
||||
let body = text.trim_start();
|
||||
if !(body.starts_with('{') || body.starts_with("```")) {
|
||||
@@ -248,8 +249,8 @@ pub(super) fn read_opener<'t>(
|
||||
Err("tool call needs <function=NAME>".to_owned())
|
||||
}
|
||||
|
||||
/// A drifted opener of a declared tool (`Options::recovery`): `<parameter=NAME>` where `<function=NAME>` belongs, or the
|
||||
/// envelope with a token off: `<=NAME>`, `<function:NAME>`, `<function =NAME>`, `<NAME>`.
|
||||
/// A drifted opener of a declared tool (`Options::recovery`): `<parameter=NAME>` where `<function=NAME>` belongs, or
|
||||
/// the envelope with a token off: `<=NAME>`, `<function:NAME>`, `<function =NAME>`, `<NAME>`.
|
||||
pub(super) fn drifted_opener<'t>(rest: &'t str, tools: &[Value]) -> Option<(&'t str, usize)> {
|
||||
if let Some(after) = rest.strip_prefix("<parameter=") {
|
||||
let end = after.find('>')?;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Moved out of the parent module by STRA-338: fn starts_batched_call, fn parse_call, fn starts_next_call, fn patch_shell, impl PatchShell, impl Kinds.
|
||||
//! Moved out of the parent module by STRA-338: fn starts_batched_call, fn parse_call, fn starts_next_call, fn
|
||||
//! patch_shell, impl PatchShell, impl Kinds.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -12,9 +13,9 @@ pub(super) fn starts_batched_call(tail: &str, tools: &[Value]) -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The next call, and how much of `text` (which starts after `<tool_call>`, or at `<function=` when `bare`) it used, and
|
||||
/// whether another call of the same wrapper follows (`Options::recovery`). `closes_call`: a `</parameter>` followed by
|
||||
/// `</tool_call>` may end a call whose `</function>` was left out (only when no `</parameter>` that is followed by
|
||||
/// The next call, and how much of `text` (which starts after `<tool_call>`, or at `<function=` when `bare`) it used,
|
||||
/// and whether another call of the same wrapper follows (`Options::recovery`). `closes_call`: a `</parameter>` followed
|
||||
/// by `</tool_call>` may end a call whose `</function>` was left out (only when no `</parameter>` that is followed by
|
||||
/// `<parameter=` or `</function>` ends the value; see `find_parameter_end`).
|
||||
pub(super) fn parse_call(
|
||||
text: &str,
|
||||
@@ -220,7 +221,8 @@ pub(super) fn patch_shell(tools: &[Value]) -> Option<PatchShell> {
|
||||
}
|
||||
|
||||
impl PatchShell {
|
||||
/// The patch text is the parameter that holds `*** Begin Patch` (else the first one); the call becomes the heredoc form.
|
||||
/// The patch text is the parameter that holds `*** Begin Patch` (else the first one); the call becomes the heredoc
|
||||
/// form.
|
||||
pub(super) fn rewrite(&self, arguments: &Map<String, Value>) -> (String, Value) {
|
||||
let patch = arguments
|
||||
.values()
|
||||
|
||||
@@ -75,7 +75,8 @@ fn calls_the_reasoning_ends_on_are_calls_and_calls_it_quotes_are_not() {
|
||||
fn parses_typed_values_and_preserves_text_around_calls() {
|
||||
let tools =
|
||||
[json!({"name":"lookup","parameters":{"properties":{"n":{"type":"integer"},"term":{"type":"string"}}}})];
|
||||
let output = "Let me check.\n\n<tool_call>\n<function=lookup>\n<parameter=n>\n12\n</parameter>\n<parameter=term>\n12\n</parameter>\n</function>\n</tool_call>\nanswer";
|
||||
let output = "Let me check.\n\n<tool_call>\n<function=lookup>\n<parameter=n>\n12\n</parameter>\n\
|
||||
<parameter=term>\n12\n</parameter>\n</function>\n</tool_call>\nanswer";
|
||||
assert_eq!(
|
||||
parse_complete(output, &tools).unwrap(),
|
||||
vec![
|
||||
|
||||
@@ -28,8 +28,8 @@ fn assert_quoted_call_stays_in_the_value(tools: &[Value]) {
|
||||
fn a_quoted_call_in_a_value_does_not_end_the_value_and_a_cut_outer_call_is_not_published() {
|
||||
let tools = path_content_tools();
|
||||
assert_quoted_call_stays_in_the_value(&tools);
|
||||
// the outer call was cut (token limit) right after the quoted one: the quoted call's closers must not end the value,
|
||||
// or a truncated write would be published as a whole call
|
||||
// the outer call was cut (token limit) right after the quoted one: the quoted call's closers must not end the
|
||||
// value, or a truncated write would be published as a whole call
|
||||
let cut = format!("{OUTER_CALL_HEAD}transcript:\n{QUOTED_CALL}");
|
||||
assert!(parse_complete(&cut, &tools).is_err());
|
||||
let mut parser = Incremental::new(&tools);
|
||||
|
||||
@@ -5,9 +5,11 @@ use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_upstream_terminator_fixture_without_truncating_content() {
|
||||
let content = "Close each value with </parameter> and the call with </function></tool_call>.\n<parameter=x>\nnot a parameter\n</parameter>\nend";
|
||||
let content = "Close each value with </parameter> and the call with </function></tool_call>.\n<parameter=x>\nnot a \
|
||||
parameter\n</parameter>\nend";
|
||||
let output = format!(
|
||||
"<tool_call>\n<function=write>\n<parameter=path>\ndoc.md\n</parameter>\n<parameter=content>\n{content}\n</parameter>\n</function>\n</tool_call>"
|
||||
"<tool_call>\n<function=write>\n<parameter=path>\ndoc.md\n</parameter>\n<parameter=content>\n{content}\n\
|
||||
</parameter>\n</function>\n</tool_call>"
|
||||
);
|
||||
let tools =
|
||||
[json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}})];
|
||||
@@ -75,7 +77,8 @@ fn other_undeclared_functions_still_fail() {
|
||||
fn a_call_without_function_close_is_read_when_the_wrapper_closes_it() {
|
||||
let tools =
|
||||
[json!({"name":"write","parameters":{"properties":{"path":{"type":"string"},"content":{"type":"string"}}}})];
|
||||
let text = "<tool_call>\n<function=write>\n<parameter=path>\nout.txt\n</parameter>\n<parameter=content>\nhello\n</parameter>\n</tool_call>";
|
||||
let text = "<tool_call>\n<function=write>\n<parameter=path>\nout.txt\n</parameter>\n<parameter=content>\nhello\n\
|
||||
</parameter>\n</tool_call>";
|
||||
let want = vec![("write".to_owned(), json!({"path":"out.txt","content":"hello"}))];
|
||||
let parsed = parse_with(text, &tools, Options::default()).unwrap();
|
||||
assert_eq!(calls_of(parsed.segments), want);
|
||||
|
||||
Reference in New Issue
Block a user