Open ai chatbot giving wrong responses after 2nd text inputs. Using text-davinci-002/completions API
I am trying to use openai API-text-davinci-002/completions in react native to create a chatbot assistant. It works for the first text input user types in, but after that it starts giving responses as if chatbot has started talking to itself and responses are completely un-related to what user has typed in. Example screenshots are shown below
Code:
const ChatBot = ({navigation}) => {
const [data, setData] = useState([]);
const [loader, setLoader] = useState(false);
const [firstResponse, setFirstResponse] = useState(false);
const apiKey = openAiKey;
const apiUrl =
'....api.openai.com/v1/engines/text-davinci-002/completions';
const [textInput, setTextInput] = useState('');
const handleSend = async () => {
setLoader(true);
const prompt = textInput;
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
prompt: prompt,
max_tokens: 1024,
temperature: 0.5,
}),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const responseData = await response.json();
console.log('response', responseData);
setLoader(false);
setFirstResponse(true);
const text = responseData.choices[0].text;
setData([
...data,
{type: 'user', text: textInput},
{type: 'bot', text: text},
]);
setTextInput('');
} catch (error) {
console.error('Error fetching data:', error);
setLoader(false);
}
};
return (
<KeyboardAvoidingView
behavior={Platform.OS === 'ios' ? 'padding' : 'height'} // 'padding' for iOS, 'height' for Android
style={{flex: 1}}>
<View style={styles.container}>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
marginHorizontal: 20,
}}>
<TouchableOpacity onPress={() => navigation.goBack()}>
<MaterialCommunityIcons name="arrow-left" size={25} color="white" />
</TouchableOpacity>
<Text style={styles.title}>AI ChatBot</Text>
</View>
<FlatList
data={data}
keyExtractor={(item, index) => index.toString()}
contentContainerStyle={styles.listContainer}
style={styles.body}
renderItem={({item}) => (
<View style={{flexDirection: 'row', padding: 10}}>
<Text
style={{
fontWeight: 'bold',
color: item.type === 'user' ? 'green' : 'red',
}}>
{item.type === 'user' ? 'You: ' : 'Bot: '}
</Text>
<Text style={styles.bot}>{item.text}</Text>
</View>
)}
/>
<View
style={{
alignItems: 'center',
flexDirection: 'row',
marginHorizontal: 20,
}}>
<TextInput
style={styles.input}
value={textInput}
onChangeText={text => setTextInput(text)}
placeholder="Send a message"
placeholderTextColor="#8E8EA0"
/>
<TouchableOpacity style={styles.button} onPress={handleSend}>
{loader ? (
<ActivityIndicator color="white" />
) : (
<MaterialCommunityIcons
name="send-circle"
size={30}
color="white"
/>
)}
{/* <Text style={styles.buttonText}>Send</Text> */}
</TouchableOpacity>
</View>
</View>
</KeyboardAvoidingView>
);
};