|
| 1 | +const OpenAI = require('openai'); |
| 2 | +const dotenv = require('dotenv'); |
| 3 | +const { MemoryVectorStore } = require('langchain/vectorstores/memory'); |
| 4 | +const { OpenAIEmbeddings } = require('@langchain/openai'); |
| 5 | + |
| 6 | +//dotenv.config(); |
| 7 | + |
| 8 | +const SYSTEM_MESSAGE = `You are a helpful assistant. \ |
| 9 | + Respond to the following prompt by using function_call and then summarize actions. \ |
| 10 | + Ask for clarification if a user request is ambiguous.`; |
| 11 | + |
| 12 | +// Maximum number of function calls allowed to prevent infinite or lengthy loops |
| 13 | +const MAX_CALLS = 10; |
| 14 | + |
| 15 | +class FlowtestAI { |
| 16 | + async generate(collection, user_instruction, model) { |
| 17 | + if (model.name === 'OPENAI') { |
| 18 | + const available_functions = await this.get_available_functions(collection); |
| 19 | + const functions = await this.filter_functions(available_functions, user_instruction, model.apiKey); |
| 20 | + return await this.process_user_instruction(functions, user_instruction, model.apiKey); |
| 21 | + } else { |
| 22 | + throw Error(`Model ${model.name} not supported`); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + async get_available_functions(collection) { |
| 27 | + let functions = []; |
| 28 | + Object.entries(collection['paths']).map(([path, methods], index) => { |
| 29 | + Object.entries(methods).map(([method, spec], index1) => { |
| 30 | + const function_name = spec['operationId']; |
| 31 | + |
| 32 | + const desc = spec['description'] || spec['summary'] || ''; |
| 33 | + |
| 34 | + let schema = { type: 'object', properties: {} }; |
| 35 | + |
| 36 | + let req_body = undefined; |
| 37 | + if (spec['requestBody']) { |
| 38 | + if (spec['requestBody']['content']) { |
| 39 | + if (spec['requestBody']['content']['application/json']) { |
| 40 | + if (spec['requestBody']['content']['application/json']['schema']) { |
| 41 | + req_body = spec['requestBody']['content']['application/json']['schema']; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + if (req_body != undefined) { |
| 48 | + schema['properties']['requestBody'] = req_body; |
| 49 | + } |
| 50 | + |
| 51 | + const params = spec['parameters'] ? spec['parameters'] : []; |
| 52 | + const param_properties = {}; |
| 53 | + if (params.length > 0) { |
| 54 | + for (const param of params) { |
| 55 | + if (param['schema']) { |
| 56 | + param_properties[param['name']] = param['schema']; |
| 57 | + } |
| 58 | + } |
| 59 | + schema['properties']['parameters'] = { |
| 60 | + type: 'object', |
| 61 | + properties: param_properties, |
| 62 | + }; |
| 63 | + } |
| 64 | + |
| 65 | + functions.push({ name: function_name, description: desc, parameters: schema }); |
| 66 | + }); |
| 67 | + }); |
| 68 | + // console.log(JSON.stringify(functions)); |
| 69 | + return functions; |
| 70 | + } |
| 71 | + |
| 72 | + async filter_functions(functions, instruction, apiKey) { |
| 73 | + const chunkSize = 32; |
| 74 | + const chunks = []; |
| 75 | + |
| 76 | + for (let i = 0; i < functions.length; i += chunkSize) { |
| 77 | + const chunk = functions.slice(i, i + chunkSize); |
| 78 | + chunks.push(chunk); |
| 79 | + } |
| 80 | + |
| 81 | + const documents = chunks.map((chunk) => JSON.stringify(chunk)); |
| 82 | + |
| 83 | + const vectorStore = await MemoryVectorStore.fromTexts( |
| 84 | + documents, |
| 85 | + [], |
| 86 | + new OpenAIEmbeddings({ |
| 87 | + openAIApiKey: apiKey, |
| 88 | + }), |
| 89 | + ); |
| 90 | + |
| 91 | + // 32 x 4 = 128 (max no of functions accepted by openAI function calling) |
| 92 | + const retrievedDocuments = await vectorStore.similaritySearch(instruction, 4); |
| 93 | + var selectedFunctions = []; |
| 94 | + retrievedDocuments.forEach((document) => { |
| 95 | + selectedFunctions = selectedFunctions.concat(JSON.parse(document.pageContent)); |
| 96 | + }); |
| 97 | + |
| 98 | + return selectedFunctions; |
| 99 | + } |
| 100 | + |
| 101 | + async get_openai_response(functions, messages, apiKey) { |
| 102 | + const openai = new OpenAI({ |
| 103 | + apiKey, |
| 104 | + }); |
| 105 | + |
| 106 | + return await openai.chat.completions.create({ |
| 107 | + model: 'gpt-3.5-turbo-16k-0613', |
| 108 | + functions: functions, |
| 109 | + function_call: 'auto', // "auto" means the model can pick between generating a message or calling a function. |
| 110 | + temperature: 0, |
| 111 | + messages: messages, |
| 112 | + }); |
| 113 | + } |
| 114 | + |
| 115 | + async process_user_instruction(functions, instruction, apiKey) { |
| 116 | + let result = []; |
| 117 | + let num_calls = 0; |
| 118 | + const messages = [ |
| 119 | + { content: SYSTEM_MESSAGE, role: 'system' }, |
| 120 | + { content: instruction, role: 'user' }, |
| 121 | + ]; |
| 122 | + |
| 123 | + while (num_calls < MAX_CALLS) { |
| 124 | + const response = await this.get_openai_response(functions, messages, apiKey); |
| 125 | + // console.log(response) |
| 126 | + const message = response['choices'][0]['message']; |
| 127 | + |
| 128 | + if (message['function_call']) { |
| 129 | + console.log('Function call #: ', num_calls + 1); |
| 130 | + console.log(message['function_call']); |
| 131 | + messages.push(message); |
| 132 | + |
| 133 | + // We'll simply add a message to simulate successful function call. |
| 134 | + messages.push({ |
| 135 | + role: 'function', |
| 136 | + content: 'success', |
| 137 | + name: message['function_call']['name'], |
| 138 | + }); |
| 139 | + result.push(message['function_call']); |
| 140 | + |
| 141 | + num_calls += 1; |
| 142 | + } else { |
| 143 | + console.log('Message: '); |
| 144 | + console.log(message['content']); |
| 145 | + break; |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + if (num_calls >= MAX_CALLS) { |
| 150 | + console.log('Reached max chained function calls: ', MAX_CALLS); |
| 151 | + } |
| 152 | + |
| 153 | + return result; |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +module.exports = FlowtestAI; |
0 commit comments