Skip to content

Python: [Bug]: FoundryAgent crashes when initializing HostedAgent sessions due to incompatible Azure SDK calls #6857

Description

@noursf

Description

Description

When attempting to use FoundryAgent in "HostedAgent" (code-first) mode by passing allow_preview=True and an isolation_key, the agent framework crashes immediately.

There are two distinct bugs in agent_framework_foundry/_agent.py caused by incompatibilities with the latest azure-ai-projects SDK (v2.2.0).

Bug 1: AttributeError on .get()

When allow_preview=True, the _create_service_session_id method attempts to resolve the agent version by calling get_agent_version(). This method executes the following code:

agent_details = await cast(Any, self.project_client.beta.agents).get(agent_name=self.agent_name)

The Issue: BetaAgentsOperations in azure-ai-projects does not have a .get() method (it was likely removed or renamed to get_agent which takes an agent_id, not an agent_name).
The Result:
AttributeError: 'BetaAgentsOperations' object has no attribute 'get'

Bug 2: TypeError on isolation_key during session creation

If you monkey-patch or bypass Bug 1, it immediately hits a second bug when calling create_session:

        create_session_kwargs: dict[str, Any] = {
            "agent_name": self.client.agent_name,
            "isolation_key": self._resolve_service_session_isolation_key(isolation_key),
        }
        # ...
        service_session = await self.client.project_client.beta.agents.create_session(**create_session_kwargs)

The Issue: The Azure SDK's create_session method expects the kwarg user_isolation_key, not isolation_key. Because isolation_key is unrecognized, it gets passed down through the Azure pipeline's **kwargs all the way to aiohttp, causing a crash.
The Result:
TypeError: ClientSession._request() got an unexpected keyword argument 'isolation_key'

Environment

  • agent-framework (latest)
  • azure-ai-projects == 2.2.0
  • Python 3.11+

Proposed Fix

  1. In get_agent_version(): Refactor how the agent details/versions are fetched to align with the public methods available in the azure-ai-projects BetaAgentsOperations class (or skip version resolution entirely for HostedAgents).
  2. In _create_service_session_id(): Rename the "isolation_key" dictionary key to "user_isolation_key" inside create_session_kwargs before passing it to create_session().

Code Sample

async def run_chat(agent: FoundryAgent, message: str, session_id: str | None = None) -> tuple[str, str]:
    """Run a chat turn against the agent with Azure-backed session persistence.

    Args:
        agent: The FoundryAgent instance to use.
        message: The user's message.
        session_id: Optional session ID for multi-turn conversation.
            If None, a new session is created and Azure will create a new thread.

    Returns:
        Tuple of (reply_text, session_id).
    """
    if session_id:
        session = AgentSession(session_id=session_id)
        log.info("[agent] Resuming session: %s", session_id)
    else:
        session = agent.create_session()
        log.info("[agent] Created new session: %s", session.session_id)

    # Pass isolation_key so Azure AI Agent Service ties this run to a persistent cloud thread.
    options = FoundryAgentOptions(isolation_key=session.session_id)
    response = await agent.run(message, session=session, options=options)
    reply_text = response.text
    log.info("[agent] Reply received (len=%d)", len(reply_text))

    return reply_text, session.session_id

Error Messages / Stack Traces

Traceback (most recent call last):
  File "D:\projects\GentiX\.venv\Lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 421, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\uvicorn\middleware\proxy_headers.py", line 62, in __call__
    return await self.app(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\applications.py", line 1163, in __call__
    await super().__call__(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\starlette\applications.py", line 90, in __call__
    await self.middleware_stack(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\starlette\middleware\errors.py", line 186, in __call__
    raise exc
  File "D:\projects\GentiX\.venv\Lib\site-packages\starlette\middleware\errors.py", line 164, in __call__
    await self.app(scope, receive, _send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\starlette\middleware\exceptions.py", line 63, in __call__
    await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app
    raise exc
  File "D:\projects\GentiX\.venv\Lib\site-packages\starlette\_exception_handler.py", line 42, in wrapped_app
    await app(scope, receive, sender)
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__
    await self.app(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\starlette\routing.py", line 660, in __call__
    await self.middleware_stack(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\routing.py", line 2543, in app
    await route.handle(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\routing.py", line 1700, in handle
    await self.original_router.handle(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\routing.py", line 2598, in handle
    await included_router._handle_selected(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\routing.py", line 1720, in _handle_selected
    await original_route.handle(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\routing.py", line 1239, in handle
    await app(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\routing.py", line 150, in app
    await wrap_app_handling_exceptions(app, request)(scope, receive, send)
  File "D:\projects\GentiX\.venv\Lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app
    raise exc
  File "D:\projects\GentiX\.venv\Lib\site-packages\starlette\_exception_handler.py", line 42, in wrapped_app
    await app(scope, receive, sender)
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\routing.py", line 136, in app
    response = await f(request)
               ^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\routing.py", line 690, in app
    raw_response = await run_endpoint_function(
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\fastapi\routing.py", line 344, in run_endpoint_function
    return await dependant.call(**values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\app\api\routes.py", line 18, in chat
    reply, session_id = await run_chat(
                        ^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\app\agent\agent.py", line 53, in run_chat
    response = await agent.run(message, session=session, options=options)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\agent_framework\observability.py", line 1938, in _run
    response: AgentResponse[Any] = await execute()
                                   ^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\agent_framework\_agents.py", line 963, in _run_non_streaming
    ctx = await _prepare_run_context()
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\agent_framework\_agents.py", line 949, in _prepare_run_context
    return await self._prepare_run_context(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\agent_framework_foundry\_agent.py", line 799, in _prepare_run_context
    session.service_session_id = await self._create_service_session_id(
                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\agent_framework_foundry\_agent.py", line 745, in _create_service_session_id
    if version := await self.client.get_agent_version():
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\agent_framework_foundry\_agent.py", line 484, in get_agent_version
    agent_details = await cast(Any, self.project_client.beta.agents).get(agent_name=self.agent_name)
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\GentiX\.venv\Lib\site-packages\azure\ai\projects\operations\_patch.py", line 60, in __getattr__
    attribute = getattr(self._operation, name)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'BetaAgentsOperations' object has no attribute 'get'

Package Versions

agent-framework: 1.10.0, agent-framework-foundry: 1.10.0

Python Version

3.12

Additional Context

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

hostingUsage: [Issues, PRs], Target: all hosting related solutionspythonUsage: [Issues, PRs], Target: PythonreproducedUsage: [Issues], Target: all issues that can be reproduced by the triage workflow

Type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions