← Back to Pull requests

[api][plan][integrations][java][python] Apply an agent output schema natively on the final response #1215

Closed
unknown closed this pull request without merging on Oct 13, 2026 03:09 UTC
View on GitHub
unknown unknown commented on Oct 09, 2026 09:30 UTC
Author

Linked issue: #912

Purpose of change

When an agent asks for structured output and its chat model can enforce a schema natively, the final answer now comes from a provider call carrying the schema, so the provider enforces the format rather than the prompt. This completes #280: providers could apply a schema, but the runtime never handed one over.

Nothing changes when the schema does not resolve to native; under the default AUTO that covers every unlisted model and every RowTypeInfo schema.

Runtime flow

1. ReActAgent asks the chat model setup whether the schema will travel natively. If yes, the loop prompt describes the schema's fields without asking for JSON; otherwise it keeps the JSON instruction.
2. The chat model action asks the same once per request, before retrying.
3. The tool-calling loop runs as today.
4. On a native final answer (no tool calls), the same attempt makes one more call with the schema and no tools: a user message holding a conversion instruction and the answer's text. Its response is parsed.

Key decisions

  • The extra call happens only on the native path. The prompt path keeps a single call.

  • The extra call sends only the answer, as one user message, so no tool traffic, turn-order rule or provider-specific response field is involved.

  • The extra call binds no tools (Gemini drops a native schema when tools are bound) and omits tool_choice, tool_choice_option and parallel_tool_calls, also inside additional_kwargs.

  • The setup's strategy is the policy; a connection only encodes. It carries the schema without checking its model list, so NATIVE on an unlisted model keeps the schema.
  • Behavioral Semantics

    Interaction decisions

    | Strategy | Connection's answer | Result |
    |---|---|---|
    | PROMPT | any | Prompt path |
    | AUTO | native recommended | Native: extra call, field instruction |
    | AUTO | feasible, or infeasible | Prompt path |
    | NATIVE | native recommended, or feasible | Native |
    | NATIVE | infeasible (e.g. RowTypeInfo) | Fails before any model call |
    | any | setup bridged to the other language | Prompt path; NATIVE fails before any model call |
    | any | no connection bound, check not overridden | Fails before any model call, naming open() |

    Behavioral contracts

    1. The extra call happens only when the strategy resolves to native and the answer has no tool calls.
    2. Its only message is a user message: the conversion instruction, then the answer's text.
    3. It carries the schema, binds no tools, and omits the tool-choice parameters.
    4. Its response is the one parsed.
    5. A chat call given tools (Java 4-arg, Python tools=) skips the bound prompt, skill-discovery message and bound tools; otherwise chat prepares the request as before.
    6. Tool-choice parameters are omitted whenever a call carries a schema and binds no tools; the native check sees the same parameters.
    7. For a non-null schema, the native check requires a bound connection.
    8. An unhonorable NATIVE fails with a message naming the connection and the schema.
    9. ReActAgent uses the field instruction only on a native answer; any other answer or a failure keeps the JSON instruction.
    10. A recovered run replays both calls from the durable record without calling the model.

    Failure behavior

  • A failed, truncated or unparseable extra call uses the existing retry budget; a retry repeats the attempt, not completed tool rounds.

  • A failing native check fails like any model failure: a Java router tries its next candidate, otherwise a failed ChatResponseEvent is sent.

  • Bridged setups refuse explicit tools or a schema.

  • Cancellation propagates everywhere, including from the ReActAgent check.
  • Tests

    <details><summary>Tests per contract</summary>

    | Contract | Pinned by |
    |---|---|
    | 1 | ChatModelActionRetryTest; test_chat_model_action_retry.py |
    | 2, 3 | nativeSchemaConvertsTheFinalAnswerInASeparateSchemaCarryingCall; test_finalization_call_carries_answer_directive_and_schema |
    | 4 | parse-from-final tests in both languages |
    | 5 | BaseChatModelTest, test_chat_model_base.py; bridge refusals in PythonChatModelSetupTest, test_java_chat_model.py |
    | 6 | tool-param tests in both base test files |
    | 7 | testWillApplyNativeStructuredOutputRequiresOpen; test_will_apply_native_structured_output_requires_open |
    | 8 | strategy x answer grids in both base test files; bridge tests |
    | 9 | ReActAgentTest; test_react_agent_schema_instruction.py |
    | 10 | ChatModelInvokerTest replay; test_flink_runner_context_reconcilable.py |

    </details>

    End to end against Ollama (qwen3:1.7b), ReActAgentTest#testReActAgentNativeStructuredOutput and test_react_agent_native_structured_output_on_remote_runner run the ReAct tool loop with a POJO / BaseModel schema under AUTO. A recording connection checks that the loop requests carried the tools and no schema, that the last request carried the schema and no tools, and that the model called a tool; the typed result is checked too. Forcing the prompt strategy makes both tests fail.

    Every commit was mutation-tested, and all non-equivalent mutants were killed.

    Not verified:

  • No call to a hosted provider; only a local Ollama model runs end to end.

  • Whether a loop answer written from the field instruction always lets the conversion call fill every field.

  • The setup's answer is not stored durably; a configuration change before recovery may switch paths, and the journal then discards the later records.
  • Known limit: Java POJO instructions carry no field descriptions, since Jackson's schema generator drops them (as on the JSON path).

    API

  • New on BaseChatModelSetup: willApplyNativeStructuredOutput and chat(messages, tools, modelParams, outputSchema) (Java); will_apply_native_structured_output and keyword-only tools / output_schema on chat (Python; prompt_args with tools raises). Users configure structured_output_strategy instead.

  • Behavior change: a custom setup that binds no connection and receives an output schema now fails unless it overrides the native check.

  • Behavior change for direct connection.chat(..., outputSchema) callers: an unlisted model now gets the native parameter, so Anthropic drops its JSON prefill, Azure and DashScope reject a caller-supplied response_format, and Python raises TypeError for a schema Pydantic cannot render.

  • The #1129 connection contract now says the native branch carries the schema unless the answer is infeasible. A ReActAgent with a schema registers one more prompt resource; an older plan gets no instruction on the native path.
  • Documentation

  • doc-needed

  • doc-not-needed

  • doc-included
  • User documentation for structured output across providers follows in a separate PR.

    Was this patch authored or co-authored using generative AI tooling?

  • Yes

  • No
  • Generated-by: Claude Code 2.1.294 and GitHub Copilot CLI 1.0.95 (Claude Opus 5.5)

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: weiqingy Review duration: 5379m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #1215"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%