Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Microsoft Agent framework AgentFactory Create Agent From YAML

From Leeroopedia
Property Value
Implementation Name AgentFactory Create Agent From YAML
SDK Microsoft Agent Framework
Repository agent-framework
Source File python/packages/declarative/agent_framework_declarative/_loader.py
Line Range L319-389 (primary), L265-317, L488-516
Import from agent_framework.declarative import AgentFactory
Type Factory methods
Domains Declarative_Systems, Agent_Architecture
Last Updated 2026-02-11 00:00 GMT

Overview

The AgentFactory class provides a family of methods for creating fully configured Agent instances from declarative YAML definitions. The primary entry point is create_agent_from_yaml(), which accepts a YAML string, parses it into a PromptAgent model object, resolves the model provider, constructs the chat client, binds tools, and returns a standard Agent instance identical to one created programmatically. Companion methods provide file-based loading and async variants for providers that require asynchronous initialization.

Code Reference

Source Location

Property Value
File python/packages/declarative/agent_framework_declarative/_loader.py
Class AgentFactory
Module agent_framework_declarative
Re-exported Via agent_framework.declarative (lazy import proxy)

Method Signatures

class AgentFactory:
    def __init__(
        self,
        *,
        client: SupportsChatGetResponse | None = None,
        bindings: Mapping[str, Any] | None = None,
        connections: Mapping[str, Any] | None = None,
        client_kwargs: Mapping[str, Any] | None = None,
        additional_mappings: Mapping[str, ProviderTypeMapping] | None = None,
        default_provider: str = "AzureAIClient",
        safe_mode: bool = True,
        env_file_path: str | None = None,
        env_file_encoding: str | None = None,
    ) -> None: ...

    # Primary: from YAML string (L319-389)
    def create_agent_from_yaml(self, yaml_str: str) -> Agent: ...

    # From file path (L265-317)
    def create_agent_from_yaml_path(self, yaml_path: str | Path) -> Agent: ...

    # Async variant for providers requiring async init (L488-516)
    async def create_agent_from_yaml_async(self, yaml_str: str) -> Agent: ...

    # Async file variant
    async def create_agent_from_yaml_path_async(self, yaml_path: str | Path) -> Agent: ...

    # From dict (shared implementation, L392-456)
    def create_agent_from_dict(self, agent_def: dict[str, Any]) -> Agent: ...

    # Async dict variant (L519-573)
    async def create_agent_from_dict_async(self, agent_def: dict[str, Any]) -> Agent: ...

Import Statement

from agent_framework.declarative import AgentFactory

Alternatively, the direct package import:

from agent_framework_declarative import AgentFactory

I/O Contract

Factory Constructor Inputs

Parameter Type Default Description
client None None Pre-configured chat client to use for all agents. When provided, the YAML model block is optional.
bindings None None Dictionary mapping tool binding names to Python callables. Required when YAML defines function tools with bindings.
connections None None Dictionary of named connection objects for resolving ReferenceConnection entries in YAML.
client_kwargs None None Additional keyword arguments passed directly to the chat client constructor (e.g., credential).
additional_mappings None None Custom provider registrations extending the built-in provider lookup table.
default_provider str "AzureAIClient" Provider used when the YAML model block omits the provider field.
safe_mode bool True When True, blocks PowerFx expressions from accessing environment variables.
env_file_path None None Path to a .env file to load environment variables from via dotenv.
env_file_encoding None None Encoding of the .env file. Defaults to utf-8.

create_agent_from_yaml() Input

Parameter Type Default Description
yaml_str str (required) A YAML string representing a PromptAgent definition. Must contain kind: Prompt.

create_agent_from_yaml_path() Input

Parameter Type Default Description
yaml_path Path (required) File system path to a YAML file. Converted to pathlib.Path internally. Raises DeclarativeLoaderError if the file does not exist.

create_agent_from_yaml_async() Input

Parameter Type Default Description
yaml_str str (required) Same as the synchronous variant. Use when the resolved provider requires async initialization (e.g., AzureAI.ProjectProvider).

Output (All Variants)

Type Description
Agent A fully configured agent instance, ready for execution via agent.run() or async with agent. Identical in behavior to an Agent constructed programmatically.

Exceptions Raised

Exception Condition
DeclarativeLoaderError The YAML does not represent a PromptAgent (i.e., kind is not Prompt), or no client/model is available.
ProviderLookupError The model.provider (and optional model.apiType) combination does not match any registered provider in the mapping table.
ModuleNotFoundError The Python package for the resolved provider is not installed (e.g., agent_framework.azure not available).
ValueError A ReferenceConnection in the YAML cannot be resolved against the provided connections dictionary.
AttributeError The resolved provider class cannot be found within its module.

Internal Processing Pipeline

The create_agent_from_yaml() method delegates to create_agent_from_dict() after parsing YAML. The dictionary-based method executes the following pipeline:

  1. Set safe mode context -- Stores the safe_mode flag in a ContextVar so that PowerFx evaluation in model classes respects it.
  2. Schema dispatch -- Calls agent_schema_dispatch(agent_def) which inspects the kind field and returns a typed PromptAgent instance.
  3. Validation -- Asserts the result is a PromptAgent; raises DeclarativeLoaderError otherwise.
  4. Client creation -- _get_client() resolves the provider mapping, dynamically imports the module, and constructs the chat client with connection and model ID parameters.
  5. Chat options parsing -- _parse_chat_options() extracts model options (temperature, top_p, max tokens, frequency/presence penalty, stop sequences, etc.) into a kwargs dictionary.
  6. Tool parsing -- _parse_tools() iterates the tool list, matching each by kind (function, web_search, file_search, code_interpreter, mcp) and converting to AFFunctionTool instances or dict-based tool descriptors.
  7. Response format -- If outputSchema is defined, converts it to a dynamically generated Pydantic model via _create_model_from_json_schema().
  8. Agent construction -- Calls Agent(client=..., name=..., description=..., instructions=..., **chat_options).

The core construction logic (from create_agent_from_dict, L434-456):

# Step 1: Create the ChatClient
client = self._get_client(prompt_agent)
# Step 2: Get the chat options
chat_options = self._parse_chat_options(prompt_agent.model)
if tools := self._parse_tools(prompt_agent.tools):
    chat_options["tools"] = tools
if output_schema := prompt_agent.outputSchema:
    chat_options["response_format"] = _create_model_from_json_schema(
        "agent", output_schema.to_json_schema()
    )
# Step 3: Create the agent instance
return Agent(
    client=client,
    name=prompt_agent.name,
    description=prompt_agent.description,
    instructions=prompt_agent.instructions,
    **chat_options,
)

YAML Schema

A minimal YAML agent definition follows this structure:

kind: Prompt
name: MyAgent
description: A helpful assistant agent
instructions: |
    You are a helpful assistant.
    Answer questions concisely.
model:
    id: gpt-4o
    provider: OpenAI
    apiType: Responses
    connection:
        kind: key
        apiKey: sk-...
    options:
        temperature: 0.7
        maxOutputTokens: 1024
tools:
    - kind: function
      name: get_weather
      description: Get current weather for a location
      bindings:
          - name: get_weather
      parameters:
          properties:
              - name: location
                kind: property
                description: City name
                required: true
outputSchema:
    properties:
        - name: answer
          kind: property
          description: The answer text

Usage Examples

Basic: Agent from File

from agent_framework.declarative import AgentFactory

factory = AgentFactory()
agent = factory.create_agent_from_yaml_path("agent.yaml")

response = await agent.run("Hello!")
print(response.text)

Agent from Inline YAML String

from agent_framework.declarative import AgentFactory

factory = AgentFactory(bindings={"get_weather": get_weather})

yaml_content = """
kind: Prompt
name: MyAgent
instructions: You are helpful.
model:
    id: gpt-4o
    provider: OpenAI
"""

agent = factory.create_agent_from_yaml(yaml_content)

# Run the agent (identical to programmatic agent)
response = await agent.run("Hello!")
print(response.text)

Agent with Tool Bindings

from agent_framework.declarative import AgentFactory

def get_weather(location: str) -> str:
    """Get weather for a location."""
    return f"Sunny, 22C in {location}"

factory = AgentFactory(bindings={"get_weather": get_weather})
agent = factory.create_agent_from_yaml_path("weather_agent.yaml")

async for event in agent.run("What is the weather in Paris?", stream=True):
    print(event)

Pre-configured Client

from agent_framework.azure import AzureOpenAIChatClient
from agent_framework.declarative import AgentFactory

client = AzureOpenAIChatClient(deployment_name="gpt-4o")
factory = AgentFactory(client=client)

# YAML can omit the model block entirely when a client is provided
agent = factory.create_agent_from_yaml("""
kind: Prompt
name: SimpleAgent
instructions: You are a helpful assistant.
""")

Async Loading for Azure AI Project Provider

from agent_framework.declarative import AgentFactory

factory = AgentFactory(
    client_kwargs={"credential": credential},
    default_provider="AzureAI.ProjectProvider",
)
agent = await factory.create_agent_from_yaml_path_async("agent.yaml")

response = await agent.run("Analyze this data")
print(response.text)

Custom Provider Registration

from agent_framework.declarative import AgentFactory

factory = AgentFactory(
    additional_mappings={
        "CustomProvider.Chat": {
            "package": "my_package.clients",
            "name": "CustomChatClient",
            "model_id_field": "model_name",
        },
    },
)

agent = factory.create_agent_from_yaml("""
kind: Prompt
name: CustomAgent
instructions: You are a custom agent.
model:
    id: custom-model-v1
    provider: CustomProvider
    apiType: Chat
""")

Async Context Manager with MCP Tools

from agent_framework.declarative import AgentFactory

factory = AgentFactory()

async with factory.create_agent_from_yaml("""
kind: Prompt
name: McpAgent
instructions: You are an assistant with MCP tools.
model:
    id: gpt-4o
    provider: OpenAI
    apiType: Responses
tools:
    - kind: mcp
      name: my_mcp_server
      url: https://mcp.example.com/sse
""") as agent:
    response = await agent.run("Use the tools to help me.")
    print(response.text)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment