microsoft/semantic-kernel · error · ValueError

Agent does not exist. Please create the agent before invokin

Error message

Agent does not exist. Please create the agent before invoking it.

What it means

Raised by BedrockAgentBase._invoke_agent when self.agent_model.agent_id is falsy. Invoking a Bedrock agent requires an existing agent (and an alias) so bedrock_runtime_client.invoke_agent has an agentId to route to. This guard short-circuits before the AWS call.

Source

Thrown at python/semantic_kernel/agents/bedrock/bedrock_agent_base.py:360

                    **kwargs,
                ),
            )
        except ClientError as e:
            logger.error(f"Failed to list associated knowledge bases for agent {self.agent_model.agent_id}.")
            raise e

    # endregion Knowledge Base Management

    async def _invoke_agent(
        self,
        thread_id: str,
        message: str | ChatMessageContent,
        agent_alias: str | None = None,
        **kwargs,
    ) -> dict[str, Any]:
        """Invoke an agent."""
        if not self.agent_model.agent_id:
            raise ValueError("Agent does not exist. Please create the agent before invoking it.")

        if isinstance(message, ChatMessageContent) and message.role != AuthorRole.USER:
            raise ValueError("Only user messages are supported for invoking a Bedrock agent.")

        agent_alias = agent_alias or self.WORKING_DRAFT_AGENT_ALIAS

        try:
            return await run_in_executor(
                None,
                partial(
                    self.bedrock_runtime_client.invoke_agent,
                    agentAliasId=agent_alias,
                    agentId=self.agent_model.agent_id,
                    sessionId=thread_id,
                    inputText=message if isinstance(message, str) else message.content,
                    **kwargs,
                ),
            )

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Complete agent creation (await create) and assert agent_model.agent_id before invoking.
  2. Ensure the agent is prepared (prepare_agent_and_wait_until_prepared) and an alias exists or use the default WORKING_DRAFT_AGENT_ALIAS.
  3. If creation fails, surface the ClientError instead of continuing to invoke.
  4. Verify AWS credentials and bedrock:InvokeAgent permission are present.

Example fix

// before
resp = await agent.get_response('hi')  # raises: no agent_id
// after
await agent.create()
await agent.prepare_agent_and_wait_until_prepared()
resp = await agent.get_response('hi')
Defensive patterns

Strategy: validation

Validate before calling

async def ensure_created_then_invoke(agent, thread_id, message):
    if not agent.agent_model.agent_id:
        await agent.create()
    assert agent.agent_model.agent_id, 'agent_id still missing after create'
    return await agent.get_response(message)

Type guard

def is_bedrock_agent_created(agent) -> bool:
    return bool(getattr(getattr(agent, 'agent_model', None), 'agent_id', None))

Try / catch

try:
    resp = await agent.get_response('hi')
except ValueError as e:
    if 'does not exist' in str(e):
        await agent.create()
        resp = await agent.get_response('hi')
    else: raise

Prevention

When it happens

Trigger: Invoking the agent via get_response/invoke before creation; creation failed or was never awaited; the agent_id was cleared. Also hit if a custom caller invokes _invoke_agent directly without setup.

Common situations: Calling agent.get_response() or agent.invoke() right after constructing a BedrockAgent without the create step; failed async create whose error was caught upstream; tests that skip the live AWS create.

Related errors


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