opencode icon indicating copy to clipboard operation
opencode copied to clipboard

fix(provider): trim whitespace and filter empty content in transformations

Open jerome-benoit opened this issue 1 week ago • 1 comments

Summary

Implement consistent whitespace trimming across all provider transformation functions to prevent API validation errors from empty or whitespace-only message content.

Changes

  • Trim all text content before length checks and assignments across all provider transformations
  • Filter out whitespace-only messages and parts to prevent empty content from reaching APIs
  • Two-phase filter+map approach in normalizeMessages for consistent handling
  • Preserve tool results and streaming deltas without modification (whitespace may be significant)
  • Add 65 comprehensive tests for whitespace handling scenarios

Affected Files

File Changes Description
anthropic.ts 44 changes Trim content in all Anthropic transformations
openai.ts 42 changes Trim content in all OpenAI transformations
openai-compatible.ts 32 changes Trim content in OpenAI-compatible transformations
transform.ts 31 changes Update normalizeMessages with two-phase filtering
transform.test.ts 91 additions Comprehensive test coverage

Total: 5 files changed, 184 insertions(+), 56 deletions(-)

Why This Change?

APIs like Anthropic and OpenAI reject requests with empty or whitespace-only text content, causing validation errors. This change ensures all text content is trimmed and empty parts are filtered before being sent to providers.

Testing

✅ All 65 tests pass, covering:

  • Whitespace-only content filtering
  • Leading/trailing whitespace trimming
  • Empty array handling
  • Tool result preservation
  • Mixed content scenarios
  • Streaming delta preservation

Pattern Applied

// Before
if (content.length > 0) {
  parts.push({ type: "text", text: content })
}

// After  
const t = content.trim()
if (t.length > 0) {
  parts.push({ type: "text", text: t })
}

jerome-benoit avatar Jan 06 '26 13:01 jerome-benoit