I have an account with OpenAI. I have created application using React & Node.js in which ChatGPT is embedded. I have created the following prompt : “Provide positive feedback when the user’s answer is correct.Continue the conversation by asking another question. You may also provide hints if the user’s answer is incorrect.” , which works in OPENAI’s Playground but doesn’t work in the app.
Hi!
In the chat completions playground, you can press “view code”, and see in multiple formats how your request needs to be made to replicate the action.
It sounds like you describe an initial system message to make a permanent behavior for the AI. This, and all other previous chat interactions in a chatbot from user messages and assistant replies, must be passed to the AI each time, as each call is independent.
Can you provide me an example?I didn’t understand well. This is that I want a permament behavior for the AI
In playground, let’s give the AI an obvious behavior like yours in the system message panel.
Place a user message that might evoke the behavior.
(and use the right knowledge cutoff for the model…)
Configure the API parameters to those you would use in a chatbot with less variations in its answering, and press “submit”
Now, you press in the upper-right the magic button. First, delete the assistant replies so you just have your system message and user input.
View code now shows how that request was made, here when JSON is chosen:
I instead take the messages and the parameters shown in Python “view code” and apply them to my chatbot in Python (the automatic user message is usually just “introduce yourself”).
from openai import OpenAI
client = OpenAI()
system = [{"role": "system", "content": (
"You are ChatExpert, a large language model AI assistant "
"trained by OpenAI.\nKnowledge cutoff: 2023-01\n"
"Current date: 2024-04-19\n\n"
"ChatExpert always complements the user excessively on "
"their cleverness and good looks. Correct answers are "
"especially rewarded with complements."
)}]
user = [{"role": "user", "content": (
"Is ChatGPT from OpenAI based on a transformer large "
"language model like GPT-3? I think it is."
)}]
# This loop constantly places ‘system’ in the messages, with past chat
chat = []
while not user[0]['content'] == "exit":
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=system + chat[-10:] + user,
temperature=0.5,
max_tokens=1000,
top_p=0.5,
stream=True) # added streaming plus stream processing
reply = ""
for delta in response:
if not delta.choices[0].finish_reason:
word = delta.choices[0].delta.content or ""
reply += word
print(word, end ="")
chat += user + [{"role": "assistant", "content": reply}]
user = [{"role": "user", "content": input("\nPrompt: ")}]
I receive my reply.
This that I have
import OpenAI from 'openai'
import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'
import { Client } from "@googlemaps/google-maps-services-js";
const app = express()
const PORT = process.env.PORT || 3001
const client = new Client({});
app.use(bodyParser.json());
const openai = new OpenAI({
apiKey: '■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■8LIiIzmi'
})
app.use(cors())
app.use(express.json())
let welcomeMessage = ""
// Express.js endpoint to get a welcome message
app.get('/api/welcome', async (req, res) => {
try {
const response = await openai.chat.completions.create({
model: "gpt-4", // Use an appropriate model
messages: [{ // Assuming a start of a conversation with no prior context
role: "system",
content: "Start by saying 'Hello!Welcome to geography lesson.Do you want start learning geogrpahy?."//"Generate a short friendly and engaging welcome message for a geography discussion chatbot."
}]
});
welcomeMessage = response.choices[0].message.content.trim(); // Store the welcome message
res.json({ message: welcomeMessage });
//res.json({ message: response.choices[0].message.content.trim() });
} catch (error) {
console.error('Error fetching welcome message:', error);
res.status(500).json({ error: 'Failed to fetch welcome message' });
}
});
// Assuming you already have the '/api/welcome' endpoint
// Endpoint to handle user messages and respond
app.post('/api/conversation', async (req, res) => {
const { userMessage } = req.body; // Get the user message from the request
try {
// Send the user message to OpenAI's API
const response = await openai.chat.completions.create({
model: "gpt-4", // Adjust according to the available models
messages: [{"role": "system", "content": welcomeMessage}, // Use the stored welcome message as the first message
//{"role": "user", "content": userMessage},
{"role":"system","content":"You are a geography teacher.You ask ramdom geography questions.When student answers correctly you give feedback by saying 'Excellent job!!!'.When student answers incorrectly you provide hints or the correct answer."},
//{"role":"system","content":"Ask random geography questions"},
// {"role":"system","content":"When student answers correctly give feedback by saying 'Excellent job!!!'."},
// {"role":"system","content":"When student answers incorrectly provide hints or the correct answer."},
{"role":"user","content":userMessage}], // Send the user's message for processing
max_tokens: 150,
});
// Return the generated response to the frontend
res.json({ botResponse: response.choices[0].message.content });
} catch (error) {
console.error('Error in conversation handling:', error);
res.status(500).json({ error: 'Failed to process the conversation' });
}
});
app.post('/api/city-info', async (req, res) => {
const { cityName } = req.body;
try {
const prompt = `Provide detailed information about ${cityName}.`;
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [{"role":"system","content": prompt}],
max_tokens: 150,
});
res.json({ info: response.choices[0].message.content });
} catch (error) {
console.error('Error fetching city information:', error);
res.status(500).json({ error: 'Failed to fetch city information' });
}
});
app.post('/api/location', async (req, res) => {
const { location } = req.body;
try {
const response = await client.geocode({
params: {
address: location,
key: apiKey,
},
});
const { lat, lng } = response.data.results[0].geometry.location;
res.json({ lat, lng });
} catch (error) {
console.error(error);
res.status(500).send('Error retrieving location data');
}
});
app.listen(PORT, () => console.log(`Server started on http://localhost:${PORT}`))
This is what I get
This in playground it works but in app doesn’t as it shows