(client, params, options)
| 81924 | return this._addChatCompletion(parseChatCompletion(chatCompletion, params)); |
| 81925 | } |
| 81926 | async _runChatCompletion(client, params, options) { |
| 81927 | for (const message of params.messages) { |
| 81928 | this._addMessage(message, false); |
| 81929 | } |
| 81930 | return await this._createChatCompletion(client, params, options); |
| 81931 | } |
| 81932 | async _runFunctions(client, params, options) { |
| 81933 | const role = "function"; |
| 81934 | const { function_call = "auto", stream: stream4, ...restParams } = params; |
| 81935 | const singleFunctionToCall = typeof function_call !== "string" && function_call?.name; |
| 81936 | const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; |
| 81937 | const functionsByName = {}; |
| 81938 | for (const f4 of params.functions) { |
| 81939 | functionsByName[f4.name || f4.function.name] = f4; |
| 81940 | } |
| 81941 | const functions = params.functions.map((f4) => ({ |
| 81942 | name: f4.name || f4.function.name, |
| 81943 | parameters: f4.parameters, |
| 81944 | description: f4.description |
| 81945 | })); |
| 81946 | for (const message of params.messages) { |
| 81947 | this._addMessage(message, false); |
| 81948 | } |
| 81949 | for (let i3 = 0; i3 < maxChatCompletions; ++i3) { |
| 81950 | const chatCompletion = await this._createChatCompletion(client, { |
| 81951 | ...restParams, |
| 81952 | function_call, |
| 81953 | functions, |
| 81954 | messages: [...this.messages] |
| 81955 | }, options); |
| 81956 | const message = chatCompletion.choices[0]?.message; |
| 81957 | if (!message) { |
| 81958 | throw new OpenAIError(`missing message in ChatCompletion response`); |
| 81959 | } |
| 81960 | if (!message.function_call) |
| 81961 | return; |
| 81962 | const { name, arguments: args } = message.function_call; |
| 81963 | const fn = functionsByName[name]; |
| 81964 | if (!fn) { |
| 81965 | const content2 = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions.map((f4) => JSON.stringify(f4.name)).join(", ")}. Please try again`; |
| 81966 | this._addMessage({ role, name, content: content2 }); |
| 81967 | continue; |
| 81968 | } else if (singleFunctionToCall && singleFunctionToCall !== name) { |
| 81969 | const content2 = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; |
| 81970 | this._addMessage({ role, name, content: content2 }); |
| 81971 | continue; |
| 81972 | } |
| 81973 | let parsed; |
| 81974 | try { |
| 81975 | parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; |
| 81976 | } catch (error) { |
| 81977 | this._addMessage({ |
| 81978 | role, |
| 81979 | name, |
| 81980 | content: error instanceof Error ? error.message : String(error) |
| 81981 | }); |
| 81982 | continue; |
| 81983 | } |
no test coverage detected