-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.jsx
103 lines (101 loc) · 2.64 KB
/
App.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import * as React from 'react';
import * as RN from 'react-native';
const { Configuration, OpenAIApi } = require("openai");
import axios from 'axios';
const configuration = new Configuration({
apiKey: 'use your openai api key'
})
export default function App() {
const [chatGptQ, setChatGptQ] = React.useState({
question: '',
answer: ''
})
const [isLoading, setIsLoading] = React.useState(false);
const getGptResponse = async () => {
if(chatGptQ.question.length === 0){
setChatGptQ({...chatGptQ,answer: "You didn't Asked any Question"})
return;
}
setIsLoading(true);
try {
const openai = new OpenAIApi(configuration)
const completion = await openai.createCompletion({
model: "text-davinci-003",
prompt: chatGptQ.question,
max_tokens: 200,
})
console.log('Generated')
updateAns(completion.data.choices[0].text);
} catch (error) {
console.log(error.message)
setChatGptQ({ ...chatGptQ, answer: error.message })
setIsLoading(false);
}
}
const updateAns = (txt) =>{
let i = 3;
const intervalId = setInterval(() => {
if (i < txt.length) {
setChatGptQ({ ...chatGptQ, answer: txt.slice(2,i) });
i++;
} else {
clearInterval(intervalId);
}
}, 100);
setIsLoading(false);
}
return (
<RN.View style={styles.container}>
<RN.TextInput
style={styles.inputField}
placeholder='Send a message'
placeholderTextColor={'#8e8e8e'}
onChangeText={(val) => setChatGptQ({ ...chatGptQ, question: val })}
onSubmitEditing={getGptResponse}
/>
<RN.ScrollView style={styles.ansBox}>
<RN.Text style={styles.ansText}>{chatGptQ.answer}</RN.Text>
</RN.ScrollView>
<RN.TouchableOpacity style={styles.button} activeOpacity={0.4}
onPress={getGptResponse} disabled={isLoading}>
{isLoading?<RN.ActivityIndicator size={22} color={'white'}/>:
<RN.Text style={styles.btnText}>Generate</RN.Text>
}
</RN.TouchableOpacity>
</RN.View>
);
};
const styles = RN.StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#343541',
padding: 5
},
button: {
backgroundColor: '#1ba680',
borderColor: 'white',
borderRadius: 5,
padding: 10,
margin: 5,
alignItems: 'center'
},
btnText: {
fontSize: 16,
color: 'white',
},
inputField: {
backgroundColor: '#444654',
padding: 10,
fontSize: 16,
color: 'white'
},
ansBox: {
backgroundColor: '#444654',
marginVertical: 10,
padding: 10
},
ansText: {
color: 'white',
fontSize: 16,
}
})