microsoft/semantic-kernel · error · ValueError

Agent does not exist. Please create the agent before associa

Error message

Agent does not exist. Please create the agent before associating it with a knowledge base.

What it means

Raised by BedrockAgentBase.associate_agent_knowledge_base when self.agent_model.agent_id is falsy. A Bedrock agent must be created on AWS (which assigns an agent_id) before it can be linked to a knowledge base. The guard prevents a boto3 call that would fail server-side with a missing agentId.

Source

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

                    **kwargs,
                ),
            )

            await self.prepare_agent_and_wait_until_prepared()

            return BedrockActionGroupModel(**response["agentActionGroup"])
        except ClientError as e:
            logger.error(f"Failed to create kernel function action group for agent {self.agent_model.agent_id}.")
            raise e

    # endregion Action Group Management

    # region Knowledge Base Management

    async def associate_agent_knowledge_base(self, knowledge_base_id: str, **kwargs) -> dict[str, Any]:
        """Associate an agent with a knowledge base."""
        if not self.agent_model.agent_id:
            raise ValueError(
                "Agent does not exist. Please create the agent before associating it with a knowledge base."
            )

        try:
            response = await run_in_executor(
                None,
                partial(
                    self.bedrock_client.associate_agent_knowledge_base,
                    agentId=self.agent_model.agent_id,
                    agentVersion=self.agent_model.agent_version,
                    knowledgeBaseId=knowledge_base_id,
                    **kwargs,
                ),
            )

            await self.prepare_agent_and_wait_until_prepared()

            return response

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Call and await the agent creation step (e.g. await agent.create(...)/the create_agent helper) before associate_agent_knowledge_base, then assert agent.agent_model.agent_id is truthy.
  2. Inspect the return of the create call to confirm an agent_id was assigned; log it before associating.
  3. If creation previously failed, re-run it or instantiate a fresh BedrockAgent rather than proceeding with the half-initialized one.
  4. Verify AWS credentials and IAM permissions allow bedrock:CreateAgent so creation actually succeeds.

Example fix

// before
agent = BedrockAgent(...)
await agent.associate_agent_knowledge_base('kb-id')  # raises
// after
agent = BedrockAgent(...)
await agent.create()  # populates agent_model.agent_id
assert agent.agent_model.agent_id
await agent.associate_agent_knowledge_base('kb-id')
Defensive patterns

Strategy: validation

Validate before calling

async def safe_associate(agent, kb_id, **kw):
    if not getattr(agent.agent_model, 'agent_id', None):
        raise RuntimeError('Bedrock agent not created; call await agent.create() first')
    return await agent.associate_agent_knowledge_base(kb_id, **kw)

Type guard

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

Try / catch

from semantic_kernel.exceptions.agent_exceptions import AgentInitializationException
try:
    await agent.associate_agent_knowledge_base(kb_id)
except ValueError as e:
    logger.error(f'KB association blocked: {e}'); raise

Prevention

When it happens

Trigger: Calling agent.associate_agent_knowledge_base('kb-id') on a BedrockAgent/BedrockFoundationModelAgent whose create_agent step was never run, failed, or whose agent_model.agent_id was cleared/reset to None.

Common situations: Instantiating BedrockAgent from a model spec without calling the async create flow; a prior create_agent call raised a ClientError that was swallowed; running in an environment without AWS credentials so creation silently no-oped; reusing an agent object after deletion.

Related errors


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