{"record":{"id":"a12726aad440458e","repo":"microsoft/semantic-kernel","slug":"failed-to-invoke-agent-status-code-invokeagentr","errorCode":null,"errorMessage":"Failed to invoke agent. Status code: {invokeAgentResponse.HttpStatusCode}","messagePattern":"Failed to invoke agent\\. Status code: (.+?)","errorType":"http","errorClass":"HttpOperationException","httpStatus":null,"severity":"error","filePath":"dotnet/src/Agents/Bedrock/Extensions/BedrockAgentInvokeExtensions.cs","lineNumber":43,"sourceCode":"        InvokeAgentRequest invokeAgentRequest,\n        KernelArguments? arguments,\n        [EnumeratorCancellation] CancellationToken cancellationToken)\n    {\n        // This session state is used to store the results of function calls to be passed back to the agent.\n        // https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/BedrockAgentRuntime/TSessionState.html\n        SessionState? sessionState = null;\n        for (var requestIndex = 0; ; requestIndex++)\n        {\n            if (sessionState != null)\n            {\n                invokeAgentRequest.SessionState = sessionState;\n                sessionState = null;\n            }\n            var invokeAgentResponse = await agent.RuntimeClient.InvokeAgentAsync(invokeAgentRequest, cancellationToken).ConfigureAwait(false);\n\n            if (invokeAgentResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)\n            {\n                throw new HttpOperationException($\"Failed to invoke agent. Status code: {invokeAgentResponse.HttpStatusCode}\");\n            }\n\n            List<FunctionCallContent> functionCallContents = [];\n            foreach (var responseEvent in invokeAgentResponse.Completion)\n            {\n                if (responseEvent is BedrockAgentRuntimeEventStreamException bedrockAgentRuntimeEventStreamException)\n                {\n                    throw new KernelException(\"Failed to handle Bedrock Agent stream event.\", bedrockAgentRuntimeEventStreamException);\n                }\n\n                var chatMessageContent =\n                    HandleChunkEvent(agent, responseEvent) ??\n                    HandleFilesEvent(agent, responseEvent) ??\n                    HandleReturnControlEvent(agent, responseEvent, arguments) ??\n                    HandleTraceEvent(agent, responseEvent) ??\n                    throw new KernelException($\"Failed to handle Bedrock Agent stream event: {responseEvent}\");\n                if (chatMessageContent.Items.Count > 0 && chatMessageContent.Items[0] is FunctionCallContent functionCallContent)\n                {","sourceCodeStart":25,"sourceCodeEnd":61,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/dotnet/src/Agents/Bedrock/Extensions/BedrockAgentInvokeExtensions.cs#L25-L61","documentation":"Thrown when InvokeAgentAsync returns an HTTP status code other than 200 OK. This HttpOperationException reports the actual status code so the caller can distinguish auth failures (401/403), not-found (404), throttling (429), and server errors (5xx). The check happens before any stream processing begins.","triggerScenarios":"Invoking a Bedrock agent that is not in PREPARED status, using an expired or unauthorized session, referencing a non-existent agentId/aliasId, exceeding concurrency limits, or hitting a server-side error during invocation.","commonSituations":"Agent was created but never prepared (still DRAFT/NOT_PREPARED); wrong aliasId; credentials expired mid-session; throttled by Bedrock service quotas; regional mismatch between client and agent.","solutions":["Map the HttpStatusCode: 401/403 → fix credentials/IAM; 404 → verify agentId and aliasId; 429 → retry with backoff; 5xx → transient, retry.","Ensure the agent is in PREPARED status before invoking (use the status polling extension).","Verify the agentId, aliasId, and region on the invoke request match a prepared agent.","For 429/5xx, implement retry with exponential backoff and jitter."],"exampleFix":"// before\ntry { await foreach (var r in agent.InvokeAsync(request, thread, cancellationToken)) { ... } }\ncatch (HttpOperationException ex) { logger.LogError(ex.Message); throw; }\n\n// after — branch on status code\ntry { await foreach (var r in agent.InvokeAsync(request, thread, cancellationToken)) { ... } }\ncatch (HttpOperationException ex) when (ex.StatusCode == System.Net.HttpStatusCode.TooManyRequests) { await Task.Delay(backoff); /* retry */ }\ncatch (HttpOperationException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) { logger.LogError(\"Agent or alias not found\"); throw; }","handlingStrategy":"retry","validationCode":"// Ensure agent is PREPARED before invoking\nvar a = await client.GetAgentAsync(new() { AgentId = agent.AgentId }, cancellationToken);\nif (a.Agent.AgentStatus != AgentStatus.Prepared)\n    throw new InvalidOperationException($\"Agent not prepared (status={a.Agent.AgentStatus}).\");","typeGuard":null,"tryCatchPattern":"try { await foreach (var r in agent.InvokeAsync(request, thread, cancellationToken)) { ... } }\ncatch (HttpOperationException ex) when (ex.StatusCode == System.Net.HttpStatusCode.TooManyRequests) { await Task.Delay(backoff); /* retry */ }\ncatch (HttpOperationException ex) when ((int)ex.StatusCode >= 500) { await Task.Delay(backoff); /* retry transient */ }\ncatch (HttpOperationException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) { logger.LogError(\"Agent/alias not found\"); throw; }","preventionTips":["Ensure the agent is PREPARED (not DRAFT) before invoking.","Verify agentId, aliasId, and region match a deployed agent.","Implement retry with backoff for 429 and 5xx; fail fast on 401/403/404 with a clear message."],"tags":["bedrock","agents","http","invoke","aws-service-error","csharp"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}