@dxos/assistant 0.8.4-main.84f28bd → 0.8.4-main.b97322e
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/index.mjs +623 -811
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node-esm/index.mjs +623 -811
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/types/src/context/binder.d.ts +4 -4
- package/dist/types/src/context/binder.d.ts.map +1 -1
- package/dist/types/src/context/binding.d.ts +24 -6
- package/dist/types/src/context/binding.d.ts.map +1 -1
- package/dist/types/src/conversation/conversation.d.ts +12 -18
- package/dist/types/src/conversation/conversation.d.ts.map +1 -1
- package/dist/types/src/errors.d.ts +38 -0
- package/dist/types/src/errors.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +127 -33
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
- package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction.d.ts +100 -42
- package/dist/types/src/extraction/extraction.d.ts.map +1 -1
- package/dist/types/src/functions/index.d.ts +2 -0
- package/dist/types/src/functions/index.d.ts.map +1 -0
- package/dist/types/src/functions/services.d.ts +6 -0
- package/dist/types/src/functions/services.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +2 -2
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/research/exa.d.ts +10 -5
- package/dist/types/src/research/exa.d.ts.map +1 -1
- package/dist/types/src/research/graph.d.ts +18 -8
- package/dist/types/src/research/graph.d.ts.map +1 -1
- package/dist/types/src/research/research.d.ts +1 -1
- package/dist/types/src/research/research.d.ts.map +1 -1
- package/dist/types/src/session/session.d.ts +170 -193
- package/dist/types/src/session/session.d.ts.map +1 -1
- package/dist/types/src/session/version-pin.d.ts +2 -2
- package/dist/types/src/session/version-pin.d.ts.map +1 -1
- package/dist/types/src/templates/index.d.ts +2 -0
- package/dist/types/src/templates/index.d.ts.map +1 -0
- package/dist/types/src/templates/prompt.d.ts +30 -0
- package/dist/types/src/templates/prompt.d.ts.map +1 -0
- package/dist/types/src/types.d.ts +10 -0
- package/dist/types/src/types.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +29 -21
- package/src/context/binder.ts +6 -4
- package/src/context/binding.ts +4 -3
- package/src/conversation/conversation.ts +54 -61
- package/src/errors.ts +10 -0
- package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +6 -18
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +18 -14
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +6 -3
- package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +2 -2
- package/src/extraction/extraction-ner-function/named-entity-recognition.ts +1 -1
- package/src/functions/index.ts +5 -0
- package/src/functions/services.ts +139 -0
- package/src/index.ts +2 -2
- package/src/research/exa.ts +56 -59
- package/src/research/graph.test.ts +50 -1
- package/src/research/graph.ts +85 -53
- package/src/research/instructions-research.tpl +1 -0
- package/src/research/research.test.ts +27 -27
- package/src/research/research.ts +50 -53
- package/src/session/__snapshots__/session.test.ts.snap +32 -0
- package/src/session/session.test.ts +90 -55
- package/src/session/session.ts +215 -461
- package/src/session/version-pin.test.ts +2 -21
- package/src/session/version-pin.ts +5 -5
- package/src/summarization/summarization.test.ts +75 -88
- package/src/templates/assistant.tpl +111 -0
- package/src/templates/index.ts +5 -0
- package/src/templates/prompt.ts +45 -0
- package/src/types.ts +40 -1
- package/dist/types/src/blueprint/blueprint.d.ts +0 -41
- package/dist/types/src/blueprint/blueprint.d.ts.map +0 -1
- package/dist/types/src/blueprint/index.d.ts +0 -3
- package/dist/types/src/blueprint/index.d.ts.map +0 -1
- package/dist/types/src/blueprint/registry.d.ts +0 -7
- package/dist/types/src/blueprint/registry.d.ts.map +0 -1
- package/src/blueprint/blueprint.ts +0 -75
- package/src/blueprint/index.ts +0 -6
- package/src/blueprint/registry.ts +0 -15
package/src/session/session.ts
CHANGED
|
@@ -2,35 +2,43 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import { AiLanguageModel, AiToolkit, type AiError, type AiResponse, type AiTool } from '@effect/ai';
|
|
6
|
+
import { Chunk, Context, Effect, Option, pipe, Stream, type Schema } from 'effect';
|
|
7
|
+
import { Array, String } from 'effect';
|
|
6
8
|
|
|
7
9
|
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
AiParser,
|
|
11
|
+
AiPreprocessor,
|
|
12
|
+
getToolCalls,
|
|
13
|
+
runTool,
|
|
14
|
+
ToolExecutionService,
|
|
15
|
+
ToolResolverService,
|
|
11
16
|
type AgentStatus,
|
|
12
|
-
|
|
13
|
-
type
|
|
17
|
+
type AiInputPreprocessingError,
|
|
18
|
+
type AiToolNotFoundError,
|
|
14
19
|
type GenerationStream,
|
|
15
|
-
type GenerateRequest,
|
|
16
|
-
Message,
|
|
17
|
-
type MessageContentBlock,
|
|
18
|
-
MixedStreamParser,
|
|
19
|
-
ToolResult,
|
|
20
|
-
createTool,
|
|
21
|
-
type ExecutableTool,
|
|
22
|
-
type ToolId,
|
|
23
|
-
type ToolResolver,
|
|
24
20
|
} from '@dxos/ai';
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
21
|
+
import { Event } from '@dxos/async';
|
|
22
|
+
import { type Blueprint } from '@dxos/blueprints';
|
|
23
|
+
import { todo } from '@dxos/debug';
|
|
27
24
|
import { Obj } from '@dxos/echo';
|
|
28
25
|
import { ObjectVersion } from '@dxos/echo-db';
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
26
|
+
import { type ObjectId } from '@dxos/echo-schema';
|
|
27
|
+
import { DatabaseService } from '@dxos/functions';
|
|
31
28
|
import { log } from '@dxos/log';
|
|
29
|
+
import { DataType, type ContentBlock } from '@dxos/schema';
|
|
32
30
|
|
|
33
|
-
import {
|
|
31
|
+
import { AiAssistantError } from '../errors';
|
|
32
|
+
|
|
33
|
+
export type AiSessionOptions = {};
|
|
34
|
+
|
|
35
|
+
export type SessionRunOptions<Tools extends AiTool.Any> = {
|
|
36
|
+
prompt: string;
|
|
37
|
+
history: DataType.Message[];
|
|
38
|
+
systemPrompt?: string;
|
|
39
|
+
toolkit?: AiToolkit.AiToolkit<Tools>;
|
|
40
|
+
blueprints?: Blueprint.Blueprint[];
|
|
41
|
+
};
|
|
34
42
|
|
|
35
43
|
/**
|
|
36
44
|
* Contains message history, tools, current context.
|
|
@@ -38,114 +46,47 @@ import { VersionPin } from './version-pin';
|
|
|
38
46
|
* It makes requests to the model, its a state machine.
|
|
39
47
|
* It keeps track of the current goal.
|
|
40
48
|
* It manages the context window.
|
|
41
|
-
* Tracks the success criteria of reaching the goal, exposing metrics (stretch)
|
|
49
|
+
* Tracks the success criteria of reaching the goal, exposing metrics (stretch).
|
|
42
50
|
* Could be run locally in the app or remotely.
|
|
43
51
|
* Could be personal or shared.
|
|
44
52
|
*/
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
* Used to give the model a sense of the changes to the artifacts made by users during the conversation.
|
|
49
|
-
* The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,
|
|
50
|
-
* a diff is inserted into the conversation.
|
|
51
|
-
*/
|
|
52
|
-
export type ArtifactDiffResolver = (artifacts: { id: ObjectId; lastVersion: ObjectVersion }[]) => Promise<
|
|
53
|
-
Map<
|
|
54
|
-
ObjectId,
|
|
55
|
-
{
|
|
56
|
-
version: ObjectVersion;
|
|
57
|
-
diff?: string;
|
|
58
|
-
}
|
|
59
|
-
>
|
|
60
|
-
>;
|
|
61
|
-
|
|
62
|
-
export type SessionRunOptions = {
|
|
63
|
-
artifacts: ArtifactDefinition[];
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Non-artifact specific tools.
|
|
67
|
-
*/
|
|
68
|
-
tools: ToolId[];
|
|
69
|
-
|
|
70
|
-
history: Message[];
|
|
71
|
-
|
|
72
|
-
prompt: string;
|
|
73
|
-
|
|
74
|
-
generationOptions?: Pick<GenerateRequest, 'model'>;
|
|
75
|
-
|
|
76
|
-
extensions?: ToolContextExtensions;
|
|
77
|
-
|
|
78
|
-
systemPrompt?: string;
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Pre-require artifacts.
|
|
82
|
-
*/
|
|
83
|
-
requiredArtifactIds?: string[];
|
|
84
|
-
|
|
85
|
-
client: AiServiceClient;
|
|
86
|
-
toolResolver: ToolResolver;
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Executable tools that do not go through the tool resolver.
|
|
90
|
-
*/
|
|
91
|
-
executableTools?: ExecutableTool[];
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* @see ArtifactDiffResolver
|
|
95
|
-
*/
|
|
96
|
-
artifactDiffResolver?: ArtifactDiffResolver;
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
type OperationModel = 'planning' | 'importing' | 'configured';
|
|
100
|
-
|
|
101
|
-
export type AiSessionOptions = {
|
|
102
|
-
/**
|
|
103
|
-
* Determines the agent's handling of the artifacts definitions:
|
|
104
|
-
*
|
|
105
|
-
* - `planning`: The model will create a plan with required artifacts for each step.
|
|
106
|
-
* - `importing`: The model can query registry and only pull in the artifacts that are required to complete the task.
|
|
107
|
-
* - `configured`: The available artifacts are pre-selected and the model cannot select additional artifacts.
|
|
108
|
-
*/
|
|
109
|
-
operationModel: OperationModel;
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
export class AISession {
|
|
113
|
-
/** SSE stream parser. */
|
|
114
|
-
private readonly _parser = new MixedStreamParser();
|
|
53
|
+
export class AiSession {
|
|
54
|
+
// TODO(burdon): Move to conversation.
|
|
55
|
+
private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
|
|
115
56
|
|
|
116
57
|
/** Pending messages (incl. the current user request). */
|
|
117
|
-
private _pending: Message[] = [];
|
|
58
|
+
private _pending: DataType.Message[] = [];
|
|
118
59
|
|
|
119
60
|
/** Current streaming response. */
|
|
120
61
|
private _stream: GenerationStream | undefined;
|
|
121
62
|
|
|
122
63
|
/** Prior history from queue. */
|
|
123
|
-
private _history: Message[] = [];
|
|
64
|
+
private _history: DataType.Message[] = [];
|
|
124
65
|
|
|
125
66
|
/**
|
|
126
67
|
* New message.
|
|
127
68
|
*/
|
|
128
|
-
public readonly message =
|
|
69
|
+
public readonly message = new Event<DataType.Message>();
|
|
129
70
|
|
|
130
71
|
/**
|
|
131
72
|
* Complete block added to Message.
|
|
132
73
|
*/
|
|
133
|
-
public readonly block =
|
|
74
|
+
public readonly block = new Event<ContentBlock.Any>();
|
|
134
75
|
|
|
135
76
|
/**
|
|
136
77
|
* Update partial block (while streaming).
|
|
137
78
|
*/
|
|
138
|
-
public readonly update =
|
|
79
|
+
public readonly update = new Event<ContentBlock.Any>();
|
|
139
80
|
|
|
140
81
|
/**
|
|
141
82
|
* Unparsed events from the underlying generation stream.
|
|
142
83
|
*/
|
|
143
|
-
public readonly streamEvent =
|
|
84
|
+
public readonly streamEvent = new Event<AiResponse.Part>();
|
|
144
85
|
|
|
145
86
|
/**
|
|
146
87
|
* User prompt or tool result.
|
|
147
88
|
*/
|
|
148
|
-
public readonly userMessage = new Event<Message>();
|
|
89
|
+
public readonly userMessage = new Event<DataType.Message>();
|
|
149
90
|
|
|
150
91
|
/**
|
|
151
92
|
* Agent self-reporting its status.
|
|
@@ -158,407 +99,180 @@ export class AISession {
|
|
|
158
99
|
*/
|
|
159
100
|
public readonly done = new Event<void>();
|
|
160
101
|
|
|
161
|
-
|
|
162
|
-
* Emits when the tool reports its status.
|
|
163
|
-
* Triggered by the tool execution function.
|
|
164
|
-
*/
|
|
165
|
-
public readonly toolStatusReport = new Event<{ message: Message; status: AgentStatus }>();
|
|
166
|
-
|
|
167
|
-
constructor(private readonly _options: AiSessionOptions) {
|
|
168
|
-
// Message complete.
|
|
169
|
-
this._parser.message.on((message) => {
|
|
170
|
-
this._pending.push(message);
|
|
171
|
-
});
|
|
172
|
-
this._parser.block.on((block) => {
|
|
173
|
-
if (block.type === 'text' && block.disposition === 'status') {
|
|
174
|
-
this.statusReport.emit(create(AgentStatusReport, { message: block.text }));
|
|
175
|
-
}
|
|
176
|
-
});
|
|
177
|
-
}
|
|
102
|
+
constructor(private readonly _options: AiSessionOptions = {}) {}
|
|
178
103
|
|
|
179
104
|
/**
|
|
180
105
|
* Runs the AI model loop interacting with tools and artifacts.
|
|
181
106
|
* @param options - The session options.
|
|
182
107
|
* @returns The messages generated by the session, including the user's prompt.
|
|
183
108
|
*/
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
}
|
|
109
|
+
// TODO(dmaretskyi): Toolkit context doesn't get added to the effect type.
|
|
110
|
+
run = <Tools extends AiTool.Any>(
|
|
111
|
+
options: SessionRunOptions<Tools>,
|
|
112
|
+
): Effect.Effect<
|
|
113
|
+
DataType.Message[],
|
|
114
|
+
AiAssistantError | AiInputPreprocessingError | AiToolNotFoundError | AiError.AiError,
|
|
115
|
+
AiLanguageModel.AiLanguageModel | ToolResolverService | ToolExecutionService | AiTool.ToHandler<Tools>
|
|
116
|
+
> =>
|
|
117
|
+
Effect.gen(this, function* () {
|
|
118
|
+
this._history = [...options.history];
|
|
119
|
+
|
|
120
|
+
const promptMessages = yield* this._formatUserPrompt(options.prompt, options.history);
|
|
121
|
+
this._pending = [promptMessages];
|
|
122
|
+
this.userMessage.emit(promptMessages);
|
|
123
|
+
|
|
124
|
+
// Potential tool use loop.
|
|
125
|
+
do {
|
|
126
|
+
log('request', {
|
|
127
|
+
pending: this._pending.length,
|
|
128
|
+
history: this._history.length,
|
|
129
|
+
tools: (Object.values(options.toolkit?.tools ?? {}) as AiTool.Any[]).map((tool: AiTool.Any) => tool.name),
|
|
130
|
+
});
|
|
207
131
|
|
|
208
|
-
|
|
209
|
-
this._pending = [await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)];
|
|
210
|
-
this.userMessage.emit(this._pending.at(-1)!);
|
|
211
|
-
this._stream = undefined;
|
|
132
|
+
const prompt = yield* AiPreprocessor.preprocessAiInput([...this._history, ...this._pending]);
|
|
212
133
|
|
|
213
|
-
|
|
134
|
+
const blueprints = options.blueprints ?? [];
|
|
214
135
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
...(options.executableTools ?? []),
|
|
224
|
-
...options.artifacts
|
|
225
|
-
.filter((artifact) => requiredArtifactIds.has(artifact.id))
|
|
226
|
-
.flatMap((artifact) => artifact.tools),
|
|
227
|
-
],
|
|
228
|
-
Array.dedupeWith((a, b) => a.id === b.id),
|
|
136
|
+
// Build system prompt from blueprint templates.
|
|
137
|
+
// TODO(dmaretskyi): Loading BP from the Database should be done at the higher level. We need a type for the resolved blueprint.
|
|
138
|
+
const systemPrompt = yield* pipe(
|
|
139
|
+
blueprints,
|
|
140
|
+
Effect.forEach((blueprint) => DatabaseService.loadRef(blueprint.instructions)),
|
|
141
|
+
Effect.flatMap(Effect.forEach((template) => DatabaseService.loadRef(template.source))),
|
|
142
|
+
Effect.map(Array.map((template) => `\n\n<blueprint>${template.content}</blueprint>`)),
|
|
143
|
+
Effect.map(Array.reduce(options.systemPrompt ?? '', String.concat)),
|
|
229
144
|
);
|
|
230
145
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
146
|
+
// Build a combined toolkit from the blueprint tools and the provided toolkit.
|
|
147
|
+
const blueprintToolkit = yield* ToolResolverService.resolveToolkit(blueprints.flatMap((bp) => bp.tools));
|
|
148
|
+
const blueprintToolkitHandler: Context.Context<AiTool.ToHandler<AiTool.Any>> =
|
|
149
|
+
yield* blueprintToolkit.toContext(yield* ToolExecutionService.handlersFor(blueprintToolkit));
|
|
150
|
+
const toolkit = options.toolkit != null ? AiToolkit.merge(options.toolkit, blueprintToolkit) : blueprintToolkit;
|
|
151
|
+
const toolkitWithBlueprintHandlers = yield* toolkit.pipe(
|
|
152
|
+
Effect.provide(blueprintToolkitHandler) as any,
|
|
153
|
+
) as Effect.Effect<AiToolkit.ToHandler<any>, never, AiTool.ToHandler<Tools>>;
|
|
154
|
+
|
|
155
|
+
log.info('run', {
|
|
156
|
+
systemPrompt: [systemPrompt.slice(0, 32), '...', systemPrompt.slice(-32), systemPrompt.length].join(' '),
|
|
157
|
+
tools: Object.keys(blueprintToolkit.tools),
|
|
235
158
|
});
|
|
236
159
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
160
|
+
const blocks = yield* AiLanguageModel.streamText({
|
|
161
|
+
prompt,
|
|
162
|
+
system: systemPrompt,
|
|
163
|
+
toolkit: toolkitWithBlueprintHandlers,
|
|
164
|
+
disableToolCallResolution: true,
|
|
165
|
+
}).pipe(
|
|
166
|
+
AiParser.parseGptStream({
|
|
167
|
+
onBlock: (block) =>
|
|
168
|
+
Effect.gen(this, function* () {
|
|
169
|
+
if (block.pending) {
|
|
170
|
+
this.update.emit(block);
|
|
171
|
+
} else {
|
|
172
|
+
this.block.emit(block);
|
|
173
|
+
}
|
|
174
|
+
}),
|
|
175
|
+
onPart: (part) =>
|
|
176
|
+
Effect.gen(this, function* () {
|
|
177
|
+
this.streamEvent.emit(part);
|
|
178
|
+
}),
|
|
179
|
+
}),
|
|
180
|
+
Stream.runCollect,
|
|
181
|
+
Effect.map(Chunk.toArray),
|
|
182
|
+
);
|
|
183
|
+
|
|
184
|
+
const response = Obj.make(DataType.Message, {
|
|
185
|
+
created: new Date().toISOString(),
|
|
186
|
+
sender: { role: 'assistant' },
|
|
187
|
+
blocks,
|
|
249
188
|
});
|
|
189
|
+
this._pending.push(response);
|
|
190
|
+
this.message.emit(response);
|
|
250
191
|
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
// Add messages.
|
|
256
|
-
log('response', { pending: this._pending });
|
|
257
|
-
|
|
258
|
-
// Resolve tool use locally.
|
|
259
|
-
more = false;
|
|
260
|
-
const message = this._pending.at(-1);
|
|
261
|
-
invariant(message);
|
|
262
|
-
if (isToolUse(message)) {
|
|
263
|
-
log('tool request...');
|
|
264
|
-
const response = await runTools({
|
|
265
|
-
message: this._pending.at(-1)!,
|
|
266
|
-
tools,
|
|
267
|
-
extensions: options.extensions ?? {},
|
|
268
|
-
reportStatus: (status) => this._onToolStatusReport(message, status),
|
|
269
|
-
});
|
|
270
|
-
|
|
271
|
-
log('tool response', { response });
|
|
272
|
-
switch (response.type) {
|
|
273
|
-
case 'continue': {
|
|
274
|
-
this._pending = [...this._pending, response.message];
|
|
275
|
-
this.userMessage.emit(response.message);
|
|
276
|
-
more = true;
|
|
277
|
-
break;
|
|
278
|
-
}
|
|
279
|
-
}
|
|
192
|
+
const toolCalls = getToolCalls(response);
|
|
193
|
+
if (toolCalls.length === 0) {
|
|
194
|
+
break;
|
|
280
195
|
}
|
|
281
|
-
} while (more);
|
|
282
|
-
} catch (err) {
|
|
283
|
-
log.catch(err);
|
|
284
|
-
if (err instanceof Error && err.message.includes('Overloaded')) {
|
|
285
|
-
error = new AIServiecOverloadedError('AI service overloaded', { cause: err } as any); // TODO(dmaretskyi): Schema errors cant have cause
|
|
286
|
-
} else {
|
|
287
|
-
error = new Error('AI service error', { cause: err });
|
|
288
|
-
}
|
|
289
|
-
} finally {
|
|
290
|
-
this._stream = undefined;
|
|
291
|
-
this.done.emit();
|
|
292
|
-
}
|
|
293
196
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
197
|
+
const toolResults = yield* runTools(toolCalls, toolkitWithBlueprintHandlers as any);
|
|
198
|
+
this._pending.push(
|
|
199
|
+
Obj.make(DataType.Message, {
|
|
200
|
+
created: new Date().toISOString(),
|
|
201
|
+
sender: { role: 'user' },
|
|
202
|
+
blocks: toolResults,
|
|
203
|
+
}),
|
|
204
|
+
);
|
|
205
|
+
} while (true);
|
|
297
206
|
|
|
298
|
-
|
|
299
|
-
|
|
207
|
+
return this._pending;
|
|
208
|
+
}).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));
|
|
300
209
|
|
|
301
210
|
async runStructured<S extends Schema.Schema.AnyNoContext>(
|
|
302
211
|
schema: S,
|
|
303
|
-
options: SessionRunOptions
|
|
212
|
+
options: SessionRunOptions<AiTool.Any>,
|
|
304
213
|
): Promise<Schema.Schema.Type<S>> {
|
|
305
|
-
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
private async _formatUserPrompt(
|
|
314
|
-
artifactDiffResolver: ArtifactDiffResolver | undefined,
|
|
315
|
-
prompt: string,
|
|
316
|
-
history: Message[],
|
|
317
|
-
) {
|
|
318
|
-
const prelude: MessageContentBlock[] = [];
|
|
319
|
-
|
|
320
|
-
if (artifactDiffResolver) {
|
|
321
|
-
const versions = gatherObjectVersions(history);
|
|
322
|
-
|
|
323
|
-
const artifactDiff = await artifactDiffResolver(
|
|
324
|
-
[...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),
|
|
325
|
-
);
|
|
326
|
-
|
|
327
|
-
log.info('vision', {
|
|
328
|
-
artifactDiff,
|
|
329
|
-
versions,
|
|
330
|
-
});
|
|
331
|
-
|
|
332
|
-
for (const [id, { version }] of [...artifactDiff.entries()]) {
|
|
333
|
-
if (ObjectVersion.equals(version, versions.get(id)!)) {
|
|
334
|
-
artifactDiff.delete(id);
|
|
335
|
-
continue;
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
prelude.push(VersionPin.createBlock(VersionPin.make({ objectId: id, version })));
|
|
339
|
-
}
|
|
340
|
-
if (artifactDiff.size > 0) {
|
|
341
|
-
prelude.push(createArtifactUpdateBlock(artifactDiff));
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
return Obj.make(Message, {
|
|
346
|
-
role: 'user',
|
|
347
|
-
content: [...prelude, { type: 'text', text: prompt }],
|
|
348
|
-
});
|
|
214
|
+
return todo();
|
|
215
|
+
// const parser = structuredOutputParser(schema);
|
|
216
|
+
// const result = await this.run({
|
|
217
|
+
// ...options,
|
|
218
|
+
// executableTools: [...(options.executableTools ?? []), parser.tool],
|
|
219
|
+
// });
|
|
220
|
+
// return parser.getResult(result);
|
|
349
221
|
}
|
|
350
222
|
|
|
351
|
-
private
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
223
|
+
private _formatUserPrompt = (prompt: string, history: DataType.Message[]) =>
|
|
224
|
+
Effect.gen(function* () {
|
|
225
|
+
const prelude: ContentBlock.Any[] = [];
|
|
226
|
+
|
|
227
|
+
// TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.
|
|
228
|
+
const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);
|
|
229
|
+
if (Option.isSome(artifactDiffResolver)) {
|
|
230
|
+
const versions = gatherObjectVersions(history);
|
|
231
|
+
|
|
232
|
+
const artifactDiff = yield* Effect.tryPromise({
|
|
233
|
+
try: () =>
|
|
234
|
+
artifactDiffResolver.value.resolve(
|
|
235
|
+
[...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),
|
|
236
|
+
),
|
|
237
|
+
catch: AiAssistantError.wrap('Artifact diff resolution error'),
|
|
363
238
|
});
|
|
364
|
-
},
|
|
365
|
-
});
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
private _createRequireTool(
|
|
369
|
-
artifacts: ArtifactDefinition[],
|
|
370
|
-
onRequire: (artifactDefinitionIds: readonly string[]) => void,
|
|
371
|
-
): ExecutableTool {
|
|
372
|
-
return createTool('system', {
|
|
373
|
-
name: 'require_artifact_definitions',
|
|
374
|
-
description:
|
|
375
|
-
'Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.',
|
|
376
|
-
schema: Schema.Struct({
|
|
377
|
-
artifactDefinitionIds: Schema.Array(Schema.String).annotations({
|
|
378
|
-
description: 'The ids of the artifact definitions to require',
|
|
379
|
-
examples: [['artifact:dxos.org/example/Test']],
|
|
380
|
-
}),
|
|
381
|
-
}),
|
|
382
|
-
execute: async ({ artifactDefinitionIds }) => {
|
|
383
|
-
const missingArtifactDefinitionIds = artifactDefinitionIds.filter(
|
|
384
|
-
(artifactId) => !artifacts.some((artifact) => artifact.id === artifactId),
|
|
385
|
-
);
|
|
386
|
-
if (missingArtifactDefinitionIds.length > 0) {
|
|
387
|
-
return ToolResult.Error(
|
|
388
|
-
`One or more artifact definition ids are invalid: ${missingArtifactDefinitionIds.join(', ')}`,
|
|
389
|
-
);
|
|
390
|
-
}
|
|
391
239
|
|
|
392
|
-
|
|
240
|
+
log.info('vision', {
|
|
241
|
+
artifactDiff,
|
|
242
|
+
versions,
|
|
243
|
+
});
|
|
393
244
|
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
245
|
+
for (const [id, { version }] of [...artifactDiff.entries()]) {
|
|
246
|
+
if (ObjectVersion.equals(version, versions.get(id)!)) {
|
|
247
|
+
artifactDiff.delete(id);
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
398
250
|
|
|
399
|
-
|
|
400
|
-
return createTool('system', {
|
|
401
|
-
name: 'create_plan',
|
|
402
|
-
description:
|
|
403
|
-
'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.',
|
|
404
|
-
schema: Schema.Struct({
|
|
405
|
-
goal: Schema.String.annotations({ description: 'The goal that the plan will achieve.' }),
|
|
406
|
-
steps: Schema.Array(
|
|
407
|
-
Schema.Struct({
|
|
408
|
-
action: Schema.String.annotations({
|
|
409
|
-
description: 'Complete, detailed action to perform.',
|
|
410
|
-
}),
|
|
411
|
-
input: Schema.String.annotations({
|
|
412
|
-
description: 'The required input data for this step. First step must not require any data.',
|
|
413
|
-
}),
|
|
414
|
-
output: Schema.String.annotations({
|
|
415
|
-
description: 'The output data from this step. This is passed to the next step as input.',
|
|
416
|
-
}),
|
|
417
|
-
requiredArtifactIds: Schema.Array(Schema.String).annotations({
|
|
418
|
-
description: 'The ids of the artifacts required to perform this step.',
|
|
419
|
-
examples: [['artifact:dxos.org/example/Test']],
|
|
420
|
-
}),
|
|
421
|
-
}),
|
|
422
|
-
).annotations({ description: 'Steps' }),
|
|
423
|
-
}),
|
|
424
|
-
execute: async ({ goal, steps }) => {
|
|
425
|
-
const missingArtifactIds = steps
|
|
426
|
-
.flatMap((step) => step.requiredArtifactIds)
|
|
427
|
-
.filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
|
|
428
|
-
if (missingArtifactIds.length > 0) {
|
|
429
|
-
return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(', ')}`);
|
|
251
|
+
prelude.push({ _tag: 'anchor', objectId: id, version });
|
|
430
252
|
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
for (const step of steps) {
|
|
434
|
-
log('executing step', { action: step.action });
|
|
435
|
-
const session = new AISession({ operationModel: 'importing' });
|
|
436
|
-
session.message.on((ev) => this.message.emit(ev));
|
|
437
|
-
session.block.on((ev) => this.block.emit(ev));
|
|
438
|
-
session.update.on((ev) => this.update.emit(ev));
|
|
439
|
-
session.streamEvent.on((ev) => this.streamEvent.emit(ev));
|
|
440
|
-
session.userMessage.on((ev) => this.userMessage.emit(ev));
|
|
441
|
-
|
|
442
|
-
const messages = await session.run({
|
|
443
|
-
artifacts: options.artifacts,
|
|
444
|
-
tools: options.tools,
|
|
445
|
-
history: options.history,
|
|
446
|
-
extensions: options.extensions,
|
|
447
|
-
requiredArtifactIds: step.requiredArtifactIds.slice(),
|
|
448
|
-
prompt: `
|
|
449
|
-
You are an agent that executes the subtask in a plan.
|
|
450
|
-
|
|
451
|
-
While you know the plan's goal only focus on your subtask
|
|
452
|
-
Use the data from the previous step to complete your task.
|
|
453
|
-
Return all of the data from "output" in your last message.
|
|
454
|
-
|
|
455
|
-
Current step (that you need to complete):
|
|
456
|
-
${JSON.stringify(
|
|
457
|
-
{
|
|
458
|
-
goal,
|
|
459
|
-
input: step.input,
|
|
460
|
-
output: step.output,
|
|
461
|
-
yourTask: step.action,
|
|
462
|
-
},
|
|
463
|
-
null,
|
|
464
|
-
2,
|
|
465
|
-
)}
|
|
466
|
-
|
|
467
|
-
Previous step results:
|
|
468
|
-
${JSON.stringify(stepResults.at(-1))}.
|
|
469
|
-
`,
|
|
470
|
-
|
|
471
|
-
generationOptions: options.generationOptions,
|
|
472
|
-
client: options.client,
|
|
473
|
-
toolResolver: options.toolResolver,
|
|
474
|
-
artifactDiffResolver: options.artifactDiffResolver,
|
|
475
|
-
});
|
|
476
|
-
const result = messages.at(-1);
|
|
477
|
-
stepResults.push(result);
|
|
253
|
+
if (artifactDiff.size > 0) {
|
|
254
|
+
prelude.push(createArtifactUpdateBlock(artifactDiff));
|
|
478
255
|
}
|
|
256
|
+
}
|
|
479
257
|
|
|
480
|
-
|
|
481
|
-
|
|
258
|
+
return Obj.make(DataType.Message, {
|
|
259
|
+
created: new Date().toISOString(),
|
|
260
|
+
sender: { role: 'user' },
|
|
261
|
+
blocks: [...prelude, { _tag: 'text', text: prompt }],
|
|
262
|
+
});
|
|
482
263
|
});
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
private _onToolStatusReport(message: Message, status: AgentStatus): void {
|
|
486
|
-
this.toolStatusReport.emit({ message, status });
|
|
487
|
-
}
|
|
488
264
|
|
|
489
265
|
abort(): void {
|
|
490
266
|
this._stream?.abort();
|
|
491
267
|
}
|
|
492
268
|
}
|
|
493
269
|
|
|
494
|
-
|
|
495
|
-
const createBaseInstructions = ({
|
|
496
|
-
availableArtifacts,
|
|
497
|
-
operationModel,
|
|
498
|
-
}: {
|
|
499
|
-
availableArtifacts: string[];
|
|
500
|
-
operationModel: OperationModel;
|
|
501
|
-
}) => `
|
|
502
|
-
You are a friendly, advanced AI assistant capable of creating and managing artifacts from available data and tools.
|
|
503
|
-
Your task is to process user commands and questions and decide how best to respond.
|
|
504
|
-
In some cases, you will need to create or reference data objects called artifacts.
|
|
505
|
-
|
|
506
|
-
Follow these guidelines carefully:
|
|
507
|
-
|
|
508
|
-
Decision-making:
|
|
509
|
-
|
|
510
|
-
- Analyze the structure and type of the content in the user's message.
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
${
|
|
514
|
-
operationModel === 'planning'
|
|
515
|
-
? `
|
|
516
|
-
- Can you complete the task using the available artifacts?
|
|
517
|
-
- If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
|
|
518
|
-
- Identify which artifacts are relevant to the user's request.
|
|
519
|
-
- 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.
|
|
520
|
-
`
|
|
521
|
-
: ''
|
|
522
|
-
}
|
|
523
|
-
${
|
|
524
|
-
operationModel === 'importing'
|
|
525
|
-
? `
|
|
526
|
-
- Can you complete the task using the available artifacts?
|
|
527
|
-
- If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
|
|
528
|
-
- Identify which artifacts are relevant to the user's request.
|
|
529
|
-
- Are the required artifacts already available?
|
|
530
|
-
- If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
|
|
531
|
-
- The require'd artifact tools will be available for use after require.
|
|
532
|
-
`
|
|
533
|
-
: ''
|
|
534
|
-
}
|
|
535
|
-
${
|
|
536
|
-
operationModel === 'configured'
|
|
537
|
-
? `
|
|
538
|
-
- Select the most relevant artifact(s) to complete the task.
|
|
539
|
-
- Call the appropriate tool to use the artifact(s).
|
|
540
|
-
`
|
|
541
|
-
: ''
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join('\n')}` : ''}
|
|
545
|
-
`;
|
|
546
|
-
|
|
547
|
-
export class AIServiecOverloadedError extends Schema.TaggedError<AIServiecOverloadedError>()(
|
|
548
|
-
'AIServiecOverloadedError',
|
|
549
|
-
{},
|
|
550
|
-
) {}
|
|
551
|
-
|
|
552
|
-
const gatherObjectVersions = (messages: Message[]): Map<ObjectId, ObjectVersion> => {
|
|
270
|
+
const gatherObjectVersions = (messages: DataType.Message[]): Map<ObjectId, ObjectVersion> => {
|
|
553
271
|
const artifactIds = new Map<ObjectId, ObjectVersion>();
|
|
554
272
|
for (const message of messages) {
|
|
555
|
-
for (const block of message.
|
|
556
|
-
if (block.
|
|
557
|
-
|
|
558
|
-
if (!pin) {
|
|
559
|
-
continue;
|
|
560
|
-
}
|
|
561
|
-
artifactIds.set(pin.objectId, pin.version);
|
|
273
|
+
for (const block of message.blocks) {
|
|
274
|
+
if (block._tag === 'anchor') {
|
|
275
|
+
artifactIds.set(block.objectId, block.version as ObjectVersion);
|
|
562
276
|
}
|
|
563
277
|
}
|
|
564
278
|
}
|
|
@@ -568,9 +282,10 @@ const gatherObjectVersions = (messages: Message[]): Map<ObjectId, ObjectVersion>
|
|
|
568
282
|
|
|
569
283
|
const createArtifactUpdateBlock = (
|
|
570
284
|
artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,
|
|
571
|
-
):
|
|
285
|
+
): ContentBlock.Any => {
|
|
572
286
|
return {
|
|
573
|
-
|
|
287
|
+
_tag: 'text',
|
|
288
|
+
// TODO(dmaretskyi): Does this need to be a special content-block?
|
|
574
289
|
disposition: 'artifact-update',
|
|
575
290
|
text: `
|
|
576
291
|
The following artifacts have been updated since the last message:
|
|
@@ -580,3 +295,42 @@ const createArtifactUpdateBlock = (
|
|
|
580
295
|
`,
|
|
581
296
|
};
|
|
582
297
|
};
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Resolves artifact ids to their versions.
|
|
301
|
+
* Used to give the model a sense of the changes to the artifacts made by users during the conversation.
|
|
302
|
+
* The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,
|
|
303
|
+
* a diff is inserted into the conversation.
|
|
304
|
+
*
|
|
305
|
+
* Can be optionally provided to the session run call.
|
|
306
|
+
*/
|
|
307
|
+
// TODO(dmaretskyi): Convert to Context.Reference
|
|
308
|
+
export class ArtifactDiffResolver extends Context.Tag('ArtifactDiffResolver')<
|
|
309
|
+
ArtifactDiffResolver,
|
|
310
|
+
ArtifactDiffResolver.Service
|
|
311
|
+
>() {}
|
|
312
|
+
|
|
313
|
+
export namespace ArtifactDiffResolver {
|
|
314
|
+
export type Service = {
|
|
315
|
+
resolve: (artifacts: { id: ObjectId; lastVersion: ObjectVersion }[]) => Promise<
|
|
316
|
+
Map<
|
|
317
|
+
ObjectId,
|
|
318
|
+
{
|
|
319
|
+
version: ObjectVersion;
|
|
320
|
+
diff?: string;
|
|
321
|
+
}
|
|
322
|
+
>
|
|
323
|
+
>;
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const runTools: <Tools extends AiTool.Any>(
|
|
328
|
+
toolCalls: ContentBlock.ToolCall[],
|
|
329
|
+
toolkit: AiToolkit.AiToolkit<Tools>,
|
|
330
|
+
) => Effect.Effect<ContentBlock.ToolResult[], AiError.AiError, AiTool.ToHandler<Tools>> = Effect.fn('runTools')(
|
|
331
|
+
function* (toolCalls, toolkit) {
|
|
332
|
+
const toolkitWithHandlers = Effect.isEffect(toolkit) ? yield* toolkit : toolkit;
|
|
333
|
+
|
|
334
|
+
return yield* Effect.forEach(toolCalls, (toolCall) => runTool(toolkitWithHandlers, toolCall));
|
|
335
|
+
},
|
|
336
|
+
);
|