Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Quick Start Guide: OpenAI Assistants API

Get Started with OpenAI Assistant API

OpenAI Assistants API provides a quick way to create smart agents that support features like Code Interpreter, Retrieval, and Function calling.

It offers an easy way to set up a generative AI agent that can be pre-loaded with a custom knowledge-base which can be used when users query information.

This is a quick start guide on working with the Assistants API. For a deeper understanding of Assistants, we recommend reviewing the OpenAI Documentation HERE.

Assistants Flow

  • 1.Create a Thread where messages are stored
  • 2.Create a Run
  • 3.Monitor Run for Status
  • 4.Retrieve Messages once Run is complete

Install Dependency

JavaScript

npm install openai

Python

pip install openai

Import and Configure Client

JavaScript

import OpenAI from "openai";
const openai = new OpenAI({
	baseURL: {BASE_URL},
    apiKey: {YOUR_KEY}
});

Python

from openai import OpenAI

client = OpenAI(
    base_url={BASE_URL},
    api_key={YOUR_KEY}
)

Creating an Assistant

Assistants can be either created programmatically via the SDK or by using the Open AI Assistants UI, which provides an easy-to-use interface for configuring the assistant.

For our projects, Assistants have already been created for you. However, if you wish to explore the creation flow, we recommend creating an account on OpenAI.

Creating a Thread

JavaScript

const thread = await openai.beta.threads.create({
	messages: [{
		"role": "user",
		"content": user_content
	}]
});

Python

thread = client.beta.threads.create(
	messages=[{
		"role": "user",
		"content": user_content
	}]
)

Creating a Run

JavaScript

openai.beta.threads.runs.create(thread_id, {
	assistant_id: assistant_id
})

Python

client.beta.threads.runs.create(
	thread_id=thread_id,
	assistant_id=assistant_id,
)

Polling for Run Status & Fetching Messages

Since the run is executed asynchronously, you will have to periodically poll to get status updates of the run. Once the run status is completed, you can get the generated message.

JavaScript

openai.beta.threads.runs.retrieve(thread_id, run_id)

Python

client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run_id)

Getting Messages

client.beta.threads.messages.list(thread_id)