adk-java icon indicating copy to clipboard operation
adk-java copied to clipboard

ChatCompletionsRequest ignores typed responseSchema and downgrades outputSchema to json_object

Open akbarkanso opened this issue 3 months ago • 2 comments

🔴 Required Information

Describe the Bug:

LlmAgent.outputSchema(...) does not reach OpenAI-compatible models as a strict JSON Schema when the request is handled by ADK Java's native chat-completions connector.

ADK's request pipeline uses two different schema representations:

  1. Basic.processRequest(...) attaches the agent's typed output schema through LlmRequest.Builder.outputSchema(...) for models that support output schemas alongside tools.
  2. LlmRequest.Builder.outputSchema(...) stores that schema in GenerateContentConfig.responseSchema and sets responseMimeType = "application/json".
  3. ChatCompletionsRequest.fromLlmRequest(...) never reads GenerateContentConfig.responseSchema.
  4. It creates response_format.type = "json_schema" only when the separate raw responseJsonSchema field is present.
  5. Because only responseMimeType = "application/json" survives, the connector silently falls back to generic JSON-object mode.

The model therefore receives:

{
  "response_format": {
    "type": "json_object"
  }
}

instead of the declared shape:

{
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "response_schema",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "rootCause": {
            "type": "string"
          },
          "confidence": {
            "type": "number"
          }
        },
        "required": [
          "rootCause",
          "confidence"
        ],
        "additionalProperties": false
      }
    }
  }
}

The downgrade is silent. No exception or warning indicates that the declared output shape was discarded.

Steps to Reproduce:

  1. Create a typed output schema:
Schema outputSchema =
    Schema.builder()
        .type(Type.Known.OBJECT)
        .properties(
            Map.of(
                "rootCause",
                Schema.builder()
                    .type(Type.Known.STRING)
                    .build(),
                "confidence",
                Schema.builder()
                    .type(Type.Known.NUMBER)
                    .build()))
        .required(List.of("rootCause", "confidence"))
        .build();
  1. Build an LlmRequest through the same API used by LlmAgent.outputSchema(...):
LlmRequest request =
    LlmRequest.builder()
        .model("openai-compatible-model")
        .contents(List.of())
        .outputSchema(outputSchema)
        .build();

ChatCompletionsRequest converted =
    ChatCompletionsRequest.fromLlmRequest(request, false);
  1. Serialize converted and inspect response_format.

  2. Alternatively, reproduce the issue through a real LlmAgent using a non-Gemini-2 model name, including when the agent has tools. Basic.processRequest(...) calls builder.outputSchema(...), but the chat-completions conversion still drops the typed shape.

Expected Behavior:

When responseJsonSchema is absent but typed responseSchema is present, ChatCompletionsRequest should convert the typed schema into an OpenAI-compatible strict JSON Schema and emit:

{
  "response_format": {
    "type": "json_schema"
  }
}

An explicitly supplied raw responseJsonSchema should retain precedence.

The conversion should produce a schema valid for strict OpenAI-compatible endpoints, including:

  • lowercase JSON Schema types;
  • additionalProperties: false for object schemas;
  • valid nested object and array schemas;
  • explicit handling of optional properties.

Optional properties should either be translated into the endpoint's supported nullable representation or rejected clearly rather than producing an invalid strict schema.

Observed Behavior:

The typed schema is ignored.

Because LlmRequest.Builder.outputSchema(...) also sets:

responseMimeType = application/json

ChatCompletionsRequest emits only:

{
  "response_format": {
    "type": "json_object"
  }
}

The model is constrained to produce some JSON object, but its fields are not constrained to the declared output schema.

Models differ in how reliably they follow prompts under this weaker mode. A model may return:

  • an arbitrary JSON shape;
  • missing required fields;
  • narration around JSON.

This can break downstream parsing of the expected output contract.

Environment Details:

  • ADK Library Version (see maven dependency): 1.7.1
  • Also verified unchanged in ADK Java 1.8.0
  • Also verified unchanged on upstream main on 2026-08-20
  • OS: N/A
  • Java: 21
  • Connector: com.google.adk.models.chat.ChatCompletionsHttpClient
  • Endpoint: OpenAI-compatible gateway

Model Information:

  • Which model is being used: OpenAI-compatible gateway routing Claude/Opus models
  • The defect is in deterministic request conversion and is model-independent. Model choice only changes how visible the weaker JSON-object constraint becomes.

🟡 Optional Information

Regression:

No known regression. The typed responseSchema and raw responseJsonSchema representations appear never to have been connected in ChatCompletionsRequest.

Logs:

N/A.

Screenshots / Video:

N/A.

Additional Context:

This is the response-side analogue of #1426 / PR #1427:

  • #1426: ChatCompletionsRequest reads typed tool parameters but ignores raw parametersJsonSchema.
  • This issue: ChatCompletionsRequest reads raw responseJsonSchema but ignores typed responseSchema.

Minimal Reproduction Code:

Schema outputSchema =
    Schema.builder()
        .type(Type.Known.OBJECT)
        .properties(
            Map.of(
                "rootCause",
                Schema.builder()
                    .type(Type.Known.STRING)
                    .build(),
                "confidence",
                Schema.builder()
                    .type(Type.Known.NUMBER)
                    .build()))
        .required(List.of("rootCause", "confidence"))
        .build();

LlmRequest request =
    LlmRequest.builder()
        .model("openai-compatible-model")
        .contents(List.of())
        .outputSchema(outputSchema)
        .build();

ChatCompletionsRequest converted =
    ChatCompletionsRequest.fromLlmRequest(request, false);

Serialize converted and inspect the resulting response_format.

Suggested Tests:

  1. Typed responseSchema only → serialized strict json_schema response format.
  2. Explicit raw responseJsonSchema → raw schema retains precedence.
  3. No schema plus responseMimeType=application/json → existing json_object behavior.
  4. Nested object/array schemas with lowercase types and strict object constraints.
  5. Optional-property semantics are translated correctly or rejected clearly.
  6. A real LlmAgent with tools and a non-Gemini-2 model name follows the same path.

How often has this issue occurred?:

  • Always (100%)

akbarkanso avatar Aug 20 '26 10:08 akbarkanso

Hi @akbarkanso, thank you for reporting this issue. I have reproduced it using your inputs and opened this PR to address the issue. hope this will resolves your problem?

hemasekhar-p avatar Aug 21 '26 11:08 hemasekhar-p

Hi @hemasekhar-p, thank you for this

I reviewed the change. It addresses the primary issue correctly:

  • Typed responseSchema now produces response_format.type=json_schema.
  • Explicit raw responseJsonSchema retains precedence.
  • strict=true is preserved.
  • Schema types are serialized in lowercase.

There is one remaining compatibility gap for the strict OpenAI compatible endpoint where we observed this.

com.google.genai.types.Schema does not expose additionalProperties, so:

objectMapper.convertValue(config.responseSchema().get(), ...)

produces object schemas without:

"additionalProperties": false

The PR then sends that schema with strict=true. Strict OpenAI compatible endpoints generally require additionalProperties: false on every object node, including nested objects and object schemas used as array items.

There is a related optional property case: a typed object can declare properties that are not all included in required, but the converted response is still marked strict. That schema may be rejected unless optional fields are translated into a supported nullable representation.

Our current local workaround therefore:

  1. Recursively adds additionalProperties: false to every object node.
  2. Verifies that properties and required contain exactly the same names.
  3. Rejects unsupported optional typed schemas before network I/O rather than allowing an opaque gateway 400.

Would you be open to extending #1447 with equivalent recursive normalization or validation?

Suggested regression coverage:

  • Root object has additionalProperties: false.
  • Nested objects/array item objects also have additionalProperties: false.
  • All object properties are represented in required, or unsupported optional properties fail clearly.
  • Raw responseJsonSchema continues to retain precedence.

With that addition, this should fully resolve our use case. We also have a credential free real LlmAgent wire test downstream and would be happy to validate an updated branch against it.

Thanks again for the quick response and fix.

akbarkanso avatar Aug 24 '26 18:08 akbarkanso