Skip to content

fix(databricks): join plain text blocks for non-Claude json_object requests - #46436

Closed
mateo-berri wants to merge 3 commits into
mainfrom
litellm_databricks_json_object_multi_text_blocks
Closed

mateo-berri wants to merge 3 commits into
mainfrom
litellm_databricks_json_object_multi_text_blocks

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

How it solves it:

  • Non-Claude json_object requests join plain text blocks into one string
  • Blocks join with no separator, the way OpenAI reads them
  • Lists with cache_control, images, or extra keys stay lists
  • Claude models and requests without json_object are unchanged
Design notes

Databricks only looks for the word "json" in string content, so list content fails in JSON mode however the text is split. The join only runs for response_format: {"type": "json_object"} on non-Claude models, where the list form always 400s today, so no request that works now changes shape. A join on every request, like the single block collapse in #45686, was rejected because models read a multi-block list differently. Gemma 3 12B and Llama 4 Maverick on Databricks read it as one run of text, while Llama 3.3 70B and gpt-oss-120b put a space between blocks, so a global join could change the prompt of working requests

The blocks join with an empty string. OpenAI reads a list of text blocks as concatenated text (gpt-5.4-mini echoed XQ7ZK9 for the blocks XQ7 and ZK9), and convert_content_list_to_str already joins the same way, so Databricks gets the prompt the caller wrote for OpenAI. A newline or space separator was rejected because it adds characters the caller never sent. Injecting the word "json" into the prompt was rejected because it changes what the model reads

The join runs per message before consecutive system messages are merged, so two system messages keep the blank line between them. Joining after the merge would glue them into one run of text. A text block that carries cache_control or any other extra key, or a list with an image, stays a list, so a cache marker is never dropped silently

The empty text block filter now reads blocks through the same typed path. One edge changes there: a text block whose text is a truthy non-string used to raise AttributeError and is now kept as is

User Flow

Before: a developer whose app builds its prompt from several text parts gets a 400 in JSON mode from a Databricks model

  1. They send POST https://litellm-domain/v1/chat/completions to Databricks Llama 3.3 or Qwen 3.5 with json_object and two text parts
  2. The proxy returns HTTP 400 "messages" must contain the word "json" in some form
  3. The same two parts sent as input_text to POST https://litellm-domain/v1/responses with json_object get the same 400

After: the same requests succeed and come back as JSON

  1. They send the same POST https://litellm-domain/v1/chat/completions with two text parts and json_object
  2. The proxy returns HTTP 200 with {"result": "ok"} as the message content
  3. The same POST https://litellm-domain/v1/responses returns HTTP 200 with {"result": "ok"} as its output text

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Shared setup, config and client

These are live runs against real Databricks serving endpoints with curl, the client from the original report. Each leg is one proxy process with --num_workers 2 and no database, booted from the config below, with the same requests on both legs. Long lines are cut at 1500 characters. /v1/messages is not a case because the Anthropic Messages API has no json_object mode, so no request there reaches the changed code

model_list:
  - model_name: dbx-qwen35
    litellm_params:
      model: databricks/databricks-qwen35-122b-a10b
      api_key: os.environ/DATABRICKS_API_KEY
      api_base: os.environ/DATABRICKS_API_BASE
  - model_name: dbx-llama70b
    litellm_params:
      model: databricks/databricks-meta-llama-3-3-70b-instruct
      api_key: os.environ/DATABRICKS_API_KEY
      api_base: os.environ/DATABRICKS_API_BASE
  - model_name: dbx-claude
    litellm_params:
      model: databricks/databricks-claude-sonnet-5-5
      api_key: os.environ/DATABRICKS_API_KEY
      api_base: os.environ/DATABRICKS_API_BASE
litellm_settings:
  num_retries: 0
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
Case Before After
Chat completions, Llama 3.3 70B, two text parts 400 200
Chat completions, Qwen 3.5, two text parts 400 200
Responses, Llama 3.3 70B, two input_text parts 400 200
Chat completions streaming, Qwen 3.5, two text parts 400 400
Control, Streaming, Qwen 3.5, one string 400 400
Control, Claude Sonnet 5.5, two text parts 200 200
Control, Qwen 3.5, one string 200 200
Control, Llama 3.3, no response_format 200 200
Control, Llama 3.3, json_schema 200 200

Before (aa0279e)

Chat completions, Llama 3.3 70B, two text parts

  1. Send the request

    curl -sS -w '\nHTTP %{http_code}\n' http://localhost:$PORT/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"dbx-llama70b","messages":[{"role":"user","content":[{"type":"text","text":"Reply in JSON"},{"type":"text","text":" with key result set to ok."}]}],"response_format":{"type":"json_object"},"max_tokens":60,"temperature":0}'
  2. Observed response

    {"error":{"message":"litellm.BadRequestError: DatabricksException - {\"error_code\":\"BAD_REQUEST\",\"message\":\"\\\"messages\\\" must contain the word \\\"json\\\" in some form, to use \\\"response_format\\\" of type \\\"json_object\\\".\\n\"}\n\nLiteLLM: model group 'dbx-llama70b' failed with the error above. No fallback was attempted.","type":"invalid_request_error","param":null,"code":"400"}}
    HTTP 400
    

Chat completions, Qwen 3.5, two text parts

Steps and output
  1. Send the request

    curl -sS -w '\nHTTP %{http_code}\n' http://localhost:$PORT/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"dbx-qwen35","messages":[{"role":"user","content":[{"type":"text","text":"Reply in JSON"},{"type":"text","text":" with key result set to ok."}]}],"response_format":{"type":"json_object"},"max_tokens":8000,"temperature":0}'
  2. Observed response

    {"error":{"message":"litellm.BadRequestError: DatabricksException - {\"error_code\":\"BAD_REQUEST\",\"message\":\"\\\"messages\\\" must contain the word \\\"json\\\" in some form, to use \\\"response_format\\\" of type \\\"json_object\\\".\\n\"}\n\nLiteLLM: model group 'dbx-qwen35' failed with the error above. No fallback was attempted.","type":"invalid_request_error","param":null,"code":"400"}}
    HTTP 400
    

Responses, Llama 3.3 70B, two input_text parts

Steps and output
  1. Send the request

    curl -sS -w '\nHTTP %{http_code}\n' http://localhost:$PORT/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"dbx-llama70b","input":[{"role":"user","content":[{"type":"input_text","text":"Reply in JSON"},{"type":"input_text","text":" with key result set to ok."}]}],"text":{"format":{"type":"json_object"}},"max_output_tokens":60,"temperature":0}'
  2. Observed response

    {"error":{"message":"litellm.BadRequestError: DatabricksException - {\"error_code\":\"BAD_REQUEST\",\"message\":\"\\\"messages\\\" must contain the word \\\"json\\\" in some form, to use \\\"response_format\\\" of type \\\"json_object\\\".\\n\"}\n\nLiteLLM: model group 'dbx-llama70b' failed with the error above. No fallback was attempted.","type":"invalid_request_error","param":null,"code":"400"}}
    HTTP 400
    

Chat completions streaming, Qwen 3.5, two text parts

Steps and output
  1. Send the request

    curl -sS -w '\nHTTP %{http_code}\n' http://localhost:$PORT/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"dbx-qwen35","stream":true,"messages":[{"role":"user","content":[{"type":"text","text":"Reply in JSON"},{"type":"text","text":" with key result set to ok."}]}],"response_format":{"type":"json_object"},"max_tokens":400,"temperature":0}'
  2. Observed response

    {"error":{"message":"litellm.BadRequestError: DatabricksException - {\"error_code\":\"BAD_REQUEST\",\"message\":\"Bad request: parameter \\\"stream\\\" is not supported with \\\"response_format\\\" of type \\\"json_object\\\"\\n\"}\n\nLiteLLM: model group 'dbx-qwen35' failed with the error above. No fallback was attempted.","type":"invalid_request_error","param":null,"code":"400"}}
    HTTP 400
    

After (29647eb)

Chat completions, Llama 3.3 70B, two text parts

  1. Send the request

    curl -sS -w '\nHTTP %{http_code}\n' http://localhost:$PORT/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"dbx-llama70b","messages":[{"role":"user","content":[{"type":"text","text":"Reply in JSON"},{"type":"text","text":" with key result set to ok."}]}],"response_format":{"type":"json_object"},"max_tokens":60,"temperature":0}'
  2. Observed response

    {"id":"chatcmpl_57b3f200-c0ec-4fad-9b2a-2fedfd80bd8d_0029e7e7-3c5f-4e08-b3f4-8e8c9708925f","created":1791986651,"model":"dbx-llama70b","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"{\"result\": \"ok\"}","role":"assistant"}}],"usage":{"completion_tokens":7,"prompt_tokens":45,"total_tokens":52,"prompt_tokens_details":{"cached_tokens":0},"cache_read_input_tokens":0}}
    HTTP 200
    

Chat completions, Qwen 3.5, two text parts

Steps and output
  1. Send the request

    curl -sS -w '\nHTTP %{http_code}\n' http://localhost:$PORT/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"dbx-qwen35","messages":[{"role":"user","content":[{"type":"text","text":"Reply in JSON"},{"type":"text","text":" with key result set to ok."}]}],"response_format":{"type":"json_object"},"max_tokens":8000,"temperature":0}'
  2. Observed response

    {"id":"chatcmpl_ff6f9531-41ce-4a24-8af9-2edc58de9e71_0dbe23ce-49bd-494e-924c-5deeefa25d73","created":1791986951,"model":"dbx-qwen35","object":"chat.completion","choices":[{"finish_reason":"stop","index":0,"message":{"content":"{\"result\": \"ok\"}","role":"assistant","reasoning_content":"Thinking Process:\n\n1.  **Analyze the Request:**\n    *   Input: \"Reply in JSON with key result set to ok.\"\n    *   Constraint: The output must be in JSON format.\n    *   Specific Requirement: The JSON object must have a key named \"result\" and its value must be \"ok\".\n\n2.  **Determine the Output Format:**\n    *   JSON (JavaScript Object Notation).\n    *   Structure: `{\"result\": \"ok\"}`\n\n3.  **Validate Constraints:**\n    *   Is it valid JSON? Yes.\n    *   Does it have the key \"result\"? Yes.\n    *   Is the value \"ok\"? Yes.\n\n4.  **Construct the Final Output:**\n    *   `{\"result\": \"ok\"}`\n\n5.  **Final Review:** Ensure no extra text, markdown code blocks (unless implicitly allowed, but usually raw JSON is safer for strict parsing), or explanations are added. The prompt asks to \"Reply in JSON\", so raw JSON is the most direct compliance. However, often markdown code blocks are acceptable for readability. Given the strictness of \"Reply in JSON\", I should output just the JSON string to be safe, or a markdown block containing JSON. Usually, for API-like requests, raw JSON is preferred. But as a chat model, wrapping in ```json``` is common. Let's look at the instructi
    HTTP 200
    

Responses, Llama 3.3 70B, two input_text parts

Steps and output
  1. Send the request

    curl -sS -w '\nHTTP %{http_code}\n' http://localhost:$PORT/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"dbx-llama70b","input":[{"role":"user","content":[{"type":"input_text","text":"Reply in JSON"},{"type":"input_text","text":" with key result set to ok."}]}],"text":{"format":{"type":"json_object"}},"max_output_tokens":60,"temperature":0}'
  2. Observed response

    {"id":"resp_vkDJP31iIKcHsl2Blxoef3C5DnWR1Dfmfq5J09NxIPWSsRn3bs6oTlI2mnDV4qgAU3JT5D5bUn1-eGzch58m096uwCOgbW8hfzd3pW8Cmfr3Fi4BHFuAFaeT-Jxe5oe4tacAFEhD5H1kskHdCIrF7DUxZZwGaSwvl4KVKB5LOpsgB0qR7r4XYn6h7hCgJpISpxWqbPN2PKLMSiJdzIYEExaq5yXClk8tzFMVBEHkS3w94v6EcgAQGlJxFtTmvyzOeX-ANQ6oZGdKZilcOVxveY4HG37Z2fUD2BmC5eEa7fKukx_aGxnNBiUQ_OM3x6KaewHCyHSRDlRbruTHz0i42IywJNg2gphYvFM0MntyfoZzu9hs-REQecy7R08T49meu2Ir9wjUo74mM8bna37ti080e89t80yJAmGcEKtbGin5oxl4km7kbCcRtoKzROF_JMIrPwwRqwGxlJg6jBNJYpzpYnIXKV60SUsHjfw2DlvgPR0fpH50LJeLZOlFZRRr1WQDrChfJqu0jg==","created_at":1791986652,"error":null,"incomplete_details":null,"instructions":null,"metadata":{},"model":"dbx-llama70b","object":"response","output":[{"type":"message","id":"msg_efce2d60-0ad9-45bd-ab42-8773c8956637","status":"completed","role":"assistant","content":[{"type":"output_text","text":"{\"result\": \"ok\"}","annotations":[]}],"phase":null}],"parallel_tool_calls":false,"temperature":0.0,"tool_choice":"auto","tools":[],"top_p":null,"max_output_tokens":60,"previous_response_id":null,"reasoning":null,"status":"completed","text":{"format":{"type":"json_object"}},"truncation":null,"usage":{"input_tokens":45,"input_tokens_details":{"audio_tokens":null,"cached_tokens":0,"cached_tokens_details":null,"image_tokens":null,"text_tokens":null,"video_tokens":null},"output_tokens":7,"output_tokens_details":null,"total_tokens":52,"cost":null},"user":null,"store":null}
    HTTP 200
    

Chat completions streaming, Qwen 3.5, two text parts

Steps and output
  1. Send the request

    curl -sS -w '\nHTTP %{http_code}\n' http://localhost:$PORT/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' -d '{"model":"dbx-qwen35","stream":true,"messages":[{"role":"user","content":[{"type":"text","text":"Reply in JSON"},{"type":"text","text":" with key result set to ok."}]}],"response_format":{"type":"json_object"},"max_tokens":400,"temperature":0}'
  2. Observed response

    {"error":{"message":"litellm.BadRequestError: DatabricksException - {\"error_code\":\"BAD_REQUEST\",\"message\":\"Bad request: parameter \\\"stream\\\" is not supported with \\\"response_format\\\" of type \\\"json_object\\\"\\n\"}\n\nLiteLLM: model group 'dbx-qwen35' failed with the error above. No fallback was attempted.","type":"invalid_request_error","param":null,"code":"400"}}
    HTTP 400
    

The Qwen 3.5 reasoning quotes the prompt as "Reply in JSON with key result set to ok.", so the parts are joined exactly as written

Observations from the run

  • Streaming json_object 400s on both legs, even with one string
  • Databricks rejects stream together with json_object upstream
  • This PR leaves both streaming results unchanged
  • Qwen 3.5 sometimes reasons until max_tokens, returning null content
  • Reruns of that same request returned {"result": "ok"}
  • Its joined prompt equals the one-string control, per the wire test

Type

🐛 Bug Fix
✅ Test

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
Bugbot summary

[!NOTE]
Medium Risk
Narrows to Databricks non-Claude json_object requests but changes upstream message shape (prompt text) for that case; mis-scoped joins could alter model input for multi-block prompts.

Overview
Fixes Databricks 400 errors when response_format: {"type": "json_object"} is used with message content split across multiple plain text blocks (Databricks only checks string content for the word "json").

DatabricksConfig.transform_request now preprocesses messages so that, on non-Claude models with json_object, consecutive plain text blocks in a message are concatenated with no separator into a single string—matching how OpenAI-style clients treat multi-part text. Lists that mix text with images, cache_control, or other keys are left unchanged; Claude, json_schema, and requests without json_object are unchanged.

Shared helpers (_plain_text / _plain_texts) also drive single-block collapse and empty text block filtering in _sanitize_empty_content (typed validation via TypeAdapter). Integration and unit tests cover chat/responses paths, streaming wire shape, and system-message merge ordering.

Reviewed by Cursor Bugbot for commit 29647eb. Bugbot is set up for automated code reviews on this repo. Configure here.

@codspeed

codspeed Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 37 untouched benchmarks


Comparing litellm_databricks_json_object_multi_text_blocks (f3d4419) with main (be649f6)

Open in CodSpeed

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 14, 2026

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

Completed · Some checks not run.

No correctness findings.

Checks and execution details
  • Passed · Real testing evidence (required): In scope: litellm/llms/databricks/chat/transformation.py changes outgoing message content for non-Claude json_object requests. The PR description includes inspectable manual E2E evidence. It names the before/after commits (aa0279e0a2 / 29647eb343), the proxy config, and the exact curl commands against real Databricks serving endpoints. It shows the observed responses: Llama 3.3 chat with two text parts went from 400 (must contain the word json) to 200 {"result": "ok"}, Qwen 3.5 chat went from 400 to 200, and /v1/responses with two input_text parts went from 400 to 200. Controls (Claude, a single string, no response_format, json_schema) stayed unchanged. The PR also adds wire-level integration cases A6–A9 in tests/integration/providers/test_databricks_chat_wire.py, which assert the upstream request body. I did not execute those here because they need the Postgres/Redis integration harness.
  • Passed · Databricks unit tests (optional): uv run pytest tests/unit/llms/databricks/chat/test_databricks_chat_transformation.py -q: 88 passed, 1 failed. The failure is test_databricks_anthropic_function_call_with_no_schema[databricks-claude-3-7-sonnet], caused by ModuleNotFoundError: No module named 'mcp' in the local env. It does not involve this change.
  • Passed · Edge-case probe of transform_request (optional): Ran DatabricksConfig().transform_request locally on four cases. (1) A pydantic Message mixed into the history passes through unchanged. (2) A message-level cache_control with two text blocks yields one joined block that keeps cache_control, so no marker is lost. (3) An empty middle text block is joined away and the output is 'a json'. (4) Empty list content is dropped the same way as before.
  • Not run · Integration wire tests A6–A9 (optional): Not run because the suite needs the CircleCI-owned Postgres/Redis/proxy harness (tests/integration/run.py providers), which is not available in this sandbox.

View review · Reviewed 29647eb343f0

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@codecov

codecov Bot commented Oct 14, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.12195% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/llms/databricks/chat/transformation.py 95.12% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 29647eb. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

Superseded by #49385, which carries the same fix and proof forward. Closing this copy so review happens in one place

@mateo-berri
mateo-berri deleted the litellm_databricks_json_object_multi_text_blocks branch October 31, 2026 02:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant