Repository navigation
Add support for structured outputs for Gemini - #1263
Conversation
Resolves receptron#1262. Signed-off-by: Masashi Honma <[email protected]>
📝 WalkthroughWalkthroughAdds typed structured-output support to the Gemini agent: introduces Changes
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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. Comment |
There was a problem hiding this comment.
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
typefield is currently typed asstring, 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.,answerandexplainfields) 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: Useconsole.warnfor warnings and include the actual type in the message.The warning uses
console.loginstead ofconsole.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.tsfile, thetypefield should use a union literal for compile-time validation.♻️ Suggested improvement
type GeminiResponseFormat = { - type: string; + type: "schema" | "json_schema"; schema: SchemaUnion; };
146-148: Useconsole.warnand 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".`); }
Signed-off-by: Masashi Honma <[email protected]>
Signed-off-by: Masashi Honma <[email protected]>
|
Thank you for this contribution! Adding structured output support for Gemini is a great addition. One change request: please align the Current issueOpenAI/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 Requested changes
See |
There was a problem hiding this comment.
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.
| type GeminiResponseFormat = { | ||
| type: string; | ||
| json_schema: SchemaUnion; | ||
| }; |
There was a problem hiding this comment.
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.
Signed-off-by: Masashi Honma <[email protected]>
|
@ystknsh Thank you for your review. Fixed. |
There was a problem hiding this comment.
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 missingnamefield for OpenAI compatibility.Per the reviewer's feedback, OpenAI/Anthropic format includes a
namefield:{ type: "json_schema", json_schema: { name: "answer", schema: {...}, strict: true } }. The current type will cause TypeScript errors when users pass OpenAI-format inputs containingname.Proposed fix to support the name field
type GeminiResponseFormat = { type: string; json_schema: { + name?: string; schema: SchemaUnion; strict?: boolean; }; };
| 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 ]
}
There was a problem hiding this comment.
No description provided.
| if (response_format.json_schema.strict !== undefined) { | ||
| GraphAILogger.warn("Gemini does not support 'strict' option, ignoring..."); | ||
| } |
There was a problem hiding this comment.
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.
| 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.
|
@masap Thanks for the quick fix! |
|
@ystknsh No problem! |
Resolves #1262.
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.