(config: Record<string, any>, question: string, options?: ICommonObject)
| 354 | } |
| 355 | |
| 356 | const generateNodesEdges = async (config: Record<string, any>, question: string, options?: ICommonObject) => { |
| 357 | try { |
| 358 | const chatModelComponent = config.componentNodes[config.selectedChatModel?.name] |
| 359 | if (!chatModelComponent) { |
| 360 | throw new Error('Chat model component not found') |
| 361 | } |
| 362 | const nodeInstanceFilePath = chatModelComponent.filePath as string |
| 363 | const nodeModule = await import(nodeInstanceFilePath) |
| 364 | const newToolNodeInstance = new nodeModule.nodeClass() |
| 365 | const model = (await newToolNodeInstance.init(config.selectedChatModel, '', options)) as BaseChatModel |
| 366 | |
| 367 | // Create a parser to validate the output |
| 368 | const parser = StructuredOutputParser.fromZodSchema(NodesEdgesType as any) |
| 369 | |
| 370 | // Generate JSON schema from our Zod schema |
| 371 | const formatInstructions = parser.getFormatInstructions() |
| 372 | |
| 373 | // Full conversation with system prompt and instructions |
| 374 | const messages = [ |
| 375 | { |
| 376 | role: 'system', |
| 377 | content: `${config.prompt}\n\n${formatInstructions}\n\nMake sure to follow the exact JSON schema structure.` |
| 378 | }, |
| 379 | { |
| 380 | role: 'user', |
| 381 | content: question |
| 382 | } |
| 383 | ] |
| 384 | |
| 385 | // Standard completion without structured output |
| 386 | const response = await model.invoke(messages) |
| 387 | |
| 388 | // Try to extract JSON from the response |
| 389 | const responseContent = extractResponseContent(response) |
| 390 | const jsonMatch = responseContent.match(/```json\n([\s\S]*?)\n```/) || responseContent.match(/{[\s\S]*?}/) |
| 391 | |
| 392 | if (jsonMatch) { |
| 393 | const jsonStr = jsonMatch[1] || jsonMatch[0] |
| 394 | try { |
| 395 | const parsedJSON = JSON.parse(jsonStr) |
| 396 | // Validate with our schema |
| 397 | return NodesEdgesType.parse(parsedJSON) |
| 398 | } catch (parseError) { |
| 399 | console.error('Error parsing JSON from response:', parseError) |
| 400 | return { error: 'Failed to parse JSON from response', content: responseContent } |
| 401 | } |
| 402 | } else { |
| 403 | console.error('No JSON found in response:', responseContent) |
| 404 | return { error: 'No JSON found in response', content: responseContent } |
| 405 | } |
| 406 | } catch (error) { |
| 407 | console.error('Error generating AgentflowV2:', error) |
| 408 | return { error: error.message || 'Unknown error occurred' } |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | const generateNodesData = (result: Record<string, any>, config: Record<string, any>) => { |
| 413 | try { |
no test coverage detected