Code Tool

Execute custom TypeScript code directly within your assistant without setting up a server.

The Code Tool allows you to write and execute custom TypeScript code that runs when your assistant needs to perform a specific action. Unlike custom function tools that require you to host a server, code tools run directly on Vapi’s infrastructure.

When to Use Code Tools

Code tools are ideal when you need to:

  • Transform or process data during a conversation
  • Make HTTP requests to external APIs
  • Perform calculations or business logic
  • Avoid the overhead of setting up and maintaining a webhook server

Creating a Code Tool

Step 1: Navigate to the Tools Section

  1. Open your Vapi Dashboard
  2. Click Tools in the left sidebar
  3. Click Create Tool and select Code

Step 2: Configure Your Code Tool

The dashboard provides a visual interface to configure your code tool:

  1. Tool Name: A descriptive identifier (e.g., get_customer_data)
  2. Description: Explain what your tool does - this helps the AI understand when to use it
  3. TypeScript Code: Write the code that will execute when the tool is called
  4. Parameters: Define the input parameters your code expects
  5. Environment Variables: Store sensitive values like API keys securely

Step 3: Write Your Code

Your code has access to two objects:

  • args: Contains the parameters passed by the assistant
  • env: Contains your environment variables
1// Access parameters from the assistant
2const { customerId, orderType } = args;
3
4// Access secure environment variables
5const { API_KEY, API_URL } = env;
6
7// Make HTTP requests to external services
8const response = await fetch(`${API_URL}/customers/${customerId}`, {
9 headers: {
10 'Authorization': `Bearer ${API_KEY}`,
11 'Content-Type': 'application/json'
12 }
13});
14
15const customer = await response.json();
16
17// Return data to the assistant
18return {
19 name: customer.name,
20 email: customer.email,
21 memberSince: customer.createdAt
22};

Your code runs in an isolated environment with a configurable timeout (default: 10 seconds, max: 60 seconds).

Example: Customer Lookup Tool

Let’s create a tool that looks up customer information:

Configuration

FieldValue
Tool Nameget_customer
DescriptionRetrieves customer information by their ID

Parameters

NameTypeRequiredDescription
customerIdstringYesThe unique customer identifier

Environment Variables

NameValue
API_KEYYour API key
API_BASE_URLhttps://api.yourservice.com

Code

1const { customerId } = args;
2const { API_KEY, API_BASE_URL } = env;
3
4const response = await fetch(`${API_BASE_URL}/customers/${customerId}`, {
5 headers: {
6 'Authorization': `Bearer ${API_KEY}`
7 }
8});
9
10if (!response.ok) {
11 return { error: 'Customer not found' };
12}
13
14const customer = await response.json();
15
16return {
17 name: customer.name,
18 email: customer.email,
19 plan: customer.subscription.plan,
20 status: customer.status
21};

Example: Order Processing Tool

A more complex example that processes an order:

Parameters

NameTypeRequiredDescription
itemsarrayYesArray of item objects with id and quantity
customerIdstringYesThe customer placing the order
shippingAddressstringNoDelivery address

Code

1const { items, customerId, shippingAddress } = args;
2const { ORDER_API_KEY, ORDER_API_URL } = env;
3
4// Calculate total
5let total = 0;
6const itemDetails = [];
7
8for (const item of items) {
9 const priceResponse = await fetch(`${ORDER_API_URL}/products/${item.id}`);
10 const product = await priceResponse.json();
11
12 const itemTotal = product.price * item.quantity;
13 total += itemTotal;
14
15 itemDetails.push({
16 name: product.name,
17 quantity: item.quantity,
18 price: product.price,
19 subtotal: itemTotal
20 });
21}
22
23// Create the order
24const orderResponse = await fetch(`${ORDER_API_URL}/orders`, {
25 method: 'POST',
26 headers: {
27 'Authorization': `Bearer ${ORDER_API_KEY}`,
28 'Content-Type': 'application/json'
29 },
30 body: JSON.stringify({
31 customerId,
32 items: itemDetails,
33 total,
34 shippingAddress
35 })
36});
37
38const order = await orderResponse.json();
39
40return {
41 orderId: order.id,
42 total: `$${total.toFixed(2)}`,
43 estimatedDelivery: order.estimatedDelivery,
44 items: itemDetails.map(i => `${i.quantity}x ${i.name}`)
45};

Using Code Tools in Assistants

Once created, add your code tool to any assistant:

In the Dashboard

  1. Go to Assistants → Select your assistant
  2. Navigate to the Tools tab
  3. Click Add Tool and select your code tool
  4. Save your assistant configuration

Via API

$curl --location --request PATCH 'https://api.vapi.ai/assistant/ASSISTANT_ID' \
>--header 'Authorization: Bearer <YOUR_API_KEY>' \
>--header 'Content-Type: application/json' \
>--data '{
> "model": {
> "toolIds": ["your-code-tool-id"]
> }
>}'

Creating Code Tools via API

You can also create code tools programmatically:

$curl --location 'https://api.vapi.ai/tool' \
>--header 'Content-Type: application/json' \
>--header 'Authorization: Bearer <YOUR_API_KEY>' \
>--data '{
> "type": "code",
> "name": "get_customer",
> "description": "Retrieves customer information by their ID",
> "code": "const { customerId } = args;\nconst { API_KEY } = env;\n\nconst response = await fetch(`https://api.example.com/customers/${customerId}`, {\n headers: { \"Authorization\": `Bearer ${API_KEY}` }\n});\n\nreturn await response.json();",
> "parameters": {
> "type": "object",
> "properties": {
> "customerId": {
> "type": "string",
> "description": "The unique customer identifier"
> }
> },
> "required": ["customerId"]
> },
> "environmentVariables": [
> {
> "name": "API_KEY",
> "value": "your-api-key-here"
> }
> ]
>}'

Best Practices

Security

  • Store sensitive values (API keys, secrets) in Environment Variables, not in your code
  • Environment variable values support Liquid templates to reference call variables

Performance

  • Keep code execution under the timeout limit
  • Use efficient API calls and avoid unnecessary loops
  • Consider caching strategies for repeated lookups

Error Handling

  • Always handle potential errors from API calls
  • Return meaningful error messages that help the assistant respond appropriately
1const { customerId } = args;
2
3try {
4 const response = await fetch(`${env.API_URL}/customers/${customerId}`);
5
6 if (!response.ok) {
7 return {
8 error: true,
9 message: `Customer ${customerId} not found`
10 };
11 }
12
13 return await response.json();
14} catch (error) {
15 return {
16 error: true,
17 message: 'Unable to reach customer service'
18 };
19}

Return Values

  • Return structured data that the assistant can easily interpret
  • Include relevant information the assistant needs to continue the conversation

Limitations

  • Timeout: Maximum execution time is 60 seconds (default: 10 seconds)
  • No file system access: Code runs in an isolated environment without file access
  • Memory: Code runs with limited memory allocation
  • Network: Only outbound HTTP/HTTPS requests are supported

Code Tool vs Custom Function Tool

FeatureCode ToolCustom Function Tool
Server RequiredNoYes
LanguageTypeScriptAny
Setup ComplexityLowHigher
CustomizationModerateFull control
Secrets ManagementEnvironment VariablesYour server
Best ForQuick integrations, API callsComplex logic, existing infrastructure

Choose Code Tools when you want to quickly add functionality without managing infrastructure. Choose Custom Function Tools when you need full control over the execution environment or have existing server infrastructure.