Skip to content

Commit f270b1b

Browse files
committed
DOC-3187: Testing openai package
1 parent 74989ba commit f270b1b

File tree

3 files changed

+265
-44
lines changed

3 files changed

+265
-44
lines changed

modules/ROOT/examples/live-demos/ai/index.js

Lines changed: 12 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
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

57
const 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
};

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,8 @@
4141
"http-server": "^0.12.3",
4242
"nodemon": "^2.0.7",
4343
"npm-run-all": "^4.1.5"
44+
},
45+
"dependencies": {
46+
"openai": "^4.90.0"
4447
}
4548
}

0 commit comments

Comments
 (0)