{"record":{"id":"1e05d6b64dceecf8","repo":"microsoft/semantic-kernel","slug":"agent-does-not-exist-please-create-the-agent-befo-1e05d6","errorCode":null,"errorMessage":"Agent does not exist. Please create the agent before associating it with a knowledge base.","messagePattern":"Agent does not exist\\. Please create the agent before associating it with a knowledge base\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/agents/bedrock/bedrock_agent_base.py","lineNumber":277,"sourceCode":"                    **kwargs,\n                ),\n            )\n\n            await self.prepare_agent_and_wait_until_prepared()\n\n            return BedrockActionGroupModel(**response[\"agentActionGroup\"])\n        except ClientError as e:\n            logger.error(f\"Failed to create kernel function action group for agent {self.agent_model.agent_id}.\")\n            raise e\n\n    # endregion Action Group Management\n\n    # region Knowledge Base Management\n\n    async def associate_agent_knowledge_base(self, knowledge_base_id: str, **kwargs) -> dict[str, Any]:\n        \"\"\"Associate an agent with a knowledge base.\"\"\"\n        if not self.agent_model.agent_id:\n            raise ValueError(\n                \"Agent does not exist. Please create the agent before associating it with a knowledge base.\"\n            )\n\n        try:\n            response = await run_in_executor(\n                None,\n                partial(\n                    self.bedrock_client.associate_agent_knowledge_base,\n                    agentId=self.agent_model.agent_id,\n                    agentVersion=self.agent_model.agent_version,\n                    knowledgeBaseId=knowledge_base_id,\n                    **kwargs,\n                ),\n            )\n\n            await self.prepare_agent_and_wait_until_prepared()\n\n            return response","sourceCodeStart":259,"sourceCodeEnd":295,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/agents/bedrock/bedrock_agent_base.py#L259-L295","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["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.","Inspect the return of the create call to confirm an agent_id was assigned; log it before associating.","If creation previously failed, re-run it or instantiate a fresh BedrockAgent rather than proceeding with the half-initialized one.","Verify AWS credentials and IAM permissions allow bedrock:CreateAgent so creation actually succeeds."],"exampleFix":"// before\nagent = BedrockAgent(...)\nawait agent.associate_agent_knowledge_base('kb-id')  # raises\n// after\nagent = BedrockAgent(...)\nawait agent.create()  # populates agent_model.agent_id\nassert agent.agent_model.agent_id\nawait agent.associate_agent_knowledge_base('kb-id')","handlingStrategy":"validation","validationCode":"async def safe_associate(agent, kb_id, **kw):\n    if not getattr(agent.agent_model, 'agent_id', None):\n        raise RuntimeError('Bedrock agent not created; call await agent.create() first')\n    return await agent.associate_agent_knowledge_base(kb_id, **kw)","typeGuard":"def is_bedrock_agent_created(agent) -> bool:\n    return bool(getattr(getattr(agent, 'agent_model', None), 'agent_id', None))","tryCatchPattern":"from semantic_kernel.exceptions.agent_exceptions import AgentInitializationException\ntry:\n    await agent.associate_agent_knowledge_base(kb_id)\nexcept ValueError as e:\n    logger.error(f'KB association blocked: {e}'); raise","preventionTips":["Always await the create flow and assert agent_id before KB operations","Centralize agent lifecycle in a helper that returns a created agent"],"tags":["bedrock","agent-lifecycle","aws","validation"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}