1- import { createGoogleGenerativeAI } from '@ai-sdk/ google' ;
2- import { generateObject } from 'ai' ;
1+ import { GoogleGenerativeAI } from "@ google/generative-ai" ;
2+ import { zodToJsonSchema } from "zod-to-json-schema" ;
33
4- export const googleExtractor = async ( { markdown, zodSchema, prompt } ) => {
4+ const genAI = new GoogleGenerativeAI ( process . env . GEMINI_API_KEY ) ;
5+
6+ export const googleExtractor = async ( { markdown, zodSchema, prompt, model } ) => {
57 if ( ! process . env . GEMINI_API_KEY ) {
68 throw new Error ( "Missing GEMINI_API_KEY" ) ;
79 }
810
9- const google = createGoogleGenerativeAI ( {
10- apiKey : process . env . GEMINI_API_KEY ,
11- } ) ;
12- const googleModel = "gemini-2.0-flash-001"
13-
14- const completion = await generateObject ( {
15- model : google ( googleModel , {
16- structuredOutputs : false ,
17- } ) ,
18- schema : zodSchema ,
19- prompt : markdown ,
20- system : prompt ,
21- } ) ;
22-
23- const event = completion . object ;
24- return event ;
25- }
11+ const googleModel = model
12+
13+ // Convert Zod schema to JSON schema
14+ let jsonSchema = zodToJsonSchema ( zodSchema ) ;
15+
16+ // Remove additionalProperties and $schema keys
17+ const removeKeys = ( obj ) => {
18+ if ( Array . isArray ( obj ) ) {
19+ return obj . map ( removeKeys ) ;
20+ } else if ( typeof obj === "object" && obj !== null ) {
21+ return Object . fromEntries (
22+ Object . entries ( obj )
23+ . filter ( ( [ key ] ) => key !== "additionalProperties" && key !== "$schema" )
24+ . map ( ( [ key , value ] ) => [ key , removeKeys ( value ) ] )
25+ ) ;
26+ }
27+ return obj ;
28+ } ;
29+
30+ jsonSchema = removeKeys ( jsonSchema ) ;
31+
32+ const modelToUse = genAI . getGenerativeModel ( {
33+ model : googleModel ,
34+ systemInstruction : prompt ,
35+ generationConfig : {
36+ responseMimeType : "application/json" ,
37+ responseSchema : jsonSchema ,
38+ } ,
39+ } ) ;
40+
41+ const result = await modelToUse . generateContent (
42+ markdown ,
43+ ) ;
44+
45+ //console.log(result.response.text());
46+ const event = result . response . text ( ) ;
47+ return event ;
48+ }
49+
0 commit comments