Skip to content

fix: preserve Cloudflare JSON Schema requests - #129

Merged
stackbilt-admin merged 8 commits into
Stackbilt-dev:mainfrom
mikemikimike:fix/cloudflare-json-schema-127
Nov 9, 2026
Merged

stackbilt-admin merged 8 commits into
Stackbilt-dev:mainfrom
mikemikimike:fix/cloudflare-json-schema-127

Conversation

@mikemikimike

Copy link
Copy Markdown
Contributor

Summary

  • Preserve Cloudflare Workers AI json_schema requests by forwarding the native JSON Schema payload.
  • Mark native structured-output capability for supported Cloudflare models so route plans do not misreport silent emulation.
  • Reject unsupported streaming JSON Schema requests with a clear configuration error.
  • Add regression coverage for request forwarding, routing capability reporting, and the streaming boundary.

Fixes #127

Issue: #127

Validation

  • npm test
  • npm run typecheck
  • npm run build
  • npm run test:worker-import
  • git diff --check

@stackbilt-admin stackbilt-admin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for picking up #127. Sending response_format.json_schema in Cloudflare's native shape is the right direction, and the forwarding test does catch the original drop. Right now, though, the capability report, the request that's actually sent, and the streaming behavior disagree with each other, so we need changes before this can merge.

Requested changes

  1. Gate forwarding on the capability. formatRequest builds nativeJsonSchema from response_format.type === 'json_schema' alone, and the new supportsStructuredOutput flag is never consulted. Please forward the schema natively only when the model declares support. Otherwise, reject clearly (see item 2) and make the route plan report it. Prompting with the schema (reported as emulated) is acceptable only when the caller explicitly permits it, because a prompt instruction doesn't give native schema enforcement.

  2. Make the streaming boundary consistent, and don't block fallback.

    • The guard checks request.stream, but CloudflareProvider.streamResponse() calls formatRequest() first and adds stream: true afterwards, so direct streaming callers skip the guard and send stream: true together with response_format: json_schema. Please enforce the rule on every streaming path, for example by passing the stream flag into formatRequest or checking in streamResponse.
    • The guard throws ConfigurationError, and the factory never falls back on that error (getFallbackDecision). Cloudflare is first in the default chain, so a streaming JSON-schema request fails outright even when a later provider supports it natively. Rejecting the unsupported combination is reasonable; preventing fallback isn't. Emulate only when the caller explicitly permits it; otherwise reject consistently and allow routing to a compatible provider. Please add a test that goes through the factory.
  3. Make route reporting match what's sent.

    • routeDegradations reports emulated for Cloudflare models without the flag, but the adapter injects no instruction for json_schema. Your test asserts no system message is added, so nothing is actually emulated.
    • For stream + json_schema on Cloudflare, the plan reports executable with no failed degradation, but the adapter throws.
    • In the other direction, json_object on flagged models now reports no degradation, while the adapter still emulates json_object with a prompt instruction.

    Please make getGatewayRoutePlan describe exactly what the adapter does in each of these cases.

  4. Make the new public field optional. GatewayRouteCapabilityReport.supportsStructuredOutput is a required boolean on an exported interface, which breaks consumers who build or mock that type by hand (the reason GatewayRoutePlan.executable is optional). Please make it supportsStructuredOutput?: boolean.

Also please cover the paths that bypass the standard formatter. formatAnthropicViaCloudflareRequest and the raw Llama vision path still drop the schema silently. At minimum they should report or reject consistently with item 3, rather than reproducing the original silent drop.

Tests we'd like to see: a model without the flag; streaming through streamResponse(); factory fallback for stream + schema; a route plan for stream + schema on Cloudflare; and one route-plan assertion for a non-flagged Cloudflare model. The current route-plan test passes on main apart from the new field.

Advisory (not blocking on its own)

  • Flag naming: #113 proposes separate supportsJsonObject / supportsJsonSchema capabilities. Since a public name can't be removed without a major version, aligning now (for example naming this supportsJsonSchema) would avoid locking in a broader flag than the behavior it controls. This PR doesn't need to complete #113.
  • Model compatibility evidence: we haven't verified which Cloudflare models reject json_schema or return "JSON Mode couldn't be met", so treat that as a risk pending docs or live results. Please cite a source for the @cf/zai-org/glm-5.3 flag (llama-3.3-70b-fp8-fast is on Cloudflare's JSON mode list), and keep CloudflareProvider.getModelCapabilities() reading from the same source so the two can't drift. Mapping "JSON Mode couldn't be met" to a clear error in wrapCFError would be a good addition.
  • A CHANGELOG entry. With the public additions this would be a minor release.

CI is waiting on maintainer approval for fork PRs. We'll require normal CI to pass on the final commit before merging. The failing supply-chain check is a known repo-level problem unrelated to this PR, tracked in #137.

@mikemikimike

Copy link
Copy Markdown
Contributor Author

Implemented the requested Cloudflare structured-output fixes in commit 21b5113f6ec6ffce4b36c5521a8c1a733bd5570e.

  • Native JSON Schema forwarding is gated by model capability.
  • Unsupported schema requests fail clearly unless prompt emulation is explicitly enabled.
  • Streaming schema requests are rejected on every path, while the factory can fall back to a compatible provider.
  • Route plans now report native, emulated, and failed behavior consistently.
  • Anthropic-via-Cloudflare and raw Llama vision paths no longer silently drop schema requests.
  • GatewayRouteCapabilityReport.supportsStructuredOutput is optional.

Validation passed: npm test (798 tests), npm run typecheck, npm run build, npm run test:worker-import, and git diff --check.

@stackbilt-admin

Copy link
Copy Markdown
Member

Thanks for the thorough update. Before we can review it again, it needs a rebase: #139 (released as 1.24.0) changed several of the same files (src/providers/cloudflare.ts, src/factory.ts, src/types.ts, src/errors.ts), and this PR now conflicts with main. Please rebase onto current main (a2bc706) and push.

When resolving the conflicts, please keep two things from #139:

  • reasoning.strict requests with an effort route only to Cloudflare and throw ReasoningEffortUnsupportedError before any call, and the factory never falls back on that error.
  • A pinned model is never silently replaced; allowFallback: false limits the request to the first planned provider.

Please also keep isCachedResponse in sync if this PR adds response fields. Once it's rebased, we'll approve CI and do a final review.

@stackbilt-admin

Copy link
Copy Markdown
Member

Thanks for the rebase and the follow-up commits. Streaming is now checked on every path, the factory falls back on STRUCTURED_OUTPUT_UNSUPPORTED and respects allowFallback: false, and GatewayRouteCapabilityReport.supportsStructuredOutput is optional. We reviewed the PR as it would land on 1.25.0. It typechecks and the suite passes. Two problems block merging, and a few earlier requests are still open.

Blocking

  1. @cf/zai-org/glm-5.3-flash gets the wrong request shape. The PR sends every model flagged supportsStructuredOutput the legacy JSON mode shape, response_format: { type: "json_schema", json_schema: <schema> }. Cloudflare's published input schema for glm-5.3-flash (and glm-5.3) uses the OpenAI-style wrapper, json_schema: { name, schema, strict? }, with name required. glm-5.3-flash is the default model for a json_schema request that doesn't name one, so this reaches the default Workers AI path:
    • if Workers AI rejects it, the error becomes InvalidRequestError, which doesn't fall back, so a request that is served today fails;
    • if Workers AI accepts it, there is no schema key, so nothing is enforced while the route plan reports native support.
  2. The GLM flags don't match Cloudflare's docs. glm-5.3 is false, though its model page says it supports structured outputs; glm-5.3-flash is true, though its page doesn't. Both publish the same response_format schema. One boolean also can't express the two wire shapes (JSON mode models take the raw schema, the GLM models take { name, schema }). Please make the capability carry the shape (or choose it per model in the adapter), cite the Cloudflare doc for each flagged model, and add a test that pins the request body for each shape.

Still open from the earlier review

  • One source for the flag. getModelCapabilities() and the catalog still each hold a copy, and they already differ (glm-5.3 is false in the provider and unset in the catalog).
  • Factory test for streaming plus a schema. The fallback test in factory.test.ts mocks the Cloudflare provider, so it doesn't exercise the real adapter error, and there is no streaming case.
  • Route plan vs adapter on the Llama vision path. With allowStructuredOutputEmulation, getGatewayRoutePlan reports emulated and executable for @cf/meta/llama-3.2-11b-vision-instruct with an image, but the adapter throws.

Also needed

  • Other providers' route plans. supportsStructuredOutput: capabilities?.supportsStructuredOutput ?? false (gateway-routing.ts) now reports false for OpenAI, Anthropic, Groq, Cerebras and NVIDIA. Leave it undefined when the capability isn't known.
  • GatewayRouteRequirements.allowStructuredOutputEmulation is a new required field on an exported type; please make it optional, as with the capability report.
  • The emulation opt-in is an untyped key in metadata, which is otherwise for observability. Please make it a typed field (for example under providerOptions.cloudflare) and document it in the README. On a flagged model with emulation allowed, the adapter currently sends both the native response_format and the prompt instruction.
  • Test fixture. The "unsupported" model in the tests, @cf/meta/llama-3.1-8b-instruct, is on Cloudflare's JSON mode list. Please pick a model that isn't, and add tests for the GLM wire shape, the vision path with emulation, and json_object still being prompt-emulated on flagged models.
  • Documented JSON mode models. Of the models on Cloudflare's JSON mode list that the catalog has, only llama-3.3-70b-instruct-fp8-fast is flagged. Pinned json_schema requests to the others now throw and fail over off Workers AI.
  • CHANGELOG. The PR adds public API (StructuredOutputUnsupportedError, ModelCapabilities.supportsStructuredOutput, the GatewayRoute* fields, the opt-in), so it needs an Added section. It also changes behaviour: direct CloudflareProvider json_schema calls on unflagged models now throw where they used to succeed, which goes under Changed. Together that makes this a minor release.
  • Rebase onto main (1.25.0). Only CHANGELOG.md conflicts; new entries go under ## [Unreleased].

Optional: map Workers AI's "JSON Mode couldn't be met" error in wrapCFError.

@mikemikimike
mikemikimike force-pushed the fix/cloudflare-json-schema-127 branch from 6247032 to 249285f Compare November 7, 2026 04:04
@stackbilt-admin

Copy link
Copy Markdown
Member

Thanks for the update. It addresses both blocking items. The capability now records the request shape per model, from one table shared by the provider and the catalog: models on Cloudflare's JSON mode list get the bare schema, and glm-5.3 and glm-5.3-flash get { name, schema, strict? }, with tests that pin each request body. The flagged JSON mode models match Cloudflare's list. Other providers' route plans leave the capability undefined. The opt-in is a typed field and documented in the README. Native output and prompt emulation are never sent together. The Llama vision path now emulates, matching its route plan. The unsupported-model fixture is off the JSON mode list, and the CHANGELOG has Added and Changed sections. We reviewed it as it would land on 1.25.0. It typechecks, the suite passes (914 tests), and the build and worker import check pass.

One item from the earlier review is still open:

  1. Factory tests against the real adapter. The new test in factory.test.ts still mocks the Cloudflare provider's generateResponse to reject, so it doesn't show that the real adapter's error falls back. Please add factory tests that use a real CloudflareProvider (with a mocked ai.run) for:
    • a json_schema request on a model without native support, which falls back to the next provider without calling ai.run;
    • a streaming json_schema request, which falls back the same way;
    • the same request with allowFallback: false, which surfaces StructuredOutputUnsupportedError.

Minor, not blocking: in formatAnthropicViaCloudflareRequest, the structuredOutputInstruction call runs before the streaming and emulation checks. A json_schema request without emulation therefore throws the shorter message without the allowStructuredOutputEmulation hint. Moving that call below the two checks fixes it.

Optional, still open: mapping Workers AI's "JSON Mode couldn't be met" error in wrapCFError.

We plan to ship this as a minor release.

mikemikimike and others added 4 commits November 9, 2026 10:03
# Conflicts:
#	CHANGELOG.md
#	src/providers/cloudflare.ts
…dels

- StructuredOutputUnsupportedError no longer counts as a Cloudflare health
  failure; it is thrown before any Workers AI call.
- Unpinned json_schema requests plan only Cloudflare models with native
  support, unless prompt emulation is allowed.
- README and CHANGELOG cover the new error, fields and route plan changes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@stackbilt-admin
stackbilt-admin merged commit 72b3ee9 into Stackbilt-dev:main Nov 9, 2026
4 checks passed
stackbilt-admin added a commit that referenced this pull request Nov 9, 2026
* chore: release 1.28.0

- Native JSON Schema output on Cloudflare Workers AI (#129, closes #127)
- Upgrade note for Cloudflare json_schema behaviour
- Checkpoint and README version references updated

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: 1.28.0 review fixes for the checkpoint, CHANGELOG and README

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Kurt Overmier <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

Workers AI silently drops json_schema while the route plan reports no degradation

3 participants