-
Notifications
You must be signed in to change notification settings - Fork 0
/
page.tsx
79 lines (69 loc) · 2.39 KB
/
page.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
"use client";
import { FormEvent, useState } from "react";
import { ChatCompletionStream } from "together-ai/lib/ChatCompletionStream";
export default function Chat() {
const [question, setQuestion] = useState("");
const [answer, setAnswer] = useState("");
const [status, setStatus] = useState<"idle" | "pending" | "done">("idle");
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
setStatus("pending");
const res = await fetch("/api/answer", {
method: "POST",
body: JSON.stringify({ question }),
});
if (!res.body) return;
ChatCompletionStream.fromReadableStream(res.body)
.on("content", (delta) => setAnswer((text) => text + delta))
.on("end", () => setStatus("done"));
}
return (
<div className="mx-auto flex w-full max-w-3xl grow flex-col px-4">
{status === "idle" ? (
<div className="flex grow flex-col justify-center">
<form onSubmit={handleSubmit} className="flex w-full gap-2">
<input
placeholder="Ask me a question"
autoFocus
name="prompt"
required
value={question}
onChange={(e) => setQuestion(e.target.value)}
className="block w-full rounded border border-gray-300 p-2 outline-black"
/>
<button
className="rounded bg-black px-3 py-1 font-medium text-white outline-offset-[3px] outline-black"
type="submit"
>
Submit
</button>
</form>
</div>
) : (
<>
<div className="mt-8 flex flex-col justify-end">
<div className="grid grid-cols-4">
<p className="col-span-3 text-xl">{question}</p>
<div className="text-right">
<button
className="rounded bg-black px-3 py-2 font-medium text-white disabled:opacity-50"
disabled={status === "pending"}
onClick={() => {
setQuestion("");
setAnswer("");
setStatus("idle");
}}
>
Reset
</button>
</div>
</div>
</div>
<div className="py-8">
<p className="whitespace-pre-wrap">{answer}</p>
</div>
</>
)}
</div>
);
}