@dxos/assistant 0.8.2-main.f081794 → 0.8.2-main.fbd8ed0
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/lib/browser/{chunk-DEIGOD4U.mjs → chunk-B4HAWUFW.mjs} +710 -246
- package/dist/lib/browser/chunk-B4HAWUFW.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +5 -324
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/testing/index.mjs +123 -86
- package/dist/lib/browser/testing/index.mjs.map +4 -4
- package/dist/lib/node/{chunk-7VH7NMIM.cjs → chunk-NOB7CIIC.cjs} +716 -259
- package/dist/lib/node/chunk-NOB7CIIC.cjs.map +7 -0
- package/dist/lib/node/index.cjs +35 -354
- package/dist/lib/node/index.cjs.map +4 -4
- package/dist/lib/node/meta.json +1 -1
- package/dist/lib/node/testing/index.cjs +112 -77
- package/dist/lib/node/testing/index.cjs.map +4 -4
- package/dist/lib/node-esm/{chunk-7JI4MDGL.mjs → chunk-SAWYU3V5.mjs} +710 -246
- package/dist/lib/node-esm/chunk-SAWYU3V5.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +5 -324
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/testing/index.mjs +123 -86
- package/dist/lib/node-esm/testing/index.mjs.map +4 -4
- package/dist/types/src/ai-service/parser.d.ts.map +1 -1
- package/dist/types/src/ai-service/stream.d.ts.map +1 -1
- package/dist/types/src/ai-service/testing/test-stream.d.ts.map +1 -1
- package/dist/types/src/ai-service/types.d.ts +133 -133
- package/dist/types/src/ai-service/types.d.ts.map +1 -1
- package/dist/types/src/ai-service/util/sse.d.ts.map +1 -1
- package/dist/types/src/{conversation → experimental/conversation}/conversation.d.ts +2 -18
- package/dist/types/src/experimental/conversation/conversation.d.ts.map +1 -0
- package/dist/types/src/experimental/conversation/conversation.test.d.ts.map +1 -0
- package/dist/types/src/experimental/conversation/index.d.ts.map +1 -0
- package/dist/types/src/{conversation → experimental/conversation}/types.d.ts +9 -9
- package/dist/types/src/experimental/conversation/types.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/ast.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/combinators.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/combinators.test.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/echo-data-source.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/execution-plan.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/execution-plan.test.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/index.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/parjs.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/parser.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/query-executor.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/query-executor.test.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/schema.d.ts.map +1 -0
- package/dist/types/src/experimental/cypher/schema.test.d.ts.map +1 -0
- package/dist/types/src/experimental/index.d.ts +3 -0
- package/dist/types/src/experimental/index.d.ts.map +1 -0
- package/dist/types/src/experimental/ner/ner.test.d.ts +2 -0
- package/dist/types/src/experimental/ner/ner.test.d.ts.map +1 -0
- package/dist/types/src/experimental/research/exa.d.ts +6 -0
- package/dist/types/src/experimental/research/exa.d.ts.map +1 -0
- package/dist/types/src/experimental/research/research.test.d.ts +2 -0
- package/dist/types/src/experimental/research/research.test.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +1 -2
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/session/index.d.ts +2 -0
- package/dist/types/src/session/index.d.ts.map +1 -1
- package/dist/types/src/session/session.d.ts +33 -7
- package/dist/types/src/session/session.d.ts.map +1 -1
- package/dist/types/src/session/tools.d.ts +18 -0
- package/dist/types/src/session/tools.d.ts.map +1 -0
- package/dist/types/src/session/version-pin.d.ts +22 -0
- package/dist/types/src/session/version-pin.d.ts.map +1 -0
- package/dist/types/src/session/version-pin.test.d.ts +2 -0
- package/dist/types/src/session/version-pin.test.d.ts.map +1 -0
- package/dist/types/src/testing/index.d.ts +1 -0
- package/dist/types/src/testing/index.d.ts.map +1 -1
- package/dist/types/src/testing/logger.d.ts +1 -1
- package/dist/types/src/testing/logger.d.ts.map +1 -1
- package/dist/types/src/testing/ollama.d.ts.map +1 -1
- package/dist/types/src/testing/printer.d.ts +6 -0
- package/dist/types/src/testing/printer.d.ts.map +1 -0
- package/dist/types/src/testing/query-promts.d.ts +4 -4
- package/dist/types/src/testing/query-promts.d.ts.map +1 -1
- package/dist/types/src/testing/test-data.d.ts +5 -5
- package/dist/types/src/testing/test-data.d.ts.map +1 -1
- package/dist/types/src/testing/test-schema.d.ts +25 -23
- package/dist/types/src/testing/test-schema.d.ts.map +1 -1
- package/dist/types/src/util/trim.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +20 -14
- package/src/ai-service/client.test.ts +5 -5
- package/src/ai-service/ollama-client.ts +8 -8
- package/src/ai-service/types.ts +14 -14
- package/src/bin/chat.ts +3 -3
- package/src/{conversation → experimental/conversation}/conversation.test.ts +5 -5
- package/src/{conversation → experimental/conversation}/conversation.ts +3 -112
- package/src/{conversation → experimental/conversation}/types.ts +10 -10
- package/src/{cypher → experimental/cypher}/combinators.test.ts +4 -4
- package/src/{cypher → experimental/cypher}/echo-data-source.ts +11 -10
- package/src/{cypher → experimental/cypher}/execution-plan.test.ts +1 -1
- package/src/{cypher → experimental/cypher}/query-executor.test.ts +2 -2
- package/src/{cypher → experimental/cypher}/schema.test.ts +3 -3
- package/src/{cypher → experimental/cypher}/schema.ts +1 -1
- package/src/experimental/index.ts +6 -0
- package/src/experimental/ner/ner.test.ts +163 -0
- package/src/experimental/research/exa.ts +38 -0
- package/src/experimental/research/instructions.tpl +64 -0
- package/src/experimental/research/research.test.ts +263 -0
- package/src/index.ts +3 -2
- package/src/session/index.ts +2 -0
- package/src/session/session.test.ts +30 -58
- package/src/session/session.ts +296 -150
- package/src/session/tools.ts +117 -0
- package/src/session/version-pin.test.ts +26 -0
- package/src/session/version-pin.ts +49 -0
- package/src/testing/artifacts.test.ts +22 -22
- package/src/testing/index.ts +1 -0
- package/src/testing/logger.ts +1 -1
- package/src/testing/printer.ts +41 -0
- package/src/testing/query-promts.ts +6 -6
- package/src/testing/query.test.ts +4 -5
- package/src/testing/test-data.ts +63 -56
- package/src/testing/test-schema.ts +28 -29
- package/src/typedefs.d.ts +8 -0
- package/dist/lib/browser/chunk-DEIGOD4U.mjs.map +0 -7
- package/dist/lib/node/chunk-7VH7NMIM.cjs.map +0 -7
- package/dist/lib/node-esm/chunk-7JI4MDGL.mjs.map +0 -7
- package/dist/types/src/conversation/conversation.d.ts.map +0 -1
- package/dist/types/src/conversation/conversation.test.d.ts.map +0 -1
- package/dist/types/src/conversation/index.d.ts.map +0 -1
- package/dist/types/src/conversation/types.d.ts.map +0 -1
- package/dist/types/src/cypher/ast.d.ts.map +0 -1
- package/dist/types/src/cypher/combinators.d.ts.map +0 -1
- package/dist/types/src/cypher/combinators.test.d.ts.map +0 -1
- package/dist/types/src/cypher/echo-data-source.d.ts.map +0 -1
- package/dist/types/src/cypher/execution-plan.d.ts.map +0 -1
- package/dist/types/src/cypher/execution-plan.test.d.ts.map +0 -1
- package/dist/types/src/cypher/index.d.ts.map +0 -1
- package/dist/types/src/cypher/parjs.d.ts.map +0 -1
- package/dist/types/src/cypher/parser.d.ts.map +0 -1
- package/dist/types/src/cypher/query-executor.d.ts.map +0 -1
- package/dist/types/src/cypher/query-executor.test.d.ts.map +0 -1
- package/dist/types/src/cypher/schema.d.ts.map +0 -1
- package/dist/types/src/cypher/schema.test.d.ts.map +0 -1
- /package/dist/types/src/{conversation → experimental/conversation}/conversation.test.d.ts +0 -0
- /package/dist/types/src/{conversation → experimental/conversation}/index.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/ast.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/combinators.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/combinators.test.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/echo-data-source.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/execution-plan.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/execution-plan.test.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/index.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/parjs.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/parser.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/query-executor.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/query-executor.test.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/schema.d.ts +0 -0
- /package/dist/types/src/{cypher → experimental/cypher}/schema.test.d.ts +0 -0
- /package/src/{conversation → experimental/conversation}/index.ts +0 -0
- /package/src/{cypher → experimental/cypher}/ast.ts +0 -0
- /package/src/{cypher → experimental/cypher}/combinators.ts +0 -0
- /package/src/{cypher → experimental/cypher}/execution-plan.ts +0 -0
- /package/src/{cypher → experimental/cypher}/index.ts +0 -0
- /package/src/{cypher → experimental/cypher}/parjs-shims.d.ts +0 -0
- /package/src/{cypher → experimental/cypher}/parjs.ts +0 -0
- /package/src/{cypher → experimental/cypher}/parser.ts +0 -0
- /package/src/{cypher → experimental/cypher}/query-executor.ts +0 -0
package/src/session/session.ts
CHANGED
|
@@ -2,16 +2,27 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import { Schema
|
|
6
|
-
|
|
7
|
-
import {
|
|
5
|
+
import { Option, Schema } from 'effect';
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
defineTool,
|
|
9
|
+
Message,
|
|
10
|
+
structuredOutputParser,
|
|
11
|
+
ToolResult,
|
|
12
|
+
type ArtifactDefinition,
|
|
13
|
+
type MessageContentBlock,
|
|
14
|
+
type Tool,
|
|
15
|
+
} from '@dxos/artifact';
|
|
8
16
|
import { Event, synchronized } from '@dxos/async';
|
|
9
|
-
import {
|
|
17
|
+
import { ObjectVersion } from '@dxos/echo-db';
|
|
18
|
+
import { create, type ObjectId } from '@dxos/echo-schema';
|
|
10
19
|
import { invariant } from '@dxos/invariant';
|
|
11
20
|
import { log } from '@dxos/log';
|
|
12
21
|
|
|
22
|
+
import { isToolUse, runTools } from './tools';
|
|
23
|
+
import { VersionPin } from './version-pin';
|
|
13
24
|
import { MixedStreamParser, type AIServiceClient, type GenerateRequest, type GenerationStream } from '../ai-service';
|
|
14
|
-
|
|
25
|
+
|
|
15
26
|
/**
|
|
16
27
|
* Contains message history, tools, current context.
|
|
17
28
|
* Current context means the state of the app, time of day, and other contextual information.
|
|
@@ -23,6 +34,22 @@ import { isToolUse, runTools } from '../conversation';
|
|
|
23
34
|
* Could be personal or shared.
|
|
24
35
|
*/
|
|
25
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Resolves artifact ids to their versions.
|
|
39
|
+
* Used to give the model a sense of the changes to the artifacts made by users during the conversation.
|
|
40
|
+
* The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,
|
|
41
|
+
* a diff is inserted into the conversation.
|
|
42
|
+
*/
|
|
43
|
+
export type ArtifactDiffResolver = (artifacts: { id: ObjectId; lastVersion: ObjectVersion }[]) => Promise<
|
|
44
|
+
Map<
|
|
45
|
+
ObjectId,
|
|
46
|
+
{
|
|
47
|
+
version: ObjectVersion;
|
|
48
|
+
diff?: string;
|
|
49
|
+
}
|
|
50
|
+
>
|
|
51
|
+
>;
|
|
52
|
+
|
|
26
53
|
export type SessionRunOptions = {
|
|
27
54
|
client: AIServiceClient;
|
|
28
55
|
|
|
@@ -47,15 +74,22 @@ export type SessionRunOptions = {
|
|
|
47
74
|
* Pre-require artifacts.
|
|
48
75
|
*/
|
|
49
76
|
requiredArtifactIds?: string[];
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @see ArtifactDiffResolver
|
|
80
|
+
*/
|
|
81
|
+
artifactDiffResolver?: ArtifactDiffResolver;
|
|
50
82
|
};
|
|
51
83
|
|
|
52
|
-
type OperationModel = 'planning' | '
|
|
84
|
+
type OperationModel = 'planning' | 'importing' | 'configured';
|
|
53
85
|
|
|
54
86
|
export type AiSessionOptions = {
|
|
55
87
|
/**
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
88
|
+
* Determines the agent's handling of the artifacts definitions:
|
|
89
|
+
*
|
|
90
|
+
* - `planning`: The model will create a plan with required artifacts for each step.
|
|
91
|
+
* - `importing`: The model can query registry and only pull in the artifacts that are required to complete the task.
|
|
92
|
+
* - `configured`: The available artifacts are pre-selected and the model cannot select additional artifacts.
|
|
59
93
|
*/
|
|
60
94
|
operationModel: OperationModel;
|
|
61
95
|
};
|
|
@@ -104,147 +138,30 @@ export class AISession {
|
|
|
104
138
|
|
|
105
139
|
@synchronized
|
|
106
140
|
async run(options: SessionRunOptions): Promise<Message[]> {
|
|
107
|
-
const systemTools: Tool[] = [
|
|
108
|
-
defineTool('system', {
|
|
109
|
-
name: 'query_artifact_definitions',
|
|
110
|
-
description: 'Query the available artifact definitions',
|
|
111
|
-
schema: S.Struct({}),
|
|
112
|
-
execute: async () => {
|
|
113
|
-
return ToolResult.Success({
|
|
114
|
-
artifactDefinitions: options.artifacts.map((artifact) => ({
|
|
115
|
-
id: artifact.id,
|
|
116
|
-
name: artifact.name,
|
|
117
|
-
description: artifact.description,
|
|
118
|
-
})),
|
|
119
|
-
});
|
|
120
|
-
},
|
|
121
|
-
}),
|
|
122
|
-
];
|
|
141
|
+
const systemTools: Tool[] = [];
|
|
123
142
|
switch (this._options.operationModel) {
|
|
124
143
|
case 'planning':
|
|
125
|
-
systemTools.push(
|
|
126
|
-
defineTool('system', {
|
|
127
|
-
name: 'create_plan',
|
|
128
|
-
description:
|
|
129
|
-
'Create a plan. Make sure that each step is independent and can be executed solely on the data returned by the previous step. The steps only share the data that is specified in the plan.',
|
|
130
|
-
schema: S.Struct({
|
|
131
|
-
goal: S.String.annotations({ description: 'The goal that the plan will achieve.' }),
|
|
132
|
-
steps: S.Array(
|
|
133
|
-
S.Struct({
|
|
134
|
-
action: S.String.annotations({
|
|
135
|
-
description: 'Complete, detailed action to perform.',
|
|
136
|
-
}),
|
|
137
|
-
input: S.String.annotations({
|
|
138
|
-
description: 'The required input data for this step. First step must not require any data.',
|
|
139
|
-
}),
|
|
140
|
-
output: S.String.annotations({
|
|
141
|
-
description: 'The output data from this step. This is passed to the next step as input.',
|
|
142
|
-
}),
|
|
143
|
-
requiredArtifactIds: S.Array(S.String).annotations({
|
|
144
|
-
description: 'The ids of the artifacts required to perform this step.',
|
|
145
|
-
examples: [['artifact:dxos.org/example/Test']],
|
|
146
|
-
}),
|
|
147
|
-
}),
|
|
148
|
-
).annotations({ description: 'Steps' }),
|
|
149
|
-
}),
|
|
150
|
-
execute: async ({ goal, steps }) => {
|
|
151
|
-
const missingArtifactIds = steps
|
|
152
|
-
.flatMap((step) => step.requiredArtifactIds)
|
|
153
|
-
.filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
|
|
154
|
-
if (missingArtifactIds.length > 0) {
|
|
155
|
-
return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(', ')}`);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
const stepResults: any[] = [];
|
|
159
|
-
for (const step of steps) {
|
|
160
|
-
log('executing step', { action: step.action });
|
|
161
|
-
const session = new AISession({ operationModel: 'immediate' });
|
|
162
|
-
session.message.on((ev) => this.message.emit(ev));
|
|
163
|
-
session.block.on((ev) => this.block.emit(ev));
|
|
164
|
-
session.update.on((ev) => this.update.emit(ev));
|
|
165
|
-
session.streamEvent.on((ev) => this.streamEvent.emit(ev));
|
|
166
|
-
session.userMessage.on((ev) => this.userMessage.emit(ev));
|
|
167
|
-
|
|
168
|
-
const messages = await session.run({
|
|
169
|
-
client: options.client,
|
|
170
|
-
artifacts: options.artifacts,
|
|
171
|
-
tools: options.tools,
|
|
172
|
-
history: options.history,
|
|
173
|
-
extensions: options.extensions,
|
|
174
|
-
generationOptions: options.generationOptions,
|
|
175
|
-
requiredArtifactIds: step.requiredArtifactIds.slice(),
|
|
176
|
-
prompt: `
|
|
177
|
-
You are an agent that executes the subtask in a plan.
|
|
178
|
-
|
|
179
|
-
While you know the plan's goal only focus on your subtask
|
|
180
|
-
Use the data from the previous step to complete your task.
|
|
181
|
-
Return all of the data from "output" in your last message.
|
|
182
|
-
|
|
183
|
-
Current step (that you need to complete):
|
|
184
|
-
${JSON.stringify(
|
|
185
|
-
{
|
|
186
|
-
goal,
|
|
187
|
-
input: step.input,
|
|
188
|
-
output: step.output,
|
|
189
|
-
yourTask: step.action,
|
|
190
|
-
},
|
|
191
|
-
null,
|
|
192
|
-
2,
|
|
193
|
-
)}
|
|
194
|
-
|
|
195
|
-
Previous step results:
|
|
196
|
-
${JSON.stringify(stepResults.at(-1))}.
|
|
197
|
-
`,
|
|
198
|
-
});
|
|
199
|
-
const result = messages.at(-1);
|
|
200
|
-
stepResults.push(result);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
return ToolResult.Success({ stepResults });
|
|
204
|
-
},
|
|
205
|
-
}),
|
|
206
|
-
);
|
|
144
|
+
systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createPlanningTool(options));
|
|
207
145
|
break;
|
|
208
|
-
case '
|
|
146
|
+
case 'importing':
|
|
209
147
|
systemTools.push(
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
artifactDefinitionIds: S.Array(S.String).annotations({
|
|
216
|
-
description: 'The ids of the artifact definitions to require',
|
|
217
|
-
examples: [['artifact:dxos.org/example/Test']],
|
|
218
|
-
}),
|
|
219
|
-
}),
|
|
220
|
-
execute: async ({ artifactDefinitionIds }) => {
|
|
221
|
-
const missingArtifactDefinitionIds = artifactDefinitionIds.filter(
|
|
222
|
-
(artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId),
|
|
223
|
-
);
|
|
224
|
-
if (missingArtifactDefinitionIds.length > 0) {
|
|
225
|
-
return ToolResult.Error(
|
|
226
|
-
`One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(', ')}`,
|
|
227
|
-
);
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
for (const artifactDefinitionId of artifactDefinitionIds) {
|
|
231
|
-
requiredArtifactIds.add(artifactDefinitionId);
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
return ToolResult.Success({});
|
|
235
|
-
},
|
|
148
|
+
this._createQueryArtifactsTool(options.artifacts),
|
|
149
|
+
this._createRequireTool(options.artifacts, (artifactDefinitionIds) => {
|
|
150
|
+
for (const artifactDefinitionId of artifactDefinitionIds) {
|
|
151
|
+
requiredArtifactIds.add(artifactDefinitionId);
|
|
152
|
+
}
|
|
236
153
|
}),
|
|
237
154
|
);
|
|
238
155
|
break;
|
|
156
|
+
case 'configured':
|
|
157
|
+
// no system tools
|
|
158
|
+
break;
|
|
159
|
+
default:
|
|
160
|
+
throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);
|
|
239
161
|
}
|
|
240
162
|
|
|
241
163
|
this._history = [...options.history];
|
|
242
|
-
this._pending = [
|
|
243
|
-
create(Message, {
|
|
244
|
-
role: 'user',
|
|
245
|
-
content: [{ type: 'text', text: options.prompt }],
|
|
246
|
-
}),
|
|
247
|
-
];
|
|
164
|
+
this._pending = [await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)];
|
|
248
165
|
this.userMessage.emit(this._pending.at(-1)!);
|
|
249
166
|
this._stream = undefined;
|
|
250
167
|
let error: Error | undefined;
|
|
@@ -314,7 +231,7 @@ export class AISession {
|
|
|
314
231
|
} catch (err) {
|
|
315
232
|
log.catch(err);
|
|
316
233
|
if (err instanceof Error && err.message.includes('Overloaded')) {
|
|
317
|
-
error = new AIServiecOverloadedError('AI service overloaded', { cause: err });
|
|
234
|
+
error = new AIServiecOverloadedError('AI service overloaded', { cause: err } as any); // TODO(dmaretskyi): Schema errors cant have cause
|
|
318
235
|
} else {
|
|
319
236
|
error = new Error('AI service error', { cause: err });
|
|
320
237
|
}
|
|
@@ -329,6 +246,185 @@ export class AISession {
|
|
|
329
246
|
return this._pending;
|
|
330
247
|
}
|
|
331
248
|
|
|
249
|
+
async runStructured<S extends Schema.Schema.AnyNoContext>(schema: S, options: SessionRunOptions) {
|
|
250
|
+
const parser = structuredOutputParser(schema);
|
|
251
|
+
const result = await this.run({
|
|
252
|
+
...options,
|
|
253
|
+
tools: [...options.tools, parser.tool],
|
|
254
|
+
});
|
|
255
|
+
return parser.getResult(result);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
private async _formatUserPrompt(
|
|
259
|
+
artifactDiffResolver: ArtifactDiffResolver | undefined,
|
|
260
|
+
prompt: string,
|
|
261
|
+
history: Message[],
|
|
262
|
+
) {
|
|
263
|
+
const prelude: MessageContentBlock[] = [];
|
|
264
|
+
|
|
265
|
+
if (artifactDiffResolver) {
|
|
266
|
+
const versions = gatherObjectVersions(history);
|
|
267
|
+
|
|
268
|
+
const artifactDiff = await artifactDiffResolver(
|
|
269
|
+
Array.from(versions.entries()).map(([id, version]) => ({ id, lastVersion: version })),
|
|
270
|
+
);
|
|
271
|
+
|
|
272
|
+
log.info('vision', {
|
|
273
|
+
artifactDiff,
|
|
274
|
+
versions,
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
for (const [id, { version }] of [...artifactDiff.entries()]) {
|
|
278
|
+
if (ObjectVersion.equals(version, versions.get(id)!)) {
|
|
279
|
+
artifactDiff.delete(id);
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
prelude.push(VersionPin.createBlock(VersionPin.make({ objectId: id, version })));
|
|
284
|
+
}
|
|
285
|
+
if (artifactDiff.size > 0) {
|
|
286
|
+
prelude.push(createArtifactUpdateBlock(artifactDiff));
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
return create(Message, {
|
|
291
|
+
role: 'user',
|
|
292
|
+
content: [...prelude, { type: 'text', text: prompt }],
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
private _createQueryArtifactsTool(artifacts: ArtifactDefinition[]) {
|
|
297
|
+
return defineTool('system', {
|
|
298
|
+
name: 'query_artifact_definitions',
|
|
299
|
+
description: 'Query the available artifact definitions',
|
|
300
|
+
schema: Schema.Struct({}),
|
|
301
|
+
execute: async () => {
|
|
302
|
+
return ToolResult.Success({
|
|
303
|
+
artifactDefinitions: artifacts.map((artifact) => ({
|
|
304
|
+
id: artifact.id,
|
|
305
|
+
name: artifact.name,
|
|
306
|
+
description: artifact.description,
|
|
307
|
+
})),
|
|
308
|
+
});
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
private _createRequireTool(
|
|
314
|
+
artifacts: ArtifactDefinition[],
|
|
315
|
+
onRequire: (artifactDefinitionIds: readonly string[]) => void,
|
|
316
|
+
) {
|
|
317
|
+
return defineTool('system', {
|
|
318
|
+
name: 'require_artifact_definitions',
|
|
319
|
+
description:
|
|
320
|
+
'Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.',
|
|
321
|
+
schema: Schema.Struct({
|
|
322
|
+
artifactDefinitionIds: Schema.Array(Schema.String).annotations({
|
|
323
|
+
description: 'The ids of the artifact definitions to require',
|
|
324
|
+
examples: [['artifact:dxos.org/example/Test']],
|
|
325
|
+
}),
|
|
326
|
+
}),
|
|
327
|
+
execute: async ({ artifactDefinitionIds }) => {
|
|
328
|
+
const missingArtifactDefinitionIds = artifactDefinitionIds.filter(
|
|
329
|
+
(artifactId) => !artifacts.some((artifact) => artifact.id === artifactId),
|
|
330
|
+
);
|
|
331
|
+
if (missingArtifactDefinitionIds.length > 0) {
|
|
332
|
+
return ToolResult.Error(
|
|
333
|
+
`One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(', ')}`,
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
onRequire(artifactDefinitionIds);
|
|
338
|
+
|
|
339
|
+
return ToolResult.Success({});
|
|
340
|
+
},
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
private _createPlanningTool(options: SessionRunOptions) {
|
|
345
|
+
return defineTool('system', {
|
|
346
|
+
name: 'create_plan',
|
|
347
|
+
description:
|
|
348
|
+
'Create a plan. Make sure that each step is independent and can be executed solely on the data returned by the previous step. The steps only share the data that is specified in the plan.',
|
|
349
|
+
schema: Schema.Struct({
|
|
350
|
+
goal: Schema.String.annotations({ description: 'The goal that the plan will achieve.' }),
|
|
351
|
+
steps: Schema.Array(
|
|
352
|
+
Schema.Struct({
|
|
353
|
+
action: Schema.String.annotations({
|
|
354
|
+
description: 'Complete, detailed action to perform.',
|
|
355
|
+
}),
|
|
356
|
+
input: Schema.String.annotations({
|
|
357
|
+
description: 'The required input data for this step. First step must not require any data.',
|
|
358
|
+
}),
|
|
359
|
+
output: Schema.String.annotations({
|
|
360
|
+
description: 'The output data from this step. This is passed to the next step as input.',
|
|
361
|
+
}),
|
|
362
|
+
requiredArtifactIds: Schema.Array(Schema.String).annotations({
|
|
363
|
+
description: 'The ids of the artifacts required to perform this step.',
|
|
364
|
+
examples: [['artifact:dxos.org/example/Test']],
|
|
365
|
+
}),
|
|
366
|
+
}),
|
|
367
|
+
).annotations({ description: 'Steps' }),
|
|
368
|
+
}),
|
|
369
|
+
execute: async ({ goal, steps }) => {
|
|
370
|
+
const missingArtifactIds = steps
|
|
371
|
+
.flatMap((step) => step.requiredArtifactIds)
|
|
372
|
+
.filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
|
|
373
|
+
if (missingArtifactIds.length > 0) {
|
|
374
|
+
return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(', ')}`);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const stepResults: any[] = [];
|
|
378
|
+
for (const step of steps) {
|
|
379
|
+
log('executing step', { action: step.action });
|
|
380
|
+
const session = new AISession({ operationModel: 'importing' });
|
|
381
|
+
session.message.on((ev) => this.message.emit(ev));
|
|
382
|
+
session.block.on((ev) => this.block.emit(ev));
|
|
383
|
+
session.update.on((ev) => this.update.emit(ev));
|
|
384
|
+
session.streamEvent.on((ev) => this.streamEvent.emit(ev));
|
|
385
|
+
session.userMessage.on((ev) => this.userMessage.emit(ev));
|
|
386
|
+
|
|
387
|
+
const messages = await session.run({
|
|
388
|
+
client: options.client,
|
|
389
|
+
artifacts: options.artifacts,
|
|
390
|
+
tools: options.tools,
|
|
391
|
+
history: options.history,
|
|
392
|
+
extensions: options.extensions,
|
|
393
|
+
generationOptions: options.generationOptions,
|
|
394
|
+
requiredArtifactIds: step.requiredArtifactIds.slice(),
|
|
395
|
+
artifactDiffResolver: options.artifactDiffResolver,
|
|
396
|
+
prompt: `
|
|
397
|
+
You are an agent that executes the subtask in a plan.
|
|
398
|
+
|
|
399
|
+
While you know the plan's goal only focus on your subtask
|
|
400
|
+
Use the data from the previous step to complete your task.
|
|
401
|
+
Return all of the data from "output" in your last message.
|
|
402
|
+
|
|
403
|
+
Current step (that you need to complete):
|
|
404
|
+
${JSON.stringify(
|
|
405
|
+
{
|
|
406
|
+
goal,
|
|
407
|
+
input: step.input,
|
|
408
|
+
output: step.output,
|
|
409
|
+
yourTask: step.action,
|
|
410
|
+
},
|
|
411
|
+
null,
|
|
412
|
+
2,
|
|
413
|
+
)}
|
|
414
|
+
|
|
415
|
+
Previous step results:
|
|
416
|
+
${JSON.stringify(stepResults.at(-1))}.
|
|
417
|
+
`,
|
|
418
|
+
});
|
|
419
|
+
const result = messages.at(-1);
|
|
420
|
+
stepResults.push(result);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
return ToolResult.Success({ stepResults });
|
|
424
|
+
},
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
|
|
332
428
|
abort() {
|
|
333
429
|
this._stream?.abort();
|
|
334
430
|
}
|
|
@@ -351,25 +447,75 @@ const createBaseInstructions = ({
|
|
|
351
447
|
Decision-making:
|
|
352
448
|
|
|
353
449
|
- Analyze the structure and type of the content in the user's message.
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
- Identify which artifacts are relevant to the user's request.
|
|
450
|
+
|
|
451
|
+
|
|
357
452
|
${
|
|
358
453
|
operationModel === 'planning'
|
|
359
454
|
? `
|
|
455
|
+
- Can you complete the task using the available artifacts?
|
|
456
|
+
- If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
|
|
457
|
+
- Identify which artifacts are relevant to the user's request.
|
|
360
458
|
- Break down the user's request into a step-by-step plan that you will use to execute the user's request, the plan items should include artifacts which will be used to perform the actions.
|
|
361
459
|
`
|
|
362
|
-
:
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
460
|
+
: ''
|
|
461
|
+
}
|
|
462
|
+
${
|
|
463
|
+
operationModel === 'importing'
|
|
464
|
+
? `
|
|
465
|
+
- Can you complete the task using the available artifacts?
|
|
466
|
+
- If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
|
|
467
|
+
- Identify which artifacts are relevant to the user's request.
|
|
468
|
+
- Are the required artifacts already available?
|
|
469
|
+
- If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
|
|
470
|
+
- The require'd artifact tools will be available for use after require.
|
|
471
|
+
`
|
|
472
|
+
: ''
|
|
473
|
+
}
|
|
474
|
+
${
|
|
475
|
+
operationModel === 'configured'
|
|
476
|
+
? `
|
|
477
|
+
- Select the most relevant artifact(s) to complete the task.
|
|
478
|
+
- Call the appropriate tool to use the artifact(s).
|
|
479
|
+
`
|
|
480
|
+
: ''
|
|
367
481
|
}
|
|
368
482
|
|
|
369
483
|
${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join('\n')}` : ''}
|
|
370
484
|
`;
|
|
371
485
|
|
|
372
|
-
export class AIServiecOverloadedError extends
|
|
486
|
+
export class AIServiecOverloadedError extends Schema.TaggedError<AIServiecOverloadedError>()(
|
|
373
487
|
'AIServiecOverloadedError',
|
|
374
488
|
{},
|
|
375
489
|
) {}
|
|
490
|
+
|
|
491
|
+
const gatherObjectVersions = (messages: Message[]): Map<ObjectId, ObjectVersion> => {
|
|
492
|
+
const artifactIds = new Map<ObjectId, ObjectVersion>();
|
|
493
|
+
for (const message of messages) {
|
|
494
|
+
for (const block of message.content) {
|
|
495
|
+
if (block.type === 'json' && block.disposition === VersionPin.DISPOSITION) {
|
|
496
|
+
const pin = VersionPin.pipe(Schema.decodeOption)(JSON.parse(block.json)).pipe(Option.getOrUndefined);
|
|
497
|
+
if (!pin) {
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
artifactIds.set(pin.objectId, pin.version);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
return artifactIds;
|
|
506
|
+
};
|
|
507
|
+
|
|
508
|
+
const createArtifactUpdateBlock = (
|
|
509
|
+
artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,
|
|
510
|
+
): MessageContentBlock => {
|
|
511
|
+
return {
|
|
512
|
+
type: 'text',
|
|
513
|
+
disposition: 'artifact-update',
|
|
514
|
+
text: `
|
|
515
|
+
The following artifacts have been updated since the last message:
|
|
516
|
+
${Array.from(artifactDiff.entries())
|
|
517
|
+
.map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `\n${diff}` : ''}</changed-artifact>`)
|
|
518
|
+
.join('\n')}
|
|
519
|
+
`,
|
|
520
|
+
};
|
|
521
|
+
};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2024 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { Message, type Tool, ToolResult } from '@dxos/artifact';
|
|
6
|
+
import { create } from '@dxos/echo-schema';
|
|
7
|
+
import { invariant } from '@dxos/invariant';
|
|
8
|
+
import { log } from '@dxos/log';
|
|
9
|
+
|
|
10
|
+
export const isToolUse = (message: Message, { onlyToolNames }: { onlyToolNames?: string[] } = {}) => {
|
|
11
|
+
const block = message.content.at(-1);
|
|
12
|
+
invariant(block);
|
|
13
|
+
return block.type === 'tool_use' && (!onlyToolNames || onlyToolNames.includes(block.name));
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type RunToolsOptions = {
|
|
17
|
+
message: Message;
|
|
18
|
+
tools: Tool[];
|
|
19
|
+
extensions?: ToolContextExtensions;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type RunToolsResult =
|
|
23
|
+
| {
|
|
24
|
+
type: 'continue';
|
|
25
|
+
message: Message;
|
|
26
|
+
}
|
|
27
|
+
| {
|
|
28
|
+
type: 'break';
|
|
29
|
+
result: unknown;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export const runTools = async ({ message, tools, extensions }: RunToolsOptions): Promise<RunToolsResult> => {
|
|
33
|
+
const toolCalls = message.content.filter((block) => block.type === 'tool_use');
|
|
34
|
+
invariant(toolCalls.length === 1);
|
|
35
|
+
const toolCall = toolCalls[0];
|
|
36
|
+
const tool = tools.find((tool) => tool.name === toolCall.name);
|
|
37
|
+
if (!tool) {
|
|
38
|
+
const resultMessage = create(Message, {
|
|
39
|
+
role: 'user',
|
|
40
|
+
content: [
|
|
41
|
+
{
|
|
42
|
+
type: 'tool_result',
|
|
43
|
+
toolUseId: toolCall.id,
|
|
44
|
+
content: `Tool not found: ${toolCall.name}`,
|
|
45
|
+
isError: true,
|
|
46
|
+
},
|
|
47
|
+
],
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
// TODO(burdon): Retry count?
|
|
51
|
+
return {
|
|
52
|
+
type: 'continue',
|
|
53
|
+
message: resultMessage,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
let toolResult: ToolResult;
|
|
58
|
+
try {
|
|
59
|
+
invariant(tool.execute);
|
|
60
|
+
toolResult = await tool.execute(toolCall.input, { extensions });
|
|
61
|
+
} catch (error: any) {
|
|
62
|
+
log('tool error', { error });
|
|
63
|
+
toolResult = ToolResult.Error(error.message);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
switch (toolResult.kind) {
|
|
67
|
+
case 'error': {
|
|
68
|
+
log('tool error', { message: toolResult.message });
|
|
69
|
+
const resultMessage = create(Message, {
|
|
70
|
+
role: 'user',
|
|
71
|
+
content: [
|
|
72
|
+
{
|
|
73
|
+
type: 'tool_result',
|
|
74
|
+
toolUseId: toolCall.id,
|
|
75
|
+
content: toolResult.message,
|
|
76
|
+
isError: true,
|
|
77
|
+
},
|
|
78
|
+
],
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// TODO(burdon): Retry count?
|
|
82
|
+
return {
|
|
83
|
+
type: 'continue',
|
|
84
|
+
message: resultMessage,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
case 'success': {
|
|
89
|
+
log('tool success', { result: toolResult.result });
|
|
90
|
+
const resultMessage = create(Message, {
|
|
91
|
+
role: 'user',
|
|
92
|
+
content: [
|
|
93
|
+
{
|
|
94
|
+
type: 'tool_result',
|
|
95
|
+
toolUseId: toolCall.id,
|
|
96
|
+
content:
|
|
97
|
+
typeof toolResult.result === 'string' ? toolResult.result : JSON.stringify(toolResult.result) ?? '',
|
|
98
|
+
},
|
|
99
|
+
...(toolResult.extractContentBlocks ?? []),
|
|
100
|
+
],
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
type: 'continue',
|
|
105
|
+
message: resultMessage,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
case 'break': {
|
|
110
|
+
log('tool break', { result: toolResult.result });
|
|
111
|
+
return {
|
|
112
|
+
type: 'break',
|
|
113
|
+
result: toolResult.result,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2025 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { pipe, Schema } from 'effect';
|
|
6
|
+
import { describe, expect, test } from 'vitest';
|
|
7
|
+
|
|
8
|
+
import { Expando } from '@dxos/echo-schema';
|
|
9
|
+
import { invariant } from '@dxos/invariant';
|
|
10
|
+
import { live } from '@dxos/live-object';
|
|
11
|
+
|
|
12
|
+
import { VersionPin } from './version-pin';
|
|
13
|
+
|
|
14
|
+
describe('VersionPin', () => {
|
|
15
|
+
test('serialization', () => {
|
|
16
|
+
const obj = live(Expando, {
|
|
17
|
+
name: 'John Doe',
|
|
18
|
+
});
|
|
19
|
+
const block = VersionPin.createBlock(VersionPin.make({ objectId: obj.id, version: obj.version }));
|
|
20
|
+
invariant(block.type === 'json' && block.disposition === VersionPin.DISPOSITION);
|
|
21
|
+
const pin = pipe(JSON.parse(block.json), VersionPin.pipe(Schema.decodeSync));
|
|
22
|
+
expect(pin).toBeDefined();
|
|
23
|
+
expect(pin?.objectId).toBe(obj.id);
|
|
24
|
+
expect(pin?.version).toBe(obj.version);
|
|
25
|
+
});
|
|
26
|
+
});
|