Automatic Function Calling
The simplest way to use function calling is to pass Python functions directly. The SDK will automatically call the functions and return the results to the model.- Recognize when it needs to call a function
- Extract the necessary arguments
- Call the function
- Use the result to generate a final response
Disabling Automatic Function Calling
If you want to manually handle function calls, disable automatic function calling:Manual Function Declaration
For more control, you can manually declare functions usingFunctionDeclaration:
Invoking Functions Manually
After receiving a function call from the model, you can invoke the function and pass the result back:Tool Configuration
ANY Mode
If you configure function calling mode toANY, the model will always return function call parts:
Limiting Automatic Function Calls
You can limit the number of automatic function call turns. For example, to allow only 1 turn of automatic function calling:Best Practices
- Clear descriptions: Write detailed docstrings and descriptions to help the model understand when and how to use your functions
- Type hints: Use Python type hints for better function declaration generation
- Error handling: Handle exceptions gracefully and pass error information back to the model
- Stateless functions: Design functions to be stateless when possible for more predictable behavior