OpenAI SDK

Swiftask AI Integration with OpenAI SDK

This documentation provides a step-by-step guide for developers to integrate AI capabilities into their Swiftask application using the OpenAI SDK.

Prerequisites

  • Swiftask Account: Ensure you have a Swiftask account.

  • API Key: You need an API key from your Swiftask account. Follow these steps to create one:

    1. Log in to your Swiftask account.

    2. Navigate to the API settings or developer section.

    3. Generate a new API key and keep it secure.

  • Node.js Environment: Ensure Node.js is installed on your machine.

  • OpenAI SDK: Access to the OpenAI SDK.

Installation

First, you need to install the OpenAI SDK. You can do this using npm:

npm install openai

Integration Steps

1. Import the OpenAI SDK

Start by importing the OpenAI SDK into your project:

import OpenAI from 'openai';

2. Initialize the OpenAI Client

Create an instance of the OpenAI client with your Swiftask API key and the appropriate base URL:

const openai = new OpenAI({
    apiKey: 'swiftask-api-key', // Replace with your actual Swiftask API key
    baseURL: 'https://graphql.swiftask.ai/v1',
});

3. Create a Chat Completion Request

To interact with the AI, create a chat completion request. Specify the model and the messages you want to send:

const completion = openai.chat.completions.create({
    model: 'gpt-4o', // Specify the model you want to use
    messages: [
        { role: 'system', content: 'You are a helpful assistant.' },
        { role: 'user', content: 'Hello, how are you?' },
    ],
});

4. Handle the Response

Use a promise to handle the response from the AI. You can access the AI's reply through the response.choices array:

completion.then((response) => {
    console.log(response.choices[0].message.content);
});

Example Code

Here is the complete example code:

import OpenAI from 'openai';

const openai = new OpenAI({
    apiKey: 'swiftask-api-key', // Replace with your actual Swiftask API key
    baseURL: 'https://graphql.swiftask.ai/v1',
});

const completion = openai.chat.completions.create({
    model: 'gpt-4o', // Specify the model slug you want to use
    messages: [
        { role: 'system', content: 'You are a helpful assistant.' },
        { role: 'user', content: 'Hello, how are you?' },
    ],
}).then((response) => {
    console.log(response.choices[0].message.content);
});

You can refer to List of AI and agents accessible via API to get ai slug

Last updated