1- const fetchApi = import (
2- 'https://unpkg.com/@microsoft/[email protected] /lib/esm/index.js' 3- ) . then ( ( module ) => module . fetchEventSource ) ;
1+ const openai = import (
2+ 'https://cdn.jsdelivr.net/npm/[email protected] ' 3+ ) . then ( ( OpenAI ) => new OpenAI ( {
4+ baseURL : '{{ openai_proxy_url }}'
5+ } ) ) ;
46
57const ai_request = ( request , respondWith ) => {
68 respondWith . stream ( ( signal , streamMessage ) => {
@@ -72,24 +74,6 @@ const ai_request = (request, respondWith) => {
7274 body : JSON . stringify ( requestBody ) ,
7375 } ;
7476
75- const onopen = async ( response ) => {
76- if ( response ) {
77- const contentType = response . headers . get ( 'content-type' ) ;
78- if ( response . ok && contentType ?. includes ( 'text/event-stream' ) ) {
79- return ;
80- } else if ( contentType ?. includes ( 'application/json' ) ) {
81- const data = await response . json ( ) ;
82- if ( data . error ) {
83- throw new Error (
84- `${ data . error . type } : ${ data . error . message } `
85- ) ;
86- }
87- }
88- } else {
89- throw new Error ( 'Failed to communicate with the ChatGPT API' ) ;
90- }
91- } ;
92-
9377 // This function passes each new message into the plugin via the `streamMessage` callback.
9478 const onmessage = ( ev ) => {
9579 const data = ev . data ;
@@ -110,28 +94,14 @@ const ai_request = (request, respondWith) => {
11094 throw error ;
11195 } ;
11296
113- // Use microsoft's fetch-event-source library to work around the 2000 character limit
114- // of the browser `EventSource` API, which requires query strings
115- return fetchApi
116- . then ( ( fetchEventSource ) =>
117- fetchEventSource ( '{{ openai_proxy_url }}' , {
118- ...openAiOptions ,
119- openWhenHidden : true ,
120- onopen,
121- onmessage,
122- onerror,
123- } )
124- )
125- . then ( async ( response ) => {
126- if ( response && ! response . ok ) {
127- const data = await response . json ( ) ;
128- if ( data . error ) {
129- throw new Error (
130- `${ data . error . type } : ${ data . error . message } `
131- ) ;
132- }
97+ return openai
98+ . then ( ( client ) => client . responses . create ( openAiOptions )
99+ . then ( ( stream ) => {
100+ console . log ( 'Stream created' ) ;
101+ for ( const event of stream ) {
102+ event . then ( onmessage ) . catch ( onerror ) ;
133103 }
134- } )
104+ } ) )
135105 . catch ( onerror ) ;
136106 } ) ;
137107} ;
0 commit comments