Skip to content

Add support for structured outputs for Gemini - #1263

Merged
isamu merged 4 commits into
receptron:mainfrom
masap:fix-1262
Jan 19, 2026
Merged

isamu merged 4 commits into
receptron:mainfrom
masap:fix-1262

Conversation

@masap

@masap masap commented Jan 18, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #1262.

Summary by CodeRabbit

  • New Features
    • Agent now applies structured response-format configurations so outputs follow specified schema formats (schema and JSON Schema modes) during generation.
  • Tests
    • Added end-to-end tests covering the agent's response-format handling for both schema modes.
    • Removed an older, redundant response-format test.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 18, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds typed structured-output support to the Gemini agent: introduces GeminiResponseFormat and SchemaUnion import, wires response_format into generationConfig (handling "schema" and "json_schema" with warnings), moves related tests into a new dedicated test file, and removes the old inline test.

Changes

Cohort / File(s) Summary
Type definitions
llm_agents/gemini_agent/lib/gemini_agent.d.ts, llm_agents/gemini_agent/src/gemini_agent.ts
Add GemniResponseFormat type, import SchemaUnion from @google/genai, and change GeminiInputs.response_format from any to GeminiResponseFormat.
Implementation
llm_agents/gemini_agent/lib/gemini_agent.js, llm_agents/gemini_agent/src/gemini_agent.ts
Extract response_format from inputs and apply it to generationConfig: for type === "schema" set responseMimeType = "application/json" and responseSchema; for type === "json_schema" set responseMimeType and responseJsonSchema; warn on unknown types and on ignored strict. Removed previous placeholder.
Tests (removed)
llm_agents/gemini_agent/tests/run_gemini.ts
Removed inline response_format test and removed Type import from @google/genai.
Tests (added)
llm_agents/gemini_agent/tests/run_gemini_response_format.ts
New test file with two tests validating OpenAPI/schema and JSON Schema response_format modes using a Fibonacci prompt; trivial assertions retained.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant GeminiAgent as Gemini Agent
    participant GenConfig as GenerationConfig
    participant Logger
    participant GeminiAPI as Gemini API

    Client->>GeminiAgent: call geminiAgent(inputs including response_format)
    GeminiAgent->>GenConfig: apply base generation settings
    alt response_format.type == "schema"
        GeminiAgent->>GenConfig: set responseMimeType="application/json" and responseSchema
    else response_format.type == "json_schema"
        GeminiAgent->>GenConfig: set responseMimeType="application/json" and responseJsonSchema
    else unknown
        GeminiAgent->>Logger: warn about invalid response_format.type
    end
    GeminiAgent->>Logger: warn if json_schema.strict present (ignored)
    GeminiAgent->>GeminiAPI: create chat with GenConfig and tools
    GeminiAPI-->>GeminiAgent: response
    GeminiAgent-->>Client: return result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Poem

🐰 I hopped through types and schema lines,
I tucked json shapes in tidy signs,
Two tests now prove the formats sing,
The agent answers in structured spring,
🥕✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR addresses issue #1262 and implements structured output support for Gemini, but the implementation does not align with reviewer feedback on cross-provider compatibility. Update response_format handling to read from json_schema.schema, ignore name field, and log warning for unsupported strict option to maintain OpenAI/Anthropic compatibility.
Out of Scope Changes check ❓ Inconclusive Changes are focused on structured outputs for Gemini. However, removal of test from run_gemini.ts and test format used in run_gemini_response_format.ts do not align with reviewer feedback. Verify that test format and response_format structure align with OpenAI format referenced in reviewer feedback before merging.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding support for structured outputs for Gemini.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@llm_agents/gemini_agent/tests/run_gemini_response_format.ts`:
- Around line 22-25: The JSON schema for the "explain" field contains a typo in
its description ("Explaination" -> "Explanation"); update the description string
for the explain property (refer to the explain schema object in
run_gemini_response_format.ts) to use the correct spelling "Explanation" in both
occurrences (the one around line 22 and the duplicate at line 57).
🧹 Nitpick comments (6)
llm_agents/gemini_agent/lib/gemini_agent.d.ts (1)

5-8: Consider using a union literal type for stricter type safety.

The type field is currently typed as string, but the implementation only accepts "schema" or "json_schema". A union type would provide compile-time safety and better IntelliSense.

♻️ Suggested improvement
 type GeminiResponseFormat = {
-    type: string;
+    type: "schema" | "json_schema";
     schema: SchemaUnion;
 };
llm_agents/gemini_agent/tests/run_gemini_response_format.ts (2)

35-39: Assertions don't validate structured output behavior.

assert.deepStrictEqual(true, true) is a no-op assertion that only confirms the agent didn't throw. Consider validating that the response contains the expected structure (e.g., answer and explain fields) to actually test the structured output feature.

♻️ Suggested improvement
   if (res) {
     console.log(res.text);
+    const parsed = JSON.parse(res.text);
+    assert.ok(parsed.answer, "Response should contain 'answer' field");
+    assert.ok(parsed.explain, "Response should contain 'explain' field");
   }
-  assert.deepStrictEqual(true, true);
+  assert.ok(res, "Response should not be empty");

66-72: Same concerns apply to this test.

This test has the same trivial assertion and typo issues as the first test. Consider applying similar improvements to validate the structured output.

llm_agents/gemini_agent/lib/gemini_agent.js (1)

90-103: Use console.warn for warnings and include the actual type in the message.

The warning uses console.log instead of console.warn, and doesn't show what invalid type was provided, making debugging harder.

♻️ Suggested improvement
     // response_format should be OpenAPI 3.0 schema (https://spec.openapis.org/oas/v3.0.3#schema) or JSON Schema (https://json-schema.org/)
     if (response_format) {
         if (response_format.type === "schema") {
             generationConfig.responseMimeType = "application/json";
             generationConfig.responseSchema = response_format.schema;
         }
         else if (response_format.type === "json_schema") {
             generationConfig.responseMimeType = "application/json";
             generationConfig.responseJsonSchema = response_format.schema;
         }
         else {
-            console.log("response_format.type should be `schema` or `json_schema`");
+            console.warn(`Invalid response_format.type: "${response_format.type}". Expected "schema" or "json_schema".`);
         }
     }
llm_agents/gemini_agent/src/gemini_agent.ts (2)

18-21: Use a union literal type for stricter type safety.

Same as the generated .d.ts file, the type field should use a union literal for compile-time validation.

♻️ Suggested improvement
 type GeminiResponseFormat = {
-  type: string;
+  type: "schema" | "json_schema";
   schema: SchemaUnion;
 };

146-148: Use console.warn and include the actual type value.

For consistency with typical warning conventions and better debugging:

♻️ Suggested improvement
     } else {
-      console.log("response_format.type should be `schema` or `json_schema`");
+      console.warn(`Invalid response_format.type: "${response_format.type}". Expected "schema" or "json_schema".`);
     }

@isamu
isamu requested a review from ystknsh January 18, 2026 00:35
masap added 2 commits January 18, 2026 09:38
Signed-off-by: Masashi Honma <[email protected]>
Signed-off-by: Masashi Honma <[email protected]>
@ystknsh

ystknsh commented Jan 18, 2026

Copy link
Copy Markdown
Contributor

@masap

Thank you for this contribution! Adding structured output support for Gemini is a great addition.

One change request: please align the response_format structure with openai_agent and anthropic_agent.

Current issue

OpenAI/Anthropic agents use:

response_format: {
  type: "json_schema",
  json_schema: { name: "answer", schema: { ... }, strict: true }
}

This PR uses:

response_format: {
  type: "json_schema",
  schema: { ... }  // different structure
}

This breaks compatibility - users can't use the same response_format across providers.

Requested changes

  1. Get schema from json_schema.schema instead of schema
  2. Ignore name (Gemini doesn't use it)
  3. For strict, log a warning:
    GraphAILogger.warn("Gemini does not support 'strict' option, ignoring...");
  4. Update tests to match OpenAI format

See llm_agents/openai_agent/tests/run_openai_response_format.ts for reference.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@llm_agents/gemini_agent/src/gemini_agent.ts`:
- Around line 18-21: The GeminiResponseFormat type is too flat and doesn't
support the OpenAI-style nested response_format that includes name/ schema/
strict; update the GeminiResponseFormat type (the type alias named
GeminiResponseFormat) to allow either the current shape or the nested
json_schema object used by OpenAI/Anthropic (for example make json_schema a
union of SchemaUnion OR an object like { name: string; schema: SchemaUnion;
strict?: boolean } and set type to accept the literal "json_schema" where
appropriate) so callers expecting response_format: { type: "json_schema",
json_schema: { name: "answer", schema: {...}, strict: true } } will type-check.

Comment on lines +18 to +21
type GeminiResponseFormat = {
type: string;
json_schema: SchemaUnion;
};

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.

⚠️ Potential issue | 🟠 Major

Type definition doesn't match OpenAI format structure.

Per the reviewer's feedback, OpenAI/Anthropic agents use response_format: { type: "json_schema", json_schema: { name: "answer", schema: {...}, strict: true } }. The current type doesn't support this nested structure for the json_schema type.

Proposed type definition to support both formats
-type GeminiResponseFormat = {
-  type: string;
-  json_schema: SchemaUnion;
-};
+type GeminiResponseFormatSchema = {
+  type: "schema";
+  json_schema: SchemaUnion;
+};
+
+type GeminiResponseFormatJsonSchema = {
+  type: "json_schema";
+  json_schema: {
+    name?: string;
+    schema: SchemaUnion;
+    strict?: boolean;
+  };
+};
+
+type GeminiResponseFormat = GeminiResponseFormatSchema | GeminiResponseFormatJsonSchema;
🤖 Prompt for AI Agents
In `@llm_agents/gemini_agent/src/gemini_agent.ts` around lines 18 - 21, The
GeminiResponseFormat type is too flat and doesn't support the OpenAI-style
nested response_format that includes name/ schema/ strict; update the
GeminiResponseFormat type (the type alias named GeminiResponseFormat) to allow
either the current shape or the nested json_schema object used by
OpenAI/Anthropic (for example make json_schema a union of SchemaUnion OR an
object like { name: string; schema: SchemaUnion; strict?: boolean } and set type
to accept the literal "json_schema" where appropriate) so callers expecting
response_format: { type: "json_schema", json_schema: { name: "answer", schema:
{...}, strict: true } } will type-check.

@masap

masap commented Jan 19, 2026

Copy link
Copy Markdown
Contributor Author

@ystknsh Thank you for your review. Fixed.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@llm_agents/gemini_agent/src/gemini_agent.ts`:
- Around line 152-154: Guard the property access to avoid a possible TypeError
by first checking that response_format and response_format.json_schema are
defined before reading response_format.json_schema.strict; modify the
conditional around the existing GraphAILogger.warn call (the block that
references response_format.json_schema.strict) to use a defensive check like
ensuring response_format && response_format.json_schema exist, then test strict,
so GraphAILogger.warn("Gemini does not support 'strict' option, ignoring...")
only runs when json_schema and its strict property are present.
- Around line 143-148: Add defensive checks around access to
response_format.json_schema to avoid runtime errors when json_schema is
undefined: in the gemini_agent.ts code path that sets generationConfig (the
block handling response_format.type "schema" and "json_schema"), validate that
response_format.json_schema exists (or use optional chaining) before reading
.schema and either skip setting
generationConfig.responseSchema/responseJsonSchema or raise a clear error/log
when missing; update the branch that handles "schema" and the branch that
handles "json_schema" to perform the same guard so both
generationConfig.responseMimeType and the corresponding schema property are only
set when response_format.json_schema?.schema is available.
♻️ Duplicate comments (1)
llm_agents/gemini_agent/src/gemini_agent.ts (1)

18-24: Type definition still missing name field for OpenAI compatibility.

Per the reviewer's feedback, OpenAI/Anthropic format includes a name field: { type: "json_schema", json_schema: { name: "answer", schema: {...}, strict: true } }. The current type will cause TypeScript errors when users pass OpenAI-format inputs containing name.

Proposed fix to support the name field
 type GeminiResponseFormat = {
   type: string;
   json_schema: {
+    name?: string;
     schema: SchemaUnion;
     strict?: boolean;
   };
 };

Comment on lines +143 to +148
if (response_format.type === "schema") {
generationConfig.responseMimeType = "application/json";
generationConfig.responseSchema = response_format.json_schema.schema;
} else if (response_format.type === "json_schema") {
generationConfig.responseMimeType = "application/json";
generationConfig.responseJsonSchema = response_format.json_schema.schema;

@coderabbitai coderabbitai Bot Jan 19, 2026 •

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.

⚠️ Potential issue | 🟠 Major

Add defensive checks for json_schema access.

Similar to the strict check, accessing response_format.json_schema.schema on lines 145 and 148 will throw if json_schema is undefined. Consider adding optional chaining or an early validation.

Proposed fix with validation
   if (response_format) {
+    if (!response_format.json_schema?.schema) {
+      GraphAILogger.warn("response_format.json_schema.schema is required");
+    } else if (response_format.type === "schema") {
-    if (response_format.type === "schema") {
       generationConfig.responseMimeType = "application/json";
       generationConfig.responseSchema = response_format.json_schema.schema;
     } else if (response_format.type === "json_schema") {
       generationConfig.responseMimeType = "application/json";
       generationConfig.responseJsonSchema = response_format.json_schema.schema;
     } else {
       GraphAILogger.warn("response_format.type should be `schema` or `json_schema`");
     }
+    if (response_format.json_schema?.strict !== undefined) {
-    if (response_format.json_schema.strict !== undefined) {
       GraphAILogger.warn("Gemini does not support 'strict' option, ignoring...");
     }
   }
🤖 Prompt for AI Agents
In `@llm_agents/gemini_agent/src/gemini_agent.ts` around lines 143 - 148, Add
defensive checks around access to response_format.json_schema to avoid runtime
errors when json_schema is undefined: in the gemini_agent.ts code path that sets
generationConfig (the block handling response_format.type "schema" and
"json_schema"), validate that response_format.json_schema exists (or use
optional chaining) before reading .schema and either skip setting
generationConfig.responseSchema/responseJsonSchema or raise a clear error/log
when missing; update the branch that handles "schema" and the branch that
handles "json_schema" to perform the same guard so both
generationConfig.responseMimeType and the corresponding schema property are only
set when response_format.json_schema?.schema is available.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thank you but it is not needed. Because we already have type for it.

type GeminiResponseFormat = {
  type: string;
  json_schema: {
    schema: SchemaUnion;
    strict?: boolean;
  };
};

If json_schema is undefined, the source code can show following error.

$ npx ts-node llm_agents/gemini_agent/tests/run_gemini_response_format.ts 
/home/honma/git/graphai/node_modules/ts-node/src/index.ts:859
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: ⨯ Unable to compile TypeScript:
llm_agents/gemini_agent/tests/run_gemini_response_format.ts:18:72 - error TS2322: Type '{ system: string; response_format: { type: "schema"; }; }' is not assignable to type 'GeminiParams'.
  Type '{ system: string; response_format: { type: "schema"; }; }' is not assignable to type '{ model?: string | undefined; temperature?: number | undefined; max_tokens?: number | undefined; tools?: Record<string, any>[] | undefined; response_format?: GeminiResponseFormat | undefined; messages?: GraphAILlmMessage[] | undefined; }'.
    Types of property 'response_format' are incompatible.
      Property 'json_schema' is missing in type '{ type: "schema"; }' but required in type 'GeminiResponseFormat'.

18   const res = (await geminiAgent({ ...defaultTestContext, namedInputs, params })) as any;
                                                                          ~~~~~~

  llm_agents/gemini_agent/src/gemini_agent.ts:20:3
    20   json_schema: {
         ~~~~~~~~~~~
    'json_schema' is declared here.
  packages/graphai/lib/type.d.ts:107:5
    107     params: NodeDataParams<ParamsType>;
            ~~~~~~
    The expected type comes from property 'params' which is declared here on type 'AgentFunctionContext<GeminiParams, GeminiInputs, GeminiConfig>'

    at createTSError (/home/honma/git/graphai/node_modules/ts-node/src/index.ts:859:12)
    at reportTSError (/home/honma/git/graphai/node_modules/ts-node/src/index.ts:863:19)
    at getOutput (/home/honma/git/graphai/node_modules/ts-node/src/index.ts:1077:36)
    at Object.compile (/home/honma/git/graphai/node_modules/ts-node/src/index.ts:1433:41)
    at Module.m._compile (/home/honma/git/graphai/node_modules/ts-node/src/index.ts:1617:30)
    at node:internal/modules/cjs/loader:1893:10
    at Object.require.extensions.<computed> [as .ts] (/home/honma/git/graphai/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:1481:32)
    at Module._load (node:internal/modules/cjs/loader:1300:12)
    at TracingChannel.traceSync (node:diagnostics_channel:328:14) {
  diagnosticCodes: [ 2322 ]
}

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.

No description provided.

Comment on lines +152 to +154
if (response_format.json_schema.strict !== undefined) {
GraphAILogger.warn("Gemini does not support 'strict' option, ignoring...");
}

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.

⚠️ Potential issue | 🟠 Major

Potential null reference error when json_schema is undefined.

If response_format exists but json_schema is undefined (e.g., malformed input), accessing response_format.json_schema.strict on line 152 will throw a TypeError. This check should be guarded.

Proposed fix with defensive check
-    if (response_format.json_schema.strict !== undefined) {
+    if (response_format.json_schema?.strict !== undefined) {
       GraphAILogger.warn("Gemini does not support 'strict' option, ignoring...");
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (response_format.json_schema.strict !== undefined) {
GraphAILogger.warn("Gemini does not support 'strict' option, ignoring...");
}
if (response_format.json_schema?.strict !== undefined) {
GraphAILogger.warn("Gemini does not support 'strict' option, ignoring...");
}
🤖 Prompt for AI Agents
In `@llm_agents/gemini_agent/src/gemini_agent.ts` around lines 152 - 154, Guard
the property access to avoid a possible TypeError by first checking that
response_format and response_format.json_schema are defined before reading
response_format.json_schema.strict; modify the conditional around the existing
GraphAILogger.warn call (the block that references
response_format.json_schema.strict) to use a defensive check like ensuring
response_format && response_format.json_schema exist, then test strict, so
GraphAILogger.warn("Gemini does not support 'strict' option, ignoring...") only
runs when json_schema and its strict property are present.

@isamu
isamu merged commit a1315d3 into receptron:main Jan 19, 2026
@masap
masap deleted the fix-1262 branch January 19, 2026 23:12
@ystknsh

ystknsh commented Jan 20, 2026

Copy link
Copy Markdown
Contributor

@masap Thanks for the quick fix!

@masap

masap commented Jan 20, 2026

Copy link
Copy Markdown
Contributor Author

@ystknsh No problem!

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.

Add support for structured outputs for Gemini

3 participants