{"record":{"id":"72726d8b596746ab","repo":"microsoft/autogen","slug":"failed-to-generate-content-status-code-response","errorCode":null,"errorMessage":"Failed to generate content. Status code: {response.StatusCode}","messagePattern":"Failed to generate content\\. Status code: (.+?)","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"dotnet/src/AutoGen.Gemini/GoogleGeminiClient.cs","lineNumber":43,"sourceCode":"        this.httpClient = httpClient;\n    }\n\n    public GoogleGeminiClient(string apiKey)\n    {\n        this.apiKey = apiKey;\n    }\n\n    public async Task<GenerateContentResponse> GenerateContentAsync(GenerateContentRequest request, CancellationToken cancellationToken = default)\n    {\n        var path = string.Format(generateContentPath, request.Model);\n        var url = $\"{endpoint}/{path}?key={apiKey}\";\n\n        var httpContent = new StringContent(JsonFormatter.Default.Format(request), System.Text.Encoding.UTF8, \"application/json\");\n        var response = await httpClient.PostAsync(url, httpContent, cancellationToken);\n\n        if (!response.IsSuccessStatusCode)\n        {\n            throw new ArgumentException($\"Failed to generate content. Status code: {response.StatusCode}\");\n        }\n\n#pragma warning disable CA2016 // Forward the CancellationToken parameter to the asynchronous method\n        var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);\n#pragma warning restore CA2016 // Forward the CancellationToken parameter to the asynchronous method\n        return GenerateContentResponse.Parser.ParseJson(json);\n    }\n\n    public async IAsyncEnumerable<GenerateContentResponse> GenerateContentStreamAsync(GenerateContentRequest request)\n    {\n        var path = string.Format(generateContentStreamPath, request.Model);\n        var url = $\"{endpoint}/{path}?key={apiKey}&alt=sse\";\n\n        var httpContent = new StringContent(JsonFormatter.Default.Format(request), System.Text.Encoding.UTF8, \"application/json\");\n        var requestMessage = new HttpRequestMessage(HttpMethod.Post, url)\n        {\n            Content = httpContent\n        };","sourceCodeStart":25,"sourceCodeEnd":61,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/src/AutoGen.Gemini/GoogleGeminiClient.cs#L25-L61","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Verify the API key and that the model id (e.g. gemini-1.5-pro) is valid for the Gemini API endpoint you target","Check quota/billing in Google Cloud console if status is 429/403","Reproduce the call with curl to read the full error body the library discards (same URL: /v1/models/{model}:generateContent?key=...)\n","Upgrade AutoGen.Gemini if a newer version maps this to a richer exception or uses Google's SDK"],"exampleFix":"// before: var resp = await client.GenerateContentAsync(request); // opaque 'Status code: 400'\n// after: reproduce to see the real error\n// curl \"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent?key=$KEY\" -d @req.json","handlingStrategy":"retry","validationCode":"// Validate config before the call\nif (string.IsNullOrWhiteSpace(apiKey)) throw new InvalidOperationException(\"Gemini API key missing\");\nif (string.IsNullOrWhiteSpace(model) || !model.StartsWith(\"gemini\")) throw new InvalidOperationException($\"Suspicious model id: {model}\");","typeGuard":null,"tryCatchPattern":"for (int i = 0; ; i++)\n{\n    try { return await client.GenerateContentAsync(request, ct); }\n    catch (ArgumentException e) when (e.Message.Contains(\"Status code: 429\") && i < 3)\n    { await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, i))); }\n}","preventionTips":["Load the API key from environment/GCP config and fail fast if absent","Pin model ids validated against the current Gemini API docs","Reproduce failing calls with curl to read the error body the library discards"],"tags":["autogen","gemini","http","api-key"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}