-
Notifications
You must be signed in to change notification settings - Fork 3
fix(agent): recover function_call JSON envelopes #28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
senamakel
merged 6 commits into
tinyhumansai:main
from
Oscar-Williams:fix/function-call-json-recovery
Sep 29, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d809270
fix(agent): recover function_call JSON envelopes
Oscar-Williams f95fae2
test(agent): cover function_call error paths
Oscar-Williams 26dd0f2
fix(agent): handle function_call stream boundaries
Oscar-Williams b02e044
Merge main and preserve both parser grammars
senamakel 247fcd8
chore(grammar): reorder module declarations for consistency
senamakel 75cc3d9
fix(parse): prevent false function call detection inside identifiers …
senamakel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
113 changes: 113 additions & 0 deletions
113
crates/tinytools-agent/src/parse/grammar/function_call.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| //! `function_call:{...}` envelopes narrated in ordinary assistant text. | ||
| //! | ||
| //! Some native-tool models put the call in the visible message as a compact | ||
| //! JSON envelope instead of filling the provider's structured field. The | ||
| //! explicit prefix is the marker: unlike the bare-JSON path, this grammar may | ||
| //! remove only the marked object from surrounding prose. | ||
|
|
||
| use super::{Block, Decoded, Grammar, Probe, ScanMode, find_ci}; | ||
| use crate::parse::json_values::find_json_end; | ||
| use crate::repair::args; | ||
| use crate::types::{CallSource, ParseOptions, ParsedToolCall}; | ||
|
|
||
| /// The marker used by the affected native-model response shape. | ||
| const PREFIX: &str = "function_call:"; | ||
|
|
||
| /// Grammar for a marked JSON call in ordinary text. | ||
| #[derive(Debug)] | ||
| pub(crate) struct FunctionCall; | ||
|
|
||
| impl Grammar for FunctionCall { | ||
| fn source(&self) -> CallSource { | ||
| // This is another explicit JSON marker, so it shares the tagged | ||
| // source classification used by the existing JSON call grammars. | ||
| CallSource::TaggedJson | ||
| } | ||
|
|
||
| fn probe(&self, text: &str, from: usize, _options: &ParseOptions<'_>, mode: ScanMode) -> Probe { | ||
| let mut cursor = from; | ||
| while let Some(start) = find_ci(text, PREFIX, cursor) { | ||
| if text[..start] | ||
| .chars() | ||
| .next_back() | ||
| .is_some_and(is_identifier_char) | ||
| { | ||
| cursor = start + PREFIX.len(); | ||
| continue; | ||
| } | ||
|
|
||
| let after = &text[start + PREFIX.len()..]; | ||
| if !after.trim_start().starts_with('{') { | ||
|
senamakel marked this conversation as resolved.
|
||
| if mode == ScanMode::Stream && after.trim_start().is_empty() { | ||
| return Probe::Pending { start }; | ||
| } | ||
| cursor = start + PREFIX.len(); | ||
| continue; | ||
| } | ||
|
|
||
| let Some(end) = find_json_end(after) else { | ||
| if mode == ScanMode::Stream { | ||
| return Probe::Pending { start }; | ||
| } | ||
| // Batch input may contain an abandoned marker before a real | ||
| // call. There is no balanced boundary to skip to, so resume | ||
| // at the marker's payload and let the next explicit marker | ||
| // make progress. | ||
| cursor = start + PREFIX.len(); | ||
| continue; | ||
| }; | ||
|
senamakel marked this conversation as resolved.
|
||
| let block_end = start + PREFIX.len() + end; | ||
| let Ok(value) = serde_json::from_str::<serde_json::Value>(&after[..end]) else { | ||
| // Skip a balanced but invalid object as one unit. This | ||
| // prevents a marker in its payload from becoming a nested | ||
| // call while still allowing a later real marker in the | ||
| // response to be considered. | ||
| cursor = block_end; | ||
| continue; | ||
| }; | ||
| let Some(call) = decode_call(&value) else { | ||
| cursor = block_end; | ||
| continue; | ||
| }; | ||
|
|
||
| return Probe::Found(Block { | ||
| start, | ||
| end: block_end, | ||
| decoded: Decoded::Calls(vec![call]), | ||
| }); | ||
| } | ||
|
|
||
| Probe::None | ||
| } | ||
|
|
||
| fn openers(&self) -> &'static [&'static str] { | ||
| &[PREFIX] | ||
| } | ||
| } | ||
|
|
||
| /// Reads the two observed name spellings without treating arbitrary JSON as a | ||
| /// call. The marker already establishes the call context, so the usual tagged | ||
| /// argument aliases remain safe here. | ||
| fn decode_call(value: &serde_json::Value) -> Option<ParsedToolCall> { | ||
| let object = value.as_object()?; | ||
| let name = object | ||
| .get("call") | ||
| .and_then(nonempty_name) | ||
| .or_else(|| object.get("name").and_then(nonempty_name))?; | ||
| Some(ParsedToolCall::new( | ||
| name, | ||
| args::from_call_object(value), | ||
| CallSource::TaggedJson, | ||
| )) | ||
| } | ||
|
|
||
| fn nonempty_name(value: &serde_json::Value) -> Option<&str> { | ||
| value | ||
| .as_str() | ||
| .map(str::trim) | ||
| .filter(|name| !name.is_empty()) | ||
| } | ||
|
|
||
| fn is_identifier_char(character: char) -> bool { | ||
| character == '_' || character.is_alphanumeric() | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| //! Regression tests for the explicit `function_call:` JSON envelope. | ||
|
|
||
| use super::parse; | ||
| use crate::types::CallSource; | ||
|
|
||
| #[test] | ||
| fn function_call_prefix_recovers_a_narrated_json_call() { | ||
| let (text, calls) = parse( | ||
| r#"Let me proceed with querying the tasks ledger. function_call:{"id":"call_3rY","call":"read_ledger","arguments":{"ledger":"tasks","query":"2026-09-01"}}"#, | ||
| ); | ||
|
|
||
| assert_eq!(text, "Let me proceed with querying the tasks ledger."); | ||
| assert_eq!(calls.len(), 1); | ||
| assert_eq!(calls[0].name, "read_ledger"); | ||
| assert_eq!(calls[0].source, CallSource::TaggedJson); | ||
| assert_eq!( | ||
| calls[0].arguments, | ||
| serde_json::json!({"ledger": "tasks", "query": "2026-09-01"}) | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn function_call_prefix_accepts_the_standard_name_field() { | ||
| let (text, calls) = | ||
| parse(r#"function_call: {"name":"echo","arguments":{"value":"ok"}} trailing"#); | ||
|
|
||
| assert_eq!(text, "trailing"); | ||
| assert_eq!(calls.len(), 1); | ||
| assert_eq!(calls[0].name, "echo"); | ||
| assert_eq!(calls[0].arguments, serde_json::json!({"value": "ok"})); | ||
| } | ||
|
|
||
| #[test] | ||
| fn embedded_function_call_marker_in_a_longer_identifier_stays_visible() { | ||
| let input = r#"not_function_call:{"name":"echo","arguments":{}}"#; | ||
|
|
||
| let (text, calls) = parse(input); | ||
|
|
||
| assert_eq!(text, input); | ||
| assert!(calls.is_empty()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn unusable_call_fields_fall_back_to_a_valid_name() { | ||
| for call in [serde_json::Value::Null, serde_json::json!("")] { | ||
| let envelope = serde_json::json!({ | ||
| "call": call, | ||
| "name": "echo", | ||
| "arguments": {"value": "ok"} | ||
| }); | ||
| let input = format!("function_call:{envelope}"); | ||
|
|
||
| let (text, calls) = parse(&input); | ||
|
|
||
| assert!(text.is_empty()); | ||
| assert_eq!(calls.len(), 1); | ||
| assert_eq!(calls[0].name, "echo"); | ||
| assert_eq!(calls[0].arguments, serde_json::json!({"value": "ok"})); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn an_unrelated_function_call_object_stays_visible() { | ||
| let input = r#"function_call:{"message":"this is not a tool call"}"#; | ||
|
|
||
| let (text, calls) = parse(input); | ||
|
|
||
| assert_eq!(text, input); | ||
| assert!(calls.is_empty()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn a_fenced_function_call_example_is_not_executed() { | ||
| let input = "```text\nfunction_call:{\"name\":\"echo\",\"arguments\":{}}\n```"; | ||
|
|
||
| let (text, calls) = parse(input); | ||
|
|
||
| assert_eq!(text, input); | ||
| assert!(calls.is_empty()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn an_invalid_marked_object_does_not_hide_a_later_call() { | ||
| let (text, calls) = parse( | ||
| r#"function_call:{"message":"not a call"} then function_call:{"call":"echo","arguments":{}}"#, | ||
| ); | ||
|
|
||
| assert_eq!(text, r#"function_call:{"message":"not a call"} then"#); | ||
| assert_eq!(calls.len(), 1); | ||
| assert_eq!(calls[0].name, "echo"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn an_unterminated_marked_object_does_not_hide_a_later_call() { | ||
| let (text, calls) = | ||
| parse(r#"function_call:{"broken" then function_call:{"name":"echo","arguments":{}}"#); | ||
|
|
||
| assert_eq!(text, r#"function_call:{"broken" then"#); | ||
| assert_eq!(calls.len(), 1); | ||
| assert_eq!(calls[0].name, "echo"); | ||
| } | ||
|
|
||
| #[test] | ||
| fn an_unterminated_marked_object_stays_visible_in_batch_mode() { | ||
| let input = r#"function_call:{"call":"echo""#; | ||
|
|
||
| let (text, calls) = parse(input); | ||
|
|
||
| assert_eq!(text, input); | ||
| assert!(calls.is_empty()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn an_invalid_marked_json_object_stays_visible() { | ||
| let input = r#"function_call:{call:"echo"}"#; | ||
|
|
||
| let (text, calls) = parse(input); | ||
|
|
||
| assert_eq!(text, input); | ||
| assert!(calls.is_empty()); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.