This guide explains how to set up and use custom function calling with VAPI to enable your AI assistant to interact with external APIs and services.
The function calling system allows your VAPI assistant to:
- Make HTTP requests to external APIs
- Get real-time weather information
- Search the web for information
- Access user profile data
- Verify user PIN codes
- Execute custom business logic
├── src/
│ ├── config/
│ │ ├── tools.js # Function definitions and handlers
│ │ └── vapi.js # VAPI configuration with tools
│ └── stores/
│ └── voice.js # Voice store with function call handling
├── server/
│ ├── index.js # Express.js server for function handling
│ ├── package.json # Server dependencies
│ └── .env.example # Server environment variables
└── FUNCTION_CALLING_SETUP.md # This guide
cd server
npm installMain Application (.env):
# Function Server Configuration
VITE_FUNCTION_SERVER_URL=http://localhost:3001/api
VITE_FUNCTION_SERVER_SECRET=your-secret-key
# External API Keys (Optional)
VITE_OPENWEATHER_API_KEY=your_openweather_api_keyServer Configuration (server/.env):
PORT=3001
VITE_FUNCTION_SERVER_SECRET=your-secret-key
OPENWEATHER_API_KEY=your_openweather_api_keycd server
npm run devnpm run devMake HTTP requests to any external API.
Parameters:
url(required): The API endpoint URLmethod(optional): HTTP method (GET, POST, PUT, DELETE, PATCH)headers(optional): HTTP headers objectbody(optional): Request body for POST/PUT/PATCHtimeout(optional): Request timeout in milliseconds
Example Usage:
// The AI can call this function like:
"Can you fetch data from https://api.example.com/users"Get current weather information for any location.
Parameters:
location(required): City and country (e.g., "London, UK")units(optional): Temperature units (metric, imperial, kelvin)
Example Usage:
// User can ask:
"What's the weather like in New York?"
"Tell me the temperature in Tokyo in Celsius"Search the web for information.
Parameters:
query(required): Search query stringlimit(optional): Maximum number of results (1-10)
Example Usage:
// User can ask:
"Search for the latest news about AI"
"Find information about Vue.js 3"Get current user profile information.
Parameters:
include_pin_status(optional): Include PIN status information
Example Usage:
// User can ask:
"Show me my profile information"
"Do I have a PIN set up?"Verify a user's PIN code.
Parameters:
pin(required): 6-digit PIN code to verify
Example Usage:
// User can ask:
"Verify my PIN: 123456"
"Check if my PIN 654321 is correct"Add your function to src/config/tools.js:
{
type: 'function',
function: {
name: 'your_custom_function',
description: 'Description of what your function does',
parameters: {
type: 'object',
properties: {
param1: {
type: 'string',
description: 'Description of parameter 1'
},
param2: {
type: 'number',
description: 'Description of parameter 2',
default: 10
}
},
required: ['param1']
}
}
}Add the handler to the FunctionCallHandler class:
async handleYourCustomFunction({ param1, param2 = 10 }) {
try {
// Your custom logic here
const result = await someApiCall(param1, param2)
return {
success: true,
data: result,
timestamp: new Date().toISOString()
}
} catch (error) {
return {
success: false,
error: error.message,
timestamp: new Date().toISOString()
}
}
}If you need server-side processing, add an endpoint to server/index.js:
app.post('/api/your-custom-endpoint', verifyVapiRequest, async (req, res) => {
const { param1, param2 } = req.body
const result = await handleYourCustomFunction({ param1, param2 })
res.json(result)
})- All function calls are authenticated using the
VITE_FUNCTION_SERVER_SECRET - Server verifies the secret before processing requests
- User authentication tokens are passed for user-specific operations
- All function parameters are validated according to their schemas
- Server-side validation prevents malicious inputs
- Rate limiting can be implemented for production use
- All functions return structured error responses
- Sensitive information is not exposed in error messages
- Timeouts prevent hanging requests
Function calls are logged in the browser console:
console.log('Function call received:', functionCall)
console.log('Function call result sent:', result)Function calls appear in the conversation history with special indicators:
- 🔧 Function execution
- 📊 Function results
- ⚙️ System messages
The Express.js server logs all function calls and their results.
- Sign up at OpenWeatherMap
- Get your API key
- Add it to your environment variables:
VITE_OPENWEATHER_API_KEY=your_api_key OPENWEATHER_API_KEY=your_api_key
Integrate with your preferred search API:
- Google Custom Search API
- Bing Search API
- DuckDuckGo API
- Custom search implementation
Connect to your database for user-specific functions:
- Supabase (already integrated)
- PostgreSQL
- MongoDB
- Firebase
Set all required environment variables in your production environment.
Deploy the Express.js server to:
- Heroku
- Vercel
- Railway
- AWS Lambda
- Your own VPS
Update CORS settings for your production domains:
app.use(cors({
origin: ['https://yourdomain.com', 'https://www.yourdomain.com'],
credentials: true
}))Implement rate limiting for production:
const rateLimit = require('express-rate-limit')
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
})
app.use('/api/', limiter)-
Function calls not working
- Check if the function server is running
- Verify environment variables are set correctly
- Check browser console for errors
-
Authentication errors
- Ensure
VITE_FUNCTION_SERVER_SECRETmatches on both client and server - Check if the secret is properly set in environment variables
- Ensure
-
API rate limits
- Implement proper rate limiting
- Cache API responses when appropriate
- Use API keys with sufficient quotas
-
CORS errors
- Update CORS configuration in the server
- Ensure the server URL is correct in client configuration
Enable debug mode by setting:
DEBUG=trueThis will provide more detailed logging for troubleshooting.
To add new functions or improve existing ones:
- Fork the repository
- Create a feature branch
- Add your function definition and handler
- Test thoroughly
- Submit a pull request
This function calling system is part of the Vue Supabase VAPI application and follows the same license terms.