microsoft/semantic-kernel · error · ValueError

Agent does not exist. Please create the agent before prepari

Error message

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

What it means

Raised by prepare_agent_and_wait_until_prepared when self.agent_model.agent_id is falsy (None or empty). The prepare_agent boto3 call requires an agentId, so the method guards upfront. This means the BedrockAgent instance was constructed without a real agent existing in the AWS service (e.g. from a dict without agent_id).

Source

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

    ) -> FunctionChoiceBehavior | None:
        """Validate the function choice behavior."""
        if function_choice_behavior and function_choice_behavior.type_ != FunctionChoiceType.AUTO:
            # Users cannot specify REQUIRED or NONE for the Bedrock agents.
            # Please note that the function choice behavior only control if the kernel will automatically
            # execute the functions the agent requests. It does not control the behavior of the agent.
            raise ValueError("Only FunctionChoiceType.AUTO is supported.")
        return function_choice_behavior

    def __repr__(self):
        """Return the string representation of the Bedrock Agent."""
        return f"{self.agent_model}"

    # region Agent Management

    async def prepare_agent_and_wait_until_prepared(self) -> None:
        """Prepare the agent for use."""
        if not self.agent_model.agent_id:
            raise ValueError("Agent does not exist. Please create the agent before preparing it.")

        try:
            await run_in_executor(
                None,
                partial(
                    self.bedrock_client.prepare_agent,
                    agentId=self.agent_model.agent_id,
                ),
            )

            # The agent will take some time to enter the PREPARING status after the prepare operation is called.
            # We need to wait for the agent to reach the PREPARING status before we can proceed, otherwise we
            # will return immediately if the agent is already in PREPARED status.
            await self._wait_for_agent_status(BedrockAgentStatus.PREPARING)
            # The agent will enter the PREPARED status when the preparation is complete.
            await self._wait_for_agent_status(BedrockAgentStatus.PREPARED)
        except ClientError as e:
            logger.error(f"Failed to prepare agent {self.agent_model.agent_id}.")

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Create the agent first using await BedrockAgent.create_and_prepare_agent(...), which provisions the agent and sets agent_id.
  2. If the agent already exists in AWS, construct the model with the real agent_id from a get_agent response.
  3. Check agent.agent_model.agent_id is set before calling prepare_agent_and_wait_until_prepared().

Example fix

// before
agent = BedrockAgent({'agentName': 'my-agent', 'foundationModel': '...'})
await agent.prepare_agent_and_wait_until_prepared()  # no agent_id -> raises

// after
agent = await BedrockAgent.create_and_prepare_agent(
    name='my-agent', instructions='...'
)  # provisions and prepares
# or, if it exists:
agent = BedrockAgent({'agentId': 'EXISTING_ID', 'agentName': 'my-agent', ...})
await agent.prepare_agent_and_wait_until_prepared()
Defensive patterns

Strategy: validation

Validate before calling

def assert_agent_exists(agent) -> None:
    if not agent.agent_model.agent_id:
        raise ValueError(
            "Agent has no agent_id. Create it via create_and_prepare_agent "
            "before calling prepare_agent_and_wait_until_prepared()."
        )

Type guard

def agent_has_id(agent) -> bool:
    return bool(getattr(getattr(agent, "agent_model", None), "agent_id", None))

Try / catch

try:
    await agent.prepare_agent_and_wait_until_prepared()
except ValueError as e:
    if "create the agent before preparing" in str(e):
        agent = await BedrockAgent.create_and_prepare_agent(name=..., instructions=...)
        await agent.prepare_agent_and_wait_until_prepared()
    else:
        raise

Prevention

When it happens

Trigger: Triggered when calling prepare_agent_and_wait_until_prepared() on a BedrockAgent whose agent_model.agent_id is None — e.g. constructed manually with an incomplete model dict rather than via create_and_prepare_agent.

Common situations: Constructing BedrockAgent({'agentName': '...'}) without first creating the agent in AWS; referencing an agent that was deleted; deserializing a stored config that lacked agent_id; calling prepare before create.

Related errors


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