{"record":{"id":"197b1f7d570a5697","repo":"microsoft/semantic-kernel","slug":"invalid-response-from-directline-bot-n-response-d","errorCode":null,"errorMessage":"Invalid response from DirectLine Bot.\\n{response_data}","messagePattern":"Invalid response from DirectLine Bot\\.\\\\n(.+?)","errorType":"exception","errorClass":"AgentInvokeException","httpStatus":null,"severity":"error","filePath":"python/samples/demos/copilot_studio_agent/src/direct_line_agent.py","lineNumber":122,"sourceCode":"    @override\n    async def invoke(\n        self,\n        history: ChatHistory,\n        arguments: dict[str, Any] | None = None,\n        **kwargs: Any,\n    ) -> AsyncIterable[ChatMessageContent]:\n        \"\"\"\n        Send the latest message from the chat history to the DirectLine Bot\n        and yield responses. This sends the payload after ensuring that:\n          1. The token is fetched.\n          2. A conversation is started.\n          3. The activity payload is posted.\n          4. Activities are polled until an event \"DynamicPlanFinished\" is received.\n        \"\"\"\n        payload = self._build_payload(history, arguments, **kwargs)\n        response_data = await self._send_message(payload)\n        if response_data is None or \"activities\" not in response_data:\n            raise AgentInvokeException(f\"Invalid response from DirectLine Bot.\\n{response_data}\")\n\n        logger.debug(\"DirectLine Bot response: %s\", response_data)\n\n        # NOTE DirectLine Activities have different formats\n        # than ChatMessageContent. We need to convert them and\n        # remove unsupported activities.\n        for activity in response_data[\"activities\"]:\n            if activity.get(\"type\") != \"message\" or activity.get(\"from\", {}).get(\"role\") == \"user\":\n                continue\n            role = activity.get(\"from\", {}).get(\"role\", \"assistant\")\n            if role == \"bot\":\n                role = \"assistant\"\n            message = ChatMessageContent(\n                role=role,\n                content=activity.get(\"text\", \"\"),\n                name=activity.get(\"from\", {}).get(\"name\", self.name),\n            )\n            yield message","sourceCodeStart":104,"sourceCodeEnd":140,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/samples/demos/copilot_studio_agent/src/direct_line_agent.py#L104-L140","documentation":"An AgentInvokeException raised at the start of invoke() when _send_message returns None or a dict lacking the 'activities' key. The agent requires a well-formed activities payload to extract bot replies; without it the conversation cannot continue. The raw response_data is interpolated into the message for diagnosis.","triggerScenarios":"_send_message(payload) returns None (request failed/null) or a JSON object without 'activities' (e.g. an error envelope like {'error': {...}}).","commonSituations":"The post-activity or poll step returned an error body that wasn't detected as a status failure; the endpoint schema changed; watermark polling returned a terminal non-activities object.","solutions":["Examine the interpolated response_data in the message to see the actual body.","Verify the payload built by _build_payload is correct and the conversation/activity post succeeded.","Check that the activities polling URL and watermark logic match the DirectLine version."],"exampleFix":"// before\nresponse_data = await self._send_message(payload)\nif response_data is None or \"activities\" not in response_data:\n    raise AgentInvokeException(f\"Invalid response from DirectLine Bot.\\n{response_data}\")\n\n// after  # distinguish null vs malformed\nresponse_data = await self._send_message(payload)\nif response_data is None:\n    raise AgentInvokeException(\"No data returned from DirectLine Bot.\")\nif \"activities\" not in response_data:\n    logger.error(\"Unexpected DirectLine body: %s\", response_data)\n    raise AgentInvokeException(f\"Invalid response from DirectLine Bot.\\n{response_data}\")","handlingStrategy":"validation","validationCode":"payload = agent._build_payload(history, arguments, **kwargs)\n# ensure payload is well-formed before sending\nassert payload and isinstance(payload, dict), \"Invalid payload for DirectLine\"","typeGuard":"def has_activities(data) -> bool:\n    return isinstance(data, dict) and isinstance(data.get('activities'), list)","tryCatchPattern":"try:\n    async for msg in agent.invoke(history, arguments, **kwargs):\n        yield msg\nexcept AgentInvokeException as e:\n    if \"Invalid response\" in str(e):\n        logger.error(\"DirectLine returned malformed body: %s\", e)\n    raise","preventionTips":["Validate _send_message output shape before accessing 'activities'.","Log the full response_data on malformed bodies to catch schema drift early."],"tags":["runtime","directline","copilot-studio","validation","semantic-kernel"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}