MCPcopy Index your code
hub / github.com/TanStack/ai / structuredOutput

Method structuredOutput

packages/ai-gemini/src/adapters/text.ts:169–223  ·  view source on GitHub ↗

* Generate structured output using Gemini's native JSON response format. * Uses responseMimeType: 'application/json' and responseSchema for structured output. * The outputSchema is already JSON Schema (converted in the ai layer).

(
    options: StructuredOutputOptions<GeminiTextProviderOptions>,
  )

Source from the content-addressed store, hash-verified

167 * The outputSchema is already JSON Schema (converted in the ai layer).
168 */
169 async structuredOutput(
170 options: StructuredOutputOptions<GeminiTextProviderOptions>,
171 ): Promise<StructuredOutputResult<unknown>> {
172 const { chatOptions, outputSchema } = options
173 const { logger } = chatOptions
174
175 const mappedOptions = this.mapCommonOptionsToGemini(chatOptions)
176
177 try {
178 logger.request(
179 `activity=chat provider=gemini model=${this.model} messages=${chatOptions.messages.length} tools=${chatOptions.tools?.length ?? 0} stream=false`,
180 { provider: 'gemini', model: this.model },
181 )
182 // Add structured output configuration
183 const result = await this.client.models.generateContent({
184 ...mappedOptions,
185 config: {
186 ...mappedOptions.config,
187 responseMimeType: 'application/json',
188 responseSchema: outputSchema,
189 },
190 })
191
192 // Extract text content from the response
193 const rawText = this.extractTextFromResponse(result)
194
195 // Parse the JSON response
196 let parsed: unknown
197 try {
198 parsed = JSON.parse(rawText)
199 } catch {
200 throw new Error(
201 `Failed to parse structured output as JSON. Content: ${rawText.slice(0, 200)}${rawText.length > 200 ? '...' : ''}`,
202 )
203 }
204
205 return {
206 data: parsed,
207 rawText,
208 usage: result.usageMetadata
209 ? buildGeminiUsage(result.usageMetadata)
210 : undefined,
211 }
212 } catch (error) {
213 logger.errors('gemini.structuredOutput fatal', {
214 error,
215 source: 'gemini.structuredOutput',
216 })
217 throw new Error(
218 error instanceof Error
219 ? error.message
220 : 'An unknown error occurred during structured output generation.',
221 )
222 }
223 }
224
225 /**
226 * Extract text content from a non-streaming response

Callers

nothing calls this directly

Calls 6

buildGeminiUsageFunction · 0.90
parseMethod · 0.80
errorsMethod · 0.80
requestMethod · 0.45

Tested by

no test coverage detected