forked from openai/openai-assistants-quickstart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.tsx
250 lines (222 loc) · 6.79 KB
/
chat.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
"use client";
import React, { useState, useEffect, useRef } from "react";
import styles from "./chat.module.css";
import { AssistantStream } from "openai/lib/AssistantStream";
import Markdown from "react-markdown";
// @ts-expect-error - no types for this yet
import { AssistantStreamEvent } from "openai/resources/beta/assistants/assistants";
import { RequiredActionFunctionToolCall } from "openai/resources/beta/threads/runs/runs";
type MessageProps = {
role: "user" | "assistant" | "code";
text: string;
};
const UserMessage = ({ text }: { text: string }) => {
return <div className={styles.userMessage}>{text}</div>;
};
const AssistantMessage = ({ text }: { text: string }) => {
return (
<div className={styles.assistantMessage}>
<Markdown>{text}</Markdown>
</div>
);
};
const CodeMessage = ({ text }: { text: string }) => {
return (
<div className={styles.codeMessage}>
{text.split("\n").map((line, index) => (
<div key={index}>
<span>{`${index + 1}. `}</span>
{line}
</div>
))}
</div>
);
};
const Message = ({ role, text }: MessageProps) => {
switch (role) {
case "user":
return <UserMessage text={text} />;
case "assistant":
return <AssistantMessage text={text} />;
case "code":
return <CodeMessage text={text} />;
default:
return null;
}
};
type ChatProps = {
functionCallHandler?: (
toolCall: RequiredActionFunctionToolCall
) => Promise<string>;
};
const Chat = ({
functionCallHandler = () => Promise.resolve(""), // default to return empty string
}: ChatProps) => {
const [userInput, setUserInput] = useState("");
const [messages, setMessages] = useState([]);
const [inputDisabled, setInputDisabled] = useState(false);
const [threadId, setThreadId] = useState("");
// automitcally scroll to bottom of chat
const messagesEndRef = useRef(null);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
useEffect(() => {
scrollToBottom();
}, [messages]);
// create a new threadID when chat component created
useEffect(() => {
const createThread = async () => {
const res = await fetch(`/api/assistants/threads`, {
method: "POST",
});
const data = await res.json();
setThreadId(data.threadId);
};
createThread();
}, []);
const sendMessage = async (text) => {
const response = await fetch(
`/api/assistants/threads/${threadId}/messages`,
{
method: "POST",
body: JSON.stringify({
content: text,
}),
}
);
const stream = AssistantStream.fromReadableStream(response.body);
handleReadableStream(stream);
};
const submitActionResult = async (runId, toolCallOutputs) => {
const response = await fetch(
`/api/assistants/threads/${threadId}/actions`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
runId: runId,
toolCallOutputs: toolCallOutputs,
}),
}
);
const stream = AssistantStream.fromReadableStream(response.body);
handleReadableStream(stream);
};
const handleSubmit = (e) => {
e.preventDefault();
if (!userInput.trim()) return;
sendMessage(userInput);
setMessages((prevMessages) => [
...prevMessages,
{ role: "user", text: userInput },
]);
setUserInput("");
setInputDisabled(true);
scrollToBottom();
};
/* Stream Event Handlers */
// textCreated - create new assistant message
const handleTextCreated = () => {
appendMessage("assistant", "");
};
// textDelta - append text to last assistant message
const handleTextDelta = (delta) => {
appendToLastMessage(delta.value);
};
// toolCallCreated - log new tool call
const toolCallCreated = (toolCall) => {
if (toolCall.type != "code_interpreter") return;
appendMessage("code", "");
};
// toolCallDelta - log delta and snapshot for the tool call
const toolCallDelta = (delta, snapshot) => {
if (delta.type != "code_interpreter") return;
if (!delta.code_interpreter.input) return;
appendToLastMessage(delta.code_interpreter.input);
};
// handleRequiresAction - handle function call
const handleRequiresAction = async (
event: AssistantStreamEvent.ThreadRunRequiresAction
) => {
const runId = event.data.id;
const toolCalls = event.data.required_action.submit_tool_outputs.tool_calls;
// loop over tool calls and call function handler
const toolCallOutputs = await Promise.all(
toolCalls.map(async (toolCall) => {
const result = await functionCallHandler(toolCall);
return { output: result, tool_call_id: toolCall.id };
})
);
setInputDisabled(true);
submitActionResult(runId, toolCallOutputs);
};
// handleRunCompleted - re-enable the input form
const handleRunCompleted = () => {
setInputDisabled(false);
};
const handleReadableStream = (stream: AssistantStream) => {
// messages
stream.on("textCreated", handleTextCreated);
stream.on("textDelta", handleTextDelta);
// code interpreter
stream.on("toolCallCreated", toolCallCreated);
stream.on("toolCallDelta", toolCallDelta);
// events without helpers yet (e.g. requires_action and run.done)
stream.on("event", (event) => {
if (event.event === "thread.run.requires_action")
handleRequiresAction(event);
if (event.event === "thread.run.completed") handleRunCompleted();
});
};
/*
=======================
=== Utility Helpers ===
=======================
*/
const appendToLastMessage = (text) => {
setMessages((prevMessages) => {
const lastMessage = prevMessages[prevMessages.length - 1];
const updatedLastMessage = {
...lastMessage,
text: lastMessage.text + text,
};
return [...prevMessages.slice(0, -1), updatedLastMessage];
});
};
const appendMessage = (role, text) => {
setMessages((prevMessages) => [...prevMessages, { role, text }]);
};
return (
<div className={styles.chatContainer}>
<div className={styles.messages}>
{messages.map((msg, index) => (
<Message key={index} role={msg.role} text={msg.text} />
))}
<div ref={messagesEndRef} />
</div>
<form
onSubmit={handleSubmit}
className={`${styles.inputForm} ${styles.clearfix}`}
>
<input
type="text"
className={styles.input}
value={userInput}
onChange={(e) => setUserInput(e.target.value)}
placeholder="Enter your question"
/>
<button
type="submit"
className={styles.button}
disabled={inputDisabled}
>
Send
</button>
</form>
</div>
);
};
export default Chat;