Skip to main content

Overview

AutoGen for .NET provides two approaches to function calling:
  1. Source Generator - Compile-time code generation with the [Function] attribute
  2. Microsoft.Extensions.AI - Runtime function creation with AIFunctionFactory
Both approaches enable agents to call C# functions based on natural language requests.

Source Generator Approach

The recommended approach using AutoGen’s source generator for type safety and performance.

Installation

Basic Example

1

Define functions with [Function] attribute

The class must be partial for the source generator to add generated code.
2

Register functions with agent

3

Use the agent

How Source Generation Works

When you mark a method with [Function], the source generator creates:
  1. Function Contract - Schema definition from method signature and XML docs
  2. Function Wrapper - Type-safe deserialization and invocation

Complex Example

Comprehensive example with multiple function types:

Microsoft.Extensions.AI Approach

Use AIFunctionFactory for runtime function creation:

Function Requirements

Functions decorated with [Function] must follow these rules:

Return Type

Must return Task<string>:

Parameter Types

Use primitive types and their arrays for best results:

XML Documentation

Provide descriptions via XML comments:
The LLM uses these descriptions to understand when and how to call functions.

Handling Function Results

Tool Call Messages

Function calls return ToolCallAggregateMessage:

Sending Results Back to LLM

Send function results back for natural language response:

Advanced Patterns

Multiple Tool Classes

Organize functions into logical groups:

Stateful Functions

Maintain state across function calls:

Async Operations

Handle async operations properly:

Error Handling

Handle errors gracefully in functions:

Best Practices

  • Keep functions focused on a single task
  • Use descriptive names that indicate the action
  • Provide clear XML documentation
  • Return human-readable strings
  • Handle errors gracefully
  • Use primitive types when possible
  • Limit the number of parameters (5 or fewer)
  • Make parameters required unless truly optional
  • Validate inputs and return error messages
  • Use meaningful parameter names
  • Cache expensive computations
  • Use async/await properly
  • Avoid long-running operations
  • Implement timeouts for external calls
  • Consider rate limiting

Next Steps

Code Execution

Execute code snippets dynamically

Group Chat

Use functions in multi-agent conversations

OpenAI Integration

Learn about OpenAI-specific features

Examples

See complete function calling examples