(llmNodeInstance: BaseChatModel, structuredOutput: any[])
| 2121 | * @returns {BaseChatModel} - The configured LLM instance |
| 2122 | */ |
| 2123 | export const configureStructuredOutput = (llmNodeInstance: BaseChatModel, structuredOutput: any[]): BaseChatModel => { |
| 2124 | try { |
| 2125 | const zodObj: ICommonObject = {} |
| 2126 | for (const sch of structuredOutput) { |
| 2127 | if (sch.type === 'string') { |
| 2128 | zodObj[sch.key] = z.string().describe(sch.description || '') |
| 2129 | } else if (sch.type === 'stringArray') { |
| 2130 | zodObj[sch.key] = z.array(z.string()).describe(sch.description || '') |
| 2131 | } else if (sch.type === 'number') { |
| 2132 | zodObj[sch.key] = z.number().describe(sch.description || '') |
| 2133 | } else if (sch.type === 'boolean') { |
| 2134 | zodObj[sch.key] = z.boolean().describe(sch.description || '') |
| 2135 | } else if (sch.type === 'enum') { |
| 2136 | const enumValues = sch.enumValues?.split(',').map((item: string) => item.trim()) || [] |
| 2137 | zodObj[sch.key] = z |
| 2138 | .enum(enumValues.length ? (enumValues as [string, ...string[]]) : ['default']) |
| 2139 | .describe(sch.description || '') |
| 2140 | } else if (sch.type === 'jsonArray') { |
| 2141 | const jsonSchema = sch.jsonSchema |
| 2142 | if (jsonSchema) { |
| 2143 | try { |
| 2144 | // Parse the JSON schema |
| 2145 | const schemaObj = JSON.parse(jsonSchema) |
| 2146 | |
| 2147 | // Create a Zod schema from the JSON schema |
| 2148 | const itemSchema = createZodSchemaFromJSON(schemaObj) |
| 2149 | |
| 2150 | // Create an array schema of the item schema |
| 2151 | zodObj[sch.key] = z.array(itemSchema).describe(sch.description || '') |
| 2152 | } catch (err) { |
| 2153 | console.error(`Error parsing JSON schema for ${sch.key}:`, err) |
| 2154 | // Fallback to generic array of records |
| 2155 | zodObj[sch.key] = z.array(z.record(z.any())).describe(sch.description || '') |
| 2156 | } |
| 2157 | } else { |
| 2158 | // If no schema provided, use generic array of records |
| 2159 | zodObj[sch.key] = z.array(z.record(z.any())).describe(sch.description || '') |
| 2160 | } |
| 2161 | } |
| 2162 | } |
| 2163 | const structuredOutputSchema = z.object(zodObj) |
| 2164 | |
| 2165 | // @ts-ignore |
| 2166 | return llmNodeInstance.withStructuredOutput(structuredOutputSchema, { |
| 2167 | method: 'functionCalling' |
| 2168 | }) |
| 2169 | } catch (exception) { |
| 2170 | console.error(exception) |
| 2171 | return llmNodeInstance |
| 2172 | } |
| 2173 | } |
| 2174 | |
| 2175 | /** |
| 2176 | * Creates a Zod schema from a JSON schema object |
no test coverage detected