Overview
AutoGen for .NET provides two approaches to function calling:- Source Generator - Compile-time code generation with the
[Function]attribute - Microsoft.Extensions.AI - Runtime function creation with
AIFunctionFactory
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:
- Function Contract - Schema definition from method signature and XML docs
- Function Wrapper - Type-safe deserialization and invocation
Complex Example
Comprehensive example with multiple function types:Microsoft.Extensions.AI Approach
UseAIFunctionFactory for runtime function creation:
Function Requirements
Return Type
Must returnTask<string>:
Parameter Types
Use primitive types and their arrays for best results:XML Documentation
Provide descriptions via XML comments:Handling Function Results
Tool Call Messages
Function calls returnToolCallAggregateMessage:
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
Function Design
Function Design
- 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
Parameter Guidelines
Parameter Guidelines
- 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
Performance
Performance
- Cache expensive computations
- Use async/await properly
- Avoid long-running operations
- Implement timeouts for external calls
- Consider rate limiting
Testing
Testing
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