forked from jonrhall/openai-streaming-hooks
/
example.tsx
92 lines (85 loc) · 2.63 KB
/
example.tsx
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
import React from 'react';
import ReactDOM from 'react-dom/client';
import './example.css';
import { useChatCompletion } from '../src';
const formatDate = (date: Date) =>
date.toLocaleString('en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short',
});
const ExampleComponent = () => {
const [promptText, setPromptText] = React.useState('');
const { messages, submitPrompt } = useChatCompletion({
model: 'gpt-3.5-turbo',
apiKey: import.meta.env.VITE_OPENAI_API_KEY,
temperature: 0.9,
});
const onSend = () => {
submitPrompt([{ content: promptText, role: 'user' }]);
setPromptText('');
};
// When content is added to the chat window, make sure we scroll to the bottom so the most
// recent content is visible to the user.
React.useEffect(() => {
window.scrollTo(0, document.body.scrollHeight);
}, [messages]);
return (
<>
<div className="chat-wrapper">
{messages.length < 1 ? (
<div className="empty">No messages</div>
) : (
messages.map((msg, i) => (
<div className="message-wrapper" key={i}>
<div className="role">Role: {msg.role}</div>
<pre className="chat-message">{msg.content}</pre>
{!msg.meta.loading && (
<div className="tag-wrapper">
<span className="tag">
Timestamp: {formatDate(new Date(msg.timestamp))}
</span>
{msg.role === 'assistant' && (
<>
<span className="tag">
Tokens: {msg.meta.chunks.length}
</span>
<span className="tag">
Response time: {msg.meta.responseTime}
</span>
</>
)}
</div>
)}
</div>
))
)}
</div>
<div className="prompt-wrapper">
<div>
<textarea
value={promptText}
placeholder="Write a prompt"
onChange={(event) => {
setPromptText(event.target.value);
}}
disabled={
messages.length > 0 && messages[messages.length - 1].meta.loading
}
/>
<button onClick={onSend}>Send</button>
</div>
</div>
</>
);
};
export default ExampleComponent;
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<ExampleComponent />
</React.StrictMode>
);