· 2 years ago · Mar 14, 2023, 03:20 PM
1import React, { useState } from 'react';
2
3function App() {
4 const [input, setInput] = useState('');
5 const [suggestions, setSuggestions] = useState([]);
6 const [output, setOutput] = useState('');
7
8 async function getCompletion() {
9 try {
10 const response = await fetch('https://api.openai.com/v1/engines/code-davinci-002/completions', {
11 method: 'POST',
12 headers: {
13 'Content-Type': 'application/json',
14 'Authorization': 'Bearer ' + 'API Key here'
15 },
16 body: JSON.stringify({
17 'prompt': input,
18 'max_tokens': 1024,
19 'n': 1,
20 'temperature': 0.5,
21 'stop': '\n'
22 })
23 });
24 const { choices } = await response.json();
25 setSuggestions(choices.map(choice => choice.text.trim()));
26 } catch (error) {
27 console.log(error);
28 }
29 }
30
31 async function generateOutput() {
32 try {
33 const response = await fetch('https://api.openai.com/v1/engines/code-davinci-002/completions', {
34 method: 'POST',
35 headers: {
36 'Content-Type': 'application/json',
37 'Authorization': 'Bearer ' + 'API Key here'
38 },
39 body: JSON.stringify({
40 'prompt': input + '\n\nOutput:',
41 'max_tokens': 1024,
42 'temperature': 0.5,
43 'n': 1,
44 'stop': '\n'
45 })
46 });
47 const { choices } = await response.json();
48 console.log(choices);
49 const outputText = choices.map(choice => choice.text.trim())[0];
50 console.log(outputText);
51 setOutput(outputText.substring(outputText.indexOf("Output: ") + 8));
52 } catch (error) {
53 console.log(error);
54 }
55 }
56
57 function handleSubmit() {
58 if (input) {
59 getCompletion();
60 generateOutput();
61 } else {
62 setSuggestions([]);
63 setOutput('');
64 }
65 }
66
67 return (
68
69 <div className="flex flex-col items-center justify-center h-screen">
70 <textarea
71 value={input}
72 onChange={(e) => setInput(e.target.value)}
73 placeholder="Type your prompt here"
74 className="p-4 border border-gray-300 rounded-md w-96 h-48"
75 />
76 <button onClick={handleSubmit} className="mt-4 px-4 py-2 bg-blue-500 text-white rounded-md">
77 Submit Prompt
78 </button>
79 {suggestions.length > 0 && (
80 <ul className="flex flex-col w-96 gap-6">
81 {suggestions.map((suggestion, index) => (
82 <li key={index}>{suggestion}</li>
83 ))}
84 </ul>
85 )}
86 {output && (
87 <div className="flex flex-col w-96 gap-6">
88 <h2 className="font-bold">Output:</h2>
89 <pre>{output}</pre>
90 </div>
91 )}
92 </div>
93 );
94}
95
96export default App;