forked from socketteer/clooi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
use-api-server-streaming.js
110 lines (102 loc) · 3.39 KB
/
use-api-server-streaming.js
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
// Run the server first with `npm run server`
import { fetchEventSource } from '@waylaidwanderer/fetch-event-source';
const opts = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: {
userMessage: 'Hello, how are you?',
// previousMessages: [
// {
// author: 'user',
// text: 'Hello',
// },
// ],
},
// modelOptions: {
// model: 'claude-3-5-sonnet-20240620',
// max_tokens: 4096,
// temperature: 1,
// stream: true,
// },
modelOptions: {
toneStyle: 'creative', // creative, precise, balanced, or fast
// advanced options
stream: true,
city: 'between words',
country: 'United States',
messageText: 'Continue the conversation in context. Assistant:', // content of user message if nothing is injected there
},
// opts: {
// n: 1,
// },
opts: {
n: 1,
// advanced options
// systemMessage: fs.readFileSync('./contexts/youArePrometheus.txt', 'utf8'),
systemInjectSite: 'location', // context or location (overrides default country)
historyInjectSite: 'location', // context or location
messageInjectSite: 'message', // message, context, or location
censoredMessageInjection: '⚠',
stopToken: '\n\n[user](#message)',
context: null, // fs.readFileSync('./contexts/context.txt', 'utf8'), // a string injected into web page context; will be prepended to messages injected to context
},
// modelOptions: {
// model: 'claude-3-5-sonnet-20240620',
// max_tokens: 4096,
// temperature: 1,
// stream: true,
// messages: [
// {
// role: 'user',
// content: 'Hello',
// },
// ]
// },
// messageOptions: {
// n: 1,
// },
//client: 'claude',
client: 'bing',
}),
};
try {
let reply = '';
const controller = new AbortController();
await fetchEventSource('http://localhost:3000/conversation', {
...opts,
signal: controller.signal,
onopen(response) {
if (response.status === 200) {
return;
}
throw new Error(`Failed to send message. HTTP ${response.status} - ${response.statusText}`);
},
onclose() {
throw new Error('Failed to send message. Server closed the connection unexpectedly.');
},
onerror(err) {
throw err;
},
onmessage(message) {
// { data: 'Hello', event: '', id: '', retry: undefined }
if (message.data === '[DONE]') {
controller.abort();
console.log(message);
return;
}
if (message.event === 'result') {
const result = JSON.parse(message.data);
console.log(result);
return;
}
console.log(message);
reply += JSON.parse(message.data);
},
});
console.log(reply);
} catch (err) {
console.log('ERROR', err);
}