| |

Microsoft Agent Framework: Extending Agent Intelligence Using Function Tools

In an earlier blog post, we looked at how you can manage conversations using threads with the Microsoft Agent Framework.

In this post, we look at how you can extend an AI agents intelligence using function tools.

The following is covered:

  • What is a function tool
  • What can you do with function tools
  • The anatomy of a function tool
  • How to create an agent with a function tool
  • Extending an ai agent to use function tools

 

A video demo is also included.  Let’s dig in.

~

What Is a Function Tool

A function tool is code that your agent can use at run-time when required.  They are like plugins and native functions in Semantic Kernel.

Learn more about plugins and native functions in one of my earlier blog posts.

Any method you write in C# can be repurposed as a function tool.

~

What Can You Do with Function Tools

Function tools let you augment your AI agent’s intelligence.  For example, LLMs have a training cut-off date and no access to your internal or current data.

Implementing function tools lets you extend the capabilities and data available to your AI agent.

At runtime, your AI agent detects which function tool is best suited for the task at hand.

Function tools, when paired with AI, let your agent infer human intent and automatically map this to the code best suited for the request at hand.

~

Anatomy of a Function Tool

Any regular method can be a function tool.  Annotating the method with human readable descriptions helps your ai agent determine which function tool to use at run-time to complete a task.

You can also decorate parameter names with description tags to help the agent map incoming data to parameters.

For example, an AI agent may be responsible for booking appointments.

A function tool that handles this could be written like the following:

[Description("Determines the next available date for a booking")]
public DateTime GetNextAvailableDate([Description("The date to start  searching from")] DateTime startDate)
{
  // get the next available date
  return _available.FirstOrDefault(d => d > startDate);
}

 

In the above example, the variable _available contains a list of available dates/times for bookings.

~

How to Create an Agent with a Function Tool

Function tools are just custom code that you want the agent to be able to call when needed.

You can turn any C# method into a function tool, by using the AIFunctionFactory.Create method to create an AIFunction instance from the method.

This method lives in the Microsoft.Extensions.AI namespace.

The bare bones code:

AIAgent agent = new OpenAIClient(apiKey)
 .GetChatClient(model)
 .CreateAIAgent(instructions: "You are a personal trainer. " +
 "You can only answer questions related to health, fitness and 5x5 stronglift.",
 name: "IronMind AI",null,
 tools: [AIFunctionFactory.Create(BookingService.GetNextAvailableDate)]
);

 

In the code above, we are making a single function tool available to the agent BookingService.GetNextAvailableDate to our Iron Mind AI personal trainer agent.

One thing to notice is the use of static methods the .Create method.

This is fine if you don’t have user specific or state data to pass through into the service class.

In the real-world, you may want to consider instance methods to pass relevant data in via instance methods.

For example:

public BookingService(string userId, ILogger logger, DbContext db)
{
  _userId = userId;
  _logger = logger;
  _db = db;
}

 

With the theory out of the way, lets extend our existing Iron Mind AI agent.

~

An Example – Extending Iron Mind AI

In this example, we extend the Iron Mind AI personal trainer agent and give it access to 4 tools:

  • Get next available date for a booking
  • Make a booking
  • Cancel a booking
  • Get list of existing bookings

 

Each tool is self-explanatory in terms of capabilities.  Available dates will be stored in a variable _available.  Booked dates will be stored a variable _ booked.

Both variables are of List<DateTime>.

In the interests of code reusability, the tools have been encapsulated within a BookingService class.  This contains each of the following function tools:

public class BookingService
{
    // a list of available dates the user can book
    private static List<DateTime> _available = new List<DateTime>
    {
        // add dates for the next 9 days, ignore the time part
        new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, 0, 0, 0),
        new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 2, 0, 0, 0),
        new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 3, 0, 0, 0),
        new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 4, 0, 0, 0),
        new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 5, 0, 0, 0)
    };

    // a list of booked dates
    private static List<DateTime> _booked = new List<DateTime>();

    [Description("Determines the next available date for a booking")]
    public static DateTime GetNextAvailableDate([Description("The date to start searching from")] DateTime startDate)
    {
        // get the next available date
        return _available.FirstOrDefault(d => d > startDate);
    }

    [Description("Allows the user to make a booking.")]
    public static string BookAppointment([Description("The date of the appointment")] DateTime date)
    {
        // check if the date is available, ignore the time part
        date = date.Date;
        if (_available.Contains(date))
        {
            // remove the date from the available list
            _available.Remove(date);
            // add the date to the booked list
            _booked.Add(date);
            // return a confirmation message
            return $"Appointment booked for {date.ToShortDateString()}";
        }
        else
        {
            // return an error message
            return "The selected date is not available";
        }
    }

    [Description("Cancels a booking.")]
    public static string CancelAppointment([Description("The date of the appointment to cancel")] DateTime date)
    {
        // check if the date is booked
        if (_booked.Contains(date))
        {
            // remove the date from the booked list
            _booked.Remove(date);
            // add the date back to the available list
            _available.Add(date);
            // return a confirmation message
            return $"Appointment on {date.ToShortDateString()} cancelled";
        }
        else
        {
            // return an error message
            return "The selected date is not booked";
        }
    }

    // list all booked appointments
    [Description("Lists all booked appointments.")]
    public static List<DateTime> ListBookedAppointments()
    {
        return _booked;
    }
}

 

In above code, we have a BookingService class.  Each method is decorated with description parameters to advertise to the agent:

  • The purpose of the method
  • The purpose of any parameters being used in a method

 

We make each of these static methods available to our agent by using the AIFunctionFactory.Create method:

AIAgent agent = new OpenAIClient(apiKey)
    .GetChatClient(model)
    .CreateAIAgent(
        instructions: "You are a personal trainer. " +
            "You can only answer questions related to health, fitness and 5x5 stronglift. " +
            "You also have access to 4 booking related tools",
        name: "IronMind AI",
        null,
        tools: [
            AIFunctionFactory.Create(BookingService.GetNextAvailableDate),
            AIFunctionFactory.Create(BookingService.CancelAppointment),
            AIFunctionFactory.Create(BookingService.BookAppointment),
            AIFunctionFactory.Create(BookingService.ListBookedAppointments)
        ]
    );

 

The instructions property as been adjusted in this iteration of the Iron Mind AI agent.

We add the string ‘You also have access to 4 booking related tools” – this lets a user ask what this agent can do for them.

~

Testing Iron Mind AI Function Tools

At this point, everything is in place.  We can interact with the agent using natural language.  We’ll test the ai agent automatically maps human intent to the relevant function tool and performs the task.

 

First, we ask the agent what it can do:

Perfect.

Next, we ask the agent when the next available appointment is.

The agent correctly maps the human request to the method GetNextAvailableDate and returns the next available date:

We can simply supply “yes”.  Under the hood, the agent will add this to it’s internal booking collection:

We can ask the agent to list all appointments.  It returns the appointment we just added:

We can ask the agent to cancel the appointment.  The ai agent informs us that we only have 1 appointment to cancel.  We confirm that we want to cancel it:

The ai agent confirms that our appointment is now cancelled:

We can ask our ai agent to list all appointments to verify it has been cancelled.  No appointments are fetched:

Perfect.  We’ve successfully tested each function tool.

More importantly, we’ve seen that we haven’t had to write any code to map human intent to the relevant function tool.  The Microsoft Agent Framework has done this for us automatically.

This makes it easier to build dynamic agents without hard coding too many rules.

~

Demo

In this demo, you can see the above in action.  We interact with the AI agent and work run each of the function tools using natural language.

~

Summary

In this blog post, we’ve introduced function tools.  We’ve look at what they are, what you can do with them, and how to create an AI agent that has access to function tools.

We saw how to extend or Iron Mind AI agent and give it access to its own set of tools to perform a variety of tasks.

In the next blog post, we’ll dive deeper into function tools. Specifically, we’ll see how agents themselves can also be used as function tools.

Stay tuned.

~

Like What You’ve Read?

Enjoy what you’ve read, have questions about this content, or would like to see another topic? Drop me a note below.

You can schedule a call using my Calendly link to discuss consulting and development services.

~

Further Reading and Resources

You can find more blogs in this series here and other resources to help you on your agentic AI journey.

More from this series

Microsoft Learn

~

 

JOIN MY EXCLUSIVE EMAIL LIST
Get the latest content and code from the blog posts!
I respect your privacy. No spam. Ever.

Similar Posts