opencode icon indicating copy to clipboard operation
opencode copied to clipboard

Empty assistant turns still reach providers: Bedrock "text content blocks must be non-empty", DeepSeek "all messages must have non-empty content"

Open jpvelasco opened this issue 1 week ago • 3 comments

Description

OpenCode can still send an assistant turn with no provider-visible content (content: [], or only empty text parts). Strict providers reject it with a 400, and the session can't recover; every following request fails the same way.

Errors you'll see:

ValidationException: messages: text content blocks must be non-empty                      (Amazon Bedrock)
InvokeModelWithResponseStream: operation error Bedrock Runtime ... StatusCode: 400 ...       (Amazon Bedrock)
400 Bad Request: messages.N: all messages must have non-empty content                        (DeepSeek)

The same bug affects LiteLLM-fronted Bedrock and Kimi.

Cause on current dev: the 2.0 rewrite fixed most of this: toLLMMessages drops empty parts at the session layer. But the wire boundary in packages/core/src/aisdk.ts (message(), case "assistant") passes assistant content through unfiltered, so anything that doesn't go through toLLMMessages can still forward an empty turn.

OpenCode version

dev @ 88ca792e02 (v2.3.2)

Steps to reproduce

  1. Build a request containing Message.assistant([]) or Message.assistant("") followed by a user message, and compile it for an @ai-sdk/openai-compatible model.
  2. Inspect the compiled prompt: both empty assistant turns are still there.
  3. Sending that to Bedrock, DeepSeek, Kimi, or LiteLLM returns a 400.

History

This has been reported since March 2026. Every earlier report and fix PR was closed without a merge, mostly by inactivity automation:

  • Reports: #15715 (Bedrock, Mar), #16332, #17705, #22364, #23260 (root-cause write-up)
  • Fix PRs: #23259, #33647, #33706, #34272

Fix for current dev: #56942

jpvelasco avatar Nov 19 '26 00:11 jpvelasco

Seen with a simulated model or a mock server, not a real provider; a maintainer should confirm.

Thanks for the precise report. I reproduced this on 2.3.2 and on the latest dev (88ca792e), with a local mock standing in for a strict provider.

To get the empty turns into a request, I used a small plugin whose context hook adds two assistant messages, one with content: [] and one with only an empty text part. The provider uses an AI SDK package that OpenCode has no native mapping for ("package": "aisdk:@ai-sdk/deepseek"), so the request goes through packages/core/src/aisdk.ts. Both turns reached the provider as {"role":"assistant","content":""}, and the run failed with messages.1: all messages must have non-empty content.

One correction to the steps: in my runs, a provider configured with @ai-sdk/openai-compatible (with or without the aisdk: prefix) is mapped to OpenCode's own openai-compatible route, which already dropped the empty turns, so that request succeeded. The gap seems limited to AI SDK packages without a native mapping.

The script below reproduces it. The provider is a local mock that rejects empty assistant content the way DeepSeek does, and the empty turns come from the plugin; the request OpenCode sends is observed directly.

Reproduction script (repro.sh)
#!/usr/bin/env bash
# Reproduces #64771: the AI SDK route forwards assistant turns with no content.
# Needs bun and `opencode` on PATH (or OC_DEV=/path/to/opencode/checkout to run from source).
set -euo pipefail
DIR=$(mktemp -d); cd "$DIR"
mkdir -p proj/.opencode/plugins
# Strict OpenAI-compatible mock: logs messages; rejects empty assistant content like DeepSeek does.
cat > mock.ts <<'TS'
Bun.serve({ port: 4599, async fetch(req) {
  const body: any = await req.json().catch(() => ({}))
  console.log("REQUEST", JSON.stringify(body.messages))
  const bad = (body.messages ?? []).findIndex((m: any) => m.role === "assistant" && !m.tool_calls?.length &&
    (m.content == null || m.content === "" || (Array.isArray(m.content) && m.content.every((p: any) => !p.text))))
  if (bad >= 0) return Response.json({ error: { message: `messages.${bad}: all messages must have non-empty content`, type: "invalid_request_error" } }, { status: 400 })
  const enc = new TextEncoder()
  const chunks = [
    { id: "x", object: "chat.completion.chunk", created: 0, model: "m", choices: [{ index: 0, delta: { role: "assistant", content: "ok" }, finish_reason: null }] },
    { id: "x", object: "chat.completion.chunk", created: 0, model: "m", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } },
  ]
  return new Response(new ReadableStream({ start(c) { for (const ch of chunks) c.enqueue(enc.encode(`data: ${JSON.stringify(ch)}\n\n`)); c.enqueue(enc.encode("data: [DONE]\n\n")); c.close() } }), { headers: { "content-type": "text/event-stream" } })
}})
TS
# A provider on the AI SDK route (an AI SDK package OpenCode has no native mapping for).
cat > proj/opencode.jsonc <<'JSON'
{ "providers": { "strict": { "name": "Strict", "env": ["STRICT_API_KEY"],
  "package": "aisdk:@ai-sdk/deepseek", "settings": { "baseURL": "http://127.0.0.1:4599/v1" },
  "models": { "m": { "name": "M" } } } } }
JSON
# A `context` hook hands the request two empty assistant turns (content [] and a single "" text part).
cat > proj/.opencode/plugins/empty-assistant.ts <<'TS'
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
  id: "empty-assistant",
  setup: async (ctx) => {
    await ctx.session.hook("context", async (event) => {
      const user = event.messages[event.messages.length - 1]
      const empty = [
        { ...user, id: "msg_empty1", role: "assistant", content: [] },
        { ...user, id: "msg_empty2", role: "assistant", content: [{ type: "text", text: "" }] },
      ] as any[]
      event.messages = [...event.messages.slice(0, -1), ...empty, user]
    })
  },
})
TS
bun mock.ts > mock.log 2>&1 & MOCK=$!; trap 'kill $MOCK' EXIT; sleep 1
cd proj; git init -q
if [ -n "${OC_DEV:-}" ]; then
  # The source CLI starts its server as a child bun process; give it the same preload via bunfig.toml.
  echo "preload = [\"$OC_DEV/packages/tui/node_modules/@opentui/solid/scripts/preload.js\"]" > bunfig.toml
  RUN=(bun --conditions=browser --preload="$OC_DEV/packages/tui/node_modules/@opentui/solid/scripts/preload.js" "$OC_DEV/packages/cli/src/index.ts")
else RUN=(opencode); fi
"${RUN[@]}" --version
STRICT_API_KEY=x timeout 180 "${RUN[@]}" run -m strict/m "say hi" 2>&1 | tail -3 || true
echo "--- messages sent to the provider:"
grep -a REQUEST ../mock.log | tail -1 | sed 's/^REQUEST //' | jq -c '.[] | {role, content: (.content|tostring|.[0:60])}'

Run it: bash repro.sh

opencodejr[bot] avatar Nov 19 '26 00:11 opencodejr[bot]

Taking this one. The fix belongs at the AI SDK wire boundary: message() in packages/core/src/aisdk.ts maps every assistant part unfiltered, so an empty turn produces { role: "assistant", content: [] } (or an empty text block). I'll mirror the existing toolMessage guard — drop empty text fragments and skip the message when nothing provider-visible remains — and cover it with a compile-level test in packages/core/test/aisdk.test.ts.

ccclucky avatar Nov 20 '26 14:11 ccclucky

Took this. The fix is at the wire boundary the report names: message() in packages/core/src/aisdk.ts now drops an empty text part while mapping, and omits a turn whose content maps to nothing, for both user and assistant.

Test: compiles Message.assistant(""), Message.assistant([]) and Message.user("") next to real turns, then asserts the prompt carries no assistant turn and exactly the two real user turns. It fails on dev and passes with the change; packages/core/test/aisdk.test.ts is 47 pass, typecheck clean.

I could not run it against Bedrock or DeepSeek (no credentials), so the evidence is the compiled prompt — the thing those providers reject.

Branch empty-turn-wire-boundary. PR creation is refused for this account right now (FORBIDDEN on CreatePullRequest, masked as 404 in REST), so it waits as a branch with the body written.

Guembri01 avatar Nov 25 '26 20:11 Guembri01