Skip to content

Python: Enhance README with detailed YAML schema documentation#2571

Closed
frdeange wants to merge 1 commit intomicrosoft:mainfrom
frdeange:patch-1
Closed

Python: Enhance README with detailed YAML schema documentation#2571
frdeange wants to merge 1 commit intomicrosoft:mainfrom
frdeange:patch-1

Conversation

@frdeange
Copy link

@frdeange frdeange commented Dec 2, 2025

Updated the README.md to include comprehensive documentation for the Microsoft Agent Framework Declarative YAML Schema, including installation instructions, features, examples, and detailed sections on model configuration, connection types, tools, and validation.

Motivation and Context

Description

Contribution Checklist

  • The code builds clean without any errors or warnings
  • The PR follows the Contribution Guidelines
  • All unit tests pass, and I have added new tests where possible
  • Is this a breaking change? If yes, add "[BREAKING]" prefix to the title of the PR.

Updated the README.md to include comprehensive documentation for the Microsoft Agent Framework Declarative YAML Schema, including installation instructions, features, examples, and detailed sections on model configuration, connection types, tools, and validation.
Copilot AI review requested due to automatic review settings December 2, 2025 08:59
@markwallace-microsoft markwallace-microsoft added documentation Improvements or additions to documentation python labels Dec 2, 2025
@github-actions github-actions bot changed the title Enhance README with detailed YAML schema documentation Python: Enhance README with detailed YAML schema documentation Dec 2, 2025
@markwallace-microsoft
Copy link
Member

Python Test Coverage

Python Test Coverage Report •
FileStmtsMissCoverMissing
TOTAL15873241284% 
report-only-changed-files is enabled. No files were changed during this commit :)

Python Unit Test Overview

Tests Skipped Failures Errors Time
2278 130 💤 0 ❌ 0 🔥 53.656s ⏱️

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR enhances the README.md for the Microsoft Agent Framework Declarative package by adding comprehensive documentation for the YAML schema used to define agents declaratively. The documentation provides detailed coverage of all configuration options, connection types, tools, and usage patterns.

Key changes:

  • Added detailed YAML schema documentation with a comprehensive table of contents
  • Documented all supported model providers, connection types, and tool configurations
  • Included 7 complete working examples covering common agent patterns
  • Added Python usage examples showing how to create and configure agents from YAML

Comment on lines +72 to +74
- [PowerFx Validation](#powerfx-validation)
- [Required Fields](#required-fields)
- [References](#references)
Copy link

Copilot AI Dec 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The table of contents references three sections that are not implemented in the document:

  • "PowerFx Validation" (line 72)
  • "Required Fields" (line 73)
  • "References" (line 74)

These sections should either be added to the document or removed from the table of contents to avoid broken links.

Suggested change
- [PowerFx Validation](#powerfx-validation)
- [Required Fields](#required-fields)
- [References](#references)

Copilot uses AI. Check for mistakes.
```

The declarative packages provides support for building agents based on a declarative yaml specification.
#### 3. ValueError
Copy link

Copilot AI Dec 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The "Validation and Errors" section appears incomplete. The "#### 3. ValueError" heading is present but has no description or example following it. This section should be completed with information about ValueError exceptions that can occur during agent creation.

Suggested change
#### 3. ValueError
#### 3. ValueError
Raised when the YAML definition is syntactically correct but contains invalid or missing values required for agent creation. For example, if a required field is missing or a value is of the wrong type.

ValueError: Missing required field 'instructions' in agent definition.

Copilot uses AI. Check for mistakes.
### With Connections

```python
from azure.identity import DefaultAzureCredential
Copy link

Copilot AI Dec 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inconsistent import of DefaultAzureCredential. In the first example (line 1020), it's imported from azure.identity.aio (async version), but here it's imported from azure.identity (sync version).

For consistency and to avoid confusion, the import should match the usage pattern. If the examples are meant to show both sync and async patterns, this should be clarified in comments. Otherwise, use the same import throughout (preferably azure.identity.aio.DefaultAzureCredential if working with async agents).

Suggested change
from azure.identity import DefaultAzureCredential
from azure.identity.aio import DefaultAzureCredential

Copilot uses AI. Check for mistakes.
Comment on lines +1078 to +1079
"async_credential": credential,
"project_endpoint": project_endpoint
Copy link

Copilot AI Dec 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code example references undefined variables credential and project_endpoint (lines 1078-1079). These variables are not defined in this code snippet, which would cause a NameError if users try to run this example as-is.

Consider either:

  1. Adding the variable definitions from the previous example
  2. Replacing them with placeholder comments like # credential and project_endpoint from previous example
  3. Removing the client_kwargs parameter if it's not essential to demonstrate bindings
Suggested change
"async_credential": credential,
"project_endpoint": project_endpoint
# "async_credential": credential, # Define 'credential' as shown in a previous example
# "project_endpoint": project_endpoint # Define 'project_endpoint' as shown in a previous example

Copilot uses AI. Check for mistakes.
@frdeange
Copy link
Author

frdeange commented Dec 2, 2025

You're right. I have added the left lines of description:

Microsoft Agent Framework - Declarative YAML Schema

Complete YAML schema documentation for defining agents declaratively in Microsoft Agent Framework.

Based on official source code:


Get Started with Microsoft Agent Framework Declarative

Please install this package via pip:

pip install agent-framework-declarative --pre

📑 Table of Contents


Main Structure

Every YAML file must start with a kind field that defines the agent type:

kind: Prompt  # or "Agent" - both create a PromptAgent

↑ Back to top


PromptAgent Definition

Main Fields

kind: Prompt                    # REQUIRED: "Prompt" or "Agent"
name: string                    # REQUIRED: Agent name
description: string             # OPTIONAL: Agent description
instructions: string            # OPTIONAL: System instructions (system prompt)
model: Model                    # OPTIONAL: Model configuration
tools: list[Tool]              # OPTIONAL: List of tools
inputSchema: PropertySchema     # OPTIONAL: Input schema
outputSchema: PropertySchema    # OPTIONAL: Output schema

Example

kind: Prompt
name: MyAssistant
description: A helpful AI assistant
instructions: You are a helpful assistant that answers questions concisely.
model:
  id: gpt-4
  connection:
    kind: remote
    endpoint: https://myendpoint.com

↑ Back to top


Model Section

Defines the LLM model to use and how to connect to it.

Complete Structure

model:
  id: string                    # REQUIRED: Model ID/deployment name
  provider: string              # OPTIONAL: Provider (default: "AzureAIClient")
  apiType: string               # OPTIONAL: API type
  connection: Connection        # OPTIONAL: Connection configuration
  options: ModelOptions         # OPTIONAL: Model options

Supported Providers

The loader looks up providers in PROVIDER_TYPE_OBJECT_MAPPING:

Provider Package Class Model ID Field
AzureOpenAI.Chat agent_framework.azure AzureOpenAIChatClient deployment_name
AzureOpenAI.Assistants agent_framework.azure AzureOpenAIAssistantsClient assistant_id
OpenAI.Chat agent_framework.openai OpenAIChatClient model
OpenAI.Assistants agent_framework.openai OpenAIAssistantsClient assistant_id
AzureAIClient agent_framework_azure_ai AzureAIClient model_id
OpenAICompatible.Chat agent_framework.openai OpenAICompatibleChatClient model

Default: If provider is not specified, uses "AzureAIClient".

Example with Provider

model:
  id: gpt-4
  provider: AzureOpenAI.Chat
  connection:
    kind: remote
    endpoint: https://myresource.openai.azure.com

↑ Back to top


Connection Types

Defines how to authenticate and connect to the model service.

1. RemoteConnection

Connection to a remote endpoint (most common with Azure AI).

connection:
  kind: remote                  # REQUIRED
  endpoint: string              # REQUIRED: Endpoint URL
  authenticationMode: string    # OPTIONAL
  usageDescription: string      # OPTIONAL
  name: string                  # OPTIONAL

Example:

model:
  id: gpt-4.1
  connection:
    kind: remote
    endpoint: =Env.AZURE_PROJECT_ENDPOINT

↑ Back to Connections

2. ApiKeyConnection

Connection with API Key.

connection:
  kind: key                     # REQUIRED
  apiKey: string                # REQUIRED (or use 'key')
  key: string                   # Alternative to 'apiKey'
  endpoint: string              # OPTIONAL
  authenticationMode: string    # OPTIONAL
  usageDescription: string      # OPTIONAL
  name: string                  # OPTIONAL

Note: If both apiKey and key are provided, key takes precedence.

Example:

model:
  id: gpt-4
  provider: OpenAI.Chat
  connection:
    kind: key
    apiKey: =Env.OPENAI_API_KEY
    endpoint: https://api.openai.com/v1

↑ Back to Connections

3. ReferenceConnection

Reference to an externally defined connection.

connection:
  kind: reference               # REQUIRED
  name: string                  # REQUIRED: Connection name
  target: string                # OPTIONAL
  authenticationMode: string    # OPTIONAL
  usageDescription: string      # OPTIONAL

Usage in Python:

factory = AgentFactory(
    connections={"my_connection": credential_object}
)

Example:

model:
  id: gpt-4
  connection:
    kind: reference
    name: my_azure_connection

↑ Back to Connections

4. AnonymousConnection

Anonymous connection without authentication.

connection:
  kind: anonymous               # REQUIRED
  endpoint: string              # REQUIRED
  authenticationMode: string    # OPTIONAL
  usageDescription: string      # OPTIONAL

Example:

model:
  id: llama-2
  connection:
    kind: anonymous
    endpoint: https://public-llm-api.com/v1

↑ Back to Connections | ↑ Back to top


ModelOptions

LLM model configuration options.

Complete Structure

model:
  options:
    frequencyPenalty: float           # OPTIONAL: -2.0 to 2.0
    maxOutputTokens: int              # OPTIONAL: Maximum output tokens
    presencePenalty: float            # OPTIONAL: -2.0 to 2.0
    seed: int                         # OPTIONAL: Seed for reproducibility
    temperature: float                # OPTIONAL: 0.0 to 2.0
    topP: float                       # OPTIONAL: 0.0 to 1.0
    stopSequences: list[string]       # OPTIONAL: Stop sequences
    allowMultipleToolCalls: bool      # OPTIONAL: Allow multiple tool calls
    additionalProperties: dict        # OPTIONAL: Additional properties

Mapping to ChatAgent Parameters

The loader converts ModelOptions to ChatAgent parameters:

YAML Field ChatAgent Parameter
frequencyPenalty frequency_penalty
presencePenalty presence_penalty
maxOutputTokens max_tokens
temperature temperature
topP top_p
seed seed
stopSequences stop
allowMultipleToolCalls allow_multiple_tool_calls
additionalProperties.chatToolMode tool_choice
additionalProperties (rest) additional_chat_options

Example

model:
  id: gpt-4
  options:
    temperature: 0.7
    maxOutputTokens: 2000
    topP: 0.95
    stopSequences: ["\n\n", "END"]
    allowMultipleToolCalls: true

↑ Back to top


Tools Section

List of tools available to the agent.

Available Tool Types:

  1. FunctionTool - Custom functions
  2. WebSearchTool - Web search
  3. FileSearchTool - File/vector search
  4. CodeInterpreterTool - Code interpreter
  5. McpTool - Model Context Protocol
  6. OpenApiTool - OpenAPI-based APIs
  7. CustomTool - Custom tools

1. FunctionTool

Defines a function that the agent can call.

tools:
  - kind: function              # REQUIRED
    name: string                # REQUIRED
    description: string         # REQUIRED
    parameters: PropertySchema  # OPTIONAL: Parameter schema
    strict: bool                # OPTIONAL: Strict mode (default: false)
    bindings: list[Binding]     # OPTIONAL: Bindings to Python functions

Example:

tools:
  - kind: function
    name: get_weather
    description: Get current weather for a location
    parameters:
      properties:
        - name: location
          kind: string
          description: City name
          required: true
        - name: units
          kind: string
          description: Temperature units
          enum: [celsius, fahrenheit]
          default: celsius
    bindings:
      - name: get_weather_func
        input: location

Usage with bindings in Python:

def my_weather_function(location: str, units: str = "celsius") -> str:
    return f"Weather in {location}: 25°{units[0].upper()}"

factory = AgentFactory(
    bindings={"get_weather_func": my_weather_function}
)

↑ Back to Tools

2. WebSearchTool

Hosted web search tool.

tools:
  - kind: web_search            # REQUIRED
    name: string                # OPTIONAL
    description: string         # OPTIONAL
    options: dict               # OPTIONAL: Additional properties

Example:

tools:
  - kind: web_search
    description: Search the web for current information

↑ Back to Tools

3. FileSearchTool

Search in stored vectors/files.

tools:
  - kind: file_search           # REQUIRED
    name: string                # OPTIONAL
    description: string         # OPTIONAL
    vectorStoreIds: list[string] # OPTIONAL: Vector store IDs
    maximumResultCount: int     # OPTIONAL: Maximum results
    ranker: string              # OPTIONAL: Ranker type
    scoreThreshold: float       # OPTIONAL: Score threshold
    filters: dict               # OPTIONAL: Search filters
    connection: Connection      # OPTIONAL: Connection

Example:

tools:
  - kind: file_search
    description: Search company documentation
    vectorStoreIds:
      - vs_abc123
      - vs_def456
    maximumResultCount: 10
    scoreThreshold: 0.75
    ranker: semantic

↑ Back to Tools

4. CodeInterpreterTool

Hosted Python code interpreter.

tools:
  - kind: code_interpreter      # REQUIRED
    name: string                # OPTIONAL
    description: string         # OPTIONAL
    fileIds: list[string]       # OPTIONAL: Available file IDs

Example:

tools:
  - kind: code_interpreter
    description: Execute Python code to analyze data
    fileIds:
      - file_abc123
      - file_def456

↑ Back to Tools

5. McpTool (Model Context Protocol)

MCP server for external tools.

tools:
  - kind: mcp                   # REQUIRED
    name: string                # REQUIRED
    description: string         # OPTIONAL
    url: string                 # REQUIRED: MCP server URL
    approvalMode: ApprovalMode  # OPTIONAL: Approval mode
    allowedTools: list[string]  # OPTIONAL: List of allowed tools

ApprovalMode - Simple Format

approvalMode:
  kind: never         # No approval (automatic execution)
  # OR
  kind: always        # Requires approval on EVERY call
  # OR
  kind: onFirstUse    # Requires approval only on first use

String format is also accepted:

approvalMode: never   # Equivalent to {kind: never}

ApprovalMode - Advanced Format (ToolSpecify)

approvalMode:
  kind: toolSpecify
  alwaysRequireApprovalTools: list[string]  # Tools that ALWAYS require approval
  neverRequireApprovalTools: list[string]   # Tools that NEVER require approval

Conversion in loader:

YAML Python (HostedMCPTool)
kind: never approval_mode="never_require"
kind: always approval_mode="always_require"
kind: toolSpecify approval_mode={"always_require_approval": [...], "never_require_approval": [...]}

Example 1: Microsoft Learn

tools:
  - kind: mcp
    name: microsoft_learn
    description: Search Microsoft Learn documentation
    url: https://learn.microsoft.com/api/mcp
    approvalMode:
      kind: never
    allowedTools:
      - microsoft_docs_search
      - microsoft_docs_fetch
      - microsoft_code_sample_search

Example 2: Selective Approval

tools:
  - kind: mcp
    name: database_tools
    description: Database operations
    url: https://myserver.com/mcp
    approvalMode:
      kind: toolSpecify
      alwaysRequireApprovalTools:
        - delete_records
        - truncate_table
      neverRequireApprovalTools:
        - select_query
        - count_records
    allowedTools:
      - select_query
      - delete_records
      - truncate_table
      - count_records

↑ Back to Tools

6. OpenApiTool

Tool based on OpenAPI specification.

tools:
  - kind: openapi               # REQUIRED
    name: string                # REQUIRED
    description: string         # OPTIONAL
    specification: string       # REQUIRED: URL or path to OpenAPI spec
    connection: Connection      # OPTIONAL: Connection configuration

Example:

tools:
  - kind: openapi
    name: petstore_api
    description: Interact with the Pet Store API
    specification: https://petstore.swagger.io/v2/swagger.json
    connection:
      kind: key
      apiKey: =Env.PETSTORE_API_KEY
      endpoint: https://petstore.swagger.io/v2

↑ Back to Tools

7. CustomTool

Custom tool with free configuration.

tools:
  - kind: custom                # REQUIRED
    name: string                # REQUIRED
    description: string         # OPTIONAL
    connection: Connection      # OPTIONAL
    options: dict               # OPTIONAL: Custom configuration

Example:

tools:
  - kind: custom
    name: my_special_tool
    description: Custom integration with internal system
    connection:
      kind: reference
      name: internal_api
    options:
      timeout: 30
      retry_count: 3
      custom_header: special-value

↑ Back to Tools | ↑ Back to top


Input/Output Schemas

Define the structure of agent input and output.

PropertySchema

inputSchema:  # or outputSchema
  properties:
    - name: string              # REQUIRED
      kind: string              # REQUIRED: field type
      description: string       # OPTIONAL
      required: bool            # OPTIONAL
      default: any              # OPTIONAL
      example: any              # OPTIONAL
      enum: list[any]           # OPTIONAL: allowed values

Property Types

1. Simple Property

Supported kinds: string, number, boolean, array, object

- name: user_name
  kind: string
  description: Name of the user
  required: true

2. ArrayProperty

- name: tags
  kind: array
  description: List of tags
  items:
    name: tag
    kind: string

3. ObjectProperty

- name: address
  kind: object
  description: User address
  properties:
    - name: street
      kind: string
    - name: city
      kind: string
    - name: zip
      kind: string

Complete Example

inputSchema:
  properties:
    - name: query
      kind: string
      description: User search query
      required: true
    - name: filters
      kind: object
      description: Search filters
      properties:
        - name: category
          kind: string
          enum: [docs, blog, video]
        - name: date_from
          kind: string
    - name: max_results
      kind: number
      default: 10

outputSchema:
  properties:
    - name: results
      kind: array
      description: Search results
      items:
        kind: object
        properties:
          - name: title
            kind: string
          - name: url
            kind: string
          - name: snippet
            kind: string
    - name: total_count
      kind: number

↑ Back to top


PowerFx Expressions

Any string in YAML can use PowerFx expressions prefixed with =.

Syntax

field: =PowerFxExpression

Environment Variables

Access environment variables with Env.VARIABLE_NAME:

model:
  id: =Env.MODEL_DEPLOYMENT_NAME
  connection:
    kind: remote
    endpoint: =Env.AZURE_ENDPOINT

Supported PowerFx Functions

  • Concatenate(): Concatenate strings
  • Arithmetic operators: +, -, *, /
  • Logical operators: And(), Or(), Not()
  • And more according to PowerFx specification

Example:

model:
  id: =Concatenate("gpt-", Env.MODEL_VERSION)
  connection:
    kind: remote
    endpoint: =Concatenate("https://", Env.REGION, ".openai.azure.com")

PowerFx Evaluation

Requirements:

  • Python ≤ 3.13 (PowerFx doesn't support 3.14+)
  • powerfx package installed

Behavior:

  • If PowerFx engine is not available, expressions are returned as literal strings
  • A warning is logged when this happens
  • The agent may fail if the literal value is invalid

↑ Back to top


Complete Examples

Example 1: Simple Agent with Azure OpenAI

kind: Prompt
name: SimpleAssistant
description: A simple AI assistant
instructions: You are a helpful assistant that answers questions concisely.

model:
  id: gpt-4
  provider: AzureOpenAI.Chat
  connection:
    kind: remote
    endpoint: https://myresource.openai.azure.com
  options:
    temperature: 0.7
    maxOutputTokens: 1000

↑ Back to Examples

Example 2: Agent with Azure AI Client and PowerFx

kind: Prompt
name: AzureAIAgent
description: Agent using Azure AI Foundry
instructions: You are an expert assistant.

model:
  id: =Env.AZURE_MODEL_ID
  provider: AzureAIClient
  connection:
    kind: remote
    endpoint: =Env.AZURE_PROJECT_ENDPOINT
  options:
    temperature: 0.8
    maxOutputTokens: 2000

↑ Back to Examples

Example 3: Agent with MCP Tool (Microsoft Learn)

kind: Prompt
name: MicrosoftLearnAgent
description: Search and retrieve Microsoft Learn documentation
instructions: You answer questions by searching the Microsoft Learn content only.

model:
  id: =Env.AZURE_FOUNDRY_PROJECT_MODEL_ID
  connection:
    kind: remote
    endpoint: =Env.AZURE_FOUNDRY_PROJECT_ENDPOINT

tools:
  - kind: mcp
    name: microsoft_learn
    description: Get information from Microsoft Learn
    url: https://learn.microsoft.com/api/mcp
    approvalMode:
      kind: never
    allowedTools:
      - microsoft_docs_search
      - microsoft_docs_fetch
      - microsoft_code_sample_search

↑ Back to Examples

Example 4: Agent with Multiple Tools

kind: Prompt
name: MultiToolAgent
description: Agent with multiple capabilities
instructions: You can search the web, analyze code, and call custom functions.

model:
  id: gpt-4
  provider: AzureOpenAI.Chat
  connection:
    kind: key
    apiKey: =Env.AZURE_OPENAI_KEY
    endpoint: =Env.AZURE_OPENAI_ENDPOINT
  options:
    temperature: 0.5

tools:
  - kind: web_search
    description: Search the web for current information

  - kind: code_interpreter
    description: Execute Python code for analysis

  - kind: function
    name: calculate_discount
    description: Calculate discount price
    parameters:
      properties:
        - name: price
          kind: number
          description: Original price
          required: true
        - name: discount_percent
          kind: number
          description: Discount percentage
          required: true
    bindings:
      - name: discount_calculator

↑ Back to Examples

Example 5: Agent with Input/Output Schema

kind: Prompt
name: StructuredAgent
description: Agent with structured input and output
instructions: Process user requests and return structured data.

model:
  id: gpt-4-turbo
  provider: OpenAI.Chat
  connection:
    kind: key
    apiKey: =Env.OPENAI_API_KEY

inputSchema:
  properties:
    - name: task
      kind: string
      description: Task to perform
      required: true
      enum: [summarize, translate, analyze]
    - name: content
      kind: string
      description: Content to process
      required: true
    - name: language
      kind: string
      description: Target language for translation
      default: en

outputSchema:
  properties:
    - name: result
      kind: string
      description: Processed result
    - name: confidence
      kind: number
      description: Confidence score 0-1
    - name: metadata
      kind: object
      properties:
        - name: processing_time
          kind: number
        - name: word_count
          kind: number

↑ Back to Examples

Example 6: Agent with File Search

kind: Prompt
name: DocumentSearchAgent
description: Search through company documents
instructions: Search and retrieve information from indexed documents. Cite sources.

model:
  id: =Env.MODEL_DEPLOYMENT
  provider: AzureAIClient
  connection:
    kind: remote
    endpoint: =Env.AZURE_AI_ENDPOINT
  options:
    temperature: 0.3
    maxOutputTokens: 4000
    topP: 0.95
    allowMultipleToolCalls: true

tools:
  - kind: file_search
    description: Search company documentation and knowledge base
    vectorStoreIds:
      - =Env.VECTOR_STORE_POLICIES
      - =Env.VECTOR_STORE_PROCEDURES
    maximumResultCount: 20
    scoreThreshold: 0.7
    ranker: semantic
    filters:
      department: engineering

↑ Back to Examples

Example 7: Agent with OpenAPI Tool

kind: Prompt
name: APIIntegrationAgent
description: Agent that can call external APIs
instructions: Use the available API to fetch and process data.

model:
  id: gpt-4
  provider: AzureOpenAI.Chat
  connection:
    kind: remote
    endpoint: =Env.AZURE_ENDPOINT

tools:
  - kind: openapi
    name: weather_api
    description: Get weather information
    specification: https://api.weather.com/openapi.json
    connection:
      kind: key
      apiKey: =Env.WEATHER_API_KEY
      endpoint: https://api.weather.com

  - kind: openapi
    name: stock_api
    description: Get stock market data
    specification: =Env.STOCK_API_SPEC_URL
    connection:
      kind: anonymous
      endpoint: https://api.stocks.com/v1

↑ Back to Examples | ↑ Back to top


Python Usage

Create Agent from YAML

from agent_framework_declarative import AgentFactory
from azure.identity.aio import DefaultAzureCredential
from pathlib import Path
import asyncio
import os

async def main():
    # Load environment variables
    from dotenv import load_dotenv
    load_dotenv()
    
    # YAML path
    yaml_path = Path(__file__).parent / "agent.yaml"
    
    # Configure project endpoint
    project_endpoint = os.getenv("AZURE_PROJECT_ENDPOINT")
    
    # Create credentials
    credential = DefaultAzureCredential()
    
    # Create factory
    factory = AgentFactory(
        client_kwargs={
            "async_credential": credential,
            "project_endpoint": project_endpoint
        }
    )
    
    # Create agent from YAML
    agent = factory.create_agent_from_yaml_path(yaml_path)
    
    # Use the agent
    async with agent:
        response = await agent.run("Your question here")
        print(response.text)

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

↑ Back to Python Usage

With Bindings (Python Functions)

def calculate_discount(price: float, discount_percent: float) -> float:
    """Calculate discounted price."""
    return price * (1 - discount_percent / 100)

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

factory = AgentFactory(
    bindings={
        "discount_calculator": calculate_discount,
        "weather_func": get_weather
    },
    client_kwargs={
        "async_credential": credential,
        "project_endpoint": project_endpoint
    }
)

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

↑ Back to Python Usage

With Connections

from azure.identity import DefaultAzureCredential

my_credential = DefaultAzureCredential()

factory = AgentFactory(
    connections={
        "azure_connection": my_credential,
        "custom_api": {"api_key": "secret123"}
    }
)

↑ Back to Python Usage

From YAML String

yaml_content = """
kind: Prompt
name: QuickAgent
description: Quick test agent
instructions: Be helpful

model:
  id: gpt-4
  connection:
    kind: remote
    endpoint: https://myendpoint.com
"""

agent = factory.create_agent_from_yaml(yaml_content)

↑ Back to Python Usage | ↑ Back to top


Validation and Errors

Common Errors

1. DeclarativeLoaderError

YAML doesn't represent a PromptAgent

Only yaml definitions for a PromptAgent are supported for agent creation.

2. ProviderLookupError

Unknown provider

Unsupported provider type: UnknownProvider

3. ValueError

3. ValueError

Missing required fields

Missing required field: model.id
Missing required field: kind

4. PowerFx Evaluation Warnings

When PowerFx engine is not available or Python > 3.13:

PowerFx engine is not available. PowerFx expressions will be returned as is.

↑ Back to Validation

PowerFx Validation

PowerFx expressions are evaluated during agent creation:

  1. Valid Expression:

    endpoint: =Env.AZURE_ENDPOINT

    ✅ Evaluates to value from environment variable

  2. Invalid Expression:

    endpoint: =InvalidFunction(Env.VAR)

    ❌ PowerFx evaluation error

  3. Missing Variable:

    endpoint: =Env.NONEXISTENT_VAR

    ⚠️ Returns empty string or default value

↑ Back to Validation

Required Fields

Agent Level:

  • kind - Must be "Prompt" or "Agent"
  • name - Agent name

Model Level:

  • model.id - Model ID or deployment name

Connection Level (depends on kind):

  • remote: endpoint
  • key: apiKey or key
  • reference: name
  • anonymous: endpoint

Tool Level (depends on kind):

  • function: name, description
  • mcp: name, url
  • openapi: name, specification
  • custom: name

↑ Back to Validation | ↑ Back to top


References

Official Documentation

Source Code

Related Packages

  • agent-framework - Core framework
  • agent-framework-core - Core models and agents
  • agent-framework-azure-ai - Azure AI integration
  • agent-framework-declarative - Declarative YAML support
  • agent-framework-devui - Development UI for testing agents
  • powerfx - PowerFx expression evaluation

Model Context Protocol (MCP)


Changelog

Version 1.0 (December 2, 2025)

  • Initial comprehensive documentation
  • All agent types, connections, tools documented
  • Complete examples for common scenarios
  • Python usage patterns
  • Validation and error reference
  • Based on official source code analysis

Last Updated: December 2, 2025
Framework Version: agent-framework-declarative 1.0.0b251120

↑ Back to top

@frdeange frdeange closed this Dec 2, 2025
@frdeange frdeange deleted the patch-1 branch December 2, 2025 10:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants