|
| 1 | +const fetchApi = import( |
| 2 | + "https://unpkg.com/@microsoft/[email protected]/lib/esm/index.js" |
| 3 | +).then((module) => module.fetchEventSource); |
| 4 | + |
| 5 | +// This example stores the OpenAI API key in the client side integration. This is not recommended for any purpose. |
| 6 | +// Instead, an alternate method for retrieving the API key should be used. |
| 7 | +const openai_api_key = "<INSERT_OPENAI_API_KEY_HERE>"; |
| 8 | + |
1 | 9 | const useDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; |
2 | 10 | const isSmallScreen = window.matchMedia('(max-width: 1023.5px)').matches; |
3 | 11 |
|
4 | 12 | tinymce.init({ |
5 | 13 | selector: 'textarea#full-featured', |
6 | | - plugins: 'preview powerpaste casechange importcss tinydrive searchreplace autolink autosave save directionality advcode visualblocks visualchars fullscreen image link math media mediaembed codesample table charmap pagebreak nonbreaking anchor tableofcontents insertdatetime advlist lists checklist wordcount tinymcespellchecker a11ychecker editimage help formatpainter permanentpen pageembed charmap tinycomments mentions quickbars linkchecker emoticons advtable footnotes mergetags autocorrect typography advtemplate markdown revisionhistory', |
| 14 | + plugins: 'ai preview powerpaste casechange importcss tinydrive searchreplace autolink autosave save directionality advcode visualblocks visualchars fullscreen image link math media mediaembed codesample table charmap pagebreak nonbreaking anchor tableofcontents insertdatetime advlist lists checklist wordcount tinymcespellchecker a11ychecker editimage help formatpainter permanentpen pageembed charmap tinycomments mentions quickbars linkchecker emoticons advtable footnotes mergetags autocorrect typography advtemplate markdown revisionhistory', |
7 | 15 | tinydrive_token_provider: 'URL_TO_YOUR_TOKEN_PROVIDER', |
8 | 16 | tinydrive_dropbox_app_key: 'YOUR_DROPBOX_APP_KEY', |
9 | 17 | tinydrive_google_drive_key: 'YOUR_GOOGLE_DRIVE_KEY', |
10 | 18 | tinydrive_google_drive_client_id: 'YOUR_GOOGLE_DRIVE_CLIENT_ID', |
11 | 19 | mobile: { |
12 | | - plugins: 'preview powerpaste casechange importcss tinydrive searchreplace autolink autosave save directionality advcode visualblocks visualchars fullscreen image link math media mediaembed codesample table charmap pagebreak nonbreaking anchor tableofcontents insertdatetime advlist lists checklist wordcount tinymcespellchecker a11ychecker help formatpainter pageembed charmap mentions quickbars linkchecker emoticons advtable footnotes mergetags autocorrect typography advtemplate', |
| 20 | + plugins: 'ai preview powerpaste casechange importcss tinydrive searchreplace autolink autosave save directionality advcode visualblocks visualchars fullscreen image link math media mediaembed codesample table charmap pagebreak nonbreaking anchor tableofcontents insertdatetime advlist lists checklist wordcount tinymcespellchecker a11ychecker help formatpainter pageembed charmap mentions quickbars linkchecker emoticons advtable footnotes mergetags autocorrect typography advtemplate', |
13 | 21 | }, |
14 | 22 | menu: { |
15 | 23 | tc: { |
@@ -105,17 +113,6 @@ tinymce.init({ |
105 | 113 | a11y_advanced_options: true, |
106 | 114 | skin: useDarkMode ? 'oxide-dark' : 'oxide', |
107 | 115 | content_css: useDarkMode ? 'dark' : 'default', |
108 | | - /* |
109 | | - The following settings require more configuration than shown here. |
110 | | - For information on configuring the mentions plugin, see: |
111 | | - https://www.tiny.cloud/docs/tinymce/6/mentions/. |
112 | | - */ |
113 | | - mentions_selector: '.mymention', |
114 | | - mentions_fetch: mentions_fetch, // TODO: Implement mentions_fetch |
115 | | - mentions_menu_hover: mentions_menu_hover, // TODO: Implement mentions_menu_hover |
116 | | - mentions_menu_complete: mentions_menu_complete, // TODO: Implement mentions_menu_complete |
117 | | - mentions_select: mentions_select, // TODO: Implement mentions_select |
118 | | - mentions_item_type: 'profile', |
119 | 116 | autocorrect_capitalize: true, |
120 | 117 | mergetags_list: [ |
121 | 118 | { |
@@ -157,5 +154,145 @@ tinymce.init({ |
157 | 154 | content: '<p>Initial content</p>' |
158 | 155 | }, |
159 | 156 | ]); |
160 | | - } |
| 157 | + }, |
| 158 | + ai_request: (request, respondWith) => { |
| 159 | + respondWith.stream((signal, streamMessage) => { |
| 160 | + // Adds each previous query and response as individual messages |
| 161 | + const conversation = request.thread.flatMap((event) => { |
| 162 | + if (event.response) { |
| 163 | + return [ |
| 164 | + { role: "user", content: event.request.query }, |
| 165 | + { role: "assistant", content: event.response.data }, |
| 166 | + ]; |
| 167 | + } else { |
| 168 | + return []; |
| 169 | + } |
| 170 | + }); |
| 171 | + |
| 172 | + // System messages provided by the plugin to format the output as HTML content. |
| 173 | + const systemMessages = request.system.map((content) => ({ |
| 174 | + role: "system", |
| 175 | + content, |
| 176 | + })); |
| 177 | + |
| 178 | + // Forms the new query sent to the API |
| 179 | + const content = |
| 180 | + request.context.length === 0 || conversation.length > 0 |
| 181 | + ? request.query |
| 182 | + : `Question: ${request.query} Context: """${request.context}"""`; |
| 183 | + |
| 184 | + const messages = [ |
| 185 | + ...conversation, |
| 186 | + ...systemMessages, |
| 187 | + { role: "user", content }, |
| 188 | + ]; |
| 189 | + |
| 190 | + let hasHead = false; |
| 191 | + let markdownHead = ""; |
| 192 | + |
| 193 | + const hasMarkdown = (message) => { |
| 194 | + if (message.includes("`") && markdownHead !== "```") { |
| 195 | + const numBackticks = message.split("`").length - 1; |
| 196 | + markdownHead += "`".repeat(numBackticks); |
| 197 | + if (hasHead && markdownHead === "```") { |
| 198 | + markdownHead = ""; |
| 199 | + hasHead = false; |
| 200 | + } |
| 201 | + return true; |
| 202 | + } else if (message.includes("html") && markdownHead === "```") { |
| 203 | + markdownHead = ""; |
| 204 | + hasHead = true; |
| 205 | + return true; |
| 206 | + } |
| 207 | + return false; |
| 208 | + }; |
| 209 | + |
| 210 | + const requestBody = { |
| 211 | + model: "gpt-4o", |
| 212 | + temperature: 0.7, |
| 213 | + max_tokens: 4000, |
| 214 | + messages, |
| 215 | + stream: true, |
| 216 | + }; |
| 217 | + |
| 218 | + const openAiOptions = { |
| 219 | + signal, |
| 220 | + method: "POST", |
| 221 | + headers: { |
| 222 | + "Content-Type": "application/json", |
| 223 | + Authorization: `Bearer ${openai_api_key}`, |
| 224 | + }, |
| 225 | + body: JSON.stringify(requestBody), |
| 226 | + }; |
| 227 | + |
| 228 | + const onopen = async (response) => { |
| 229 | + if (response) { |
| 230 | + const contentType = response.headers.get("content-type"); |
| 231 | + if (response.ok && contentType?.includes("text/event-stream")) { |
| 232 | + return; |
| 233 | + } else if (contentType?.includes("application/json")) { |
| 234 | + const data = await response.json(); |
| 235 | + if (data.error) { |
| 236 | + throw new Error(`${data.error.type}: ${data.error.message}`); |
| 237 | + } |
| 238 | + } |
| 239 | + } else { |
| 240 | + throw new Error("Failed to communicate with the ChatGPT API"); |
| 241 | + } |
| 242 | + }; |
| 243 | + |
| 244 | + // This function passes each new message into the plugin via the `streamMessage` callback. |
| 245 | + const onmessage = (ev) => { |
| 246 | + const data = ev.data; |
| 247 | + if (data !== "[DONE]") { |
| 248 | + const parsedData = JSON.parse(data); |
| 249 | + const firstChoice = parsedData?.choices[0]; |
| 250 | + const message = firstChoice?.delta?.content; |
| 251 | + if (message && message !== "") { |
| 252 | + if (!hasMarkdown(message)) { |
| 253 | + streamMessage(message); |
| 254 | + } |
| 255 | + } |
| 256 | + } |
| 257 | + }; |
| 258 | + |
| 259 | + const onerror = (error) => { |
| 260 | + // Stop operation and do not retry by the fetch-event-source |
| 261 | + throw error; |
| 262 | + }; |
| 263 | + |
| 264 | + // Use microsoft's fetch-event-source library to work around the 2000 character limit |
| 265 | + // of the browser `EventSource` API, which requires query strings |
| 266 | + return fetchApi |
| 267 | + .then((fetchEventSource) => |
| 268 | + fetchEventSource("https://api.openai.com/v1/chat/completions", { |
| 269 | + ...openAiOptions, |
| 270 | + openWhenHidden: true, |
| 271 | + onopen, |
| 272 | + onmessage, |
| 273 | + onerror, |
| 274 | + }) |
| 275 | + ) |
| 276 | + .then(async (response) => { |
| 277 | + if (response && !response.ok) { |
| 278 | + const data = await response.json(); |
| 279 | + if (data.error) { |
| 280 | + throw new Error(`${data.error.type}: ${data.error.message}`); |
| 281 | + } |
| 282 | + } |
| 283 | + }) |
| 284 | + .catch(onerror); |
| 285 | + }); |
| 286 | + }, |
| 287 | + /* |
| 288 | + The following settings require more configuration than shown here. |
| 289 | + For information on configuring the mentions plugin, see: |
| 290 | + https://www.tiny.cloud/docs/tinymce/latest/mentions/. |
| 291 | + */ |
| 292 | + mentions_selector: ".mymention", |
| 293 | + mentions_fetch: mentions_fetch, // TODO: Implement mentions_fetch |
| 294 | + mentions_menu_hover: mentions_menu_hover, // TODO: Implement mentions_menu_hover |
| 295 | + mentions_menu_complete: mentions_menu_complete, // TODO: Implement mentions_menu_complete |
| 296 | + mentions_select: mentions_select, // TODO: Implement mentions_select |
| 297 | + mentions_item_type: "profile", |
161 | 298 | }); |
0 commit comments