{"record":{"id":"1ad0be1d5de71a46","repo":"microsoft/semantic-kernel","slug":"invalid-response-from-model","errorCode":null,"errorMessage":"Invalid response from model","messagePattern":"Invalid response from model","errorType":"exception","errorClass":"KernelException","httpStatus":null,"severity":"error","filePath":"dotnet/src/Connectors/Connectors.Google/Core/Gemini/Clients/GeminiTokenCounterClient.cs","lineNumber":109,"sourceCode":"        string prompt,\n        PromptExecutionSettings? executionSettings = null,\n        CancellationToken cancellationToken = default)\n    {\n        Verify.NotNullOrWhiteSpace(prompt);\n\n        var geminiRequest = CreateGeminiRequest(prompt, executionSettings);\n        using var httpRequestMessage = await this.CreateHttpRequestAsync(geminiRequest, this._tokenCountingEndpoint).ConfigureAwait(false);\n\n        string body = await this.SendRequestAndGetStringBodyAsync(httpRequestMessage, cancellationToken)\n            .ConfigureAwait(false);\n\n        return DeserializeAndProcessCountTokensResponse(body);\n    }\n\n    private static int DeserializeAndProcessCountTokensResponse(string body)\n    {\n        var node = DeserializeResponse<JsonNode>(body);\n        return node[\"totalTokens\"]?.GetValue<int>() ?? throw new KernelException(\"Invalid response from model\");\n    }\n\n    private static GeminiRequest CreateGeminiRequest(\n        string prompt,\n        PromptExecutionSettings? promptExecutionSettings)\n    {\n        var geminiExecutionSettings = GeminiPromptExecutionSettings.FromExecutionSettings(promptExecutionSettings);\n        ValidateMaxTokens(geminiExecutionSettings.MaxTokens);\n        var geminiRequest = GeminiRequest.FromPromptAndExecutionSettings(prompt, geminiExecutionSettings);\n        return geminiRequest;\n    }\n}\n","sourceCodeStart":91,"sourceCodeEnd":122,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/dotnet/src/Connectors/Connectors.Google/Core/Gemini/Clients/GeminiTokenCounterClient.cs#L91-L122","documentation":"Thrown by GeminiTokenCounterClient.DeserializeAndProcessCountTokensResponse when the deserialized JSON node's 'totalTokens' field is null or cannot be resolved as an integer. The count-tokens endpoint is expected to return { \"totalTokens\": <int> }; if that field is absent or has a non-integer value, this KernelException fires.","triggerScenarios":"Calling the Gemini token-counting endpoint (via CountTokensAsync or equivalent) and receiving a response that either lacks the totalTokens field, contains it as a non-integer (e.g. a string), or returns an error structure instead of the expected count payload.","commonSituations":"API version mismatch where the count-tokens response format changed. An error response (e.g. invalid model, auth failure) that was not caught as an HTTP error but partially parsed as JSON. Google changes the field name or structure in a newer API version.","solutions":["Catch KernelException around token-counting calls and fall back to an estimated token count (e.g. len/4 heuristic).","Upgrade the Connectors.Google package to match the API version being used.","Verify the model ID supports the count-tokens endpoint.","Inspect the underlying HTTP response by enabling debug logging on the Google connector."],"exampleFix":"try\n{\n    int count = await tokenCounter.CountTokensAsync(prompt, settings, ct);\n}\ncatch (KernelException)\n{\n    // fallback estimate\n    int estimatedCount = prompt.Length / 4;\n}","handlingStrategy":"try-catch","validationCode":"null","typeGuard":"null","tryCatchPattern":"try\n{\n    tokenCount = await tokenCounter.CountTokensAsync(prompt, settings, ct);\n}\ncatch (KernelException ex) when (ex.Message == \"Invalid response from model\")\n{\n    logger.LogWarning(\"Token counting failed, using estimate: {Estimate}\", prompt.Length / 4);\n    tokenCount = prompt.Length / 4; // rough heuristic\n}","preventionTips":["Always have a fallback token estimation strategy when relying on the count-tokens endpoint.","Verify the model ID supports token counting before calling the endpoint.","Keep the connector package version aligned with the Gemini API version."],"tags":["google","gemini","token-counting","response-error","kernel-exception"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}