microsoft/semantic-kernel · error · AgentInvokeException

Failed to generate token using bot_secret.

Error message

Failed to generate token using bot_secret.

What it means

An AgentInvokeException raised when the bot_secret token-generation POST returns a non-200 HTTP status. This means the request itself was rejected (auth failure, bad endpoint, server error) before any token could be parsed; the status code is logged.

Source

Thrown at python/samples/demos/copilot_studio_agent/src/direct_line_agent.py:67

        """
        Retrieve the DirectLine token either by using the bot_secret or by querying the token_endpoint.
        If bot_secret is provided, it posts to "https://directline.botframework.com/v3/directline/tokens/generate".
        """
        await self._ensure_session()
        try:
            if self.bot_secret:
                url = f"{self.bot_endpoint}/tokens/generate"
                headers = {"Authorization": f"Bearer {self.bot_secret}"}
                async with self.session.post(url, headers=headers) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        self.directline_token = data.get("token")
                        if not self.directline_token:
                            logger.error("Token generation response missing token: %s", data)
                            raise AgentInvokeException("No token received from token generation.")
                    else:
                        logger.error("Token generation endpoint error status: %s", resp.status)
                        raise AgentInvokeException("Failed to generate token using bot_secret.")
            else:
                async with self.session.get(self.token_endpoint) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        self.directline_token = data.get("token")
                        if not self.directline_token:
                            logger.error("Token endpoint returned no token: %s", data)
                            raise AgentInvokeException("No token received.")
                    else:
                        logger.error("Token endpoint error status: %s", resp.status)
                        raise AgentInvokeException("Failed to fetch token from token endpoint.")
        except Exception as ex:
            logger.exception("Exception fetching token: %s", ex)
            raise AgentInvokeException("Exception occurred while fetching token.") from ex

    @trace_agent_get_response
    @override
    async def get_response(

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Regenerate the DirectLine/Copilot secret and set the correct BOT_SECRET value.
  2. Verify bot_endpoint is the full base URL of your DirectLine relay (no trailing path mismatch).
  3. Check the logged status code: 401/403 => secret problem; 404 => endpoint; 5xx => upstream outage worth retrying.

Example fix

// before
BOT_SECRET=old-or-wrong-secret

// after
BOT_SECRET=<regenerated secret from Copilot Studio DirectLine channel>
Defensive patterns

Strategy: retry

Try / catch

for attempt in range(3):
    try:
        await fetch_token()
        break
    except AgentInvokeException as e:
        if "Failed to generate token" in str(e) and attempt < 2:
            await asyncio.sleep(2 ** attempt)
            continue
        raise

Prevention

When it happens

Trigger: POST to {bot_endpoint}/tokens/generate with Bearer {bot_secret} returns a status outside the 2xx range (401/403 for bad secret, 404 for wrong endpoint, 5xx for server fault).

Common situations: Expired or incorrect bot_secret; bot_endpoint misconfigured; DirectLine/Copilot service outage; network proxy returning an error page.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/d1bf6de9dc490a5d. Report an issue: GitHub.