From 94c1f3bd3eb9412e3321a46730c1572da11bd951 Mon Sep 17 00:00:00 2001 From: Philipp Zagar Date: Thu, 25 Jan 2024 16:08:29 -0800 Subject: [PATCH] Fix for empty OpenAI functions array (#44) # Fix for empty functions array ## :recycle: Current situation & Problem If no function calls are present and we pass an empty array of functions to the OpenAI library, the OpenAI API call randomly returns an error (only sometimes!) ## :gear: Release Notes - Fix OpenAI error return if function calls are empty ## :books: Documentation -- ## :white_check_mark: Testing Properly tested on simulator and real device. ## :pencil: Code of Conduct & Contributing Guidelines By submitting creating this pull request, you agree to follow our [Code of Conduct](https://github.com/StanfordSpezi/.github/blob/main/CODE_OF_CONDUCT.md) and [Contributing Guidelines](https://github.com/StanfordSpezi/.github/blob/main/CONTRIBUTING.md): - [x] I agree to follow the [Code of Conduct](https://github.com/StanfordSpezi/.github/blob/main/CODE_OF_CONDUCT.md) and [Contributing Guidelines](https://github.com/StanfordSpezi/.github/blob/main/CONTRIBUTING.md). --- .../LLMOpenAI+Configuration.swift | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/Sources/SpeziLLMOpenAI/LLMOpenAI+Configuration.swift b/Sources/SpeziLLMOpenAI/LLMOpenAI+Configuration.swift index a024fd5..78fe6a6 100644 --- a/Sources/SpeziLLMOpenAI/LLMOpenAI+Configuration.swift +++ b/Sources/SpeziLLMOpenAI/LLMOpenAI+Configuration.swift @@ -33,19 +33,21 @@ extension LLMOpenAI { /// in an OpenAI `ChatQuery` representation used for querying the OpenAI API. var openAIChatQuery: ChatQuery { get async { - await .init( + let functions: [ChatFunctionDeclaration] = self.functions.values.compactMap { function in + let functionType = Swift.type(of: function) + + return .init( + name: functionType.name, + description: functionType.description, + parameters: function.schema + ) + } + + return await .init( model: self.parameters.modelType, messages: self.openAIContext, responseFormat: self.modelParameters.responseFormat, - functions: self.functions.values.compactMap { function in - let functionType = Swift.type(of: function) - - return .init( - name: functionType.name, - description: functionType.description, - parameters: function.schema - ) - }, + functions: functions.isEmpty ? nil : functions, temperature: self.modelParameters.temperature, topP: self.modelParameters.topP, n: self.modelParameters.completionsPerOutput,