@statelyai/agent 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +3 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +124 -0
- package/dist/index.mjs +7 -0
- package/examples/joke.ts +185 -0
- package/examples/ticTacToe.ts +249 -0
- package/package.json +26 -0
- package/src/index.ts +5 -0
- package/src/openai.ts +135 -0
- package/src/utils.ts +10 -0
- package/tsconfig.json +109 -0
package/dist/index.d.mts
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import * as xstate from 'xstate';
|
|
2
|
+
import { AnyEventObject } from 'xstate';
|
|
3
|
+
import OpenAI from 'openai';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Creates [promise actor logic](https://stately.ai/docs/promise-actors) that uses the OpenAI API to generate a completion.
|
|
7
|
+
*
|
|
8
|
+
* @param openai The OpenAI instance.
|
|
9
|
+
* @param inputFn A function that maps arbitrary input to OpenAI chat completion input.
|
|
10
|
+
*
|
|
11
|
+
*/
|
|
12
|
+
declare function fromChatCompletion<TInput>(openai: OpenAI, inputFn: (input: TInput) => OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming): xstate.PromiseActorLogic<OpenAI.Chat.Completions.ChatCompletion, TInput>;
|
|
13
|
+
/**
|
|
14
|
+
* Creates [observable actor logic](https://stately.ai/docs/observable-actors) that uses the OpenAI API to generate a completion stream.
|
|
15
|
+
*
|
|
16
|
+
* @param openai The OpenAI instance to use.
|
|
17
|
+
* @param inputFn A function that maps arbitrary input to OpenAI chat completion input.
|
|
18
|
+
*/
|
|
19
|
+
declare function fromChatCompletionStream<TInput>(openai: OpenAI, inputFn: (input: TInput) => OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming): xstate.ObservableActorLogic<OpenAI.Chat.Completions.ChatCompletionChunk, TInput>;
|
|
20
|
+
/**
|
|
21
|
+
* Creates [promise actor logic](https://stately.ai/docs/promise-actors) that passes the next possible transitions as functions to [OpenAI tool calls](https://platform.openai.com/docs/guides/function-calling) and returns an array of potential next events.
|
|
22
|
+
*
|
|
23
|
+
* @param openai The OpenAI instance to use.
|
|
24
|
+
* @param inputFn A function that maps arbitrary input to OpenAI chat completion input.
|
|
25
|
+
*/
|
|
26
|
+
declare function fromEventChoice<TInput>(openai: OpenAI, inputFn: (input: TInput) => OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming): xstate.PromiseActorLogic<AnyEventObject[] | undefined, TInput>;
|
|
27
|
+
|
|
28
|
+
export { fromChatCompletion, fromChatCompletionStream, fromEventChoice };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
fromChatCompletion: () => fromChatCompletion,
|
|
24
|
+
fromChatCompletionStream: () => fromChatCompletionStream,
|
|
25
|
+
fromEventChoice: () => fromEventChoice
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(src_exports);
|
|
28
|
+
|
|
29
|
+
// src/openai.ts
|
|
30
|
+
var import_xstate = require("xstate");
|
|
31
|
+
|
|
32
|
+
// src/utils.ts
|
|
33
|
+
function getAllTransitions(state) {
|
|
34
|
+
const nodes = state._nodes;
|
|
35
|
+
const transitions = nodes.map((node) => [...node.transitions.values()]).flat(2);
|
|
36
|
+
return transitions;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// src/openai.ts
|
|
40
|
+
function fromChatCompletion(openai, inputFn) {
|
|
41
|
+
return (0, import_xstate.fromPromise)(
|
|
42
|
+
async ({ input }) => {
|
|
43
|
+
const openAiInput = inputFn(input);
|
|
44
|
+
const response = await openai.chat.completions.create(openAiInput);
|
|
45
|
+
return response;
|
|
46
|
+
}
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
function fromChatCompletionStream(openai, inputFn) {
|
|
50
|
+
return (0, import_xstate.fromObservable)(
|
|
51
|
+
({ input }) => {
|
|
52
|
+
const observers = /* @__PURE__ */ new Set();
|
|
53
|
+
(async () => {
|
|
54
|
+
const openAiInput = inputFn(input);
|
|
55
|
+
const stream = await openai.chat.completions.create({
|
|
56
|
+
...openAiInput,
|
|
57
|
+
stream: true
|
|
58
|
+
});
|
|
59
|
+
for await (const part of stream) {
|
|
60
|
+
observers.forEach((observer) => {
|
|
61
|
+
observer.next?.(part);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
})();
|
|
65
|
+
return {
|
|
66
|
+
subscribe: (...args) => {
|
|
67
|
+
const observer = (0, import_xstate.toObserver)(...args);
|
|
68
|
+
observers.add(observer);
|
|
69
|
+
return {
|
|
70
|
+
unsubscribe: () => {
|
|
71
|
+
observers.delete(observer);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
function fromEventChoice(openai, inputFn) {
|
|
80
|
+
return (0, import_xstate.fromPromise)(
|
|
81
|
+
async ({ input, self }) => {
|
|
82
|
+
const transitions = getAllTransitions(self._parent.getSnapshot());
|
|
83
|
+
const functionNameMapping = {};
|
|
84
|
+
const tools = transitions.filter((t) => {
|
|
85
|
+
return !t.eventType.startsWith("xstate.");
|
|
86
|
+
}).map((t) => {
|
|
87
|
+
const name = t.eventType.replace(/\./g, "_");
|
|
88
|
+
functionNameMapping[name] = t.eventType;
|
|
89
|
+
return {
|
|
90
|
+
type: "function",
|
|
91
|
+
function: {
|
|
92
|
+
name,
|
|
93
|
+
description: t.description,
|
|
94
|
+
parameters: {
|
|
95
|
+
type: "object",
|
|
96
|
+
properties: t.meta?.parameters ?? {}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
});
|
|
101
|
+
const openAiInput = inputFn(input);
|
|
102
|
+
const completion = await openai.chat.completions.create({
|
|
103
|
+
...openAiInput,
|
|
104
|
+
tools
|
|
105
|
+
});
|
|
106
|
+
const toolCalls = completion.choices[0]?.message.tool_calls;
|
|
107
|
+
if (toolCalls) {
|
|
108
|
+
return toolCalls.map((tc) => {
|
|
109
|
+
return {
|
|
110
|
+
type: functionNameMapping[tc.function.name],
|
|
111
|
+
...JSON.parse(tc.function.arguments)
|
|
112
|
+
};
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return toolCalls ?? void 0;
|
|
116
|
+
}
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
120
|
+
0 && (module.exports = {
|
|
121
|
+
fromChatCompletion,
|
|
122
|
+
fromChatCompletionStream,
|
|
123
|
+
fromEventChoice
|
|
124
|
+
});
|
package/dist/index.mjs
ADDED
package/examples/joke.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import OpenAI from 'openai';
|
|
2
|
+
import { assign, fromPromise, createActor, waitFor, setup } from 'xstate';
|
|
3
|
+
import { fromEventChoice } from '../src/index';
|
|
4
|
+
|
|
5
|
+
const openai = new OpenAI({
|
|
6
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
async function start() {
|
|
10
|
+
const promptTemplate = (topic: string) => `Tell me a joke about ${topic}.`;
|
|
11
|
+
|
|
12
|
+
const getJokeCompletion = fromPromise(
|
|
13
|
+
async ({ input }: { input: { topic: string } }) => {
|
|
14
|
+
const res = await openai.chat.completions.create({
|
|
15
|
+
messages: [
|
|
16
|
+
{
|
|
17
|
+
role: 'user',
|
|
18
|
+
content: promptTemplate(input.topic),
|
|
19
|
+
},
|
|
20
|
+
],
|
|
21
|
+
model: 'gpt-3.5-turbo',
|
|
22
|
+
n: 1,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
return res.choices[0]?.message.content;
|
|
26
|
+
}
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
const rateJoke = fromPromise(
|
|
30
|
+
async ({ input }: { input: { joke: string } }) => {
|
|
31
|
+
const res = await openai.chat.completions.create({
|
|
32
|
+
messages: [
|
|
33
|
+
{
|
|
34
|
+
role: 'user',
|
|
35
|
+
content: `Rate this joke on a scale of 1 to 10: ${input.joke}`,
|
|
36
|
+
},
|
|
37
|
+
],
|
|
38
|
+
model: 'gpt-3.5-turbo',
|
|
39
|
+
n: 1,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
return res.choices[0]?.message.content;
|
|
43
|
+
}
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
const getTopic = fromPromise(async () => {
|
|
47
|
+
const topic = await new Promise<string>((res) => {
|
|
48
|
+
console.log('Give me a topic: \n\n');
|
|
49
|
+
process.stdin.on('data', (data) => {
|
|
50
|
+
const eventType = data.toString().trim();
|
|
51
|
+
res(eventType);
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
return topic;
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
const chain = setup({
|
|
59
|
+
types: {
|
|
60
|
+
context: {} as {
|
|
61
|
+
topic: string;
|
|
62
|
+
jokes: string[];
|
|
63
|
+
desire: string | null;
|
|
64
|
+
lastRating: string | null;
|
|
65
|
+
},
|
|
66
|
+
input: {} as { topic: string },
|
|
67
|
+
},
|
|
68
|
+
actors: {
|
|
69
|
+
getJokeCompletion,
|
|
70
|
+
getTopic,
|
|
71
|
+
rateJoke,
|
|
72
|
+
decide: fromEventChoice(openai, (desire: string) => ({
|
|
73
|
+
model: 'gpt-4-1106-preview',
|
|
74
|
+
messages: [
|
|
75
|
+
{
|
|
76
|
+
role: 'user',
|
|
77
|
+
content: `Execute the function that best satisfies this desire:
|
|
78
|
+
|
|
79
|
+
${desire}
|
|
80
|
+
`,
|
|
81
|
+
},
|
|
82
|
+
],
|
|
83
|
+
})),
|
|
84
|
+
},
|
|
85
|
+
}).createMachine({
|
|
86
|
+
context: ({ input }) => ({
|
|
87
|
+
topic: input.topic,
|
|
88
|
+
jokes: [],
|
|
89
|
+
desire: null,
|
|
90
|
+
lastRating: null,
|
|
91
|
+
}),
|
|
92
|
+
initial: 'waitingForTopic',
|
|
93
|
+
states: {
|
|
94
|
+
waitingForTopic: {
|
|
95
|
+
invoke: {
|
|
96
|
+
src: 'getTopic',
|
|
97
|
+
onDone: {
|
|
98
|
+
actions: assign({
|
|
99
|
+
topic: ({ event }) => event.output,
|
|
100
|
+
}),
|
|
101
|
+
target: 'tellingJoke',
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
tellingJoke: {
|
|
106
|
+
invoke: {
|
|
107
|
+
src: 'getJokeCompletion',
|
|
108
|
+
input: ({ context }) => ({ topic: context.topic }),
|
|
109
|
+
onDone: {
|
|
110
|
+
actions: assign({
|
|
111
|
+
jokes: ({ context, event }) =>
|
|
112
|
+
context.jokes.concat(event.output as string),
|
|
113
|
+
}),
|
|
114
|
+
target: 'rateJoke',
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
rateJoke: {
|
|
119
|
+
invoke: {
|
|
120
|
+
src: 'rateJoke',
|
|
121
|
+
input: ({ context }) => ({
|
|
122
|
+
joke: context.jokes[context.jokes.length - 1]!,
|
|
123
|
+
}),
|
|
124
|
+
onDone: {
|
|
125
|
+
actions: assign({
|
|
126
|
+
lastRating: ({ event }) => event.output as string,
|
|
127
|
+
}),
|
|
128
|
+
target: 'joked',
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
joked: {
|
|
133
|
+
invoke: {
|
|
134
|
+
src: 'getTopic',
|
|
135
|
+
onDone: {
|
|
136
|
+
actions: assign({
|
|
137
|
+
desire: ({ event }) => event.output,
|
|
138
|
+
}),
|
|
139
|
+
target: 'decide',
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
decide: {
|
|
144
|
+
invoke: {
|
|
145
|
+
src: 'decide',
|
|
146
|
+
input: ({ context }) => context.desire!,
|
|
147
|
+
},
|
|
148
|
+
on: {
|
|
149
|
+
askForTopic: {
|
|
150
|
+
target: 'waitingForTopic',
|
|
151
|
+
description:
|
|
152
|
+
'Ask for a new topic, because the last joke was almost perfect',
|
|
153
|
+
},
|
|
154
|
+
endJokes: {
|
|
155
|
+
target: 'end',
|
|
156
|
+
description: 'End the jokes, since the last joke was not too good',
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
},
|
|
160
|
+
end: {},
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
const actor = createActor(chain, {
|
|
165
|
+
input: {
|
|
166
|
+
topic: 'donuts',
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
actor.subscribe((st) => {
|
|
171
|
+
console.log('State: ', st.value);
|
|
172
|
+
|
|
173
|
+
if (st.context.jokes) {
|
|
174
|
+
console.log('Joke: ', st.context.jokes[st.context.jokes.length - 1]);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
actor.start();
|
|
179
|
+
|
|
180
|
+
await waitFor(actor, (snap) => snap.status === 'done', {
|
|
181
|
+
timeout: Infinity,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
start();
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { assign, setup, assertEvent, createActor, raise } from 'xstate';
|
|
2
|
+
import { fromChatCompletionStream, fromEventChoice } from '../src/openai';
|
|
3
|
+
import OpenAI from 'openai';
|
|
4
|
+
|
|
5
|
+
const openai = new OpenAI({
|
|
6
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
type Player = 'x' | 'o';
|
|
10
|
+
|
|
11
|
+
const initialContext = {
|
|
12
|
+
board: Array(9).fill(null) as Array<Player | null>,
|
|
13
|
+
moves: 0,
|
|
14
|
+
player: 'x' as Player,
|
|
15
|
+
winner: undefined as Player | undefined,
|
|
16
|
+
gameReport: '',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const ticTacToeMachine = setup({
|
|
20
|
+
types: {} as {
|
|
21
|
+
context: typeof initialContext;
|
|
22
|
+
events:
|
|
23
|
+
| { type: 'x.play'; index: number }
|
|
24
|
+
| {
|
|
25
|
+
type: 'o.play';
|
|
26
|
+
index: number;
|
|
27
|
+
}
|
|
28
|
+
| { type: 'RESET' };
|
|
29
|
+
},
|
|
30
|
+
actors: {
|
|
31
|
+
bot: fromEventChoice(
|
|
32
|
+
openai,
|
|
33
|
+
({ context }: { context: typeof initialContext }) => ({
|
|
34
|
+
model: 'gpt-4-1106-preview',
|
|
35
|
+
messages: [
|
|
36
|
+
{
|
|
37
|
+
role: 'system',
|
|
38
|
+
content: `You are playing a game of tic tac toe. This is the current game state. The 3x3 board is represented by a 9-element array. The first element is the top-left cell, the second element is the top-middle cell, the third element is the top-right cell, the fourth element is the middle-left cell, and so on. The value of each cell is either null, x, or o. The value of null means that the cell is empty. The value of x means that the cell is occupied by an x. The value of o means that the cell is occupied by an o.
|
|
39
|
+
|
|
40
|
+
${JSON.stringify(context, null, 2)}`,
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
role: 'user',
|
|
44
|
+
content:
|
|
45
|
+
'Execute the single best next move to try to win the game. Do not play on an existing cell.',
|
|
46
|
+
},
|
|
47
|
+
],
|
|
48
|
+
})
|
|
49
|
+
),
|
|
50
|
+
gameReporter: fromChatCompletionStream(
|
|
51
|
+
openai,
|
|
52
|
+
({ context }: { context: typeof initialContext }) => ({
|
|
53
|
+
model: 'gpt-4-1106-preview',
|
|
54
|
+
messages: [
|
|
55
|
+
{
|
|
56
|
+
role: 'user',
|
|
57
|
+
content: `The tic-tac-toe game is over. The winner is ${
|
|
58
|
+
context.winner ?? 'nobody'
|
|
59
|
+
}. This was the ending board state:
|
|
60
|
+
|
|
61
|
+
${JSON.stringify(context.board, null, 2)}
|
|
62
|
+
|
|
63
|
+
Provide a game report analyzing the game.`,
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
stream: true,
|
|
67
|
+
})
|
|
68
|
+
),
|
|
69
|
+
},
|
|
70
|
+
actions: {
|
|
71
|
+
updateBoard: assign({
|
|
72
|
+
board: ({ context, event }) => {
|
|
73
|
+
assertEvent(event, ['x.play', 'o.play']);
|
|
74
|
+
const updatedBoard = [...context.board];
|
|
75
|
+
updatedBoard[event.index] = context.player;
|
|
76
|
+
return updatedBoard;
|
|
77
|
+
},
|
|
78
|
+
moves: ({ context }) => context.moves + 1,
|
|
79
|
+
player: ({ context }) => (context.player === 'x' ? 'o' : 'x'),
|
|
80
|
+
}),
|
|
81
|
+
resetGame: assign(initialContext),
|
|
82
|
+
setWinner: assign({
|
|
83
|
+
winner: ({ context }) => (context.player === 'x' ? 'o' : 'x'),
|
|
84
|
+
}),
|
|
85
|
+
},
|
|
86
|
+
guards: {
|
|
87
|
+
checkWin: ({ context }) => {
|
|
88
|
+
const { board } = context;
|
|
89
|
+
const winningLines = [
|
|
90
|
+
[0, 1, 2],
|
|
91
|
+
[3, 4, 5],
|
|
92
|
+
[6, 7, 8],
|
|
93
|
+
[0, 3, 6],
|
|
94
|
+
[1, 4, 7],
|
|
95
|
+
[2, 5, 8],
|
|
96
|
+
[0, 4, 8],
|
|
97
|
+
[2, 4, 6],
|
|
98
|
+
];
|
|
99
|
+
|
|
100
|
+
for (let line of winningLines) {
|
|
101
|
+
const xWon = line.every((index) => {
|
|
102
|
+
return board[index] === 'x';
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
if (xWon) {
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const oWon = line.every((index) => {
|
|
110
|
+
return board[index] === 'o';
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
if (oWon) {
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return false;
|
|
119
|
+
},
|
|
120
|
+
checkDraw: ({ context }) => {
|
|
121
|
+
return context.moves === 9;
|
|
122
|
+
},
|
|
123
|
+
isValidMove: ({ context, event }) => {
|
|
124
|
+
try {
|
|
125
|
+
assertEvent(event, ['o.play', 'x.play']);
|
|
126
|
+
} catch {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return context.board[event.index] === null;
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
}).createMachine({
|
|
134
|
+
initial: 'playing',
|
|
135
|
+
context: initialContext,
|
|
136
|
+
states: {
|
|
137
|
+
playing: {
|
|
138
|
+
always: [
|
|
139
|
+
{ target: 'gameOver.winner', guard: 'checkWin' },
|
|
140
|
+
{ target: 'gameOver.draw', guard: 'checkDraw' },
|
|
141
|
+
],
|
|
142
|
+
initial: 'x',
|
|
143
|
+
states: {
|
|
144
|
+
x: {
|
|
145
|
+
invoke: {
|
|
146
|
+
src: 'bot',
|
|
147
|
+
input: ({ context }) => ({ context }),
|
|
148
|
+
onDone: {
|
|
149
|
+
actions: raise(({ event }) => {
|
|
150
|
+
return event.output![0] as any;
|
|
151
|
+
}),
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
on: {
|
|
155
|
+
'x.play': [
|
|
156
|
+
{
|
|
157
|
+
target: 'o',
|
|
158
|
+
guard: 'isValidMove',
|
|
159
|
+
actions: 'updateBoard',
|
|
160
|
+
meta: {
|
|
161
|
+
parameters: {
|
|
162
|
+
index: {
|
|
163
|
+
description: 'The index of the cell to play on',
|
|
164
|
+
type: 'number',
|
|
165
|
+
min: 0,
|
|
166
|
+
max: 8,
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
{ reenter: true },
|
|
172
|
+
],
|
|
173
|
+
},
|
|
174
|
+
},
|
|
175
|
+
o: {
|
|
176
|
+
invoke: {
|
|
177
|
+
src: 'bot',
|
|
178
|
+
input: ({ context }) => ({ context }),
|
|
179
|
+
onDone: {
|
|
180
|
+
// @ts-ignore
|
|
181
|
+
actions: raise(({ event }) => {
|
|
182
|
+
console.log('output', event.output);
|
|
183
|
+
return event.output![0];
|
|
184
|
+
}),
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
on: {
|
|
188
|
+
'o.play': [
|
|
189
|
+
{
|
|
190
|
+
target: 'x',
|
|
191
|
+
guard: 'isValidMove',
|
|
192
|
+
actions: 'updateBoard',
|
|
193
|
+
meta: {
|
|
194
|
+
parameters: {
|
|
195
|
+
index: {
|
|
196
|
+
description: 'The index of the cell to play on',
|
|
197
|
+
type: 'number',
|
|
198
|
+
min: 0,
|
|
199
|
+
max: 8,
|
|
200
|
+
},
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
},
|
|
204
|
+
{ reenter: true },
|
|
205
|
+
],
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
gameOver: {
|
|
211
|
+
initial: 'winner',
|
|
212
|
+
invoke: {
|
|
213
|
+
src: 'gameReporter',
|
|
214
|
+
input: ({ context }) => ({ context }),
|
|
215
|
+
onSnapshot: {
|
|
216
|
+
actions: assign({
|
|
217
|
+
gameReport: ({ context, event }) => {
|
|
218
|
+
return (
|
|
219
|
+
context.gameReport +
|
|
220
|
+
(event.snapshot.context?.choices[0]?.delta.content ?? '')
|
|
221
|
+
);
|
|
222
|
+
},
|
|
223
|
+
}),
|
|
224
|
+
},
|
|
225
|
+
},
|
|
226
|
+
states: {
|
|
227
|
+
winner: {
|
|
228
|
+
tags: 'winner',
|
|
229
|
+
entry: 'setWinner',
|
|
230
|
+
},
|
|
231
|
+
draw: {
|
|
232
|
+
tags: 'draw',
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
on: {
|
|
236
|
+
RESET: {
|
|
237
|
+
target: 'playing',
|
|
238
|
+
actions: 'resetGame',
|
|
239
|
+
},
|
|
240
|
+
},
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
const actor = createActor(ticTacToeMachine);
|
|
246
|
+
actor.subscribe((s) => {
|
|
247
|
+
console.log(s.value, s.context);
|
|
248
|
+
});
|
|
249
|
+
actor.start();
|
package/package.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@statelyai/agent",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"build": "tsup src/index.ts --format cjs,esm --dts",
|
|
10
|
+
"lint": "tsc",
|
|
11
|
+
"test": "vitest run",
|
|
12
|
+
"prepublishOnly": "tsup src/index.ts --dts"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [],
|
|
15
|
+
"author": "",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"@types/node": "^20.10.6",
|
|
19
|
+
"tsup": "^8.0.1",
|
|
20
|
+
"typescript": "^5.3.3"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"openai": "^4.24.1",
|
|
24
|
+
"xstate": "^5.3.1"
|
|
25
|
+
}
|
|
26
|
+
}
|
package/src/index.ts
ADDED
package/src/openai.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import OpenAI from 'openai';
|
|
2
|
+
import {
|
|
3
|
+
AnyEventObject,
|
|
4
|
+
Observer,
|
|
5
|
+
fromObservable,
|
|
6
|
+
fromPromise,
|
|
7
|
+
toObserver,
|
|
8
|
+
} from 'xstate';
|
|
9
|
+
import { getAllTransitions } from './utils';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Creates [promise actor logic](https://stately.ai/docs/promise-actors) that uses the OpenAI API to generate a completion.
|
|
13
|
+
*
|
|
14
|
+
* @param openai The OpenAI instance.
|
|
15
|
+
* @param inputFn A function that maps arbitrary input to OpenAI chat completion input.
|
|
16
|
+
*
|
|
17
|
+
*/
|
|
18
|
+
export function fromChatCompletion<TInput>(
|
|
19
|
+
openai: OpenAI,
|
|
20
|
+
inputFn: (
|
|
21
|
+
input: TInput
|
|
22
|
+
) => OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming
|
|
23
|
+
) {
|
|
24
|
+
return fromPromise<OpenAI.Chat.Completions.ChatCompletion, TInput>(
|
|
25
|
+
async ({ input }) => {
|
|
26
|
+
const openAiInput = inputFn(input);
|
|
27
|
+
const response = await openai.chat.completions.create(openAiInput);
|
|
28
|
+
|
|
29
|
+
return response;
|
|
30
|
+
}
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Creates [observable actor logic](https://stately.ai/docs/observable-actors) that uses the OpenAI API to generate a completion stream.
|
|
36
|
+
*
|
|
37
|
+
* @param openai The OpenAI instance to use.
|
|
38
|
+
* @param inputFn A function that maps arbitrary input to OpenAI chat completion input.
|
|
39
|
+
*/
|
|
40
|
+
export function fromChatCompletionStream<TInput>(
|
|
41
|
+
openai: OpenAI,
|
|
42
|
+
inputFn: (
|
|
43
|
+
input: TInput
|
|
44
|
+
) => OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming
|
|
45
|
+
) {
|
|
46
|
+
return fromObservable<OpenAI.Chat.Completions.ChatCompletionChunk, TInput>(
|
|
47
|
+
({ input }) => {
|
|
48
|
+
const observers = new Set<Observer<any>>();
|
|
49
|
+
|
|
50
|
+
(async () => {
|
|
51
|
+
const openAiInput = inputFn(input);
|
|
52
|
+
const stream = await openai.chat.completions.create({
|
|
53
|
+
...openAiInput,
|
|
54
|
+
stream: true,
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
for await (const part of stream) {
|
|
58
|
+
observers.forEach((observer) => {
|
|
59
|
+
observer.next?.(part);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
})();
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
subscribe: (...args) => {
|
|
66
|
+
const observer = toObserver(...(args as any));
|
|
67
|
+
observers.add(observer);
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
unsubscribe: () => {
|
|
71
|
+
observers.delete(observer);
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Creates [promise actor logic](https://stately.ai/docs/promise-actors) that passes the next possible transitions as functions to [OpenAI tool calls](https://platform.openai.com/docs/guides/function-calling) and returns an array of potential next events.
|
|
82
|
+
*
|
|
83
|
+
* @param openai The OpenAI instance to use.
|
|
84
|
+
* @param inputFn A function that maps arbitrary input to OpenAI chat completion input.
|
|
85
|
+
*/
|
|
86
|
+
export function fromEventChoice<TInput>(
|
|
87
|
+
openai: OpenAI,
|
|
88
|
+
inputFn: (
|
|
89
|
+
input: TInput
|
|
90
|
+
) => OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming
|
|
91
|
+
) {
|
|
92
|
+
return fromPromise<AnyEventObject[] | undefined, TInput>(
|
|
93
|
+
async ({ input, self }) => {
|
|
94
|
+
const transitions = getAllTransitions(self._parent!.getSnapshot());
|
|
95
|
+
const functionNameMapping: Record<string, string> = {};
|
|
96
|
+
const tools = transitions
|
|
97
|
+
.filter((t) => {
|
|
98
|
+
return !t.eventType.startsWith('xstate.');
|
|
99
|
+
})
|
|
100
|
+
.map((t) => {
|
|
101
|
+
const name = t.eventType.replace(/\./g, '_');
|
|
102
|
+
functionNameMapping[name] = t.eventType;
|
|
103
|
+
return {
|
|
104
|
+
type: 'function',
|
|
105
|
+
function: {
|
|
106
|
+
name,
|
|
107
|
+
description: t.description,
|
|
108
|
+
parameters: {
|
|
109
|
+
type: 'object',
|
|
110
|
+
properties: t.meta?.parameters ?? {},
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
} as const;
|
|
114
|
+
});
|
|
115
|
+
const openAiInput = inputFn(input);
|
|
116
|
+
const completion = await openai.chat.completions.create({
|
|
117
|
+
...openAiInput,
|
|
118
|
+
tools,
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
const toolCalls = completion.choices[0]?.message.tool_calls;
|
|
122
|
+
|
|
123
|
+
if (toolCalls) {
|
|
124
|
+
return toolCalls.map((tc) => {
|
|
125
|
+
return {
|
|
126
|
+
type: functionNameMapping[tc.function.name],
|
|
127
|
+
...JSON.parse(tc.function.arguments),
|
|
128
|
+
};
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return toolCalls ?? undefined;
|
|
133
|
+
}
|
|
134
|
+
);
|
|
135
|
+
}
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { AnyMachineSnapshot, AnyStateNode } from 'xstate';
|
|
2
|
+
|
|
3
|
+
export function getAllTransitions(state: AnyMachineSnapshot) {
|
|
4
|
+
const nodes = state._nodes;
|
|
5
|
+
const transitions = (nodes as AnyStateNode[])
|
|
6
|
+
.map((node) => [...(node as AnyStateNode).transitions.values()])
|
|
7
|
+
.flat(2);
|
|
8
|
+
|
|
9
|
+
return transitions;
|
|
10
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
/* Visit https://aka.ms/tsconfig to read more about this file */
|
|
4
|
+
|
|
5
|
+
/* Projects */
|
|
6
|
+
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
|
7
|
+
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
|
8
|
+
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
|
9
|
+
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
|
10
|
+
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
|
11
|
+
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
|
12
|
+
|
|
13
|
+
/* Language and Environment */
|
|
14
|
+
"target": "es2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
|
15
|
+
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
|
16
|
+
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
|
17
|
+
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
|
18
|
+
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
|
19
|
+
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
|
20
|
+
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
|
21
|
+
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
|
22
|
+
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
|
23
|
+
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
|
24
|
+
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
|
25
|
+
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
|
26
|
+
|
|
27
|
+
/* Modules */
|
|
28
|
+
"module": "commonjs" /* Specify what module code is generated. */,
|
|
29
|
+
// "rootDir": "./", /* Specify the root folder within your source files. */
|
|
30
|
+
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
|
31
|
+
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
|
32
|
+
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
|
33
|
+
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
34
|
+
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
|
35
|
+
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
|
36
|
+
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
37
|
+
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
|
38
|
+
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
|
39
|
+
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
|
40
|
+
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
|
41
|
+
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
|
42
|
+
// "resolveJsonModule": true, /* Enable importing .json files. */
|
|
43
|
+
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
|
44
|
+
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
|
45
|
+
|
|
46
|
+
/* JavaScript Support */
|
|
47
|
+
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
|
48
|
+
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
|
49
|
+
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
|
50
|
+
|
|
51
|
+
/* Emit */
|
|
52
|
+
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
|
53
|
+
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
|
54
|
+
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
|
55
|
+
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
|
56
|
+
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
|
57
|
+
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
|
58
|
+
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
|
59
|
+
// "removeComments": true, /* Disable emitting comments. */
|
|
60
|
+
"noEmit": true /* Disable emitting files from a compilation. */,
|
|
61
|
+
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
|
62
|
+
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
|
63
|
+
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
|
64
|
+
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
|
65
|
+
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
66
|
+
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
|
67
|
+
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
|
68
|
+
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
|
69
|
+
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
|
70
|
+
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
|
71
|
+
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
|
72
|
+
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
|
73
|
+
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
|
74
|
+
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
|
75
|
+
|
|
76
|
+
/* Interop Constraints */
|
|
77
|
+
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
|
78
|
+
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
|
79
|
+
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
|
80
|
+
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
|
|
81
|
+
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
|
82
|
+
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
|
|
83
|
+
|
|
84
|
+
/* Type Checking */
|
|
85
|
+
"strict": true /* Enable all strict type-checking options. */,
|
|
86
|
+
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
|
87
|
+
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
|
88
|
+
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
|
89
|
+
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
|
90
|
+
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
|
91
|
+
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
|
92
|
+
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
|
93
|
+
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
|
94
|
+
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
|
95
|
+
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
|
96
|
+
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
|
97
|
+
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
|
98
|
+
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
|
99
|
+
"noUncheckedIndexedAccess": true /* Add 'undefined' to a type when accessed using an index. */,
|
|
100
|
+
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
|
101
|
+
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
|
102
|
+
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
|
103
|
+
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
|
104
|
+
|
|
105
|
+
/* Completeness */
|
|
106
|
+
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
|
107
|
+
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
|
108
|
+
}
|
|
109
|
+
}
|