{"record":{"id":"68aeaeeda5541f68","repo":"microsoft/semantic-kernel","slug":"failed-to-handle-bedrock-agent-stream-event","errorCode":null,"errorMessage":"Failed to handle Bedrock Agent stream event.","messagePattern":"Failed to handle Bedrock Agent stream event\\.","errorType":"exception","errorClass":"KernelException","httpStatus":null,"severity":"error","filePath":"dotnet/src/Agents/Bedrock/Extensions/BedrockAgentInvokeExtensions.cs","lineNumber":51,"sourceCode":"        {\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                {\n                    functionCallContents.AddRange(chatMessageContent.Items.Where(item => item is FunctionCallContent).Cast<FunctionCallContent>());\n                }\n                else\n                {\n                    yield return chatMessageContent;\n                }\n            }\n","sourceCodeStart":33,"sourceCodeEnd":69,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/dotnet/src/Agents/Bedrock/Extensions/BedrockAgentInvokeExtensions.cs#L33-L69","documentation":"Thrown while iterating the InvokeAgentAsync response stream when an individual event in the Completion stream is a BedrockAgentRuntimeEventStreamException. This indicates the Bedrock service sent an error mid-stream (after the initial 200 OK). The original event-stream exception is attached as InnerException for diagnostics.","triggerScenarios":"The agent invocation starts successfully (HTTP 200) but the Bedrock runtime emits an error event partway through generation — internal model errors, content policy violations, session state corruption, or service degradation during streaming.","commonSituations":"The model produced content flagged by Bedrock guardrails mid-generation; the session state became inconsistent during a multi-turn flow; transient Bedrock runtime errors; token/quota limits hit mid-stream.","solutions":["Inspect InnerException (BedrockAgentRuntimeEventStreamException) for the specific service error type and message.","For content-policy/guardrail errors, adjust the input or agent instructions to avoid flagged content.","For transient runtime errors, retry the invocation (the session state may need resetting).","If mid-stream during function-calling loops, ensure session state and function results are consistent before re-invoking."],"exampleFix":"// before\nawait foreach (var msg in agent.InvokeStreamingAsync(...)) { yield return msg; }\n\n// after — surface stream errors with context\ntry { await foreach (var msg in agent.InvokeStreamingAsync(...)) { yield return msg; } }\ncatch (KernelException ex) when (ex.InnerException is BedrockAgentRuntimeEventStreamException streamEx)\n{\n    logger.LogError(streamEx, \"Bedrock stream error: {Message}\", streamEx.Message);\n    throw;\n}","handlingStrategy":"try-catch","validationCode":"// No pre-validation possible for mid-stream service errors; ensure session state is consistent\n// and inputs comply with guardrails before invoking.","typeGuard":null,"tryCatchPattern":"try { await foreach (var r in agent.InvokeStreamingAsync(request, thread, cancellationToken)) { ... } }\ncatch (KernelException ex) when (ex.InnerException is BedrockAgentRuntimeEventStreamException streamEx)\n{\n    logger.LogError(streamEx, \"Bedrock stream error mid-generation: {Message}\", streamEx.Message);\n    // retry, reset session, or adjust input per the error type\n    throw;\n}","preventionTips":["Keep session state consistent across multi-turn flows to avoid mid-stream corruption.","Review Bedrock guardrail settings if content-policy errors recur.","Log the inner event-stream exception type to classify retryable vs non-retryable errors."],"tags":["bedrock","agents","streaming","event-stream","aws-service-error","csharp"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}