microsoft/semantic-kernel · error · ArgumentException

MaxTokens {maxTokens} is not valid, the value must be greate

Error message

MaxTokens {maxTokens} is not valid, the value must be greater than zero

What it means

Thrown by ValidateMaxTokens. MaxTokens must be a positive integer when set; a value of zero or negative is invalid because OpenAI's max_completion_tokens/max_tokens field requires >= 1. The check runs before the request is sent so the API never sees a malformed value.

Source

Thrown at dotnet/src/Connectors/Connectors.OpenAI/Core/ClientCore.ChatCompletion.cs:1100

                    id: toolCall.Id,
                    arguments: arguments)
                {
                    InnerContent = toolCall,
                    Exception = exception
                };

                result.Add(functionCallContent);
            }
        }

        return result;
    }

    private static void ValidateMaxTokens(int? maxTokens)
    {
        if (maxTokens.HasValue && maxTokens < 1)
        {
            throw new ArgumentException($"MaxTokens {maxTokens} is not valid, the value must be greater than zero");
        }
    }

    /// <summary>
    /// Gets the response modalities from the execution settings.
    /// </summary>
    /// <param name="executionSettings">The execution settings.</param>
    /// <returns>The response modalities as a <see cref="ChatResponseModalities"/> flags enum.</returns>
    /// <remarks>
    /// This method supports converting from various formats:
    /// <list type="bullet">
    /// <item><description>A <see cref="ChatResponseModalities"/> flags enum</description></item>
    /// <item><description>A string representation of the enum (e.g., "Text, Audio")</description></item>
    /// <item><description>An <see cref="IEnumerable{String}"/> of modality names (e.g., ["text", "audio"])</description></item>
    /// <item><description>A <see cref="JsonElement"/> containing either a string, or array of strings</description></item>
    /// </list>
    /// </remarks>
    private static ChatResponseModalities GetResponseModalities(OpenAIPromptExecutionSettings executionSettings)

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Set MaxTokens to a positive integer, or leave it null to let the model decide.
  2. If 'unlimited' was intended, pass null rather than 0.
  3. Clamp computed values to at least 1 before assigning.

Example fix

// before
settings.MaxTokens = 0; // or -1
// after
settings.MaxTokens = null; // or a positive int like 1024
Defensive patterns

Strategy: validation

Validate before calling

static int? NormalizeMaxTokens(int? v) => v switch { null => null, > 0 => v, _ => throw new ArgumentException("MaxTokens must be > 0; use null for unlimited") };

Type guard

static bool IsValidMaxTokens(int? v) => v is null or > 0;

Try / catch

try { await client.GetChatCompletionAsync(...); }
catch (ArgumentException ex) when (ex.Message.Contains("MaxTokens")) { settings.MaxTokens = null; /* retry */ }

Prevention

When it happens

Trigger: Setting executionSettings.MaxTokens to 0 or a negative number (e.g. from a config default of 0, a computed value that underflowed, or deserialized -1 meaning 'unlimited').

Common situations: Treating 0/-1 as 'no limit' (the connector uses null for that); config with max_tokens:0; arithmetic that produced a non-positive budget.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/5b9dc9ce0559f81e. Report an issue: GitHub.