microsoft/autogen · error · ArgumentException

Failed to generate content. Status code: {response.StatusCod

Error message

Failed to generate content. Status code: {response.StatusCode}

What it means

Thrown by GoogleGeminiClient.GenerateContentAsync when the HTTP POST to the Gemini generateContent endpoint returns a non-success status code. The exception (mis-typed as ArgumentException) includes the status code but not the response body, so the underlying API error detail (invalid API key, bad model name, quota, malformed request) is hidden.

Source

Thrown at dotnet/src/AutoGen.Gemini/GoogleGeminiClient.cs:43

        this.httpClient = httpClient;
    }

    public GoogleGeminiClient(string apiKey)
    {
        this.apiKey = apiKey;
    }

    public async Task<GenerateContentResponse> GenerateContentAsync(GenerateContentRequest request, CancellationToken cancellationToken = default)
    {
        var path = string.Format(generateContentPath, request.Model);
        var url = $"{endpoint}/{path}?key={apiKey}";

        var httpContent = new StringContent(JsonFormatter.Default.Format(request), System.Text.Encoding.UTF8, "application/json");
        var response = await httpClient.PostAsync(url, httpContent, cancellationToken);

        if (!response.IsSuccessStatusCode)
        {
            throw new ArgumentException($"Failed to generate content. Status code: {response.StatusCode}");
        }

#pragma warning disable CA2016 // Forward the CancellationToken parameter to the asynchronous method
        var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
#pragma warning restore CA2016 // Forward the CancellationToken parameter to the asynchronous method
        return GenerateContentResponse.Parser.ParseJson(json);
    }

    public async IAsyncEnumerable<GenerateContentResponse> GenerateContentStreamAsync(GenerateContentRequest request)
    {
        var path = string.Format(generateContentStreamPath, request.Model);
        var url = $"{endpoint}/{path}?key={apiKey}&alt=sse";

        var httpContent = new StringContent(JsonFormatter.Default.Format(request), System.Text.Encoding.UTF8, "application/json");
        var requestMessage = new HttpRequestMessage(HttpMethod.Post, url)
        {
            Content = httpContent
        };

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Verify the API key and that the model id (e.g. gemini-1.5-pro) is valid for the Gemini API endpoint you target
  2. Check quota/billing in Google Cloud console if status is 429/403
  3. Reproduce the call with curl to read the full error body the library discards (same URL: /v1/models/{model}:generateContent?key=...)
  4. Upgrade AutoGen.Gemini if a newer version maps this to a richer exception or uses Google's SDK

Example fix

// before: var resp = await client.GenerateContentAsync(request); // opaque 'Status code: 400'
// after: reproduce to see the real error
// curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key=$KEY" -d @req.json
Defensive patterns

Strategy: retry

Validate before calling

// Validate config before the call
if (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException("Gemini API key missing");
if (string.IsNullOrWhiteSpace(model) || !model.StartsWith("gemini")) throw new InvalidOperationException($"Suspicious model id: {model}");

Try / catch

for (int i = 0; ; i++)
{
    try { return await client.GenerateContentAsync(request, ct); }
    catch (ArgumentException e) when (e.Message.Contains("Status code: 429") && i < 3)
    { await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, i))); }
}

Prevention

When it happens

Trigger: Calling GenerateContentAsync with an invalid API key (401/403), a non-existent model id (404), malformed Content (400), or when quota/rate limits are exceeded (429) — any non-2xx from the Google endpoint.

Common situations: Wrong/expired GOOGLE API key in config, model names from the wrong API generation (PaLM vs Gemini), region restrictions, quota exhaustion, or request payloads violating role/parts rules caught server-side.

Related errors


AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15). Data as JSON: /api/errors/72726d8b596746ab. Report an issue: GitHub.