Using ArkType with @google/genai
I had some trouble getting ArkType working with the latest Google AI SDK. Gemini complains about certain JSON Schema fields, so I had to remove them.
This seems to work for my use case:
Hope this saves someone some time!
This seems to work for my use case:
import { GoogleGenAI } from '@google/genai'
import { config } from '$/config'
import { toGeminiSchema } from './utils'
import { type, type Type } from 'arktype'
const genAI = new GoogleGenAI({ apiKey: config.apiKeys.google })
/**
* Generates a reponse as JSON data constrained to an Arktype schema.
*/
export async function generateJsonContent<t extends type>({
text,
prompt,
schema,
}: {
text: string
prompt: string
schema: t
}): Promise<t['infer'] | undefined> {
const response = await genAI.models.generateContent({
model: config.models.generate,
contents: `User input: ${text}
Assistant:`,
config: {
systemInstruction: prompt,
responseMimeType: 'application/json',
responseJsonSchema: toGeminiSchema(schema),
},
})
const data = parseJsonString.to(schema as type.cast<t['t']>)(response.text)
if (data instanceof type.errors) {
console.error(new Error('GoogleGenAI returned an invalid JSON response', { cause: data }))
return
}
return data
}
const data = await generateJsonContent({
text: 'hello',
prompt: 'You are a helpful assistant',
schema: type({ a: 'string', b: 'number' }),
}) // { a: string; b: number }import { GoogleGenAI } from '@google/genai'
import { config } from '$/config'
import { toGeminiSchema } from './utils'
import { type, type Type } from 'arktype'
const genAI = new GoogleGenAI({ apiKey: config.apiKeys.google })
/**
* Generates a reponse as JSON data constrained to an Arktype schema.
*/
export async function generateJsonContent<t extends type>({
text,
prompt,
schema,
}: {
text: string
prompt: string
schema: t
}): Promise<t['infer'] | undefined> {
const response = await genAI.models.generateContent({
model: config.models.generate,
contents: `User input: ${text}
Assistant:`,
config: {
systemInstruction: prompt,
responseMimeType: 'application/json',
responseJsonSchema: toGeminiSchema(schema),
},
})
const data = parseJsonString.to(schema as type.cast<t['t']>)(response.text)
if (data instanceof type.errors) {
console.error(new Error('GoogleGenAI returned an invalid JSON response', { cause: data }))
return
}
return data
}
const data = await generateJsonContent({
text: 'hello',
prompt: 'You are a helpful assistant',
schema: type({ a: 'string', b: 'number' }),
}) // { a: string; b: number }Hope this saves someone some time!