Getting started with the Swiftask JavaScript SDK

Written By Stanislas

Last updated About 1 month ago


Integrate AI agents into your applications using the Swiftask Public Bot API. You control the user interface; Swiftask manages the AI ​​agent, knowledge base, and message processing.

Overview

The Swiftask Public Bot API lets you embed AI-powered chat directly into your applications. You control the UI; Swiftask handles the AI agent, knowledge base, and message processing.

What you can build:

  • Custom chat interfaces powered by your Swiftask agents

  • Multi-session conversations (support, sales, tech support, etc.)

  • Real-time streaming responses, character by character

  • Monitor what your agent is doing (tool calls, data analysis)

  • Web apps, mobile apps, or embedded widgets


Prerequisites

Before you start, you need:

  • A Swiftask account (sign up at swiftask.ai)

  • An AI agent created in your workspace

  • Your agent's Client Token (from Developer section)

  • Node.js 14+ or a modern browser

  • Apollo Client installed (npm install @apollo/client graphql)

  • Basic JavaScript knowledge (async/await, promises)

Installation & setup

Step 1: Get your client token

  1. Click Agents in the left sidebar

  2. Find your agent and click the edit (pen icon) button

  3. In the left menu, click DΓ©veloppeur (Developer)

  4. You'll see the Developer panel with:

    • Client token de l'agent (Client token of the agent) β€” Copy this

    • Slug unique de l'agent (Unique agent slug)

    • Integration options below

Keep your client token secure; it identifies your agent to the API.

Step 2: Install dependencies

npm install @apollo/client graphql 

The Swiftask API uses Apollo Client (a GraphQL client) for queries, mutations, and real-time subscriptions.

Step 3: Authenticate in 30 seconds

// Generate a unique ID for this user/session
const clientUuid = crypto.randomUUID();
localStorage.setItem('swiftask_client_uuid', clientUuid);

// Authenticate using your client token from Developer panel
const clientToken = '88576b1c-f933-4679-99b8-3f95e27ef46e'; // Replace with your token
const response = await fetch(
  `https://graphql.swiftask.ai/public/widget-bot/${clientToken}`,
  {
    method: 'GET',
    headers: { 'x-client-uuid': clientUuid },
  }
);

const { data } = await response.json();
const { accessToken, workspaceId, starterSessionId } = data;

// You now have everything you need to chat
console.log('βœ… Authenticated! Ready to send messages.');

Step 4: Send your first message

import { ApolloClient, InMemoryCache, createHttpLink, gql } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

// Setup Apollo Client
const httpLink = createHttpLink({
  uri: 'https://graphql.swiftask.ai/graphql',
});

const authLink = setContext((_, { headers }) => ({
  headers: {
    ...headers,
    authorization: `Bearer ${accessToken}`,
    'x-workspace-id': workspaceId,
    'x-client': 'widget',
  },
}));

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
});

// Send a message
const SEND_MESSAGE = gql`
  mutation SendNewMessage($newMessageData: NewMessageInput!) {
    sendNewMessage(newMessageData: $newMessageData) {
      id
      message
      createdAt
    }
  }
`;

const result = await client.mutate({
  mutation: SEND_MESSAGE,
  variables: {
    newMessageData: {
      message: 'Hello, agent!',
      sessionId: starterSessionId,
      isForAiReply: true,
    },
  },
});

console.log('Agent will respond:', result.data.sendNewMessage);

That's it! You've authenticated and sent a message.

Key concepts

REST vs. GraphQL

  • REST (authentication only): GET /public/widget-bot/:clientToken β€” Exchange your token for an access token

  • GraphQL (everything else): https://graphql.swiftask.ai/graphql β€” Send messages, create sessions, subscribe to updates

  • WebSocket (real-time): wss://graphql.swiftask.ai/graphql β€” Stream responses in real-time

Sessions & messages

Think of it like folders:

User (authenticated)
  └── Session 1 (conversation thread)
       β”œβ”€β”€ Message 1 (user)
       β”œβ”€β”€ Message 2 (agent response)
       └── Message 3 (user)
  └── Session 2 (another conversation)
       └── ...

You get a starterSessionId automatically. Or create new sessions for different conversations (support, sales, etc.).

Real-time streaming

Instead of waiting for the full response, you can stream it character by character using WebSocket subscriptions. Great for chat UIs.

Framework integrations

React

Use a custom hook to manage authentication and sessions:

import { useState, useEffect } from 'react';

export function useSwiftaskChat(clientToken) {
  const [messages, setMessages] = useState([]);
  const [streamingMessage, setStreamingMessage] = useState('');
  const [session, setSession] = useState(null);

  useEffect(() => {
    // Initialize client, create session, setup subscriptions
  }, [clientToken]);

  const sendMessage = async (text) => {
    // Send message and listen for response
  };

  return { messages, streamingMessage, sendMessage };
}

// Use in your component
function ChatApp() {
  const { messages, sendMessage } = useSwiftaskChat('your-token');
  // Build your UI...
}

Common patterns

Multiple sessions

const supportSession = await chat.createSession('Support');
const salesSession = await chat.createSession('Sales');

await sendMessage(supportSession.id, 'My order is broken');
await sendMessage(salesSession.id, 'Tell me about pricing');

Stream responses in real-time

chat.subscribeToStream(
  sessionId,
  (fullMessage) => {
    // Update UI with each character as it arrives
    console.log('Streaming:', fullMessage);
  },
  () => {
    // Called when response is complete
    console.log('Response done');
  }
);

Handle errors gracefully

try {
  await chat.authenticate();
} catch (error) {
  if (error.message.includes('Invalid client token')) {
    console.error('Check your token in Agents β†’ Edit β†’ Developer');
  } else if (error.message.includes('Agent not found')) {
    console.error('Agent does not exist or is not public');
  }
}

Troubleshooting

"Invalid client token" error

  • Verify your token is copied correctly from Agents β†’ Edit β†’ Developer β†’ Client token de l'agent

  • Make sure you're copying the full token string

  • Don't add extra spaces or characters

"Agent not found"

  • Check that your agent exists and is visible in the Agents menu

  • Agent must be in the same workspace

WebSocket connection fails

  • Use wss:// (secure WebSocket), not ws://

  • Include authorization and workspaceId in connection params

  • Check your network allows WebSocket connections

No response from agent

  • Make sure isForAiReply: true when sending messages

  • Verify your agent has objectives/instructions configured

  • Check agent has access to required knowledge bases and skills

Best practices

  1. Store client UUID persistently β€” Save it in localStorage so the same user gets the same ID across sessions

  2. Handle token expiration β€” Tokens last about 1 hour; refresh before they expire

  3. Use try-catch blocks β€” Always wrap API calls in error handling

  4. Stream responses β€” Better UX than waiting for full responses

  5. Organize sessions β€” Use clear session names ("Support", "Sales", etc.)

  6. Validate input β€” Check message text before sending

  7. Rate limit β€” Implement client-side delays between messages to avoid overloading your agent

API endpoints

  • REST (auth): https://graphql.swiftask.ai/public/widget-bot/:clientToken

  • GraphQL (queries/mutations): https://graphql.swiftask.ai/graphql

  • WebSocket (subscriptions): wss://graphql.swiftask.ai/graphql


Ready to build? Start with authentication, then explore the deeper guides as you add features. You'll have a working chat integration in minutes. πŸš€