Created
June 1, 2024 10:19
-
-
Save CiprianSpiridon/a6dc59575fd459e59db2f556b9e335fc to your computer and use it in GitHub Desktop.
Strapi Service to send data to OpenAI Assistant v2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
const {OpenAI} = require("openai"); | |
const openai = new OpenAI({ | |
apiKey: process.env.OPENAI, | |
}); | |
//openai assistant ID to make sure we only use 1 assistant - limits costs | |
const assistantId = process.env.OPENAI_ASSISTANT_ID; | |
//assistant instructions | |
const assistantInstructions = process.env.OPENAI_ASSISTANT_INSTRUCTIONS | |
/** | |
* Anonymize CV with GPT Service | |
*/ | |
module.exports = ({strapi}) => ({ | |
anonimyzeService: async (input) => { | |
try { | |
const thread = await openai.beta.threads.create(); | |
const message = await openai.beta.threads.messages.create( | |
thread.id, | |
{ | |
role: "user", | |
content: input | |
} | |
); | |
console.log('-------------openai.beta.threads.messages.create') | |
let run = await openai.beta.threads.runs.createAndPoll( | |
thread.id, | |
{ | |
assistant_id: assistantId, | |
instructions: assistantInstructions | |
} | |
); | |
console.log('-------------openai.beta.threads.runs.createAndPoll') | |
// Check if the run was completed and log the messages | |
if (run.status === 'completed') { | |
const messages = await openai.beta.threads.messages.list(run.thread_id); | |
const responseMessages = messages.data.reverse().map(message => message.content[0].text.value); | |
return JSON.parse(responseMessages[1]); | |
} else { | |
ctx.body = run.status; | |
console.log(run.status); | |
} | |
} catch (err) { | |
console.log('err'); | |
console.log(err); | |
ctx.body = err; | |
} | |
console.log('end'); | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment