DEV Community

Cover image for Porting an ADK Research and Judge Loop to Microsoft Agent Framework on Azure, With Phi-4-mini
xbill
xbill Subscriber

Posted on

Porting an ADK Research and Judge Loop to Microsoft Agent Framework on Azure, With Phi-4-mini

This article provides a step by step guide to porting a Google ADK multi-agent system to Microsoft Agent Framework on Azure. A researcher searches the web, a judge passes or fails the research for up to three rounds, and a content builder turns the approved research into a course. All three agents run on Microsoft's Phi-4-mini on Azure AI Foundry, each one is its own A2A service on Azure Container Apps, and the original web app runs unchanged in front of them.

Repository: https://github.com/xbill9/maf-azure-research-loop


What Is Being Ported?

The source is the course creator in multi-agent-loop, an update of Google's ADK 2.0 and A2A codelab. Four ADK services: a researcher with google_search, a judge with a Pydantic output schema, a content builder, and an orchestrator that wires them together with SequentialAgent and LoopAgent. The same loop is already on AWS in Porting an ADK Research and Judge Loop to Strands on Bedrock AgentCore; this is the Azure version.

The port keeps the prompts, the judge's JudgeFeedback schema, the three-round limit and the web app's frontend. Everything underneath changes:

ADK on Google Cloud Microsoft Agent Framework on Azure
SequentialAgent(LoopAgent(...), content_builder) One MAF WorkflowBuilder graph
output_schema=JudgeFeedback JSON mode, validated as JudgeFeedback
google_search Foundry web_search, run before the model turn
RemoteA2aAgent MAF A2AAgent
gemini-3-flash-preview Phi-4-mini-instruct on Foundry
Cloud Run Azure Container Apps

At This Point You Should Have

  • An Azure subscription where you can create an Azure AI Foundry account in eastus2.
  • The Azure CLI signed in (az login). The same login calls the models from your machine.
  • Python 3.14 with the packages from the repository's Dockerfile installed.
  • make. The repository wraps every step below in one target.

The versions used throughout:

python 3.14.7
a2a-sdk                                    1.3.1
agent-framework-a2a                        1.0.0b261112
agent-framework-core                       1.26.0
agent-framework-openai                     1.18.2
azure-identity                             1.25.3
Enter fullscreen mode Exit fullscreen mode

Step 1 — Deploy the Models on Foundry

make foundry creates a Foundry account and project and two pay-per-token (GlobalStandard) deployments: Phi-4-mini-instruct for the three agents, and gpt-4.1-mini for web search. It also gives your own user the Foundry User role so make local can call both.

az cognitiveservices account deployment create -g "$RG" -n "$FOUNDRY" --deployment-name "$MODEL_ID" \
  --model-name "$MODEL_ID" --model-version "$MODEL_VERSION" --model-format Microsoft \
  --sku-name GlobalStandard --sku-capacity "$MODEL_CAPACITY" -o none
Enter fullscreen mode Exit fullscreen mode
MODEL_ID=${MODEL_ID:-Phi-4-mini-instruct}     # hosted Phi deployment that runs the three agents
MODEL_VERSION=${MODEL_VERSION:-1}
MODEL_CAPACITY=${MODEL_CAPACITY:-20}          # GlobalStandard: 20 = 20 requests, 20,000 tokens per minute
Enter fullscreen mode Exit fullscreen mode

Every agent calls Phi through the deployment's OpenAI-compatible endpoint with an Entra token. MAF's OpenAIChatCompletionClient takes an AsyncOpenAI client, so the token provider goes in as the key:

client = AsyncOpenAI(
    base_url=MODEL_ENDPOINT,
    api_key=get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"),
    timeout=float(os.environ.get("MODEL_TIMEOUT", "120")),
    max_retries=3,
)
return OpenAIChatCompletionClient(model=MODEL_ID, async_client=client)
Enter fullscreen mode Exit fullscreen mode

Step 2 — Check What Hosted Phi-4-mini Supports

The ADK agents lean on two model features: tool calls for search, and a JSON schema for the judge. One script asked the hosted deployment for each:

Phi-4-mini-instruct v1, GlobalStandard capacity 20 (20 requests, 20,000 tokens per minute), eastus2
plain: secs=23.8 completion_tokens=323 tok_per_s=13.6
tool_choice=None      run0 secs=58.1 finish=length tool_calls=[] content='Curling is a sport that involves sliding wooden stones towards a target called t'
tool_choice=auto      run0 secs=59.9 finish=length tool_calls=[] content='Curling is a sport that is played on ice, similar to ice hockey, but the stones '
tool_choice=required  run0 ERROR BadRequestError: Error code: 400 - {'error': {'code': 'Bad Request', 'message': '{"object":"error","message":"The provided JSON schema contains features not supported by xgrammar."
json json_schema: ERROR UnprocessableEntityError: Error code: 422
json json_object: secs=3.4 parses=True
Enter fullscreen mode Exit fullscreen mode
Request Result
A tool, tool_choice unset or auto ❌ text replies, no tool calls
tool_choice="required" ❌ 400 from xgrammar
response_format json_schema ❌ 422
response_format json_object 🟢 valid JSON

So the port keeps Phi to plain text and JSON mode. Search runs before the model turn (Step 4), and the judge's schema is checked in the orchestrator (Step 3).


🔎 Tip: Phi-4-mini Follows Only the Last User Message

The same judge request in JSON mode, twelve times each, with the instructions naming the keys status and feedback:

judge-keys-system.txt valid JudgeFeedback: 0 of 12
judge-keys-user.txt valid JudgeFeedback: 12 of 12
Enter fullscreen mode Exit fullscreen mode

With the instructions in the system message, every reply was JSON about the topic:

keys named    thin  run0 INVALID  '{\n  "topic": "Curling",\n  "researchFindings": "Curling is a sport on ice. The sport origin'
keys named    thin  run2 INVALID  '{\n  "action": "search",\n  "query": "curler"\n}'
Enter fullscreen mode Exit fullscreen mode

MAF's instruction_role="user" sends the instructions as a separate user message, and Phi follows the last one. A small AgentMiddleware puts each agent's instructions at the top of the request message itself:

class InlineInstructions(AgentMiddleware):
    """Put the agent's instructions at the top of the request's last user message."""

    def __init__(self, instructions: str):
        self.instructions = instructions.strip()

    async def process(self, context: AgentContext, call_next) -> None:
        for i in range(len(context.messages) - 1, -1, -1):
            m = context.messages[i]
            if m.role == "user" and m.text:
                context.messages[i] = Message("user", [f"{self.instructions}\n\n{m.text}"])
                break
        await call_next()
Enter fullscreen mode Exit fullscreen mode

Every agent in the repository is built with it.


Step 3 — Port the Judge: Same Prompt, JSON Mode

The judge keeps the ADK instruction and adds one line naming the two keys. JSON mode makes the reply parse; the instruction makes it the right JSON.

judge = agent(
    name="judge",
    description="Evaluates research findings for completeness and accuracy.",
    instructions="""
    You are a strict editor and fact-checker.
    ...
    Reply with one JSON object with exactly two keys: "status" ("pass" or "fail") and "feedback".
    """,
    default_options={"response_format": {"type": "json_object"}},
)
Enter fullscreen mode Exit fullscreen mode

The orchestrator validates the reply against the same Pydantic JudgeFeedback class ADK used, and anything that fails validation counts as a fail:

def parse_verdict(text: str) -> tuple[str, str]:
    from common import JudgeFeedback

    try:
        fb = JudgeFeedback.model_validate_json(text[text.index("{") : text.rindex("}") + 1])
        return fb.status, fb.feedback
    except ValueError:
        return "fail", text
Enter fullscreen mode Exit fullscreen mode

Step 4 — Search Before the Model Turn

Foundry has a web_search tool on its Responses API. Phi cannot call it, so a second small deployment, gpt-4.1-mini, runs the search with tool_choice="required":

def _search(query: str):
    client = OpenAI(base_url=f"{ENDPOINT}/openai/v1", api_key=_token())
    return client.responses.create(
        model=SEARCH_DEPLOYMENT,
        input=query,
        tools=[{"type": "web_search"}],
        tool_choice="required",
        include=["web_search_call.action.sources"],
    )
Enter fullscreen mode Exit fullscreen mode

A second middleware on the researcher calls it with the request, and adds the results to the same message, where Phi reads them:

class SearchFirst(AgentMiddleware):
    """Run web_search for the request and hand Phi the results before it answers."""

    async def process(self, context: AgentContext, call_next) -> None:
        for i in range(len(context.messages) - 1, -1, -1):
            m = context.messages[i]
            if m.role == "user" and m.text:
                results = await asyncio.to_thread(web_search, query_for(m.text))
                context.messages[i] = Message(
                    "user", [f"{m.text}\n\nWeb search results for this request:\n\n{results}"]
                )
                break
        await call_next()
Enter fullscreen mode Exit fullscreen mode

On a retry, query_for adds the judge's feedback to the topic, so the next search follows it.


🔎 Tip: The Default Content Filter Blocks Some Search Answers

The search runs, and Azure's default content filter can then block the answer. Six queries against gpt-4.1-mini with the default filter:

'Curling'                                          incomplete content_filter search=['curling'] chars=49
'curling rules'                                    completed  None search=['curling rules'] chars=1945
'history of curling'                               completed  None search=['history of curling'] chars=2160
'Photosynthesis'                                   completed  None search=['photosynthesis'] chars=1634
'Python programming language'                      completed  None search=['Python programming language'] chars=1491
'What are the rules of curling? Cite sources.'     completed  None search=['rules of curling'] chars=2249
Enter fullscreen mode Exit fullscreen mode

The bare topic is the one that gets blocked, and only some of the time. web_search retries a blocked query once, phrased as a research request:

if _blocked(resp):
    resp, tries = _search(f"Find comprehensive, factual information about: {query}"), 2
Enter fullscreen mode Exit fullscreen mode

Step 5 — Rebuild the Loop as a MAF Workflow

ADK expresses the loop with three orchestration agents. MAF expresses it as a workflow of three executors with typed messages: the researcher sends Findings, the judge sends Verdict, and two conditional edges read the verdict.

def passed(v: Verdict) -> bool:
    return v.status == "pass"


def failed(v: Verdict) -> bool:
    """Loop back only while rounds remain: ADK's LoopAgent stops after max_iterations."""
    return v.status == "fail" and v.round < MAX_ROUNDS


def build_workflow():
    research, judge, build = Research(), Judge(), Build()
    return (
        WorkflowBuilder(start_executor=research, max_iterations=2 * MAX_ROUNDS + 2)
        .add_edge(research, judge)
        .add_edge(judge, research, condition=failed)
        .add_edge(judge, build, condition=passed)
        .build()
    )
Enter fullscreen mode Exit fullscreen mode

The round limit sits on the fail edge. After the third fail no edge out of the judge holds, and the workflow completes with no course. Each executor calls its remote agent with MAF's A2AAgent:

def remote(name: str, default_url: str) -> A2AAgent:
    return A2AAgent(name=name, url=os.environ.get(f"{name.upper()}_URL", default_url), timeout=TIMEOUT)
Enter fullscreen mode Exit fullscreen mode

🔎 Tip: A Failed A2A Task Comes Back as Your Own Prompt

When a remote task fails with no artifacts, A2AAgent builds its reply from the task's last history entry, which is the request it sent. The judge would then read the researcher's prompt as research. The orchestrator checks the task state on every reply:

async def ask(agent: A2AAgent, prompt: str) -> str:
    reply = await agent.run(prompt)
    for raw in reply.raw_representation or []:
        state = getattr(getattr(raw, "status", None), "state", None)
        if state in (TaskState.TASK_STATE_FAILED, TaskState.TASK_STATE_REJECTED, TaskState.TASK_STATE_CANCELED):
            raise RemoteFailure(f"{agent.name} task {TaskState.Name(state)}")
    return reply.text
Enter fullscreen mode Exit fullscreen mode

Step 6 — Serve Each Agent Over A2A

agent_framework.a2a.A2AExecutor turns a MAF agent into an a2a-sdk 1.x request handler. Each server has A2A at /, its card at /.well-known/agent-card.json, and a /ping health check:

handler = DefaultRequestHandler(
    agent_executor=A2AExecutor(
        agent, run_kwargs={"options": {"max_tokens": int(os.environ.get("MAX_TOKENS", max_tokens))}}
    ),
    task_store=InMemoryTaskStore(),
    agent_card=public,
)
app = Starlette(
    routes=[
        Route("/ping", lambda _: JSONResponse({"status": "Healthy"})),
        *create_agent_card_routes(public),
        *create_jsonrpc_routes(handler, "/"),
    ]
)
Enter fullscreen mode Exit fullscreen mode

The card advertises PUBLIC_URL, the address the caller sends its messages to: localhost on a laptop, the app's internal address on Container Apps.


Step 7 — Run It Locally

make local starts the three agents and the web app as four processes on the host, with no Docker:

make local
Enter fullscreen mode Exit fullscreen mode

One run of the orchestrator on "Curling", against the hosted models:

total_s=215.8 order=['researcher', 'judge', 'content_builder'] verdicts=['pass']
  researcher        167.9 s
  judge               7.2 s
  content_builder    40.6 s

# Curling: A Blend of Precision, Strategy, and Teamwork
Enter fullscreen mode Exit fullscreen mode

The researcher's 167.9 s holds one model call that hung until the client's 120 s timeout, and the retry answered. The timeout and three retries in Step 1 are there for that case.


Step 8 — Test the Fail Path

A judge that passes everything leaves the loop untested. tests/fail_judge.py is a stand-in judge that fails every submission, and make test points the orchestrator at it:

make test
Enter fullscreen mode Exit fullscreen mode
total_s=79.7 order=['researcher', 'judge', 'researcher', 'judge', 'researcher', 'judge'] verdicts=['fail', 'fail', 'fail']
  researcher         27.6 s
  judge               8.0 s
  researcher         25.3 s
  judge               1.9 s
  researcher         15.2 s
  judge               1.4 s

(no course: the judge never passed the research)
Enter fullscreen mode Exit fullscreen mode

Three rounds, a clean stop, and no course. The searches follow the judge's feedback, and the first one shows the content filter retry:

INFO:researcher:web_search query='Curling' tries=2 status=completed blocked=False sources=11 secs=13.2
INFO:researcher:web_search query='Curling. Add more detail on the rules.' tries=1 status=completed blocked=False sources=11 secs=7.0
INFO:researcher:web_search query='Curling. Add more detail on the rules.' tries=1 status=completed blocked=False sources=11 secs=7.6
Enter fullscreen mode Exit fullscreen mode

Step 9 — Test the Workflow Offline

make test calls Phi, so every run needs a login and spends tokens. make unit runs a pytest suite with the remote agents, the model and the search replaced by stand-ins. The stand-in agent answers from a list and records every prompt it receives:

class FakeAgent:
    def __init__(self, name, replies, state=None):
        self.name = name
        self.replies = replies
        self.state = state  # an a2a TaskState for every reply, or None for no task
        self.prompts = []

    async def run(self, prompt):
        self.prompts.append(prompt)
        ...
        raw = [SimpleNamespace(status=SimpleNamespace(state=self.state))] if self.state is not None else []
        return SimpleNamespace(text=text, raw_representation=raw)
Enter fullscreen mode Exit fullscreen mode

Swapping orchestrator.remote for one that hands out stand-ins runs the real WorkflowBuilder graph end to end:

def test_pass_second_round_carries_feedback(monkeypatch):
    agents = fake_remotes(monkeypatch, [FAIL, PASS])
    _, verdicts, course = asyncio.run(orchestrator.run("Curling"))
    assert verdicts == ["fail", "pass"]
    assert course == "# Course"
    retry = agents["researcher"].prompts[1]
    assert retry.startswith("Curling\n") and "Feedback: Add more detail on the rules." in retry
Enter fullscreen mode Exit fullscreen mode

The suite covers the verdict parsing, the round limit, ask() on failed tasks, the workflow's pass and fail paths, both middlewares, the content filter retry and the web app's stream:

make unit
Enter fullscreen mode Exit fullscreen mode
============================== 37 passed in 3.27s ==============================
Enter fullscreen mode Exit fullscreen mode

To check that the tests catch real mistakes, a script breaks the code one way at a time, runs the suite and puts the code back:

round limit off by one                       3 failed, 34 passed in 3.85s
ask() ignores failed tasks                   5 failed, 32 passed in 3.47s
instructions in the first user message       1 failed, 36 passed in 3.40s
no retry on a content-filter block           2 failed, 35 passed in 3.40s
no blank-line heartbeat                      1 failed, 36 passed in 3.39s
raise on the first failure event             2 failed, 35 passed in 3.49s
Enter fullscreen mode Exit fullscreen mode

Every break fails at least one test.


🔎 Tip: MAF Failure Events Carry Only the Exception's Class Name

When an executor raises, MAF sends an executor_failed event and then raises the exception from the run. The event's WorkflowErrorDetails holds the message only when MAF's observability setting SENSITIVE_DATA_ENABLED is on; otherwise its message is the class name. An orchestrator that raises on the event reports a judge failure like this:

before (6c550fa)  RuntimeError: executor_failed: WorkflowErrorDetails(error_type='RemoteFailure', message='RemoteFailure', traceback=None, executor_id=None, extra=None)
after  (b971080)  RemoteFailure: judge task TASK_STATE_FAILED
Enter fullscreen mode Exit fullscreen mode

events() records the first failure event and keeps reading, so the run's own exception comes through with its message. A failure event from a run that ends without raising is still an error:

    failure = None
    async for ev in wf.run(topic, stream=True):
        ...
        elif ev.type in ("failed", "executor_failed", "error") and failure is None:
            failure = f"{ev.type}: {getattr(ev, 'details', None) or getattr(ev, 'data', None)}"
    if failure:
        raise RuntimeError(failure)
Enter fullscreen mode Exit fullscreen mode

The web page now shows RemoteFailure: researcher task TASK_STATE_REJECTED for a rejected researcher task. Turning on SENSITIVE_DATA_ENABLED would also put prompts and replies in the telemetry. The live fail path still runs the same after the change:

total_s=72.3 order=['researcher', 'judge', 'researcher', 'judge', 'researcher', 'judge'] verdicts=['fail', 'fail', 'fail']
Enter fullscreen mode Exit fullscreen mode

Step 10 — Deploy to Azure Container Apps

make deploy builds one image in Azure Container Registry with az acr build, then runs four container apps in one environment from it: three agents with internal ingress, and the web app as the only public endpoint. One user-assigned managed identity pulls the image and calls both models.

app mrl-researcher "mrl-agents:$TAG" 8001 internal 0.5 1Gi "python researcher.py" "${AGENT_ENV[@]}" "PUBLIC_URL=$(internal mrl-researcher)"
app mrl-judge "mrl-agents:$TAG" 8002 internal 0.5 1Gi "python judge.py" "${AGENT_ENV[@]}" "PUBLIC_URL=$(internal mrl-judge)"
app mrl-content-builder "mrl-agents:$TAG" 8003 internal 0.5 1Gi "python content_builder.py" "${AGENT_ENV[@]}" "PUBLIC_URL=$(internal mrl-content-builder)"
app mrl-web "mrl-agents:$TAG" 8000 external 0.5 1Gi "python /app/app/main.py" "AZURE_CLIENT_ID=$ID_CLIENT" \
  "RESEARCHER_URL=$(internal mrl-researcher)" "JUDGE_URL=$(internal mrl-judge)" "CONTENT_BUILDER_URL=$(internal mrl-content-builder)"
Enter fullscreen mode Exit fullscreen mode
make deploy
make url
Enter fullscreen mode Exit fullscreen mode

🔎 Tip: --command Takes One Executable

az containerapp create --command "python researcher.py" stores one argument, and the container fails to start:

exec: "python researcher.py": stat python researcher.py: no such file or directory
Enter fullscreen mode Exit fullscreen mode

The executable goes in --command and the rest in --args:

[ -n "$cmd" ] && args+=(--command "${cmd%% *}" --args "${cmd#* }")
Enter fullscreen mode Exit fullscreen mode

🔎 Tip: The Async Azure Credential Needs aiohttp

azure.identity.aio.DefaultAzureCredential with a managed identity imports aiohttp, which azure-identity does not install. Without it the revision stays Activating:

ImportError: aiohttp package is not installed
Enter fullscreen mode Exit fullscreen mode

The image pins aiohttp==3.14.3.


Step 11 — Keep the Public Stream Open

Container Apps ingress has a 240 second HTTP request timeout, and one Phi reply can take minutes. The web app runs the workflow in the background and writes a blank line every 20 s while it waits; the ADK frontend skips blank lines.

try:
    kind, payload = await asyncio.wait_for(queue.get(), HEARTBEAT)
except TimeoutError:
    yield "\n"
    continue
Enter fullscreen mode Exit fullscreen mode

One course requested through the public URL, as the browser sees the stream, seconds on the left:

  0.4 progress 🔍 Researcher is gathering information... (round 1)
 17.5 progress ⚖️ Judge is evaluating findings... (round 1)
 23.5 progress ⚖️ Judge verdict: fail
 23.5 progress 🔍 Researcher is gathering information... (round 2)
 32.4 progress ⚖️ Judge is evaluating findings... (round 2)
 36.0 progress ⚖️ Judge verdict: pass
 36.0 progress ✍️ Content Builder is writing the course...
 56.6 result   # Curling: The Strategic Ice Team Sport
Enter fullscreen mode Exit fullscreen mode

Compare and Contrast: Strands on AWS or MAF on Azure?

Strands on Bedrock MAF on Azure
Model Amazon Nova 2 Lite Phi-4-mini-instruct
Loop Graph with conditional edges Workflow with typed messages and conditional edges
Structured judge structured_output_model JSON mode plus JudgeFeedback validation
Web search nova_grounding inside a @tool Foundry web_search before the model turn
A2A 1.x Unmerged pull request Released agent-framework-a2a
Hosting AgentCore Runtime and ECS Express Mode Azure Container Apps
Failed remote task Arrives as a reply Arrives as the caller's prompt

So, Which One?

🥇 MAF on Azure ships A2A 1.x in a released package, and its workflow carries typed messages between executors, so the verdict and the round count travel as fields. 🥈 Strands on Bedrock gives the agents a model that calls tools and takes a schema, so its researcher and judge port with less code. On either cloud the small model sets the shape of the port: with Phi-4-mini, search and instructions go into the request, and the orchestrator checks the judge's JSON.


Teardown

The web app is public with no sign-in, and every course is billed to the subscription. Everything lives in one resource group, and the Foundry account is purged after deletion so its name can be reused:

make destroy
Enter fullscreen mode Exit fullscreen mode
az group delete -n "$RG" --yes
az cognitiveservices account purge -g "$RG" -n "$FOUNDRY" -l "$LOCATION" 2>/dev/null || true
Enter fullscreen mode Exit fullscreen mode

Summary

The goal of this article was to port an ADK research, judge and course loop to Microsoft Agent Framework on Azure. The key to the solution was a MAF workflow over three A2A agents on Phi-4-mini, with search and instructions placed in the request message where Phi reads them. The results were:

  • 🟢 The prompts and the JudgeFeedback schema carried over; JSON mode plus validation in the orchestrator replaced the output schema.
  • 🟢 One WorkflowBuilder graph replaced SequentialAgent, LoopAgent and the escalation agent; the fail path ran three rounds in 79.7 s and stopped with no course.
  • 🟢 Through the public Container Apps URL a two-round course took 56.6 s end to end.
  • 🟢 37 offline tests run in 3.27 s with no Azure calls, and each of six deliberate breaks failed at least one.
  • ❌ Hosted Phi-4-mini makes no tool calls and rejects JSON schemas, and with instructions in the system message it returned valid JudgeFeedback 0 times in 12.
  • ⚠️ A failed A2A task comes back as the caller's own prompt, and MAF's failure events keep only the exception's class name; both need handling in the orchestrator.

Scope: one Azure subscription in eastus2 on 2026-11-29 and 2026-11-30, Phi-4-mini-instruct version 1 at GlobalStandard capacity 20 for all three agents, gpt-4.1-mini behind web_search, Microsoft Agent Framework 1.26.0 with agent-framework-a2a 1.0.0b261112 and a2a-sdk 1.3.1, Python 3.14. Each timing is a single run on "Curling": the local runs on one workstation, the public run through Container Apps at 0.5 vCPU and 1 GiB per app. The model's searches and verdicts vary between runs, so the times and round counts will too.

The strategy for porting an ADK multi-agent loop to Microsoft Agent Framework on Azure was validated with an incremental step by step approach.


References

Top comments (0)