API Agent
Written By Stanislas
Last updated 18 days ago
Call Swiftask agents directly from your application via API. Learn how to authenticate with an agent token, send requests, and receive responses.
Overview
The Agent API allows you to invoke Swiftask agents from your own applications. Instead of building complex AI logic yourself, you can leverage pre-configured agents with their own knowledge bases, skills, and instructions through a simple REST API.
Each agent has its own authentication token and unique slug. Once authenticated, you can send requests to the agent and receive intelligent responses powered by the agent's configuration, knowledge base, and connected skills.
Prerequisites
Before calling an agent via API, ensure you have:
Agent authentication token — Obtained from your agent's Developer section
Agent slug — The unique identifier for your agent
Basic HTTP knowledge — Understanding of REST API requests and JSON
Getting your agent token and slug
Log in to your Swiftask workspace
Navigate to the Agents section
Select the agent you want to call
Click the pen icon (edit) to open agent settings
Navigate to the Developer section
Copy your Client token and Agent slug
Keep your client token secure—anyone with access to it can make API requests on behalf of your agent and consume your credits.
Step-by-step guide
Step 1: Authenticate with the agent
Send a REST request to get an access token for the agent.
const authenticate = async (clientToken) => {
const clientUuid = crypto.randomUUID(); // Generate a unique ID for this session
const response = await fetch(
'https://graphql.swiftask.ai/public/widget-bot/' + clientToken,
{
method: 'GET',
headers: {
'x-client-uuid': clientUuid,
'Content-Type': 'application/json',
},
}
);
if (!response.ok) {
throw new Error('Authentication failed');
}
const data = await response.json();
return {
accessToken: data.data.accessToken,
botSlug: data.data.botSlug,
todoId: data.data.todoId,
starterSessionId: data.data.starterSessionId,
};
};
// Usage
const auth = await authenticate('your-agent-client-token');
console.log('Authenticated! Access token:', auth.accessToken);
Step 2: Send a request to the agent
Use the access token to send a message to the agent and get a response.
const sendRequest = async (accessToken, sessionId, message) => {
const response = await fetch(
'https://graphql.swiftask.ai/graphql',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken,
},
body: JSON.stringify({
query: `
mutation SendNewMessage($newMessageData: NewMessageInput!) {
sendNewMessage(newMessageData: $newMessageData) {
id
message
createdAt
}
}
`,
variables: {
newMessageData: {
message: message,
sessionId: sessionId,
isForAiReply: true,
},
},
}),
}
);
const result = await response.json();
return result.data.sendNewMessage;
};
// Usage
const message = await sendRequest(auth.accessToken, auth.starterSessionId, 'Hello, agent!');
console.log('Message sent:', message.id);
Step 3: Get the agent's response
Listen for the agent's response as it streams back in real-time.
const subscribeToResponse = (accessToken, sessionId, onChunk, onComplete) => {
const ws = new WebSocket('wss://graphql.swiftask.ai/graphql', ['graphql-ws']);
let fullMessage = '';
ws.addEventListener('open', () => {
ws.send(JSON.stringify({
type: 'connection_init',
payload: {
authorization: 'Bearer ' + accessToken,
},
}));
// Subscribe to message stream
ws.send(JSON.stringify({
id: '1',
type: 'start',
payload: {
query: `
subscription OnMessageStream($sessionId: Float!) {
onMessageStream(sessionId: $sessionId) {
messageChunk
botResponseMessageId
isStoppable
}
}
`,
variables: { sessionId: sessionId },
},
}));
});
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.type === 'data' && message.payload.data.onMessageStream) {
const chunk = message.payload.data.onMessageStream.messageChunk;
fullMessage += chunk;
onChunk(fullMessage);
}
});
ws.addEventListener('close', () => {
onComplete(fullMessage);
});
return ws;
};
// Usage
subscribeToResponse(
auth.accessToken,
auth.starterSessionId,
(fullMessage) => {
console.log('Response so far:', fullMessage);
},
(finalMessage) => {
console.log('Final response:', finalMessage);
}
);
Core operations
Send a message to the agent
Send a message and trigger the agent to respond.
Endpoint: POST https://graphql.swiftask.ai/graphql
Headers:
Authorization: Bearer {accessToken}
Content-Type: application/jsonGraphQL Mutation:
mutation SendNewMessage($newMessageData: NewMessageInput!) {
sendNewMessage(newMessageData: $newMessageData) {
id
message
createdAt
sessionId
isBotReply
}
}
Input parameters:
Example:
const callAgent = async (accessToken, sessionId, userMessage) => {
const response = await fetch('https://graphql.swiftask.ai/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken,
},
body: JSON.stringify({
query: `
mutation SendNewMessage($newMessageData: NewMessageInput!) {
sendNewMessage(newMessageData: $newMessageData) {
id
message
createdAt
}
}
`,
variables: {
newMessageData: {
message: userMessage,
sessionId: sessionId,
isForAiReply: true,
},
},
}),
});
const result = await response.json();
if (result.errors) {
throw new Error(result.errors[0].message);
}
return result.data.sendNewMessage;
};
// Usage
const msg = await callAgent(auth.accessToken, auth.starterSessionId, 'What can you help me with?');
console.log('Agent received your message:', msg.id);
Get the agent's response (synchronous)
For simple requests where you don't need streaming, get the complete response immediately.
GraphQL Mutation:
mutation SyncBotRequest($newMessageData: NewMessageInput!) {
syncBotRequest(newMessageData: $newMessageData) {
text
botId
botSlug
isBotError
sessionId
sources
}
}Example:
const callAgentSync = async (accessToken, sessionId, userMessage) => {
const response = await fetch('https://graphql.swiftask.ai/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken,
},
body: JSON.stringify({
query: `
mutation SyncBotRequest($newMessageData: NewMessageInput!) {
syncBotRequest(newMessageData: $newMessageData) {
text
isBotError
sessionId
sources
}
}
`,
variables: {
newMessageData: {
message: userMessage,
sessionId: sessionId,
},
},
}),
});
const result = await response.json();
if (result.errors) {
throw new Error(result.errors[0].message);
}
return result.data.syncBotRequest;
};
// Usage
const response = await callAgentSync(
auth.accessToken,
auth.starterSessionId,
'What is your pricing?'
);
console.log('Agent response:', response.text);
console.log('Error?', response.isBotError);
console.log('Sources used:', response.sources);Practical use cases
Customer support chatbot
Embed your Swiftask support agent into your website to answer customer questions.
const handleUserQuestion = async (userQuestion) => {
try {
// Authenticate (do this once and cache the token)
const auth = await authenticate('your-support-agent-token');
// Call the agent
const response = await callAgentSync(
auth.accessToken,
auth.starterSessionId,
userQuestion
);
if (response.isBotError) {
return 'Sorry, I encountered an error. Please try again.';
}
return response.text;
} catch (error) {
console.error('Error calling agent:', error);
return 'Unable to reach support agent.';
}
};
// Usage in your chat widget
const answer = await handleUserQuestion('How do I reset my password?');
displayAnswer(answer);
Document analysis service
Send documents to your agent for analysis and get structured responses.
const analyzeDocument = async (accessToken, sessionId, documentContent) => {
const message = `Please analyze this document:\n\n${documentContent}`;
const response = await callAgentSync(
accessToken,
sessionId,
message
);
return {
analysis: response.text,
sources: response.sources,
success: !response.isBotError,
};
};
// Usage
const result = await analyzeDocument(
auth.accessToken,
auth.starterSessionId,
'Your document content here...'
);
console.log('Analysis:', result.analysis);
Real-time streaming responses
Display agent responses as they're generated for a better user experience.
const displayStreamingResponse = async (accessToken, sessionId, userMessage) => {
// Send the message
await callAgent(accessToken, sessionId, userMessage);
// Subscribe to streaming response
return new Promise((resolve) => {
subscribeToResponse(
accessToken,
sessionId,
(fullMessage) => {
// Update UI with partial response
updateChatDisplay(fullMessage);
},
(finalMessage) => {
// Response complete
console.log('Final response:', finalMessage);
resolve(finalMessage);
}
);
});
};
// Usage
const finalResponse = await displayStreamingResponse(
auth.accessToken,
auth.starterSessionId,
'Explain machine learning'
);
Tips & best practices
Cache your authentication token. Don't authenticate on every request. Store the access token and reuse it for multiple calls within the same session.
let cachedAuth = null;
const getAuth = async (clientToken) => {
if (!cachedAuth) {
cachedAuth = await authenticate(clientToken);
}
return cachedAuth;
};
Use synchronous requests for simple queries. If you don't need streaming, use syncBotRequest for simpler code and faster responses.
Always set isForAiReply: true. Without this flag, your message is stored but the agent won't respond. Only set it to false if you're just logging messages.
Handle errors gracefully. Always check for isBotError in responses and handle network errors.
try {
const response = await callAgentSync(accessToken, sessionId, message);
if (response.isBotError) {
console.error('Agent error:', response.text);
showUserError('The agent encountered an error.');
} else {
displayResponse(response.text);
}
} catch (error) {
console.error('Network error:', error);
showUserError('Unable to reach the agent.');
}
Validate your input. Check message length and content before sending.
const validateMessage = (message) => {
if (!message || message.trim().length === 0) {
throw new Error('Message cannot be empty');
}
if (message.length > 5000) {
throw new Error('Message exceeds 5000 character limit');
}
return message.trim();
};
Use the agent's knowledge base. Your agent's responses are powered by its configured knowledge base and skills. Make sure these are set up correctly in the agent configuration.
Ready to call your first agent? Use the step-by-step guide above to authenticate and send your first request to your agent.