Skip to content

Instantly share code, notes, and snippets.

@drifterz13
Last active April 15, 2024 13:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drifterz13/0cbe93ced5dc7958d7841a29c1721d1c to your computer and use it in GitHub Desktop.
Save drifterz13/0cbe93ced5dc7958d7841a29c1721d1c to your computer and use it in GitHub Desktop.
Node.js + OpenAI assistant example
require('dotenv').config()
import OpenAI from 'openai'
import fs from 'fs'
import path from 'path'
import { MessageContentText } from 'openai/resources/beta/threads/messages/messages'
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
})
export async function run() {
const file = await openai.files.create({
file: fs.createReadStream(path.join(__dirname, '../data/cv.pdf')),
purpose: 'assistants',
})
console.log('Upload file for assistant: ', file.id)
const thread = await openai.beta.threads.create({})
console.log('Thred has been created: ', thread)
const assistant = await openai.beta.assistants.create({
instructions:
'You are a recruiter support chatbot. Use your knowledge base to best respond to customer queries. Please also keep the answer short and concise.',
model: 'gpt-4-1106-preview',
tools: [{ type: 'retrieval' }],
file_ids: [file.id],
})
console.log('Assistant has been created: ', assistant)
const message = await openai.beta.threads.messages.create(thread.id, {
role: 'user',
content:
'Summarize technologies that the candidate has worked with in the past and how long they have worked with them without mention company name or the candidate name.',
})
console.log('Adding message to thread: ', message)
const run = await openai.beta.threads.runs.create(thread.id, {
assistant_id: assistant.id,
})
console.log('Run has been created: ', run)
const checkRun = async () => {
return new Promise((resolve, reject) => {
const interval = setInterval(async () => {
const retrieveRun = await openai.beta.threads.runs.retrieve(
thread.id,
run.id
)
console.log('Run status: ', retrieveRun.status)
if (retrieveRun.status === 'completed') {
console.log('Run completed: ', retrieveRun)
clearInterval(interval)
resolve(retrieveRun)
}
}, 3000)
})
}
await checkRun()
const messages = await openai.beta.threads.messages.list(thread.id)
const answer = (messages.data ?? []).find((m) => m?.role === 'assistant')
?.content?.[0] as MessageContentText
console.log('Answer: ', answer.text)
}
;(async () => {
console.log('Running job...⏳')
await run()
console.log('Successfully ran job! ✅')
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment