Trigger tool when before attending a call
# support
r
For inbound calls, I’d like to fetch some customer data from my database before the call is connected to the voice agent. Basically, I want to call an API pre-call to pull customer-specific data (like name, plan, status, etc.) based on the caller’s number or some identifier. What I’m trying to achieve: A customer calls in (inbound call) Before the agent picks up, I want to hit my API using the caller ID (or similar) Use that data to personalize the conversation or context for the AI agent
v
Hi there! 👋 I wasn't able to find specific information about triggering a tool before a call is connected in Vapi. However, I can definitely help with several approaches to achieve what you're looking for! Here are some methods to use the caller ID to trigger an API call and fetch customer data: ### 1. Using SIP Headers You can pass a unique identifier via custom SIP headers during the initial call to Vapi. According to [information I found](https://discord.com/channels/1211482211119796234/1211483291191083018/threads/1329106554041012265), you can pass something like
X-Call-ID: <unique-id>
in the SIP headers for the first call leg, which can then be used to associate calls and trigger your API. ### 2. Using Twilio as an Intermediary A practical approach is to use Twilio to intercept calls before they reach Vapi:
Copy code
It is possible to accomplish this without importing the phone number to VAPI. Twilio will send a request to your server URL, after which you will need to forward the calls to the VAPI API
There's a reference implementation available at [this GitHub repo](https://github.com/VapiAI/advanced-concepts-phone-call-provider-bypass) that shows how to set this up. ### 3. Personalizing the Conversation with the Data Once you've fetched the customer data, you can personalize the conversation in several ways: 1. **Inject data into the system message**:
Copy code
json
{
  "assistant": {
    "model": {
      "provider": "openai",
      "model": "gpt-4",
      "messages": [
        {
          "role": "system",
          "content": "You're a support assistant. Customer info: [YOUR FETCHED DATA HERE]"
        }
      ]
    }
  }
}
2. **Using dynamic variables**:
Copy code
json
{
  "variableValues": {
    "name": "CustomerNameFromAPI",
    "plan": "CustomerPlanFromAPI"
  }
}
3. **Setting the customer field when creating a call**: ```javascript const call = await vapiClient.calls.create({ phoneNumberId: "your-phone-number-id", customer: {
number: "+1234567890", name: "John Doe", metadata: { plan: "premium", status: "active" } }, assistant: { // Your assistant configuration } }); ``` Would you like me to elaborate on any of these approaches or provide more details on how to implement them? Sources: - [Discord Thread about SIP Headers](https://discord.com/channels/1211482211119796234/1211483291191083018/threads/1329106554041012265) - [Discord Thread about Twilio Forwarding](https://discord.com/channels/1211482211119796234/1211483291191083018/threads/1334941334368419850) - [Discord Thread about Dynamic Variables](https://discord.com/channels/1211482211119796234/1211483291191083018/threads/1335054553250533439) - [Discord Thread about Customer Field](https://discord.com/channels/1211482211119796234/1211483291191083018/threads/1341835905656291369) - [Docs about Personalizing Conversations](https://docs.vapi.ai/examples/inbound-support)
s
To fetch customer data before an inbound call is connected to your VAPI voice agent, you'll need to implement a webhook that: 1. Receives an "assistant-request" webhook when a call comes in 2. Uses the caller's number to fetch customer data from your database 3. Returns the data as part of the assistant configuration or variables
### Step 1: Set up a Server URL in VAPI Configure a webhook URL in VAPI where your server will receive inbound call notifications: 1. Go to your VAPI dashboard 2. Set the Server URL at one of these levels (in order of precedence): - Assistant level: In your assistant settings - Phone Number level: In your phone number settings - Organization level: In your organization settings ### Step 2: Create a Webhook Endpoint Create an endpoint on your server to handle the "assistant-request" webhook:
Copy code
javascript
// Example with Express.js
const express = require('express');
const app = express();
app.use(express.json());

app.post('/vapi-webhook', async (req, res) => {
  // The webhook payload contains information about the incoming call
  const { message } = req.body;
  
  if (message.type === 'assistant-request') {
    try {
      // Extract the caller's phone number
      const callerNumber = message.customer?.number;
      
      if (!callerNumber) {
        return res.json({
          messageResponse: {
            assistantId: "YOUR_ASSISTANT_ID", // Your existing assistant ID
            error: null
          }
        });
      }
      
      // Fetch customer data from your database using the caller's number
      const customerData = await fetchCustomerData(callerNumber);
      
      // Return the assistant configuration with customer data as variables
      return res.json({
        messageResponse: {
          assistantId: "YOUR_ASSISTANT_ID", // Your existing assistant ID
          assistantOverrides: {
            variableValues: {
              // Add all your fetched customer data as variables
              customer_name: customerData.name,
              customer_plan: customerData.plan,
              customer_status: customerData.status,
              // Add any other relevant customer data
              is_premium: customerData.isPremium,
              last_interaction: customerData.lastInteraction
            }
          }
        }
      });
    } catch (error) {
      console.error('Error fetching customer data:', error);
      // If there's an error, still proceed with the call but without custom data
      return res.json({
        messageResponse: {
          assistantId: "YOUR_ASSISTANT_ID"
        }
      });
    }
  }
  
  // Handle other webhook types if needed
  res.json({ messageResponse: {} });
});

// Function to fetch customer data from your database
async function fetchCustomerData(phoneNumber) {
  // Implement your database query here
  // Return customer data object
}

app.listen(3000, () => {
  console.log('Webhook server running on port 3000');
});
### Step 3: Update Your Assistant Prompt Make sure your assistant's prompt utilizes the customer data variables you're providing:
Copy code
You are a helpful customer service agent for {{company_name}}.

Customer Information:
- Name: {{customer_name}}
- Plan: {{customer_plan}}
- Status: {{customer_status}}
- Premium Customer: {{is_premium}}
- Last Interaction: {{last_interaction}}

Use this information to provide personalized service, but don't explicitly tell 
the customer you have this data unless they ask for confirmation.
### Step 4: Deploy Your Webhook 1. Deploy your webhook to a publicly accessible URL 2. Ensure it has HTTPS (required by VAPI) 3. Update your VAPI configuration with this URL ## How This Works: 1. A customer calls your VAPI phone number 2. VAPI sends an "assistant-request" webhook to your server 3. Your server extracts the caller's phone number from the webhook 4. Your server queries your database for customer information 5. Your server returns this data as part of the assistant configuration 6. VAPI uses this configuration and data when connecting the call to the AI agent 7. The AI agent has access to the customer data in its variables This approach allows you to provide personalized context to the AI agent without requiring the caller to identify themselves again, creating a much smoother customer experience.
17 Views