microsoft/semantic-kernel · error · KernelException
Unexpected response from model
Error message
Unexpected response from model
What it means
Thrown by ClientBase.DeserializeResponse<T> when JsonSerializer.Deserialize throws a JsonException or returns null while parsing the model's HTTP response body. The original JsonException is wrapped in a KernelException with the raw response string stored in the exception's Data dictionary under the key 'ResponseData'. This is a catch-all for malformed or unexpected response payloads from the Google/Gemini API.
Source
Thrown at dotnet/src/Connectors/Connectors.Google/Core/ClientBase.cs:83
protected async Task<HttpResponseMessage> SendRequestAndGetResponseImmediatelyAfterHeadersReadAsync(
HttpRequestMessage httpRequestMessage,
CancellationToken cancellationToken)
{
var response = await this.HttpClient.SendWithSuccessCheckAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
.ConfigureAwait(false);
return response;
}
protected static T DeserializeResponse<T>(string body)
{
try
{
return JsonSerializer.Deserialize<T>(body) ?? throw new JsonException("Response is null");
}
catch (JsonException exc)
{
throw new KernelException("Unexpected response from model", exc)
{
Data = { { "ResponseData", body } },
};
}
}
protected async Task<HttpRequestMessage> CreateHttpRequestAsync(object requestData, Uri endpoint)
{
var httpRequestMessage = HttpRequest.CreatePostRequest(endpoint, requestData);
httpRequestMessage.Headers.Add("User-Agent", HttpHeaderConstant.Values.UserAgent);
httpRequestMessage.Headers.Add(HttpHeaderConstant.Names.SemanticKernelVersion,
HttpHeaderConstant.Values.GetAssemblyVersion(typeof(ClientBase)));
if (this._bearerTokenProvider is not null && await this._bearerTokenProvider().ConfigureAwait(false) is { } bearerKey)
{
httpRequestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", bearerKey);
}View on GitHub (pinned to c028a0c7dc)
Solutions
- Catch KernelException and inspect exception.Data['ResponseData'] for the raw response body.
- Upgrade the Connectors.Google NuGet package to match the API version you are targeting.
- Verify the API version and model ID are compatible with the installed connector version.
- Check for proxy/gateway interference that may alter the response body.
Example fix
// inspect the raw response when this fires
try { var result = await client.GetChatMessageContentsAsync(history); }
catch (KernelException ex)
{
var rawBody = ex.Data.Contains("ResponseData") ? ex.Data["ResponseData"] : null;
logger.LogError(ex, "Deserialization failed. Raw body: {Body}", rawBody);
} Defensive patterns
Strategy: try-catch
Validate before calling
null
Type guard
null
Try / catch
try
{
var result = await client.GetChatMessageContentsAsync(history, settings, ct);
}
catch (KernelException ex) when (ex.Message == "Unexpected response from model")
{
var rawBody = ex.Data.Contains("ResponseData") ? ex.Data["ResponseData"]?.ToString() : "<unavailable>";
logger.LogError(ex, "Failed to deserialize Gemini response. Raw body: {Body}", rawBody);
throw;
} Prevention
- Keep the Connectors.Google package version aligned with the Gemini API version you target.
- Log the ResponseData from the KernelException.Data dictionary for post-mortem analysis.
- Verify network paths (proxies, gateways) are not injecting non-JSON content.
- Monitor for API version deprecation notices from Google.
When it happens
Trigger: The Gemini or Vertex AI API returns a response body that does not deserialize into the expected type T (e.g. GeminiResponse). This includes: JSON schema mismatch, truncated response body, HTML error page instead of JSON, or a response shape from a newer/older API version that the connector's model classes do not match.
Common situations: Google changes the API response format in a new version and the installed connector package is outdated. A network proxy or gateway injects HTML or non-JSON content. Rate limiting or auth failure returns an error page instead of the expected JSON. Mismatch between the API version configured and the connector's model classes.
Related errors
- GeminiPart is invalid. One and only one property among Text,
- Unexpected author role: {role}
- Gemini API doesn't support author role: {value}
- Prompt was blocked due to Gemini API safety reasons.
- Invalid response from model
AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13).
Data as JSON: /api/errors/bbabda2d73669648.
Report an issue: GitHub.