-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.js
56 lines (44 loc) · 1.37 KB
/
example.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
import {createChatCompletionsMachine} from './lib/index.js';
import {env, stderr, stdout} from 'node:process';
const apiKey = /** @type {string} */ (env.API_KEY);
/** @type {import('./lib/index.js').ChatCompletionsMessage[]} */
const messages = [{role: `user`, content: `Hello`}];
const machine = createChatCompletionsMachine();
machine.subscribe(() => {
const snapshot = machine.get();
switch (snapshot.state) {
case `isReceivingContent`: {
stdout.write(snapshot.value.contentDelta);
break;
}
case `isContentFinished`: {
stdout.write(`\n`);
break;
}
case `isFunctionCallFinished`: {
const {functionName, functionArgs} = snapshot.value;
messages.push({
role: `assistant`,
content: null,
function_call: {name: functionName, arguments: functionArgs},
});
messages.push({role: `function`, content: `John Doe`, name: functionName});
setTimeout(() => {
snapshot.actions.sendRequest({apiKey, body: {model: `gpt-4`, messages}});
});
break;
}
case `isFailed`: {
stderr.write(`${snapshot.value.error}\n`);
}
}
});
machine.assert(`isInitialized`).actions.sendRequest({
apiKey,
body: {
model: `gpt-4`,
messages,
functions: [{name: `getUserName`, parameters: {type: `object`, properties: {}}}],
function_call: {name: `getUserName`},
},
});