Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 174 additions & 7 deletions crates/goose-providers/src/formats/openai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,11 +260,27 @@ pub fn format_messages_with_options(

tool_calls.as_array_mut().unwrap().push(tool_call_json);
}
Err(e) => {
output.push(json!({
"role": "tool",
"content": format!("Error: {}", e),
"tool_call_id": request.id
Err(_e) => {
// An unparseable tool call still needs a valid assistant
// `tool_calls` entry. Emitting the error as a bare `role:"tool"`
// message (the old behavior) leaves the paired tool response —
// which carries the parse error — as an orphan `role:"tool"` with
// no preceding assistant `tool_calls`, which strict
// OpenAI-compatible APIs reject. Emit a placeholder call with the
// same id so the history stays well-formed; the error rides on the
// following tool response.
let tool_calls = converted
.as_object_mut()
.unwrap()
.entry("tool_calls")
.or_insert(json!([]));
tool_calls.as_array_mut().unwrap().push(json!({
"id": request.id,
"type": "function",
"function": {
"name": "unparseable_tool_call",
Comment on lines +313 to +317

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve provider metadata on placeholder calls

When the malformed tool call carried provider metadata, this placeholder drops it even though the normal Ok branch copies every request.metadata field onto the replayed tool call. The new decoders keep metadata on ToolRequest(Err) (for example streamed OpenAI-compatible calls attach thoughtSignature/extra_content before returning the error), and the retry path in agent.rs now relies on this formatter to replay that assistant call. For Gemini-style OpenAI-compatible endpoints, losing the thought signature on exactly these parse-error retries can make the next request fail or lose reasoning continuity before the model gets a chance to correct the arguments; copy the metadata onto the placeholder as the Ok branch does.

Useful? React with 👍 / 👎.

"arguments": "{}",
}
}));
}
},
Expand Down Expand Up @@ -654,14 +670,43 @@ pub fn response_to_message(response: &Value) -> anyhow::Result<Message> {
));
} else {
match safely_parse_json(&arguments_str) {
Ok(params) => {
// Valid JSON, and an object: the normal path.
Ok(params) if params.is_object() => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Guard streamed tool-call arguments as well

This guard only protects the non-streaming response_to_message path. The default OpenAI-compatible providers I checked route streaming responses through stream_openai_compat into response_to_streaming_message, and that decoder still accepts Ok(params) and calls object(params) without an object check at openai.rs:1130-1134. When a streamed tool call ends with arguments such as [1, 2, 3], the same rmcp debug assertion or release empty-args behavior described by this fix still occurs for streaming-enabled OpenAI/OpenRouter/Databricks-compatible runs.

Useful? React with 👍 / 👎.

content.push(MessageContent::tool_request_with_metadata(
id,
Ok(CallToolRequestParams::new(function_name)
.with_arguments(object(params))),
metadata.as_ref(),
));
}
// Valid JSON but NOT an object (a bare array/string/number).
// Weaker models emit this; surface a tool error so the model
// retries with a proper object instead of crashing the run
// (rmcp's `object()` debug-asserts on non-objects).
Ok(other) => {
let error = ErrorData {
code: ErrorCode::INVALID_PARAMS,
message: Cow::from(format!(
"Tool arguments for id {} must be a JSON object, got {}. Raw arguments: '{}'",
id,
match other {
Value::Array(_) => "an array",
Value::String(_) => "a string",
Value::Number(_) => "a number",
Value::Bool(_) => "a boolean",
Value::Null => "null",
Value::Object(_) => unreachable!(),
},
arguments_str
)),
data: None,
};
content.push(MessageContent::tool_request_with_metadata(
id,
Err(error),
metadata.as_ref(),
Comment on lines +752 to +755

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Feed non-object argument errors back to the model

For the newly handled case where a model emits valid JSON that is not an object, this creates a ToolRequest whose tool_call is Err. I checked the agent loop in crates/goose/src/agents/agent.rs:2128-2163: errored tool requests are not added as an assistant tool call plus tool response for the next model turn; the agent logs the parse error, emits a generic assistant message, sets exit_chat = true, and breaks. That means the exact weak-model scenario this branch handles terminates the run instead of giving the model the INVALID_PARAMS feedback needed to retry.

Useful? React with 👍 / 👎.

));
}
Err(e) => {
let error = ErrorData {
code: ErrorCode::INVALID_PARAMS,
Expand Down Expand Up @@ -1103,13 +1148,29 @@ where
};

let content = match parsed {
Ok(params) => {
// Valid JSON, and an object: the normal path.
Ok(params) if params.is_object() => {
MessageContent::tool_request_with_metadata(
id.clone(),
Ok(CallToolRequestParams::new(function_name.clone()).with_arguments(object(params))),
metadata.as_ref(),
)
},
// Valid JSON but NOT an object (a bare array/string/number).
// Surface a tool error so the model retries instead of
// crashing the run (rmcp's `object()` debug-asserts on
// non-objects). Mirrors the non-streaming decoder.
Ok(_) => {
let error = ErrorData {
code: ErrorCode::INVALID_PARAMS,
message: Cow::from(format!(
"Tool arguments for id {} must be a JSON object. Raw arguments: '{}'",
id, arguments
)),
data: None,
};
MessageContent::tool_request_with_metadata(id.clone(), Err(error), metadata.as_ref())
}
Err(e) => {
let error = ErrorData {
code: ErrorCode::INVALID_PARAMS,
Expand Down Expand Up @@ -1945,6 +2006,36 @@ mod tests {
Ok(())
}

#[test]
fn test_response_to_message_non_object_arguments() -> anyhow::Result<()> {
// Weaker models sometimes emit tool arguments that are valid JSON but
// not an object (here, a bare array). This must surface as a tool error,
// NOT panic via rmcp's `object()` debug-assert.
let mut response: Value = serde_json::from_str(OPENAI_TOOL_USE_RESPONSE)?;
response["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"] =
json!("[1, 2, 3]");

let message = response_to_message(&response)?;

if let MessageContent::ToolRequest(request) = &message.content[0] {
match &request.tool_call {
Err(ErrorData {
code: ErrorCode::INVALID_PARAMS,
message: msg,
data: None,
}) => {
assert!(msg.contains("must be a JSON object"));
assert!(msg.contains("an array"));
}
_ => panic!("Expected InvalidParameters error for non-object args"),
}
} else {
panic!("Expected ToolRequest content");
}

Ok(())
}

#[test]
fn test_response_to_message_empty_argument() -> anyhow::Result<()> {
let mut response: Value = serde_json::from_str(OPENAI_TOOL_USE_RESPONSE)?;
Expand Down Expand Up @@ -2733,6 +2824,38 @@ data: [DONE]"#;
panic!("Expected tool call message with nested extra_content metadata");
}

#[tokio::test]
async fn test_streaming_non_object_arguments_does_not_panic() -> anyhow::Result<()> {
// Streamed tool call whose arguments are valid JSON but NOT an object.
// Must yield an INVALID_PARAMS tool error, not panic via rmcp `object()`.
let response_lines = r#"data: {"model":"test-model","choices":[{"delta":{"role":"assistant","tool_calls":[{"id":"call_bad","function":{"name":"test_tool","arguments":"[1, 2, 3]"},"type":"function","index":0}]},"index":0,"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":100,"completion_tokens":10,"total_tokens":110},"object":"chat.completion.chunk","id":"test-id","created":1234567890}
data: [DONE]"#;

let response_stream =
tokio_stream::iter(response_lines.lines().map(|line| Ok(line.to_string())));
let messages = response_to_streaming_message(response_stream);
pin!(messages);

while let Some(Ok((message, _usage))) = messages.next().await {
if let Some(msg) = message {
if let MessageContent::ToolRequest(request) = &msg.content[0] {
match &request.tool_call {
Err(ErrorData {
code: ErrorCode::INVALID_PARAMS,
message: m,
..
}) => {
assert!(m.contains("must be a JSON object"));
return Ok(());
}
_ => panic!("expected INVALID_PARAMS for non-object streamed args"),
}
}
}
}
panic!("expected a tool request message");
}

#[tokio::test]
async fn test_streaming_response_extracts_inline_think_blocks() -> anyhow::Result<()> {
let response_lines = concat!(
Expand Down Expand Up @@ -3554,4 +3677,48 @@ data: [DONE]"#;
assert!(!is_valid_function_name("hello world"));
assert!(!is_valid_function_name("hello@world"));
}

#[test]
fn formatter_post_parse_error_history_is_wellformed() {
use rmcp::model::{ErrorCode, ErrorData};
let err = ErrorData::new(
ErrorCode::INVALID_PARAMS,
"Tool arguments for id call_bad must be a JSON object".to_string(),
None,
);
// Shape the agent loop builds today for a failed parse:
let request_msg = Message::assistant().with_tool_request("call_bad", Err(err.clone()));
let mut final_resp = Message::user();
final_resp.add_tool_response_with_metadata("call_bad", Err(err), None);
let messages = vec![
Message::user().with_text("do the thing"),
request_msg,
final_resp,
];

let spec = format_messages(&messages, &ImageFormat::OpenAi);

let mut open = std::collections::HashSet::new();
for m in &spec {
match m.get("role").and_then(|v| v.as_str()) {
Some("assistant") => {
for tc in m
.get("tool_calls")
.and_then(|v| v.as_array())
.into_iter()
.flatten()
{
if let Some(id) = tc.get("id").and_then(|v| v.as_str()) {
open.insert(id.to_string());
}
}
}
Some("tool") => {
let id = m.get("tool_call_id").and_then(|v| v.as_str()).unwrap_or("");
assert!(open.contains(id), "orphan role:tool message for id {id:?}");
}
_ => {}
}
}
}
}
99 changes: 63 additions & 36 deletions crates/goose/src/agents/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2194,46 +2194,73 @@ impl Agent {
.collect();

for request in frontend_requests.iter().chain(remaining_requests.iter()) {
if request.tool_call.is_ok() {
let mut request_msg = Message::assistant()
.with_id(format!("msg_{}", Uuid::new_v4()));

// Providers like Kimi require reasoning_content on all assistant
// messages with tool_calls when thinking mode is enabled.
for rc in &reasoning_content {
request_msg = request_msg.with_content(rc.clone());
}
let mut request_msg = Message::assistant()
.with_id(format!("msg_{}", Uuid::new_v4()));

request_msg = request_msg
.with_tool_request_with_metadata(
request.id.clone(),
request.tool_call.clone(),
request.metadata.as_ref(),
request.tool_meta.clone(),
);
let final_response = request_to_response_map
// Providers like Kimi require reasoning_content on all assistant
// messages with tool_calls when thinking mode is enabled.
for rc in &reasoning_content {
request_msg = request_msg.with_content(rc.clone());
}

// For an unparseable tool call (Err), store a valid
// placeholder Ok tool-call in history instead of the Err. This
// keeps the conversation well-formed through EVERY provider
// formatter's normal Ok path — so we don't have to special-case
// each formatter's Err arm — and preserves provider metadata
// (e.g. thought signatures), which is passed through below and
// copied by the Ok path. The actual parse error rides on the
// paired tool response.
let history_tool_call = match &request.tool_call {
Ok(_) => request.tool_call.clone(),
Err(_) => Ok(CallToolRequestParams::new(
"unparseable_tool_call",
)
.with_arguments(serde_json::Map::new())),
Comment on lines +2314 to +2319

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the original tool name for retries

When a provider returns an unparseable argument payload for a valid tool, this stores the history as a call to unparseable_tool_call with {} and the paired error only mentions the id/raw args, so the next model turn no longer sees which real tool (for example developer__shell or search) failed. This matters especially when a response had multiple possible tools or the user request is ambiguous: the retry feedback can no longer direct the model to correct the original tool call. Preserve the original function name in the stored placeholder or at least include it in the error metadata/message before replacing the call.

Useful? React with 👍 / 👎.

};
request_msg = request_msg
.with_tool_request_with_metadata(
request.id.clone(),
history_tool_call,
request.metadata.as_ref(),
Comment on lines +2321 to +2325

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep a matching assistant tool call for parse errors

When request.tool_call is Err (the new non-object/invalid-JSON path), this stores the error as a ToolRequest in conversation history. I checked the OpenAI formatter: ToolRequest(Err(_)) is emitted as a role: "tool" message (crates/goose-providers/src/formats/openai.rs:262-267), not as an assistant tool_calls entry; the Err branch below also adds a ToolResponse for the same id. The retry request sent to OpenAI-compatible providers therefore contains tool-role messages with no preceding assistant tool call, which strict APIs reject, so the model still cannot correct its bad arguments. Persist a valid assistant tool-call representation for the bad call, or only add a tool response in a form the formatter can pair with it.

Useful? React with 👍 / 👎.

Comment on lines +2321 to +2325

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Add Bedrock replay support before storing parse-error calls

Fresh evidence: Bedrock still emits MessageContent::tool_request(..., Err(...)) when streamed tool arguments fail to parse (crates/goose/src/providers/bedrock.rs:655-663), but its formatter turns a ToolRequest(Err) into a ToolUseBlock with only the id and no name/input (crates/goose/src/providers/formats/bedrock.rs:152-156). Because this new path now persists every errored tool request in history and pairs it with a tool-response error, the next Bedrock turn fails during request formatting instead of letting the model correct the arguments; either add a valid Bedrock placeholder or keep the old terminal behavior for formats that cannot replay parse errors.

Useful? React with 👍 / 👎.

request.tool_meta.clone(),
);

let final_response = match &request.tool_call {
Ok(_) => request_to_response_map
.remove(&request.id)
.unwrap_or_else(|| Message::user().with_generated_id());
// Response placeholder is created before tools run, so clamp request to avoid inverted ordering.
if request_msg.created > final_response.created {
request_msg.created = final_response.created;
.unwrap_or_else(|| Message::user().with_generated_id()),
Err(error) => {
error!("Tool call could not be parsed: {error}");
let mut response = request_to_response_map
.remove(&request.id)
.unwrap_or_else(|| Message::user().with_generated_id());
// Only feed the parse error back if this id isn't
// already answered. In Chat mode the skip branch above
// already added a tool response for it; adding another
// here would duplicate the tool_call_id (which strict
// providers reject).
let already_answered = response.content.iter().any(|c| {
matches!(c, MessageContent::ToolResponse(r) if r.id == request.id)
});
if !already_answered {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Replace chat skips with parse-error feedback

Fresh evidence in this revision is that already_answered now suppresses Err(error.clone()) whenever any response for the id exists. In GooseMode::Chat, the branch at agent.rs:2024-2031 pre-populates every remaining request — including ToolRequest(Err) — with the successful CHAT_MODE_TOOL_SKIPPED_RESPONSE, so malformed tool arguments are replayed as a placeholder assistant tool call plus a successful skip result instead of the INVALID_PARAMS error. In chat sessions the model then cannot correct the bad arguments and may explain a skipped unparseable_tool_call; clear or avoid the chat skip for Err requests and send the parse error instead.

Useful? React with 👍 / 👎.

response.add_tool_response_with_metadata(
request.id.clone(),
Err(error.clone()),
request.metadata.as_ref(),
);
}
response
}
messages_to_add.push(request_msg);
yield AgentEvent::Message(final_response.clone());
messages_to_add.push(final_response);
} else {
error!(
"Tool call could not be parsed: {}",
request.tool_call.as_ref().unwrap_err(),
);
yield AgentEvent::Message(
Message::assistant().with_text(
"A tool call could not be parsed — the response may have been truncated. Try breaking the task into smaller steps or resending your message."
)
);
exit_chat = true;
break;
};

// Response placeholder is created before tools run, so clamp request to avoid inverted ordering.
if request_msg.created > final_response.created {
request_msg.created = final_response.created;
}
messages_to_add.push(request_msg);
yield AgentEvent::Message(final_response.clone());
messages_to_add.push(final_response);
}

no_tools_called = false;
Expand Down
Loading
Loading