chatgpt conversations

This commit is contained in:
Claeb101 2023-03-04 16:16:01 -05:00
parent 96f2d2ea69
commit 4e6c94fbfa
3 changed files with 38 additions and 48 deletions

72
chat.js
View File

@ -5,60 +5,38 @@ dotenv.config()
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
console.log(process.env.OPENAI_API_KEY)
const openai = new OpenAIApi(configuration);
export default async function (req, res) {
if (!configuration.apiKey) {
res.status(500).json({
error: {
message: "OpenAI API key not configured, please follow instructions in README.md",
class Conversation {
messages;
constructor(context = "ChatGPT, for the following conversation, please pretend to be a therapist working at a suicide. Respond as if I've called you.") {
this.messages = [
{
"role": "system",
"content": context
}
});
return;
]
}
const animal = req.body.animal || '';
if (animal.trim().length === 0) {
res.status(400).json({
error: {
message: "Please enter a valid animal",
}
});
return;
}
async message(msg) {
this.messages.push({
"role": "user",
"content": msg
})
try {
const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: generatePrompt(animal),
temperature: 0.6,
});
res.status(200).json({ result: completion.data.choices[0].text });
} catch (error) {
// Consider adjusting the error handling logic for your use case
if (error.response) {
console.error(error.response.status, error.response.data);
res.status(error.response.status).json(error.response.data);
} else {
console.error(`Error with OpenAI API request: ${error.message}`);
res.status(500).json({
error: {
message: 'An error occurred during your request.',
}
});
}
const res = await openai.createChatCompletion({
model: "gpt-3.5-turbo",
messages: this.messages
})
const next = res.data.choices[0].message
this.messages.push(next)
return next.content
}
}
function generatePrompt(animal) {
const capitalizedAnimal =
animal[0].toUpperCase() + animal.slice(1).toLowerCase();
return `Suggest three names for an animal that is a superhero.
Animal: Cat
Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
Animal: Dog
Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
Animal: ${capitalizedAnimal}
Names:`;
export {
Conversation
}

View File

@ -5,7 +5,8 @@
"private": true,
"scripts": {
"chat": "node chat.js",
"call": "node call.js"
"call": "node call.js",
"test": "node test.js"
},
"dependencies": {
"express": "^4.18.2",

11
test.js Normal file
View File

@ -0,0 +1,11 @@
import { Conversation } from "./chat.js"
const main = async () => {
let convo = new Conversation()
let res = await convo.message("I'm just feeling sad.")
console.log("RESPONSE", res)
res = await convo.message("Yeah. My parents got divorced last week, and I think it's my fault.")
console.log("RESPONSE", res)
}
main()