Commit 87552a9
fix(llm-dialog): Filter empty text content blocks to prevent API errors (commontoolsinc#2034)
* fix(llm-dialog): Filter empty text content blocks to prevent API errors
## Problem
After enabling tool call caching (d394ec8, Nov 6), users encountered
'text content blocks must be non-empty' errors when:
1. Running demo-setup Execute button multiple times
2. Using omnibot after tool calls
3. Any cached conversation with tool calls
Error from Anthropic API:
```
AI_APICallError: messages: text content blocks must be non-empty
```
## Root Cause
When Claude responds with tool calls, it can include empty text parts:
```json
{
"role": "assistant",
"content": [
{"type": "text", "text": ""}, // Empty!
{"type": "tool_use", ...}
]
}
```
Before tool call caching was enabled, these messages weren't cached so the
issue didn't surface. After caching was enabled:
1. First request: LLM returns empty text + tool call
2. Tool results added to conversation
3. Response cached with empty text parts
4. Next request: Cached messages (with empty text) sent to API
5. API rejects: "text content blocks must be non-empty"
Anthropic API recently became stricter about rejecting empty text blocks.
## The Fix
**Two-point defense:**
1. **buildAssistantMessage (line 611-613)**: Filter out empty text parts when
constructing assistant messages from LLM responses
2. **Request construction (lines 1069-1082)**: Filter all messages before
sending to API to remove any empty text content that may have been cached
Both filters check:
- Part is type "text"
- Part has non-null text field
- Text is non-empty after trimming
## Why Both Filters Are Needed
- Filter #1: Prevents storing empty text parts initially
- Filter #2: Defense in depth for cached messages that already have empty text
## Testing
Verified fix resolves:
- ✅ demo-setup Execute button works on first and subsequent runs
- ✅ demo-setup Reset + Execute works without errors
- ✅ Tool calls execute successfully
- ✅ Conversation continues after tool calls
- ✅ No API errors in logs
## Related
- Introduced by: d394ec8 "Allow caching of tool calls"
- Workaround used in patterns: Cache-busting with Date.now() timestamps
- Those workarounds can now be removed (though they're harmless)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
* fix(llm-dialog): Handle invalid responses at source instead of just filtering
## Problem with Previous Fix
The previous fix filtered empty text blocks, but could create invalid states:
- Message with only empty text: `content: [{type:"text", text:""}]`
- After filtering: `content: []` ← Invalid (except for final message)
## Root Cause
Vercel AI SDK v5.x bug: returns empty text blocks before tool calls.
Critical scenario: stream aborts after empty text but BEFORE tool calls.
Result:
1. Stream sends: {type:"text", text:""}
2. Stream crashes before tool-call events
3. We store: content: [{type:"text", text:""}] (no tool calls!)
4. Gets cached
5. Next request: filter creates content: []
6. API rejects: "messages must have non-empty content"
## New Solution
### 1. Validate Fresh Responses
Check if response has valid content before storing:
- If invalid (empty/only whitespace), insert proper error message
- Provides user feedback: "I encountered an error generating a response..."
- Maintains valid message history
### 2. Enhanced Cached Message Filtering
- Filter empty text blocks from cached messages
- Remove messages that become empty after filtering
- Respect API rule: final assistant message CAN be empty
### 3. Remove Unnecessary Filtering
Removed filtering from buildAssistantMessage since we now validate upstream.
## Benefits
- Handles root cause (aborted/incomplete responses)
- User gets clear error message instead of silent failure
- Logs warnings for debugging
- Never sends invalid payloads to Anthropic API
- Backward compatible with already-cached invalid messages
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
* fix(llm-dialog): Handle invalid responses and tool result edge cases
## Problems Fixed
1. **Empty/invalid LLM responses**: Stream aborts after empty text but before tool calls
2. **Tool results with no output**: Tools returning undefined/null broke API validation
3. **Tool result filtering**: Cached tool result messages could be removed incorrectly
4. **Mismatched tool calls/results**: If executeToolCalls fails partially
## Root Causes
**Vercel AI SDK bug**: Returns empty text blocks before tool calls:
```json
{
"content": [
{ "type": "text", "text": "" }, // ← SDK bug
{ "type": "tool-call", ... }
]
}
```
**Critical scenario**: Stream crashes after empty text but BEFORE tool calls:
- Receive: `content: [{type:"text", text:""}]` (no tool calls!)
- Store as-is, gets cached
- Next request: Filter creates `content: []` ← Invalid!
- API rejects: "messages must have non-empty content"
**Tool result validation**: Anthropic API **requires** tool_result for every tool_use:
- If tool returns undefined/null, output field was undefined
- Error: "tool_use ids were found without tool_result blocks"
## Solution
### 1. Validate Fresh Responses
Check if response has valid content before storing:
```typescript
function hasValidContent(content): boolean {
// Returns true only if content has non-empty text OR tool calls OR tool results
}
if (!hasValidContent(llmResult.content)) {
// Insert proper error message instead of invalid content
content: "I encountered an error generating a response. Please try again."
}
```
### 2. Ensure Tool Results Always Valid
Convert undefined/null results to explicit null value:
```typescript
if (toolResult.result === undefined || toolResult.result === null) {
output = { type: "json", value: null };
}
```
### 3. Never Filter Tool Messages
Tool result messages must always be preserved:
```typescript
if (msg.role === "tool") return true; // Never filter
```
### 4. Validate Tool Call/Result Match
Ensure every tool call has a corresponding result:
```typescript
if (toolResults.length !== toolCallParts.length) {
// Log detailed error, insert error message
}
```
### 5. Enhanced Cached Message Filtering
- Filter empty text blocks from cached messages (backward compat)
- Remove messages that become empty after filtering (except final)
- Respect Anthropic API rule: final assistant message CAN be empty
## Benefits
- ✅ Handles root cause (aborted/incomplete responses)
- ✅ User gets clear error messages instead of silent failure
- ✅ Logs warnings for debugging
- ✅ Never sends invalid payloads to Anthropic API
- ✅ Backward compatible with already-cached invalid messages
- ✅ Test coverage for all edge cases
## Test Coverage
Added 7 new test cases:
- hasValidContent validates empty/non-empty text
- hasValidContent validates tool calls and results
- createToolResultMessages handles undefined/null results
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
* chore: Apply deno fmt formatting
* chore: Fix lint warning - remove unused index parameter
* refactor: Use validation instead of filtering for message history
Instead of filtering empty text blocks from within messages and then
removing messages that become empty, use the same hasValidContent()
validation as fresh responses. This is cleaner and more consistent:
Before:
- Map over messages to filter empty text blocks from content arrays
- Then filter out messages that became empty after text filtering
- Complex multi-step transformation
After:
- Single validation pass using hasValidContent()
- Remove messages that fail validation entirely
- Same validation logic as fresh responses
Benefits:
- Simpler code (one filter instead of map + filter)
- Consistent validation across fresh and cached messages
- Don't try to "fix" invalid data, just remove invalid messages
- Clearer intent: validate and remove, not transform and patch
* refactor: Remove cached message validation - let legacy data fail
Instead of validating and filtering cached messages, let the API reject
invalid legacy data. This significantly simplifies the code:
Before:
- Validate all cached messages with hasValidContent()
- Filter out invalid messages with logging
- Special handling for tool messages and final assistant messages
After:
- Send messages as-is to API
- If legacy invalid data exists, API will reject with clear error
- User can start fresh conversation
This is acceptable because:
1. Going forward, we never write invalid data (validated at source)
2. Legacy conversations with invalid data are rare edge cases
3. Clear API error is better than silent data manipulation
4. Much simpler code
The prevention happens entirely at write time:
- Fresh responses validated with hasValidContent()
- Tool results always have valid output
- Tool call/result counts validated
---------
Co-authored-by: Claude <[email protected]>
Co-authored-by: Ben Follington <[email protected]>1 parent 310b072 commit 87552a9
File tree
2 files changed
+181
-11
lines changed- packages/runner
- src/builtins
- test
2 files changed
+181
-11
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
593 | 593 | | |
594 | 594 | | |
595 | 595 | | |
| 596 | + | |
| 597 | + | |
| 598 | + | |
| 599 | + | |
| 600 | + | |
| 601 | + | |
| 602 | + | |
| 603 | + | |
| 604 | + | |
| 605 | + | |
| 606 | + | |
| 607 | + | |
| 608 | + | |
| 609 | + | |
| 610 | + | |
| 611 | + | |
| 612 | + | |
| 613 | + | |
| 614 | + | |
| 615 | + | |
| 616 | + | |
| 617 | + | |
| 618 | + | |
| 619 | + | |
596 | 620 | | |
597 | 621 | | |
598 | 622 | | |
| |||
664 | 688 | | |
665 | 689 | | |
666 | 690 | | |
667 | | - | |
668 | | - | |
669 | | - | |
670 | | - | |
671 | | - | |
672 | | - | |
673 | | - | |
674 | | - | |
675 | | - | |
676 | | - | |
677 | | - | |
| 691 | + | |
| 692 | + | |
| 693 | + | |
| 694 | + | |
| 695 | + | |
| 696 | + | |
| 697 | + | |
| 698 | + | |
| 699 | + | |
| 700 | + | |
| 701 | + | |
| 702 | + | |
| 703 | + | |
| 704 | + | |
| 705 | + | |
| 706 | + | |
| 707 | + | |
| 708 | + | |
| 709 | + | |
| 710 | + | |
| 711 | + | |
| 712 | + | |
| 713 | + | |
678 | 714 | | |
679 | 715 | | |
680 | 716 | | |
| |||
684 | 720 | | |
685 | 721 | | |
686 | 722 | | |
| 723 | + | |
687 | 724 | | |
688 | 725 | | |
689 | 726 | | |
| |||
1080 | 1117 | | |
1081 | 1118 | | |
1082 | 1119 | | |
| 1120 | + | |
| 1121 | + | |
| 1122 | + | |
| 1123 | + | |
| 1124 | + | |
| 1125 | + | |
| 1126 | + | |
| 1127 | + | |
| 1128 | + | |
| 1129 | + | |
| 1130 | + | |
| 1131 | + | |
| 1132 | + | |
| 1133 | + | |
| 1134 | + | |
| 1135 | + | |
| 1136 | + | |
| 1137 | + | |
| 1138 | + | |
| 1139 | + | |
| 1140 | + | |
| 1141 | + | |
| 1142 | + | |
| 1143 | + | |
| 1144 | + | |
| 1145 | + | |
| 1146 | + | |
| 1147 | + | |
1083 | 1148 | | |
1084 | 1149 | | |
1085 | 1150 | | |
| |||
1098 | 1163 | | |
1099 | 1164 | | |
1100 | 1165 | | |
| 1166 | + | |
| 1167 | + | |
| 1168 | + | |
| 1169 | + | |
| 1170 | + | |
| 1171 | + | |
| 1172 | + | |
| 1173 | + | |
| 1174 | + | |
| 1175 | + | |
| 1176 | + | |
| 1177 | + | |
| 1178 | + | |
| 1179 | + | |
| 1180 | + | |
| 1181 | + | |
| 1182 | + | |
| 1183 | + | |
| 1184 | + | |
| 1185 | + | |
| 1186 | + | |
| 1187 | + | |
| 1188 | + | |
| 1189 | + | |
| 1190 | + | |
| 1191 | + | |
| 1192 | + | |
| 1193 | + | |
| 1194 | + | |
| 1195 | + | |
| 1196 | + | |
| 1197 | + | |
| 1198 | + | |
| 1199 | + | |
| 1200 | + | |
1101 | 1201 | | |
1102 | 1202 | | |
1103 | 1203 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
9 | 9 | | |
10 | 10 | | |
11 | 11 | | |
| 12 | + | |
12 | 13 | | |
13 | 14 | | |
14 | 15 | | |
| |||
112 | 113 | | |
113 | 114 | | |
114 | 115 | | |
| 116 | + | |
| 117 | + | |
| 118 | + | |
| 119 | + | |
| 120 | + | |
| 121 | + | |
| 122 | + | |
| 123 | + | |
| 124 | + | |
| 125 | + | |
| 126 | + | |
| 127 | + | |
| 128 | + | |
| 129 | + | |
| 130 | + | |
| 131 | + | |
| 132 | + | |
| 133 | + | |
| 134 | + | |
| 135 | + | |
| 136 | + | |
| 137 | + | |
| 138 | + | |
| 139 | + | |
| 140 | + | |
| 141 | + | |
| 142 | + | |
| 143 | + | |
| 144 | + | |
| 145 | + | |
| 146 | + | |
| 147 | + | |
| 148 | + | |
| 149 | + | |
| 150 | + | |
| 151 | + | |
| 152 | + | |
| 153 | + | |
| 154 | + | |
| 155 | + | |
| 156 | + | |
| 157 | + | |
| 158 | + | |
| 159 | + | |
| 160 | + | |
| 161 | + | |
| 162 | + | |
| 163 | + | |
| 164 | + | |
| 165 | + | |
| 166 | + | |
| 167 | + | |
| 168 | + | |
| 169 | + | |
| 170 | + | |
| 171 | + | |
| 172 | + | |
| 173 | + | |
| 174 | + | |
| 175 | + | |
| 176 | + | |
| 177 | + | |
| 178 | + | |
| 179 | + | |
| 180 | + | |
| 181 | + | |
| 182 | + | |
| 183 | + | |
| 184 | + | |
0 commit comments