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