🐛 fix(model-runtime): handle array content in anthropic assistant messages (#11206)

When assistant messages have array content (e.g., containing thinking
blocks) but no tool_calls, the code incorrectly tried to call .trim()
on the array, causing "TypeError: content?.trim is not a function".

Changes:
- Add check for array content type before processing
- Use buildArrayContent() to properly handle array content
- Return undefined for empty array content (consistent with empty string)
- Add 2 test cases for array content scenarios

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Arvin Xu
2026-01-04 21:12:02 +08:00
committed by GitHub
parent 503c3eba4e
commit b03845d006
2 changed files with 35 additions and 1 deletions

View File

@@ -216,6 +216,33 @@ describe('anthropicHelpers', () => {
role: 'assistant',
});
});
it('should correctly convert assistant message with array content but no tool_calls', async () => {
const message: OpenAIChatMessage = {
content: [
{ thinking: 'Let me think about this...', type: 'thinking', signature: 'sig123' },
{ type: 'text', text: 'Here is my response.' },
],
role: 'assistant',
};
const result = await buildAnthropicMessage(message);
expect(result).toEqual({
content: [
{ thinking: 'Let me think about this...', type: 'thinking', signature: 'sig123' },
{ type: 'text', text: 'Here is my response.' },
],
role: 'assistant',
});
});
it('should return undefined for assistant message with empty array content', async () => {
const message: OpenAIChatMessage = {
content: [],
role: 'assistant',
};
const result = await buildAnthropicMessage(message);
expect(result).toBeUndefined();
});
});
describe('buildAnthropicMessages', () => {

View File

@@ -118,8 +118,15 @@ export const buildAnthropicMessage = async (
}
// or it's a plain assistant message
// Handle array content (e.g., content with thinking blocks)
if (Array.isArray(content)) {
const messageContent = await buildArrayContent(content);
if (messageContent.length === 0) return undefined;
return { content: messageContent, role: 'assistant' };
}
// Anthropic API requires non-empty content, filter out empty/whitespace-only content
const textContent = (content as string)?.trim();
const textContent = content?.trim();
if (!textContent) return undefined;
return { content: textContent, role: 'assistant' };
}