fix(cohere): cap stop_sequences at five entries and omit null

PC
7h ago
+85-4

Description

Cohere's /v2/chat endpoint rejects requests with more than 5 stop_sequences with HTTP 400. Previously, internal/providers/cohere/chat.go forwarded stop and stop_sequences without capping the list length, and treated a JSON null value for stop as "" (serializing stop_sequences: [""]) or forwarded stop_sequences: null literally.

Root cause

  • stopSequences in internal/providers/cohere/chat.go did not check for JSON null before unmarshaling into a string (in Go, unmarshaling null into string succeeds with ""), and did not cap array length to Cohere's 5-sequence limit.
  • copyChatExtraFields bypassed stopSequences when falling back to stop_sequences.

Fix

  • Omit stop_sequences when stop or stop_sequences is empty or JSON null, allowing stop: null to fall back to stop_sequences if provided.
  • Truncate stop / stop_sequences arrays longer than 5 entries to maxStopSequences = 5 and log a warning (slog.Warn), matching providers.CapStopSequences and the Gemini provider (#1591).
  • Pass stop_sequences through stopSequences as well.

Testing

  • Added TestChatCompletion_StopSequences in internal/providers/cohere/cohere_test.go covering within-limit lists, over-limit truncation for both stop and stop_sequences, bare string wrapping, null omission, and stop: null fallback to stop_sequences.
  • Verified go test ./internal/providers/cohere/... and go test ./internal/testconventions/... pass.

Summary by CodeRabbit

  • Bug Fixes
    • Stop sequences now handle null values consistently, support a single string, and use the fallback field when the primary value is null.
    • Requests with more than five stop sequences are limited to five.