Velamuvi AIAcademy

Lesson 35 of 39 · Production

Declarative Agents and Workflows

Define Agent Framework agents and workflows in YAML: AgentFactory, WorkflowFactory, questions, HTTP and MCP actions, Power Fx expressions and handlers.

  • 15 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain what declarative agents and workflows are, and when YAML beats Python
  • Load an agent from YAML with AgentFactory, with a tool bound to a Python function
  • Build and run a YAML workflow with WorkflowFactory, including registered agents
  • Pause a workflow for user input with Question and resume it with ExternalInputResponse
  • Call HTTP APIs and MCP tools from YAML through HttpRequestHandler and MCPToolHandler
  • Use Power Fx expressions, and know what they need to run

Agents and workflows as data

So far, every agent and workflow in this course was Python code. Agent Framework can also load them from YAML files. The YAML describes what the agent or workflow is; the framework turns it into the same Agent and Workflow objects you've been using.

Why use it:

  • Change without redeploying code. A product owner can edit instructions or the steps of a support flow, and the same Python program loads the new version.
  • Portability. Agent Framework's .NET version reads the same workflow format, so a workflow can move between languages.
  • Review and versioning. A YAML diff shows exactly which step or instruction changed.

The idea in a few lines of plain Python: a list of actions is data, and a small runner gives each action kind its behaviour:

Try it yourselfPython
import re

# A workflow written as data (what YAML becomes after loading): a list of actions
WORKFLOW = [
    {"kind": "SendActivity", "activity": "Welcome to Velo!"},
    {"kind": "Question", "question": "How many days do you need the bike?", "variable": "Local.days"},
    {"kind": "SetVariable", "variable": "Local.bike", "value": "City E"},
    {"kind": "SendActivity", "activity": "Booked a {Local.bike} for {Local.days} days."},
]


def run(actions, answers):
    state = {}
    for action in actions:                      # each action kind has its own small handler
        if action["kind"] == "SendActivity":
            text = re.sub(r"\{([\w.]+)\}", lambda m: str(state.get(m.group(1), "")), action["activity"])
            print("bot:", text)
        elif action["kind"] == "Question":
            print("bot:", action["question"])
            state[action["variable"]] = answers.pop(0)      # a real workflow pauses here
            print("user:", state[action["variable"]])
        elif action["kind"] == "SetVariable":
            state[action["variable"]] = action["value"]
        else:
            raise ValueError(f"Unknown action kind: {action['kind']}")


run(WORKFLOW, answers=["3"])

WorkflowFactory does the same job for real: every YAML action becomes an executor in a workflow graph, so declarative workflows get checkpoints, pausing and visualization like the ones you built in Python.

A YAML agent with AgentFactory

An agent file uses kind: Prompt. This one has instructions, a model option and one function tool:

kind: Prompt
name: VeloDesk
description: Answers questions about Velo bike rentals
instructions: You are Velo's rental desk in Porto. Use the bike_price tool for prices.
model:
  options:
    temperature: 0.2
tools:
  - kind: function
    name: bike_price
    description: Daily rental price of one Velo bike model.
    parameters:
      properties:
        - name: model
          kind: string
          description: The bike model, for example City E
          required: true
    bindings:
      - name: bike_price

The tool's binding names a Python function, which you pass to AgentFactory when you load the file. velo_tools.py holds the function:

def bike_price(model: str) -> str:
    """Daily rental price of one Velo bike model."""
    return {"City E": "35 EUR a day", "Trail X": "50 EUR a day"}.get(model, "unknown model")
import asyncio

from agent_framework.declarative import AgentFactory
from agent_framework.openai import OpenAIChatClient

from velo_tools import bike_price          # the Python function behind the YAML tool


async def main():
    factory = AgentFactory(
        client=OpenAIChatClient(model="MODEL_NAME"),   # used because the YAML names no provider
        bindings={"bike_price": bike_price},           # binding name -> Python function
    )
    desk = factory.create_agent_from_yaml_path("velo_desk.yaml")
    print(type(desk).__name__, desk.name, "|", desk.description)
    response = await desk.run("How much is a City E?")
    print(response.text)


asyncio.run(main())
Output
Agent VeloDesk | Answers questions about Velo bike rentals
A City E costs 35 EUR a day.

What happened:

  • create_agent_from_yaml_path returned an ordinary Agent, with the name, description and instructions from the file. create_agent_from_yaml does the same for a YAML string.
  • The YAML tool became a real tool, calling bike_price through its binding. A tool with no matching binding can't run, so keep binding names and the dictionary in step.
  • model.options such as temperature become the agent's default chat options.
  • Because the YAML names no provider, the agent uses the client= you gave the factory. A file can instead name one, for example model: {id: MODEL_NAME, provider: OpenAI}, and the factory then creates the client from your environment variables.

A YAML workflow with WorkflowFactory

A workflow file has kind: Workflow and a trigger with a list of actions. Each action has a kind and an id:

kind: Workflow
trigger:
  kind: OnConversationStart
  id: welcome_flow
  actions:
    - kind: SendActivity
      id: hello
      activity: Welcome to Velo!
    - kind: InvokeAzureAgent
      id: ask_desk
      agent:
        name: VeloDesk
    - kind: SendActivity
      id: bye
      activity: Thanks for riding with Velo.
import asyncio

from agent_framework.declarative import AgentFactory, WorkflowFactory
from agent_framework.openai import OpenAIChatClient

from velo_tools import bike_price


async def main():
    agents = AgentFactory(client=OpenAIChatClient(model="MODEL_NAME"), bindings={"bike_price": bike_price})
    desk = agents.create_agent_from_yaml_path("velo_desk.yaml")

    factory = WorkflowFactory(agents={"VeloDesk": desk})       # names used by InvokeAzureAgent
    workflow = factory.create_workflow_from_yaml_path("welcome_flow.yaml")

    result = await workflow.run("How much does a City E cost?")
    for output in result.get_outputs():
        print(output)


asyncio.run(main())
Output
Welcome to Velo!
A City E costs 35 EUR a day.
Thanks for riding with Velo.
  • SendActivity sends text as workflow output.
  • InvokeAzureAgent runs an agent with the conversation so far. Despite the name, it works with any agent: here, the YAML agent from above. You give agents to the factory with agents={"VeloDesk": desk} (or factory.register_agent(...)); the name in the YAML must match.
  • create_workflow_from_yaml_path returns a normal Workflow, so run(), get_outputs(), streaming and checkpoints all work as in the workflow lessons. Pass checkpoint_storage= to the factory to save progress at action boundaries.

Other action kinds cover variables (SetVariable, SetMultipleVariables, ResetVariable), branching (If, ConditionGroup), loops (Foreach, GotoAction), tables (EditTable), function tools (InvokeFunctionTool, with functions from register_tool) and ending (EndWorkflow, EndConversation).

Questions, HTTP calls and MCP tools

Real flows ask the user things and call other systems. This workflow asks which bike the customer wants, fetches prices from an HTTP API, checks stock with an MCP tool, then sums up:

kind: Workflow
trigger:
  kind: OnConversationStart
  id: rental_flow
  actions:
    - kind: SendActivity
      id: welcome
      activity: Welcome to Velo rentals!
    - kind: Question
      id: ask_bike
      question: Which bike would you like, City E or Trail X?
      variable: Local.bike
    - kind: HttpRequestAction
      id: get_prices
      method: GET
      url: https://api.velo.example/prices
      response: Local.prices
    - kind: InvokeMcpTool
      id: check_stock
      serverUrl: https://mcp.velo.example/mcp
      toolName: check_stock
      arguments:
        shop: Porto
      output:
        result: Local.stock
        autoSend: false
    - kind: SendActivity
      id: summary
      activity: "You chose {Local.bike}. Prices: {Local.prices}. Stock in Porto: {Local.stock}"

The workflow never opens a network connection itself. It hands every HTTP call to an HttpRequestHandler and every MCP call to an MCPToolHandler, which you pass to the factory. A workflow that contains these actions fails to build without the matching handler. For this example, two small test doubles answer instead of real services:

import asyncio
import json

from agent_framework import Content
from agent_framework.declarative import (ExternalInputRequest, ExternalInputResponse, HttpRequestInfo,
                                         HttpRequestResult, MCPToolInvocation, MCPToolResult, WorkflowFactory)


class TestHttp:
    """Stands in for DefaultHttpRequestHandler, so the example needs no real API."""

    async def send(self, info: HttpRequestInfo) -> HttpRequestResult:
        print("HTTP request:", info.method, info.url)
        return HttpRequestResult(status_code=200, is_success_status_code=True,
                                 body=json.dumps({"City E": 35, "Trail X": 50}))


class TestMcp:
    """Stands in for DefaultMCPToolHandler, so the example needs no real MCP server."""

    async def invoke_tool(self, invocation: MCPToolInvocation) -> MCPToolResult:
        print("MCP call:", invocation.tool_name, invocation.arguments)
        return MCPToolResult(outputs=[Content.from_text("City E: 4 bikes, Trail X: 1 bike")])


async def main():
    factory = WorkflowFactory(http_request_handler=TestHttp(), mcp_tool_handler=TestMcp())
    workflow = factory.create_workflow_from_yaml_path("rental_flow.yaml")

    result = await workflow.run("Hi")                     # runs until the Question pauses it
    print(result.get_outputs())
    request = result.get_request_info_events()[0]
    question: ExternalInputRequest = request.data
    print("Question:", question.message, f"({question.request_type})")

    answer = ExternalInputResponse(user_input="City E")    # what the user typed
    result = await workflow.run(responses={request.request_id: answer})
    for output in result.get_outputs():
        print(output)


asyncio.run(main())
Output
['Welcome to Velo rentals!']
Question: Which bike would you like, City E or Trail X? (question)
HTTP request: GET https://api.velo.example/prices
MCP call: check_stock {'shop': 'Porto'}
You chose City E. Prices: {'City E': 35, 'Trail X': 50}. Stock in Porto: ['City E: 4 bikes, Trail X: 1 bike']

Step by step:

  1. Question pauses the workflow. The first run() ends with one output and a pending request whose data is an ExternalInputRequest: its message is the question and its request_type is "question". RequestExternalInput works the same way, with a request type you choose, such as "approval".
  2. The answer goes back as an ExternalInputResponse(user_input=...) with workflow.run(responses={request_id: answer}), exactly like the human-in-the-loop lesson. It's stored in Local.bike, the action's variable.
  3. HttpRequestAction sends the request through the handler and stores the parsed JSON body in Local.prices (response). It also takes headers, queryParameters, body and requestTimeoutInMilliseconds.
  4. InvokeMcpTool calls check_stock on the MCP server through the handler and stores the result in Local.stock (output.result). autoSend: false keeps the raw result out of the conversation.
  5. The last SendActivity fills in the {Local.bike} placeholders from the workflow state.

In production, use the built-in handlers:

  • DefaultHttpRequestHandler sends real requests with httpx. It limits response bodies to 10 MiB by default (max_response_body_bytes) and doesn't keep cookies; pass your own client= if an API needs them.
  • DefaultMCPToolHandler connects to the MCP server over HTTP, opening a fresh session for every call, so separate workflows never share MCP state.

Add requireApproval: true to an InvokeMcpTool action and the workflow pauses before the call with an MCPToolApprovalRequest showing the tool, server and arguments; answer it with ToolApprovalResponse(approved=True) or approved=False.

Power Fx expressions

Values that start with = are Power Fx expressions. Power Fx is the formula language of Microsoft Power Platform, and it works much like spreadsheet formulas. They compute values and conditions from the workflow state:

kind: Workflow
trigger:
  kind: OnConversationStart
  id: quote_flow
  actions:
    - kind: SetVariable
      id: set_days
      variable: Local.days
      value: 10
    - kind: ConditionGroup
      id: rate_check
      conditions:
        - condition: =Local.days >= 7
          actions:
            - kind: SendActivity
              id: weekly
              activity: "Weekly rate for {Local.days} days."
      elseActions:
        - kind: SendActivity
          id: daily
          activity: "Daily rate for {Local.days} days."

Local.days is a variable in the Local scope (the workflow's own variables); System holds values such as the conversation, and Env reads configuration values you pass with configuration=. The condition =Local.days >= 7 picks the branch, so with 10 days the weekly message is sent.

Power Fx runs on .NET: it needs the .NET runtime (8 or later) and the powerfx Python package (installed with agent-framework-declarative), on Python 3.11 to 3.13. Without .NET, the workflow still loads, but running it stops at the first expression:

import asyncio

from agent_framework.declarative import WorkflowFactory


async def main():
    workflow = WorkflowFactory().create_workflow_from_yaml_path("quote_flow.yaml")
    result = await workflow.run("quote")
    print(result.get_outputs())


asyncio.run(main())
Output
RuntimeError: PowerFx is not available (dotnet runtime not installed). Expression '=Local.days >= 7' cannot be evaluated. Install dotnet and the powerfx package for full PowerFx support.

Plain values (value: 10), {Local.name} placeholders and a few built-in helpers such as =UserMessage(...) and =MessageText(...) work without .NET; everything else written with = needs it.

Common mistakes

Practice exercise

Write the template step of SendActivity: fill {Variable.Path} placeholders from the workflow state.

Your solutionPython
import re

def interpolate(text, state):
    # Replace every {Variable.Path} in text with str(state[path]), like SendActivity does.
    # A path that isn't in state becomes an empty string.
    return text

state = {"Local.bike": "Trail X", "Local.days": 3}
print(interpolate("You chose {Local.bike} for {Local.days} days.", state))
print(interpolate("Helmet size: {Local.helmet}!", state))
Knowledge check

A YAML workflow contains an InvokeMcpTool action. What must the Python host provide?

Summary

  • Declarative agents and workflows are YAML files that the framework turns into normal Agent and Workflow objects.
  • AgentFactory (experimental) loads kind: Prompt agents; tools are bound to Python functions with bindings.
  • WorkflowFactory (stable) loads kind: Workflow files; each action becomes an executor, so checkpoints and pausing work.
  • InvokeAzureAgent runs agents you register by name; SendActivity sends text with {Local.name} placeholders.
  • Question pauses with an ExternalInputRequest; resume with an ExternalInputResponse.
  • HttpRequestAction and InvokeMcpTool go through an HttpRequestHandler and an MCPToolHandler; MCP calls can require approval.
  • Values starting with = are Power Fx expressions, which need the .NET runtime.

Next: Hosting: A2A, AG-UI, ChatKit and Azure Functions.

Finished reading? Tick it off to track your progress.