Introduction

AI Agents enable applications to perform tasks autonomously by understanding user requests, making decisions, invoking tools, and generating responses. With Azure AI Agents, developers can build intelligent applications that interact with databases, APIs, and enterprise systems while leveraging Azure OpenAI models.

This article provides a complete step-by-step guide to integrating Azure AI Agents into Azure Functions using .NET.

Overview of Azure AI Agents

Azure AI Agents provide:

  • Conversational AI capabilities
  • Tool calling and function execution
  • Multi-turn conversations
  • Integration with Azure OpenAI
  • Enterprise-grade security
  • Support for custom business workflows

Why Use Azure Functions?

Azure Functions offers:

  • Serverless architecture
  • Automatic scaling
  • Reduced infrastructure management
  • Pay-per-execution model
  • Easy integration with Azure Services

Combining Azure Functions with Azure AI Agents creates a powerful architecture for building intelligent APIs.

Prerequisites

Before starting, ensure you have:

✔ Azure Subscription

✔ Azure AI Foundry Project

✔ Azure AI Agent Created

✔ Azure OpenAI Deployment

✔ .NET 8 SDK or Later

✔ Visual Studio 2022

✔ Azure Functions Core Tools

✔ Azure Function App

✔ Basic Knowledge of C#

Step 1: Create an Azure AI Agent

  1. Open Azure AI Foundry.
  2. Create a Project.
  3. Add an Azure OpenAI Model.
  4. Navigate to Agents.
  5. Create a New Agent.
  6. Configure:
    • Agent Name
    • Instructions
    • Model
    • Tools
  7. Save the Agent.
  8. Copy the Agent ID.

Example

agent_abc123xyz789

Step 2: Create an Azure Function Project

Create a new Azure Function:

Bash
func init AiAgentFunction --worker-runtime dotnet-isolated
Bash
cd AiAgentFunction
Bash
func new --template "HTTP Trigger" --name AskAgent

Step 3: Install Required Packages

Install Azure AI packages:

Bash
dotnet add package Azure.AI.Projects
Bash
dotnet add package Azure.Identity

Step 4: Configure Application Settings

Add the following configuration:

JSON
{
  "AI_PROJECT_ENDPOINT": "https://your-project.services.ai.azure.com/api/projects/your-project",
  "AGENT_ID": "agent_abc123xyz789"
}

Store these values securely using:

  • Azure Key Vault
  • Azure Function App Settings

Step 5: Create AI Project Client

Create the client:

C#
using Azure.AI.Projects;
using Azure.Identity;
var projectClient = new AIProjectClient(
    new Uri(Environment.GetEnvironmentVariable("AI_PROJECT_ENDPOINT")),
    new DefaultAzureCredential());

Step 6: Implement Azure Function

Create the HTTP-triggered Azure Function:

C#
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using System.Net;
public class AskAgent
{
    private readonly AIProjectClient _projectClient;
    public AskAgent()
    {
        _projectClient = new AIProjectClient(
            new Uri(Environment.GetEnvironmentVariable("AI_PROJECT_ENDPOINT")),
            new DefaultAzureCredential());
    }
    [Function("AskAgent")]
    public async Task<HttpResponseData> Run(
        [HttpTrigger(AuthorizationLevel.Function,
        "post")]
        HttpRequestData req)
    {
        var question =
            await new StreamReader(req.Body)
            .ReadToEndAsync();
        var agentClient =
            _projectClient.GetAgentsClient();
        var thread =
            await agentClient.CreateThreadAsync();
        await agentClient.CreateMessageAsync(
            thread.Value.Id,
            MessageRole.User,
            question);
        var run =
            await agentClient.CreateRunAsync(
                thread.Value.Id,
                Environment.GetEnvironmentVariable("AGENT_ID"));
        while (run.Value.Status == RunStatus.Queued ||
              run.Value.Status == RunStatus.InProgress)
        {
            await Task.Delay(1000);
            run = await agentClient.GetRunAsync(
                thread.Value.Id,
                run.Value.Id);
        }
        string responseText = "";
        await foreach (var msg in
            agentClient.GetMessagesAsync(thread.Value.Id))
        {
            if (msg.Role == MessageRole.Agent)
            {
                responseText =
                    msg.ContentItems[0].ToString();
                break;
            }
        }
        var response =
            req.CreateResponse(HttpStatusCode.OK);
        await response.WriteStringAsync(responseText);
        return response;
    }
}

Step 7: Test the Function

Request:

Code
POST https://localhost:7071/api/AskAgent

Body:

Code
What is Generative AI?

Response:

JSON
{
  "answer": "Generative AI creates new content such as text, images, code, and other media using AI models."
}

Step 8: Add Custom Tools

Agents become more powerful when connected to business functions.

Example Tool:

C#
public interface IOrderService
{
    Task<OrderStatus> GetOrderStatusAsync(
        string orderId);
}

Example User Request:

Code
Where is my order 12345?

Agent Workflow:

  1. Understand the request.
  2. Extract order ID.
  3. Call GetOrderStatusAsync().
  4. Generate a natural language response.
  5. Return the result.

Example Response:

Code
Your order 12345 was shipped on 24 October and is expected to arrive tomorrow.

Real-World Use Cases

Customer Support Agent

  • Track Orders
  • Return Requests
  • Customer Queries

HR Assistant

  • Leave Balances
  • HR Policies
  • Employee Information

IT Support Agent

  • Password Resets
  • Ticket Creation
  • Knowledge Base Search

Operations Assistant

  • Inventory Lookup
  • Shipment Tracking
  • Vendor Information

Best Practices

  • Use Managed Identity whenever possible.
  • Store secrets in Azure Key Vault.
  • Keep system instructions focused.
  • Log Agent interactions.
  • Implement proper error handling.
  • Monitor Agent performance using Application Insights.
  • Use separate environments for Development and Production.
  • Validate user input before sending requests to the Agent.

Common Challenges

Issue Solution
Authentication Failure Verify Managed Identity permissions
Agent Not Responding Check Agent ID and Project Endpoint
Tool Calls Fail Validate tool configuration
Long Response Times Optimize prompts and tools
Quota Errors Verify Azure OpenAI limits

Conclusion

Azure AI Agents combined with Azure Functions provide a scalable and serverless architecture for building intelligent applications. By exposing AI Agents through HTTP-triggered Azure Functions, developers can create APIs that understand user intent, execute business operations, and generate natural language responses.

This approach is ideal for customer support systems, enterprise assistants, workflow automation, and modern AI-powered applications.