### Install Vapi TypeScript SDK Source: https://github.com/vapiai/server-sdk-typescript/blob/main/README.md Install the Vapi TypeScript server SDK using npm. ```sh npm i -s @vapi-ai/server-sdk ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/vapiai/server-sdk-typescript/blob/main/CONTRIBUTING.md Installs all necessary dependencies for the project using the pnpm package manager. ```bash pnpm install ``` -------------------------------- ### Create Assistant Request Body Example Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Example JSON for the request body when creating a new assistant. It specifies the assistant's name, model, and voice configurations. ```json { "name": "Support Bot", "model": { "provider": "openai", "model": "gpt-4" }, "voice": { "provider": "elevenlabs", "voiceId": "adam" } } ``` -------------------------------- ### Client Setup Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/09-quick-reference.md Demonstrates how to initialize the VapiClient with minimal and full configuration options. ```APIDOC ## Client Setup ### Description Initializes the VapiClient for interacting with the Vapi API. Supports minimal configuration with just a token, or full configuration including base URL, timeouts, retries, and custom headers. ### Usage ```typescript import { VapiClient } from "@vapi-ai/server-sdk"; // Minimal setup const client = new VapiClient({ token: "your-token" }); // Full configuration const client = new VapiClient({ token: "your-token", baseUrl: "https://api.vapi.ai", timeoutInSeconds: 60, maxRetries: 2, headers: { "X-Custom": "value" } }); ``` ``` -------------------------------- ### Create Call Response Example Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Example JSON response after successfully creating a call. It returns the call's ID, status, and type. ```json { "id": "call-789", "status": "queued", "type": "outboundPhoneCall", ... } ``` -------------------------------- ### Create Simple Assistant Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/ANALYSIS-SUMMARY.txt Initializes a basic assistant. For more complex configurations, refer to advanced assistant examples. ```typescript import { Assistants } from "@vonage/server-sdk"; const assistants = new Assistants(YOUR_API_KEY, YOUR_API_SECRET, YOUR_API_REGION); async function createSimpleAssistant() { try { const assistant = await assistants.create_assistant({ name: "My Simple Assistant", voice_name: "en-US-Jenny-Apollo", // Add other minimal required configurations }); console.log("Simple assistant created:", assistant); return assistant; } catch (error) { console.error("Error creating simple assistant:", error); return null; } } createSimpleAssistant(); ``` -------------------------------- ### Creating an Assistant Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/09-quick-reference.md Details on how to create assistants, from simple configurations to advanced setups with custom prompts, transcribers, and analysis plans. ```APIDOC ## Creating an Assistant ### Description Allows the creation of AI assistants with various configurations, including model selection, voice, transcription services, and advanced AI behaviors like system prompts and analysis plans. ### Method - **Method**: POST - **Endpoint**: `/assistants` ### Request Body Parameters - `name` (string) - Required - The name of the assistant. - `model` (object) - Required - Configuration for the AI model. - `provider` (string) - Required - The provider of the model (e.g., "openai"). - `model` (string) - Required - The specific model identifier (e.g., "gpt-4"). - `systemPrompt` (string) - Optional - A system prompt to guide the assistant's behavior. - `voice` (object) - Required - Configuration for the voice output. - `provider` (string) - Required - The provider of the voice (e.g., "elevenlabs"). - `voiceId` (string) - Required - The identifier for the specific voice. - `transcriber` (object) - Optional - Configuration for the speech-to-text service. - `provider` (string) - Required - The provider of the transcriber (e.g., "deepgram"). - `model` (string) - Required - The model to use for transcription (e.g., "nova-2"). - `firstMessage` (string) - Optional - The initial message the assistant sends when a call starts. - `maxDurationSeconds` (number) - Optional - The maximum duration of a call in seconds. - `analysisPlan` (object) - Optional - Configuration for call analysis. - `summaryPlan` (object) - Optional - Configuration for generating a call summary. - `prompt` (string) - Required - The prompt to use for summarization. - `successEvaluationPlan` (object) - Optional - Configuration for evaluating call success. - `prompt` (string) - Required - The prompt to use for success evaluation. ### Usage Example ```typescript // Simple assistant const assistant = await client.assistants.create({ name: "Support Bot", model: { provider: "openai", model: "gpt-4" }, voice: { provider: "elevenlabs", voiceId: "adam" } }); // With advanced configuration const advanced = await client.assistants.create({ name: "Advanced Bot", model: { provider: "openai", model: "gpt-4", systemPrompt: "You are a helpful customer support assistant." }, voice: { provider: "elevenlabs", voiceId: "adam" }, transcriber: { provider: "deepgram", model: "nova-2" }, firstMessage: "Hello, how can I help you?", maxDurationSeconds: 1200, analysisPlan: { summaryPlan: { prompt: "Summarize this call" }, successEvaluationPlan: { prompt: "Was this successful?" } } }); ``` ``` -------------------------------- ### Assistant Creation Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/ANALYSIS-SUMMARY.txt Documentation for creating assistants, ranging from simple configurations to advanced setups with all available options. ```APIDOC ## Assistant Creation ### Description Guides on creating assistants, supporting both simple and advanced configurations. ### Methods - Simple assistant - Advanced assistant with all configurations ``` -------------------------------- ### Create Squad Request Body Example Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Example JSON for the request body when creating a new squad. It includes the squad's name and a list of member assistant IDs. ```json { "name": "Sales Team", "members": [ { "assistantId": "assistant-1" }, { "assistantId": "assistant-2" } ] } ``` -------------------------------- ### Get Call Response Example Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Example JSON response when retrieving a specific call by its ID. It includes the call's ID, status, and other details. ```json { "id": "call-123", "status": "ended", ... } ``` -------------------------------- ### Create Call Request Body Example Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Example JSON for the request body when creating a new call. It includes essential details like assistant ID, name, phone number ID, and customer ID. ```json { "assistantId": "assistant-123", "name": "Support Call", "phoneNumberId": "phone-456", "customerId": "customer-789" } ``` -------------------------------- ### Per-Request Configuration Examples Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/07-configuration.md Demonstrates how to override client-level configurations like timeout, retries, headers, and use AbortSignal for individual requests. ```typescript // Override timeout for a single request const calls = await client.calls.list( { limit: 100 }, { timeoutInSeconds: 120 } ); // Override retries const assistant = await client.assistants.create( { name: "New Assistant" }, { maxRetries: 5 } ); // Add request-specific headers const response = await client.calls.get( { id: "call-123" }, { headers: { "X-Request-ID": "trace-123", "X-User-ID": "user-456" } } ); // Use AbortSignal for cancellation const controller = new AbortController(); const promise = client.calls.list( {}, { abortSignal: controller.signal } ); // Cancel after 5 seconds setTimeout(() => controller.abort(), 5000); ``` -------------------------------- ### Update Call Request Body Example Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Example JSON for the request body when updating an existing call. This example shows how to change the call's name. ```json { "name": "Updated Call Name" } ``` -------------------------------- ### List Calls Response Example Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Example JSON response when listing calls. It shows the structure of a call object including ID, status, type, and cost. ```json [ { "id": "call-123", "status": "ended", "type": "outboundPhoneCall", "cost": 0.45, ... } ] ``` -------------------------------- ### Basic VapiClient Usage Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/README.md Demonstrates initializing the VapiClient and performing basic operations like listing, creating, getting, updating, and deleting calls. ```typescript import { VapiClient } from "@vapi-ai/server-sdk"; // Initialize client const client = new VapiClient({ token: "your-api-token" }); // List calls const calls = await client.calls.list({ limit: 10 }); // Create a call const newCall = await client.calls.create({ assistantId: "assistant-123", phoneNumberId: "phone-456", customerId: "customer-789" }); // Get call details const callDetails = await client.calls.get({ id: newCall.id }); // Update call const updated = await client.calls.update({ id: newCall.id, name: "Updated call name" }); // Delete call await client.calls.delete({ id: newCall.id }); ``` -------------------------------- ### Create a Call with Inline Assistant and Customer Configuration Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/03-api-reference-calls.md This example demonstrates creating a call with an inline assistant configuration, including model and voice details, and an inline customer configuration with a phone number. This is useful for transient or ad-hoc calls. ```typescript const transient = await client.calls.create({ assistant: { name: "Greeting Bot", model: { provider: "openai", model: "gpt-4" }, voice: { provider: "elevenlabs", voiceId: "adam" } }, phoneNumberId: "phone-456", customer: { phoneNumber: "+1234567890" } }); ``` -------------------------------- ### Create Assistant with GPT-4 Model Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Example of creating an assistant that uses the GPT-4 model with custom temperature, max tokens, and system prompt. ```typescript const assistant = await client.assistants.create({ name: "GPT-4 Assistant", model: { provider: "openai", model: "gpt-4", temperature: 0.7, maxTokens: 1000, systemPrompt: "You are a helpful assistant." } }); ``` -------------------------------- ### Create Assistant with Analysis Plan and Retrieve Analysis Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Example of creating an assistant with a summary and success evaluation plan, and later retrieving call analysis. Requires 'call-123' to exist. ```typescript const assistant = await client.assistants.create({ name: "Analytical Bot", analysisPlan: { summaryPlan: { prompt: "Summarize the call in 2 sentences." }, successEvaluationPlan: { prompt: "Did the assistant successfully resolve the customer's issue? Answer yes or no." } } }); // Later, retrieve the analysis from a call const call = await client.calls.get({ id: "call-123" }); console.log(call.analysis.summary); console.log(call.analysis.successEvaluation); ``` -------------------------------- ### Create Assistant with Server Webhook Configuration Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Example of creating an assistant that sends specific server messages like 'conversation-update', 'end-of-call-report', and 'tool-calls' to your server. ```typescript const assistant = await client.assistants.create({ name: "Webhook Bot", serverMessages: [ "conversation-update", "end-of-call-report", "tool-calls" ] }); ``` -------------------------------- ### Create a Function Tool Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Example of creating a function tool that an assistant can call, specifying its name, description, parameters, and a URL for handling the tool's execution. ```typescript const tool = await client.tools.create({ type: "function", definition: { name: "check_inventory", description: "Check if an item is in stock", parameters: { properties: { itemId: { type: "string", description: "Item ID" }, quantity: { type: "number", description: "Quantity needed" } }, required: ["itemId"] }, url: "https://example.com/check-inventory" } }); ``` -------------------------------- ### Create, Run, and Get Evaluation Results Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Demonstrates the workflow for creating an evaluation, running it, and retrieving the results using the Vapiai client. ```typescript // Create an eval const eval = await client.eval.evalControllerCreate({ name: "Call Quality Eval", type: "quality", metric: "customer-satisfaction" }); // Run evaluation const run = await client.eval.evalControllerRun({ evalId: eval.id }); // Get run results const result = await client.eval.evalControllerGetRun({ evalId: eval.id, runId: run.id }); // List runs const runs = await client.eval.evalControllerGetRunsPaginated({ evalId: eval.id }); ``` -------------------------------- ### Create Assistant with Webhook Hooks Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Example of creating an assistant that triggers a webhook on call end, sending a POST request to a specified URL. ```typescript const assistant = await client.assistants.create({ name: "Hooked Bot", hooks: [ { type: "on-call-end", url: "https://example.com/webhook", method: "POST" } ] }); ``` -------------------------------- ### Create Assistant with ElevenLabs Voice Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Example of creating an assistant that uses the ElevenLabs voice provider with a specific voice ID and speed. ```typescript const assistant = await client.assistants.create({ name: "Voice Bot", voice: { provider: "elevenlabs", voiceId: "adam", speed: 1.0 } }); ``` -------------------------------- ### Create Assistant with Dynamic Credentials Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Example of creating an assistant that uses dynamic credentials, such as OpenAI credentials with a specific ID, for API access. ```typescript const assistant = await client.assistants.create({ name: "Credentialed Bot", credentials: [ { provider: "openai", credentialId: "cred-123" } ] }); ``` -------------------------------- ### Type-Safe SDK Usage with Vapi Types Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/09-quick-reference.md Demonstrates how to use Vapi's TypeScript types for request and response objects to ensure type safety when interacting with the SDK. Includes examples for listing calls, creating calls, and defining request parameters. ```typescript import { Vapi } from "@vapi-ai/server-sdk"; // Request types const listReq: Vapi.ListCallsRequest = { assistantId: "assistant-123", limit: 50 }; // Response types const calls: Vapi.Call[] = await client.calls.list(listReq); // Create types const createReq: Vapi.CreateCallDto = { assistantId: "assistant-123" }; const call: Vapi.Call = await client.calls.create(createReq); ``` -------------------------------- ### Per-Request Configuration Example Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/01-client-setup.md Override default client settings like timeout and retries for individual requests. Custom headers can also be applied per request. ```typescript const response = await client.calls.list( { limit: 10 }, { timeoutInSeconds: 15, maxRetries: 1, headers: { "X-Request-ID": "123" } } ); ``` -------------------------------- ### Create Assistant with Deepgram Transcriber Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Example of creating an assistant that uses the Deepgram transcriber with a specified model and language. ```typescript const assistant = await client.assistants.create({ name: "Transcription Bot", transcriber: { provider: "deepgram", model: "nova-2", language: "en-US" } }); ``` -------------------------------- ### Initialize Vapi Client Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/09-quick-reference.md Set up the Vapi client with minimal or full configuration. Ensure you provide your API token. ```typescript import { VapiClient } from "@vapi-ai/server-sdk"; // Minimal setup const client = new VapiClient({ token: "your-token" }); // Full configuration const client = new VapiClient({ token: "your-token", baseUrl: "https://api.vapi.ai", timeoutInSeconds: 60, maxRetries: 2, headers: { "X-Custom": "value" } }); ``` -------------------------------- ### Building a Chat Bot Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/09-quick-reference.md Guides on creating chat sessions and managing multi-turn conversations, including sending messages and retrieving chat history. ```APIDOC ## Building a Chat Bot ### Description Facilitates the creation of conversational AI experiences by managing chat sessions, handling multi-turn dialogues, and retrieving conversation history. ### Methods #### Create Session Creates a new session for a multi-turn conversation. - **Method**: POST - **Endpoint**: `/sessions` - **Request Body Parameters**: - `externalId` (string) - Optional - An external identifier for the user or session. - `metadata` (object) - Optional - Custom key-value pairs for session metadata. ### Create Chat Message Sends a message within a chat session and receives a response. - **Method**: POST - **Endpoint**: `/chats` - **Request Body Parameters**: - `input` (string) - Required - The user's message. - `assistantId` (string) - Required - The ID of the assistant to handle the message. - `sessionId` (string) - Required - The ID of the chat session. ### List Chat History Retrieves the history of messages within a chat session. - **Method**: GET - **Endpoint**: `/chats` - **Query Parameters**: - `sessionId` (string) - Required - The ID of the chat session. - `limit` (number) - Optional - The maximum number of messages to retrieve. ### Usage Example ```typescript // Create a session for multi-turn conversation const session = await client.sessions.create({ externalId: "user-456", metadata: { userId: "user-456" } }); // First message const chat1 = await client.chats.create({ input: "Hi, can you help me place an order?", assistantId: "assistant-support", sessionId: session.id }); // Continue conversation const chat2 = await client.chats.create({ input: "What's the status of order #123?", sessionId: session.id }); // List conversation history const history = await client.chats.list({ sessionId: session.id, limit: 50 }); ``` ``` -------------------------------- ### Chain Operations: Create Assistant and Use in Call Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/09-quick-reference.md Demonstrates creating an assistant and then immediately using its ID to create a call. This is useful for dynamic call setups. ```typescript // Create assistant, then use in call const assistant = await client.assistants.create({ name: "New Bot", model: { provider: "openai", model: "gpt-4" } }); const call = await client.calls.create({ assistantId: assistant.id, phoneNumberId: "phone-123", customerId: "customer-456" }); console.log(`Call ${call.id} started with assistant ${assistant.id}`); ``` -------------------------------- ### Build the Project Source: https://github.com/vapiai/server-sdk-typescript/blob/main/CONTRIBUTING.md Compiles the project's code. ```bash pnpm build ``` -------------------------------- ### Create Squad with Multiple Assistant Members Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Example of creating a squad named 'Customer Support Team' with three assistant members: sales, support, and billing. ```typescript const squad = await client.squads.create({ name: "Customer Support Team", members: [ { assistantId: "assistant-sales" }, { assistantId: "assistant-support" }, { assistantId: "assistant-billing" } ] }); ``` -------------------------------- ### Get a Specific Tool Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieves details for a specific tool by its ID. Use this to get information about a previously created tool. ```typescript await client.tools.get({ id: "id" }); ``` -------------------------------- ### Manage Provider Resources (CRUD Operations) Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Provides examples for creating, listing, retrieving, updating, and deleting provider-specific resources like Twilio credentials. ```typescript // Create provider resource const resource = await client.providerResources.providerResourceControllerCreateProviderResource({ provider: "twilio", name: "Main Twilio Account", config: { accountSid: "AC...", authToken: "..." } }); // List provider resources const resources = await client.providerResources.providerResourceControllerGetProviderResourcesPaginated({ provider: "twilio" }); // Get specific resource const resource = await client.providerResources.providerResourceControllerGetProviderResource({ resourceId: "resource-123" }); // Update resource await client.providerResources.providerResourceControllerUpdateProviderResource({ resourceId: "resource-123", config: { /* updated config */ } }); // Delete resource await client.providerResources.providerResourceControllerDeleteProviderResource({ resourceId: "resource-123" }); ``` -------------------------------- ### Get Specific Resource by ID Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/04-api-reference-resources.md Use the get method to retrieve a single resource by its unique identifier. This is essential for accessing the details of a particular assistant or phone number. ```typescript public get( request: GetRequest, requestOptions?: Client.RequestOptions ): Promise ``` ```typescript const assistant = await client.assistants.get({ id: "assistant-123" }); const phoneNumber = await client.phoneNumbers.get({ id: "phone-456" }); ``` -------------------------------- ### Get Scorecard Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves the scorecard object. ```APIDOC ## GET /scorecard ### Description Retrieves the scorecard object. ### Method GET ### Endpoint /scorecard ### Response #### Success Response (200 OK) - **Scorecard object** - The scorecard object. ``` -------------------------------- ### Create a Call Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/ANALYSIS-SUMMARY.txt Demonstrates the basic process of creating a new call using the SDK. ```typescript import { Calls } from "@vonage/server-sdk"; const calls = new Calls(YOUR_API_KEY, YOUR_API_SECRET, YOUR_API_REGION); async function createCall() { try { const call = await calls.create_call({ to: [{ type: "phone", number: "14155550101" }], from: { type: "phone", number: "14155550102" }, answer_url: ["https://example.com/answer"] }); console.log("Call created successfully:", call); } catch (error) { console.error("Error creating call:", error); } } createCall(); ``` -------------------------------- ### Get Insight Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves a specific Insight by its ID. ```APIDOC ## GET /insight/{id} ### Description Retrieves a specific Insight object by its unique identifier. ### Method GET ### Endpoint /insight/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the Insight. ``` -------------------------------- ### Get Eval Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves a specific Eval by its ID. ```APIDOC ## GET /eval/{id} ### Description Retrieves a specific Eval object by its unique identifier. ### Method GET ### Endpoint /eval/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the Eval. ``` -------------------------------- ### Get Campaign Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves a specific campaign by its ID. ```APIDOC ## GET /campaign/{id} ### Description Retrieves a specific campaign by its ID. ### Method GET ### Endpoint /campaign/{id} ### Response #### Success Response (200 OK) - **Campaign object** - The retrieved campaign object. ``` -------------------------------- ### Complete VapiClient Initialization Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/07-configuration.md Initialize the VapiClient with all available configuration options, including environment, base URL, timeouts, retries, custom headers, and logging. ```typescript import { VapiClient, VapiEnvironment } from "@vapi-ai/server-sdk"; const client = new VapiClient({ token: "your-api-token", environment: VapiEnvironment.Default, baseUrl: "https://api.vapi.ai", // custom URL timeoutInSeconds: 30, maxRetries: 3, headers: { "X-Custom-Header": "value", "X-Request-ID": "unique-id-123" }, logging: { level: "debug" } }); ``` -------------------------------- ### Get File Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves a specific file by its ID. ```APIDOC ## GET /file/{id} ### Description Retrieves a specific file by its ID. ### Method GET ### Endpoint /file/{id} ### Response #### Success Response (200 OK) - **File object** - The retrieved file object. ``` -------------------------------- ### Get Tool Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves a specific tool by its ID. ```APIDOC ## GET /tool/{id} ### Description Retrieves a specific tool by its ID. ### Method GET ### Endpoint /tool/{id} ### Response #### Success Response (200 OK) - **Tool object** - The retrieved tool object. ``` -------------------------------- ### Get Session Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves a specific session by its ID. ```APIDOC ## GET /session/{id} ### Description Retrieves a specific session by its ID. ### Method GET ### Endpoint /session/{id} ### Response #### Success Response (200 OK) - **Session object** - The retrieved session object. ``` -------------------------------- ### Performance Tips Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/README.md Optimize SDK usage by reusing client instances, setting appropriate timeouts, utilizing filtering and pagination, and handling retries gracefully. ```APIDOC ## Performance Tips 1. **Reuse client instances** - Create once, reuse for all API calls 2. **Set appropriate timeouts** - Longer for large queries, shorter for status checks 3. **Use filtering** - Filter on the API side rather than in your application 4. **Implement pagination** - For large result sets, use the limit parameter 5. **Handle retries gracefully** - Exponential backoff happens automatically ``` -------------------------------- ### Get Chat Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves a specific chat by its ID. ```APIDOC ## GET /chat/{id} ### Description Retrieves a specific chat by its ID. ### Method GET ### Endpoint /chat/{id} ### Response #### Success Response (200 OK) - **Chat object** - The retrieved chat object. ``` -------------------------------- ### Get Provider Resource Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves a specific provider resource by its ID. ```APIDOC ## GET /providerResource/{id} ### Description Retrieves a specific provider resource by its unique identifier. ### Method GET ### Endpoint /providerResource/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the provider resource. ``` -------------------------------- ### create() Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/04-api-reference-resources.md Creates a new resource with the provided configuration. Requires a CreateRequest object containing the resource's details. ```APIDOC ## create() ### Description Create a new resource with the provided configuration. ### Method POST (Implied) ### Endpoint /{resource_type} ### Parameters #### Request Body - **request** (CreateRequest) - Required - The configuration for the new resource. ### Request Example ```typescript const assistant = await client.assistants.create({ name: "Support Bot", model: { provider: "openai", model: "gpt-4" }, voice: { provider: "elevenlabs", voiceId: "adam" } }); const squad = await client.squads.create({ name: "Sales Team", members: [ { assistantId: "assistant-1" }, { assistantId: "assistant-2" } ] }); ``` ### Response #### Success Response (200) - **ResourceType** - The newly created resource object. ``` -------------------------------- ### Get Eval Run Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves the details of a specific Eval run. ```APIDOC ## GET /eval/{id}/run/{runId} ### Description Retrieves the details of a specific run for an Eval. ### Method GET ### Endpoint /eval/{id}/run/{runId} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the Eval. - **runId** (string) - Required - The unique identifier of the run. ``` -------------------------------- ### Run Test Suite Source: https://github.com/vapiai/server-sdk-typescript/blob/main/CONTRIBUTING.md Executes the complete test suite for the project. ```bash pnpm test ``` -------------------------------- ### Basic VapiClient Initialization Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/01-client-setup.md Instantiate the VapiClient using only the required API token. ```typescript import { VapiClient } from "@vapi-ai/server-sdk"; const client = new VapiClient({ token: "your-api-token" }); ``` -------------------------------- ### Get Structured Output Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves a specific structured output by its ID. ```APIDOC ## GET /structuredOutput/{id} ### Description Retrieves a specific structured output by its ID. ### Method GET ### Endpoint /structuredOutput/{id} ### Response #### Success Response (200 OK) - **StructuredOutput object** - The retrieved structured output object. ``` -------------------------------- ### VapiClient Initialization with Custom Fetch Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/07-configuration.md Initialize the VapiClient using a custom fetch implementation, useful for environments without native fetch or for specific requirements. ```typescript import fetch from "node-fetch"; // or any fetch polyfill const client = new VapiClient({ token: "your-api-token", fetch: fetch as typeof global.fetch }); ``` -------------------------------- ### Get Phone Number Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves a specific phone number by its ID. ```APIDOC ## GET /phoneNumber/{id} ### Description Retrieves a specific phone number by its ID. ### Method GET ### Endpoint /phoneNumber/{id} ### Response #### Success Response (200 OK) - **PhoneNumber object** - The retrieved phone number object. ``` -------------------------------- ### Get Squad Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves details for a specific squad using its ID. ```APIDOC ## GET /squad/{id} ### Description Retrieves details for a specific squad using its ID. ### Method GET ### Endpoint /squad/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Squad ID ### Response #### Success Response (200 OK) - The Squad object with details. ``` -------------------------------- ### VapiClient Initialization with Custom Configuration Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/01-client-setup.md Configure the VapiClient with additional options such as base URL, timeout, retries, and custom headers. ```typescript // With custom configuration const customClient = new VapiClient({ token: "your-api-token", baseUrl: "https://api.vapi.ai", timeoutInSeconds: 30, maxRetries: 3, headers: { "X-Custom-Header": "value" } }); ``` -------------------------------- ### Get Assistant Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves details for a specific assistant using its ID. ```APIDOC ## GET /assistant/{id} ### Description Retrieves details for a specific assistant using its ID. ### Method GET ### Endpoint /assistant/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Assistant ID ### Response #### Success Response (200 OK) - The Assistant object with details. ``` -------------------------------- ### Create Advanced Assistant Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/ANALYSIS-SUMMARY.txt Sets up an assistant with a comprehensive range of configurations, including tools and webhooks. ```typescript import { Assistants } from "@vonage/server-sdk"; const assistants = new Assistants(YOUR_API_KEY, YOUR_API_SECRET, YOUR_API_REGION); async function createAdvancedAssistant() { try { const assistant = await assistants.create_assistant({ name: "My Advanced Assistant", voice_name: "en-GB-Sonia-Apollo", streaming_enabled: true, // Include tool_code, webhook_url, etc. for advanced functionality tool_code: "// Your tool code here\nfunction add(a, b) { return a + b; }", webhook_url: "https://example.com/assistant-webhook" }); console.log("Advanced assistant created:", assistant); return assistant; } catch (error) { console.error("Error creating advanced assistant:", error); return null; } } createAdvancedAssistant(); ``` -------------------------------- ### Create, Run, and Preview Insight Definitions Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Shows how to create an insight definition, run it to extract data, and preview the results before saving. ```typescript // Create insight definition const insight = await client.insight.insightControllerCreate({ name: "Revenue Analysis", type: "revenue" }); // Run insight const result = await client.insight.insightControllerRun({ insightId: insight.id }); // Preview before saving const preview = await client.insight.insightControllerPreview({ insightId: insight.id }); ``` -------------------------------- ### Get Call Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves details for a specific call using its ID. ```APIDOC ## GET /call/{id} ### Description Retrieves details for a specific call using its ID. ### Method GET ### Endpoint /call/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Call ID ### Response #### Success Response (200 OK) - The call object with details. #### Response Example ```json { "id": "call-123", "status": "ended", ... } ``` #### Error Response (404 Not Found) - Returned if the call ID does not exist. ``` -------------------------------- ### Get an Evaluation Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieves a specific evaluation by its ID. Ensure you have the correct evaluation ID. ```typescript await client.eval.evalControllerGet({ id: "id" }); ``` -------------------------------- ### client.assistants.create Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Creates a new assistant. Accepts an optional request object and request options. ```APIDOC ## create Assistant ### Description Creates a new assistant. Accepts an optional request object and request options. ### Method client.assistants.create ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **request** (Vapi.CreateAssistantDto) - Required - The data to create the assistant. - **requestOptions** (AssistantsClient.RequestOptions) - Optional - Additional request options. ### Request Example ```typescript await client.assistants.create({}); ``` ### Response #### Success Response (200) - **assistant** (Vapi.Assistant) - The newly created assistant. #### Response Example ```json { "id": "string", "name": "string", "model": "string", "description": "string", "voice": { "id": "string", "name": "string", "voice_id": "string", "model": "string" }, "transcription": { "id": "string", "model": "string" }, "language": "string", "metadata": {}, "created_at": "string", "updated_at": "string" } ``` ``` -------------------------------- ### Run an Insight Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Execute an insight to get its results. This method requires the ID of the insight to be run. ```typescript await client.insight.insightControllerRun({ id: "id" }); ``` -------------------------------- ### Get Chat by ID Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieves a specific chat using its ID. The 'id' parameter is required. ```typescript await client.chats.get({ id: "id" }); ``` -------------------------------- ### Configure Vapi Client with Custom Fetch Implementation Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/09-quick-reference.md Initializes the Vapi client using a custom fetch implementation, such as 'node-fetch', for environments where the global fetch API is not available or needs to be customized. ```typescript import fetch from "node-fetch"; const client = new VapiClient({ token: "...", fetch: fetch as typeof global.fetch }); ``` -------------------------------- ### Get Call by ID Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieves a specific call using its ID. The 'id' parameter is required. ```typescript await client.calls.get({ id: "id" }); ``` -------------------------------- ### Initializing Resource Clients Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/README.md Initialize the VapiClient with a token. Resource clients like calls, assistants, and chats are lazily initialized upon first access. ```typescript const client = new VapiClient({ token: "..." }); // These are lazily initialized on first access client.calls // CallsClient client.assistants // AssistantsClient client.squads // SquadsClient client.chats // ChatsClient client.sessions // SessionsClient client.phoneNumbers // PhoneNumbersClient client.tools // ToolsClient client.files // FilesClient client.campaigns // CampaignsClient client.insight // InsightClient client.eval // EvalClient client.structuredOutputs // StructuredOutputsClient client.observabilityScorecard // ObservabilityScorecardClient client.providerResources // ProviderResourcesClient client.analytics // AnalyticsClient ``` -------------------------------- ### Get Analytics Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Retrieves analytics data based on specified query parameters and request body. ```APIDOC ## GET /analytics ### Description Retrieves analytics data based on specified query parameters and request body. ### Method GET ### Endpoint /analytics ### Query Parameters - **limit** (number) - Optional - Maximum results to return (typically 100). - **page** (number) - Optional - Page number (for paginated responses). ### Request Body - **AnalyticsQueryDto** - Required - Defines the analytics query. ```json { "table": "call", "operation": { "operation": "count", "column": "id" }, "groupBy": ["status"] } ``` ### Response #### Success Response (200 OK) - AnalyticsQueryResult ``` -------------------------------- ### Troubleshooting Authentication Failures Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/README.md Verify your API token by initializing the client and performing a simple call like listing assistants. Ensure the VAPI_TOKEN environment variable is correctly set. ```typescript const client = new VapiClient({ token: process.env.VAPI_API_TOKEN || "" }); // Test with a simple call await client.assistants.list(); ``` -------------------------------- ### Get Call Status Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/ANALYSIS-SUMMARY.txt Retrieves the current status of a specific call using its unique ID. ```typescript import { Calls } from "@vonage/server-sdk"; const calls = new Calls(YOUR_API_KEY, YOUR_API_SECRET, YOUR_API_REGION); async function getCallStatus(callId: string) { try { const status = await calls.get_call_status(callId); console.log(`Call ${callId} status:`, status); return status; } catch (error) { console.error(`Error getting status for call ${callId}:`, error); return null; } } // Example usage: // getCallStatus("YOUR_CALL_ID"); ``` -------------------------------- ### Load Configuration from Environment Variables Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/07-configuration.md Initialize the Vapi client using environment variables for token, base URL, timeout, and retries. Ensure environment variables are set before running. ```typescript import { VapiClient } from "@vapi-ai/server-sdk"; const client = new VapiClient({ token: process.env.VAPI_TOKEN || "", baseUrl: process.env.VAPI_BASE_URL, timeoutInSeconds: parseInt(process.env.VAPI_TIMEOUT || "60"), maxRetries: parseInt(process.env.VAPI_MAX_RETRIES || "2") }); ``` -------------------------------- ### Get Observability Scorecard Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieves an observability scorecard by its ID. This is used to assess the performance and quality of an assistant. ```typescript await client.observabilityScorecard.scorecardControllerGet({ id: "id" }); ``` -------------------------------- ### Create File Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md Creates a new file. ```APIDOC ## POST /file ### Description Creates a new file. ### Method POST ### Endpoint /file ### Request Body #### (Request body details not specified in source) ### Response #### Success Response (200 OK) - **File object** - The newly created file object. ``` -------------------------------- ### client.insight.insightControllerFindOne Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieves a single insight by its ID. Use this method to get detailed information about a specific insight. ```APIDOC ## client.insight.insightControllerFindOne ### Description Retrieves a single insight by its ID. Use this method to get detailed information about a specific insight. ### Method GET (inferred) ### Endpoint /insight/{id} (inferred) ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the insight to retrieve. #### Request Body - **requestOptions** (InsightClient.RequestOptions) - Optional - Options for the request. ### Response #### Success Response (200) - **Vapi.InsightControllerFindOneResponse** - The response object containing the insight details. ``` -------------------------------- ### client.tools.create Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Creates a new tool with specified properties such as type, HTTP method, and URL. ```APIDOC ## client.tools.create ### Description Creates a new tool with specified properties such as type, HTTP method, and URL. ### Method Not specified (SDK method) ### Parameters #### Request Body - **request** (Vapi.CreateToolsRequest) - Required - The request object for creating a tool. - **type** (string) - Required - The type of the tool (e.g., "apiRequest"). - **method** (string) - Required - The HTTP method for the API request. - **url** (string) - Required - The URL for the API request. ``` -------------------------------- ### Get Paginated Evaluations Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieve a paginated list of evaluations. This method is used for fetching evaluations in batches. ```typescript await client.eval.evalControllerGetPaginated(); ``` -------------------------------- ### Get Assistant by ID Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieves a specific assistant by its unique ID. Ensure the ID is correctly formatted. ```typescript await client.assistants.get({ id: "id" }); ``` -------------------------------- ### Resource Clients Initialization Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/README.md Each resource type is accessed through a lazily-initialized client. Instantiate the main client with your API token. ```APIDOC ## Resource Clients Each resource type is accessed through a lazily-initialized client: ```typescript const client = new VapiClient({ token: "..." }); // These are lazily initialized on first access client.calls // CallsClient client.assistants // AssistantsClient client.squads // SquadsClient client.chats // ChatsClient client.sessions // SessionsClient client.phoneNumbers // PhoneNumbersClient client.tools // ToolsClient client.files // FilesClient client.campaigns // CampaignsClient client.insight // InsightClient client.eval // EvalClient client.structuredOutputs // StructuredOutputsClient client.observabilityScorecard // ObservabilityScorecardClient client.providerResources // ProviderResourcesClient client.analytics // AnalyticsClient ``` ``` -------------------------------- ### Get Specific Phone Number Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/ANALYSIS-SUMMARY.txt Fetches details for a particular phone number using its unique ID. ```typescript import { Numbers } from "@vonage/server-sdk"; const numbers = new Numbers(YOUR_API_KEY, YOUR_API_SECRET, YOUR_API_REGION); async function getPhoneNumber(numberId: string) { try { const phoneNumber = await numbers.get_number(numberId); console.log(`Details for number ${numberId}:`, phoneNumber); return phoneNumber; } catch (error) { console.error(`Error getting number ${numberId}:`, error); return null; } } // Example usage: // getPhoneNumber("YOUR_NUMBER_ID"); ``` -------------------------------- ### Configure and Retrieve Observability Scorecards Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Demonstrates how to create a scorecard configuration with specified metrics and retrieve scorecard data, including paginated results. ```typescript const scorecard = await client.observabilityScorecard.scorecardControllerCreate({ name: "Performance Scorecard", metrics: [ "call-success-rate", "average-call-duration", "cost-per-call", "customer-satisfaction" ] }); // Retrieve scorecard data const score = await client.observabilityScorecard.scorecardControllerGet({ scorecardId: scorecard.id }); // Paginated list const scores = await client.observabilityScorecard.scorecardControllerGetPaginated({ limit: 20 }); ``` -------------------------------- ### get() Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/04-api-reference-resources.md Retrieves a specific resource by its unique identifier. Requires a GetRequest object containing the resource ID. ```APIDOC ## get() ### Description Retrieve a specific resource by ID. ### Method GET (Implied) ### Endpoint /{resource_type}/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the resource. ### Request Example ```typescript const assistant = await client.assistants.get({ id: "assistant-123" }); const phoneNumber = await client.phoneNumbers.get({ id: "phone-456" }); ``` ### Response #### Success Response (200) - **ResourceType** - The requested resource object. ``` -------------------------------- ### Create New Resource Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/04-api-reference-resources.md Employ the create method to instantiate a new resource, providing its configuration details. This is the standard way to add new entities like assistants or squads to the system. ```typescript public create( request: CreateRequest, requestOptions?: Client.RequestOptions ): Promise ``` ```typescript const assistant = await client.assistants.create({ name: "Support Bot", model: { provider: "openai", model: "gpt-4" }, voice: { provider: "elevenlabs", voiceId: "adam" } }); const squad = await client.squads.create({ name: "Sales Team", members: [ { assistantId: "assistant-1" }, { assistantId: "assistant-2" } ] }); ``` -------------------------------- ### Analytics Query Example Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/06-endpoints.md This JSON object demonstrates a query for analytics data, specifying the table, operation, and grouping. ```json { "table": "call", "operation": { "operation": "count", "column": "id" }, "groupBy": ["status"] } ``` -------------------------------- ### File Operations Source: https://github.com/vapiai/server-sdk-typescript/blob/main/_autodocs/08-advanced-resources.md Demonstrates the lifecycle of file management, including creating, retrieving, updating, and deleting files using the SDK. ```typescript const file = await client.files.create({ name: "document.pdf", type: "pdf" }); const retrieved = await client.files.get({ id: file.id }); const updated = await client.files.update({ id: file.id, name: "updated-document.pdf" }); await client.files.delete({ id: file.id }); ``` -------------------------------- ### Get an Evaluation Run Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieves a specific evaluation run by its ID. This is useful for inspecting the results of a past evaluation. ```typescript await client.eval.evalControllerGetRun({ id: "id" }); ``` -------------------------------- ### Get a Specific File Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieves details for a specific file by its ID. Use this to access information about an uploaded file. ```typescript await client.files.get({ id: "id" }); ``` -------------------------------- ### Get paginated phone numbers Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieve a paginated list of phone numbers. This operation does not require any specific parameters. ```typescript await client.phoneNumbers.phoneNumberControllerFindAllPaginated(); ``` -------------------------------- ### List All Tools Source: https://github.com/vapiai/server-sdk-typescript/blob/main/reference.md Retrieves a list of all available tools. This is useful for understanding the tools that can be integrated with Vapi. ```typescript await client.tools.list(); ```