Save chat turns when the model sends malformed tool arguments

Merged
NE
8d ago
+43-5

Problem

When a model sends tool arguments that are not valid JSON, the AI SDK keeps them as a raw string on the tool part. toolInput is a RAW_JSON field, and the ORM runs JSON.parse on string values for those fields. The parse throws while the turn is being saved, so the whole answer is lost and the chat shows "Failed to get response".

Fix

mapUIMessagePartsToDBParts now stores {} when the input is not a plain object. This matches what the AI SDK does for invalid tool calls in its own response messages, and it keeps the stored call valid when it is replayed to the provider. The error message is still saved on the part.

Testing

Reproduced in Chrome with a local fake Anthropic server that always returns malformed tool arguments.

  • Before: the turn fails with Expected ',' or '}' after property value in JSON, with formatFieldMetadataValue in the stack.
  • After: the turn completes, the part is stored with toolInput: {} and its error message, and a follow-up message in the same thread replays it as an object and gets a reply.

Added a unit test for malformed arguments in map-ui-message-parts-to-db-parts.util.spec.ts.