Skip to content

Python: [Python]: When using agent manager (AzureAIClient), ServiceResponseException show up. #2746

Description

@q33566

Problem

When using agent manager (AzureAIClient), ServiceResponseException show up.

agent_framework.exceptions.ServiceResponseException: <class 'agent_framework_azure_ai._client.AzureAIClient'> service failed to complete the prompt: Error code: 400 - {'error': {'message': "Invalid schema for response_format 'ManagerSelectionResponse': In context=(), 'required' is required to be supplied and to be an array including every key in properties. Missing 'selected_participant'.", 'type': 'invalid_request_error', 'param': 'text.format.schema', 'code': 'invalid_json_schema'}}

Reproduce

This code were modified from python/samples/getting_started/workflows/orchestration/group_chat_agent_manager.py
Only following two things were changed.

  1. AzureCliCredential-> DefaultAzureCredential
  2. AzureOpenAIChatClient -> AzureAIClient
# Copyright (c) Microsoft. All rights reserved.

import asyncio
import logging
from typing import cast

from agent_framework import (
    AgentRunUpdateEvent,
    ChatAgent,
    ChatMessage,
    GroupChatBuilder,
    Role,
    WorkflowOutputEvent,
)
from agent_framework.azure import AzureAIClient
from azure.identity.aio import DefaultAzureCredential

logging.basicConfig(level=logging.INFO)

"""
Sample: Group Chat with Agent-Based Manager

What it does:
- Demonstrates the new set_manager() API for agent-based coordination
- Manager is a full ChatAgent with access to tools, context, and observability
- Coordinates a researcher and writer agent to solve tasks collaboratively

Prerequisites:
- OpenAI environment variables configured for OpenAIChatClient
"""


def _get_chat_client() -> AzureAIClient:
    return AzureAIClient(credential=DefaultAzureCredential())


async def main() -> None:
    # Create coordinator agent with structured output for speaker selection
    # Note: response_format is enforced to ManagerSelectionResponse by set_manager()
    coordinator = ChatAgent(
        name="Coordinator",
        description="Coordinates multi-agent collaboration by selecting speakers",
        instructions="""
You coordinate a team conversation to solve the user's task.

Review the conversation history and select the next participant to speak.

Guidelines:
- Start with Researcher to gather information
- Then have Writer synthesize the final answer
- Only finish after both have contributed meaningfully
- Allow for multiple rounds of information gathering if needed
""",
        chat_client=_get_chat_client(),
    )

    researcher = ChatAgent(
        name="Researcher",
        description="Collects relevant background information",
        instructions="Gather concise facts that help a teammate answer the question.",
        chat_client=_get_chat_client(),
    )

    writer = ChatAgent(
        name="Writer",
        description="Synthesizes polished answers from gathered information",
        instructions="Compose clear and structured answers using any notes provided.",
        chat_client=_get_chat_client(),
    )

    workflow = (
        GroupChatBuilder()
        .set_manager(coordinator, display_name="Orchestrator")
        .with_termination_condition(
            lambda messages: sum(1 for msg in messages if msg.role == Role.ASSISTANT)
            >= 2
        )
        .participants([researcher, writer])
        .build()
    )

    task = "What are the key benefits of using async/await in Python? Provide a concise summary."

    print("\nStarting Group Chat with Agent-Based Manager...\n")
    print(f"TASK: {task}\n")
    print("=" * 80)

    final_conversation: list[ChatMessage] = []
    last_executor_id: str | None = None
    async for event in workflow.run_stream(task):
        if isinstance(event, AgentRunUpdateEvent):
            eid = event.executor_id
            if eid != last_executor_id:
                if last_executor_id is not None:
                    print()
                print(f"{eid}:", end=" ", flush=True)
                last_executor_id = eid
            print(event.data, end="", flush=True)
        elif isinstance(event, WorkflowOutputEvent):
            final_conversation = cast(list[ChatMessage], event.data)

    if final_conversation and isinstance(final_conversation, list):
        print("\n\n" + "=" * 80)
        print("FINAL CONVERSATION")
        print("=" * 80)
        for msg in final_conversation:
            author = getattr(msg, "author_name", "Unknown")
            text = getattr(msg, "text", str(msg))
            print(f"\n[{author}]")
            print(text)
            print("-" * 80)


if __name__ == "__main__":
    asyncio.run(main())

Error messages

================================================================================
INFO:agent_framework._workflows._runner:Yielding pre-loop events
INFO:agent_framework._workflows._runner:Starting superstep 1
INFO:azure.core.pipeline.policies.http_logging_policy:Request URL: 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=REDACTED&resource=REDACTED'
Request method: 'GET'
Request headers:
    'User-Agent': 'azsdk-python-identity/1.25.1 Python/3.12.0 (Windows-11-10.0.26200-SP0)'
No body was attached to the request
INFO:azure.identity.aio._credentials.chained:DefaultAzureCredential acquired a token from AzureCliCredential
INFO:azure.core.pipeline.policies.http_logging_policy:Request URL: 'https://kurt-west-us-3.services.ai.azure.com/api/projects/travel/agents/Coordinator/versions?api-version=REDACTED'
Request method: 'POST'
Request headers:
    'Content-Type': 'application/json'
    'Content-Length': '1974'
    'Accept': 'application/json'
    'x-ms-client-request-id': '71552e35-d5a8-11f0-9217-a0d36586000a'
    'User-Agent': 'agent-framework-python/1.0.0b251209 azsdk-python-ai-projects/2.0.0b2 Python/3.12.0 (Windows-11-10.0.26200-SP0)'
    'Authorization': 'REDACTED'
A body is sent with the request
INFO:azure.core.pipeline.policies.http_logging_policy:Response status: 200
Response headers:
    'Transfer-Encoding': 'chunked'
    'Content-Type': 'application/json; charset=utf-8'
    'Content-Encoding': 'REDACTED'
    'Vary': 'REDACTED'
    'request-context': 'REDACTED'
    'x-ms-response-type': 'REDACTED'
    'x-request-id': 'REDACTED'
    'api-supported-versions': 'REDACTED'
    'azureml-served-by-cluster': 'REDACTED'
    'apim-request-id': 'REDACTED'
    'Strict-Transport-Security': 'REDACTED'
    'x-content-type-options': 'REDACTED'
    'x-ms-region': 'REDACTED'
    'Date': 'Wed, 10 Dec 2025 09:13:10 GMT'
INFO:azure.identity.aio._internal.decorators:AzureCliCredential.get_token_info succeeded
INFO:azure.identity.aio._credentials.default:DefaultAzureCredential acquired a token from AzureCliCredential
INFO:httpx:HTTP Request: POST https://kurt-west-us-3.services.ai.azure.com/api/projects/travel/openai/responses?api-version=2025-11-15-preview "HTTP/1.1 400 Bad Request"
Traceback (most recent call last):
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\openai\_responses_client.py", line 147, in _inner_get_streaming_response
    response = await client.responses.create(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\openai\resources\responses\responses.py", line 2476, in create
    return await self._post(
           ^^^^^^^^^^^^^^^^^
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\openai\_base_client.py", line 1794, in post    
    return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\openai\_base_client.py", line 1594, in request 
    raise self._make_status_error_from_response(err.response) from None
openai.BadRequestError: Error code: 400 - {'error': {'message': "Invalid schema for response_format 'ManagerSelectionResponse': In context=(), 'required' is required to be supplied and to be an array including every key in properties. Missing 'selected_participant'.", 'type': 'invalid_request_error', 'param': 'text.format.schema', 'code': 'invalid_json_schema'}}

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\test.py", line 115, in <module>
    asyncio.run(main())
  File "C:\Users\a-kurtshen\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 194, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\a-kurtshen\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\a-kurtshen\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 664, in run_until_complete 
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\test.py", line 90, in main
    async for event in workflow.run_stream(task):
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_workflow.py", line 521, in run_stream
    async for event in self._run_workflow_with_tracing(
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_workflow.py", line 346, in _run_workflow_with_tracing
    async for event in self._runner.run_until_convergence():
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_runner.py", line 111, in run_until_convergence
    await iteration_task
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_runner.py", line 182, in _run_iteration
    await asyncio.gather(*tasks)
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_runner.py", line 178, in _deliver_messages
    await asyncio.gather(*tasks)
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_runner.py", line 153, in _deliver_message_inner
    return await edge_runner.send_message(message, self._shared_state, self._ctx)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_edge_runner.py", line 145, in send_message
    await self._execute_on_target(target_id, [source_id], message, shared_state, ctx)
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_edge_runner.py", line 76, in _execute_on_target
    await target_executor.execute(
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_executor.py", line 270, in execute
    await handler(message, context)
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_executor.py", line 541, in wrapper
    return await func(self, message, ctx)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_agent_executor.py", line 119, in run
    await self._run_agent_and_emit(ctx)
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_agent_executor.py", line 276, in _run_agent_and_emit
    response = await self._run_agent_streaming(cast(WorkflowContext, ctx))
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_workflows\_agent_executor.py", line 333, in _run_agent_streaming
    async for update in self._agent.run_stream(
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\observability.py", line 1168, in trace_run_streaming
    async for streaming_agent_response in run_streaming_func(self, messages=messages, thread=thread, **kwargs):
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_agents.py", line 1023, in run_stream
    async for update in self.chat_client.get_streaming_response(
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_tools.py", line 1800, in streaming_function_invocation_wrapper
    async for update in func(self, messages=prepped_messages, **kwargs):
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\observability.py", line 924, in trace_get_streaming_response
    async for update in func(self, messages=messages, **kwargs):
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_middleware.py", line 1415, in _stream_generator
    async for update in original_get_streaming_response(self, messages, **kwargs):
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\_clients.py", line 673, in get_streaming_response
    async for update in self._inner_get_streaming_response(
  File "C:\Kurt\MS_03_Microsoft_Agent_Framework_migration\.venv\Lib\site-packages\agent_framework\openai\_responses_client.py", line 172, in _inner_get_streaming_response
    raise ServiceResponseException(
agent_framework.exceptions.ServiceResponseException: <class 'agent_framework_azure_ai._client.AzureAIClient'> service failed to complete the prompt: Error code: 400 - {'error': {'message': "Invalid schema for response_format 'ManagerSelectionResponse': In context=(), 'required' is required to be supplied and to be an array including every key in properties. Missing 'selected_participant'.", 'type': 'invalid_request_error', 'param': 'text.format.schema', 'code': 'invalid_json_schema'}}
ERROR:asyncio:Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000015045C68E00>
ERROR:asyncio:Unclosed connector
connections: ['deque([(<aiohttp.client_proto.ResponseHandler object at 0x0000015046D5C890>, 2276525.328)])']
connector: <aiohttp.connector.TCPConnector object at 0x0000015046FC4440>
ERROR:asyncio:Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000015046D597C0>

Metadata

Metadata

Assignees

Labels

bugUsage: [Issues], Target: all issues (Legacy, prefer issue type: bug)orchestrationUsage: [Issues, PRs], Target: multi-agent orchestration (high-level patterns)pythonUsage: [Issues, PRs], Target: Python

Type

Projects

Status
Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions