@dxos/assistant 0.8.4-main.f9ba587 → 0.8.4-main.fd6878d
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-6WRGDEMH.mjs +89 -0
- package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +7 -0
- package/dist/lib/browser/chunk-NZGGCEF3.mjs +341 -0
- package/dist/lib/browser/chunk-NZGGCEF3.mjs.map +7 -0
- package/dist/lib/browser/extraction/index.mjs +269 -0
- package/dist/lib/browser/extraction/index.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +240 -1905
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +13 -0
- package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs.map +7 -0
- package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +91 -0
- package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +7 -0
- package/dist/lib/node-esm/chunk-XOOPGSGW.mjs +343 -0
- package/dist/lib/node-esm/chunk-XOOPGSGW.mjs.map +7 -0
- package/dist/lib/node-esm/extraction/index.mjs +270 -0
- package/dist/lib/node-esm/extraction/index.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +240 -1906
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +14 -0
- package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs.map +7 -0
- package/dist/types/src/conversation/context.d.ts +90 -0
- package/dist/types/src/conversation/context.d.ts.map +1 -0
- package/dist/types/src/conversation/conversation.d.ts +31 -25
- package/dist/types/src/conversation/conversation.d.ts.map +1 -1
- package/dist/types/src/conversation/index.d.ts +1 -0
- package/dist/types/src/conversation/index.d.ts.map +1 -1
- package/dist/types/src/errors.d.ts +39 -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 +143 -45
- 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 +106 -44
- 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 +7 -0
- package/dist/types/src/functions/services.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +3 -5
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/session/artifact-diff.d.ts +27 -0
- package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
- package/dist/types/src/session/format.d.ts +168 -0
- package/dist/types/src/session/format.d.ts.map +1 -0
- package/dist/types/src/session/format.test.d.ts +2 -0
- package/dist/types/src/session/format.test.d.ts.map +1 -0
- package/dist/types/src/session/index.d.ts +1 -0
- package/dist/types/src/session/index.d.ts.map +1 -1
- package/dist/types/src/session/session.d.ts +123 -239
- package/dist/types/src/session/session.d.ts.map +1 -1
- package/dist/types/src/session/version-pin.d.ts +4 -4
- 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/system.d.ts +22 -0
- package/dist/types/src/templates/system.d.ts.map +1 -0
- package/dist/types/src/types.d.ts +13 -0
- package/dist/types/src/types.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +46 -22
- package/src/{context/binder.ts → conversation/context.ts} +51 -19
- package/src/conversation/conversation.ts +90 -68
- package/src/conversation/index.ts +1 -0
- package/src/errors.ts +10 -0
- package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +7 -18
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +22 -17
- package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +4 -3
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +7 -4
- 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/extraction/quotes.test.ts +1 -1
- package/src/extraction/quotes.ts +1 -1
- package/src/functions/index.ts +5 -0
- package/src/functions/services.ts +114 -0
- package/src/index.ts +3 -5
- package/src/session/__snapshots__/session.test.ts.snap +32 -0
- package/src/session/artifact-diff.ts +37 -0
- package/src/session/format.test.ts +60 -0
- package/src/session/format.ts +139 -0
- package/src/session/index.ts +1 -0
- package/src/session/session.test.ts +87 -57
- package/src/session/session.ts +220 -523
- package/src/session/version-pin.test.ts +2 -21
- package/src/session/version-pin.ts +9 -9
- package/src/summarization/summarization.test.ts +82 -106
- package/src/templates/format.tpl +55 -0
- package/src/templates/index.ts +5 -0
- package/src/templates/system.tpl +47 -0
- package/src/templates/system.ts +32 -0
- package/src/types.ts +45 -1
- package/src/typings.d.ts +5 -0
- package/dist/types/bin/chat.d.ts +0 -2
- package/dist/types/bin/chat.d.ts.map +0 -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/dist/types/src/context/binder.d.ts +0 -34
- package/dist/types/src/context/binder.d.ts.map +0 -1
- package/dist/types/src/context/binding.d.ts +0 -38
- package/dist/types/src/context/binding.d.ts.map +0 -1
- package/dist/types/src/context/index.d.ts +0 -3
- package/dist/types/src/context/index.d.ts.map +0 -1
- package/dist/types/src/research/exa.d.ts +0 -7
- package/dist/types/src/research/exa.d.ts.map +0 -1
- package/dist/types/src/research/graph.d.ts +0 -41
- package/dist/types/src/research/graph.d.ts.map +0 -1
- package/dist/types/src/research/graph.test.d.ts +0 -2
- package/dist/types/src/research/graph.test.d.ts.map +0 -1
- package/dist/types/src/research/index.d.ts +0 -4
- package/dist/types/src/research/index.d.ts.map +0 -1
- package/dist/types/src/research/research.d.ts +0 -10
- package/dist/types/src/research/research.d.ts.map +0 -1
- package/dist/types/src/research/research.test.d.ts +0 -2
- package/dist/types/src/research/research.test.d.ts.map +0 -1
- package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
- package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
- package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
- package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
- package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
- package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
- package/dist/types/src/testing/index.d.ts +0 -3
- package/dist/types/src/testing/index.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/context/binding.ts +0 -31
- package/src/context/index.ts +0 -6
- package/src/research/exa.ts +0 -100
- package/src/research/graph.test.ts +0 -15
- package/src/research/graph.ts +0 -337
- package/src/research/index.ts +0 -7
- package/src/research/instructions-research.tpl +0 -97
- package/src/research/research.test.ts +0 -190
- package/src/research/research.ts +0 -90
- package/src/testing/exa-search-1748337321991.ts +0 -131
- package/src/testing/exa-search-1748337331526.ts +0 -144
- package/src/testing/exa-search-1748337344119.ts +0 -133
- package/src/testing/index.ts +0 -11
- package/src/typedefs.d.ts +0 -8
package/src/session/session.ts
CHANGED
|
@@ -2,581 +2,278 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import { type AiError, AiLanguageModel, type AiResponse, type AiTool, AiToolkit } from '@effect/ai';
|
|
6
|
+
import { Chunk, type Context, Effect, Function, Option, Queue, type Schema, Stream } from 'effect';
|
|
6
7
|
|
|
7
8
|
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
type
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
type MessageContentBlock,
|
|
18
|
-
MixedStreamParser,
|
|
19
|
-
ToolResult,
|
|
20
|
-
createTool,
|
|
21
|
-
type ExecutableTool,
|
|
22
|
-
type ToolId,
|
|
23
|
-
type ToolResolver,
|
|
9
|
+
type AiInputPreprocessingError,
|
|
10
|
+
AiParser,
|
|
11
|
+
AiPreprocessor,
|
|
12
|
+
type AiToolNotFoundError,
|
|
13
|
+
type ConsolePrinter,
|
|
14
|
+
ToolExecutionService,
|
|
15
|
+
ToolResolverService,
|
|
16
|
+
callTools,
|
|
17
|
+
getToolCalls,
|
|
24
18
|
} from '@dxos/ai';
|
|
25
|
-
import { type
|
|
26
|
-
import {
|
|
19
|
+
import { type Blueprint } from '@dxos/blueprints';
|
|
20
|
+
import { todo } from '@dxos/debug';
|
|
27
21
|
import { Obj } from '@dxos/echo';
|
|
28
|
-
import { ObjectVersion } from '@dxos/echo-db';
|
|
29
|
-
import { create, type ObjectId } from '@dxos/echo-schema';
|
|
30
|
-
import { invariant } from '@dxos/invariant';
|
|
31
22
|
import { log } from '@dxos/log';
|
|
23
|
+
import { type ContentBlock, DataType } from '@dxos/schema';
|
|
24
|
+
import { isNotFalsy } from '@dxos/util';
|
|
32
25
|
|
|
33
|
-
import {
|
|
26
|
+
import { type AiAssistantError } from '../errors';
|
|
34
27
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
* It makes requests to the model, its a state machine.
|
|
39
|
-
* It keeps track of the current goal.
|
|
40
|
-
* It manages the context window.
|
|
41
|
-
* Tracks the success criteria of reaching the goal, exposing metrics (stretch)
|
|
42
|
-
* Could be run locally in the app or remotely.
|
|
43
|
-
* Could be personal or shared.
|
|
44
|
-
*/
|
|
28
|
+
import { formatSystemPrompt, formatUserPrompt } from './format';
|
|
29
|
+
|
|
30
|
+
export type AiSessionOptions = {};
|
|
45
31
|
|
|
46
32
|
/**
|
|
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.
|
|
33
|
+
* Live observer of the generation process.
|
|
51
34
|
*/
|
|
52
|
-
export
|
|
53
|
-
Map<
|
|
54
|
-
ObjectId,
|
|
55
|
-
{
|
|
56
|
-
version: ObjectVersion;
|
|
57
|
-
diff?: string;
|
|
58
|
-
}
|
|
59
|
-
>
|
|
60
|
-
>;
|
|
61
|
-
|
|
62
|
-
export type SessionRunOptions = {
|
|
63
|
-
artifacts: ArtifactDefinition[];
|
|
64
|
-
|
|
35
|
+
export interface GenerationObserver {
|
|
65
36
|
/**
|
|
66
|
-
*
|
|
37
|
+
* Unparsed content block parts from the model.
|
|
67
38
|
*/
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
history: Message[];
|
|
71
|
-
|
|
72
|
-
prompt: string;
|
|
73
|
-
|
|
74
|
-
generationOptions?: Pick<GenerateRequest, 'model'>;
|
|
75
|
-
|
|
76
|
-
extensions?: ToolContextExtensions;
|
|
77
|
-
|
|
78
|
-
systemPrompt?: string;
|
|
39
|
+
onPart: (part: AiResponse.Part) => Effect.Effect<void>;
|
|
79
40
|
|
|
80
41
|
/**
|
|
81
|
-
*
|
|
42
|
+
* Parsed content blocks from the model.
|
|
43
|
+
* NOTE: Use block.pending to determine if the block was completed.
|
|
44
|
+
* For each block this will be called 0..n times with a pending block and then once with the final state of the block.
|
|
45
|
+
*
|
|
46
|
+
* Example:
|
|
47
|
+
* 1. { pending: true, text: "Hello"}
|
|
48
|
+
* 2. { pending: true, text: "Hello, I am a"}
|
|
49
|
+
* 3. { pending: false, text: "Hello, I am a helpful assistant!"}
|
|
82
50
|
*/
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
client: AiServiceClient;
|
|
86
|
-
toolResolver: ToolResolver;
|
|
51
|
+
onBlock: (block: ContentBlock.Any) => Effect.Effect<void>;
|
|
87
52
|
|
|
88
53
|
/**
|
|
89
|
-
*
|
|
54
|
+
* Complete messages fired during the session, both from the model and from the user.
|
|
55
|
+
* This message will contain all message blocks emitted through the `onBlock` callback.
|
|
90
56
|
*/
|
|
91
|
-
|
|
57
|
+
onMessage: (message: DataType.Message) => Effect.Effect<void>;
|
|
58
|
+
}
|
|
92
59
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
60
|
+
export const GenerationObserver = Object.freeze({
|
|
61
|
+
make: ({
|
|
62
|
+
onPart = Function.constant(Effect.void),
|
|
63
|
+
onBlock = Function.constant(Effect.void),
|
|
64
|
+
onMessage = Function.constant(Effect.void),
|
|
65
|
+
}: Partial<GenerationObserver> = {}): GenerationObserver => ({
|
|
66
|
+
onPart,
|
|
67
|
+
onBlock,
|
|
68
|
+
onMessage,
|
|
69
|
+
}),
|
|
98
70
|
|
|
99
|
-
|
|
71
|
+
noop: () => GenerationObserver.make(),
|
|
100
72
|
|
|
101
|
-
export type AiSessionOptions = {
|
|
102
73
|
/**
|
|
103
|
-
*
|
|
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.
|
|
74
|
+
* Debug printer to be used in unit-tests and browser devtools.
|
|
108
75
|
*/
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
76
|
+
fromPrinter: (printer: ConsolePrinter) =>
|
|
77
|
+
GenerationObserver.make({
|
|
78
|
+
onBlock: (block) =>
|
|
79
|
+
Effect.sync(() => {
|
|
80
|
+
if (block.pending) {
|
|
81
|
+
return; // Only prints full blocks (better for unit-tests and browser devtools).
|
|
82
|
+
}
|
|
83
|
+
printer.printContentBlock(block);
|
|
84
|
+
}),
|
|
85
|
+
onMessage: (message) =>
|
|
86
|
+
Effect.sync(() => {
|
|
87
|
+
if (message.sender.role === 'assistant') {
|
|
88
|
+
return; // Skip assistant messages since they are printed in the `onBlock` callback.
|
|
89
|
+
}
|
|
90
|
+
printer.printMessage(message);
|
|
91
|
+
}),
|
|
92
|
+
}),
|
|
93
|
+
});
|
|
121
94
|
|
|
122
|
-
|
|
123
|
-
|
|
95
|
+
export type SessionRunParams<Tools extends AiTool.Any> = {
|
|
96
|
+
prompt: string;
|
|
97
|
+
system?: string;
|
|
98
|
+
history?: DataType.Message[];
|
|
99
|
+
objects?: Obj.Any[]; // TODO(burdon): Meta only (typename and id -- write to binder).
|
|
100
|
+
blueprints?: Blueprint.Blueprint[];
|
|
101
|
+
toolkit?: AiToolkit.AiToolkit<Tools>;
|
|
102
|
+
observer?: GenerationObserver;
|
|
103
|
+
};
|
|
124
104
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
105
|
+
/**
|
|
106
|
+
* Contains message history, tools, current context.
|
|
107
|
+
* Current context means the state of the app, time of day, and other contextual information.
|
|
108
|
+
* It makes requests to the model, its a state machine.
|
|
109
|
+
* It keeps track of the current goal.
|
|
110
|
+
* It manages the context window.
|
|
111
|
+
* Tracks the success criteria of reaching the goal, exposing metrics (stretch).
|
|
112
|
+
* Could be run locally in the app or remotely.
|
|
113
|
+
* Could be personal or shared.
|
|
114
|
+
*/
|
|
115
|
+
export class AiSession {
|
|
116
|
+
/** Complete messages fired during the session, both from the model and from the user. */
|
|
117
|
+
public readonly messageQueue = Effect.runSync(Queue.unbounded<DataType.Message>());
|
|
129
118
|
|
|
130
|
-
|
|
131
|
-
* Complete block added to Message.
|
|
132
|
-
*/
|
|
133
|
-
public readonly block = this._parser.block;
|
|
119
|
+
// TODO(dmaretskyi): Remove the queues and convert everything to observer.
|
|
134
120
|
|
|
135
121
|
/**
|
|
136
|
-
*
|
|
122
|
+
* Blocks streaming from the model during the session.
|
|
123
|
+
* @deprecated Use `observer.onBlock` instead.
|
|
137
124
|
*/
|
|
138
|
-
public readonly
|
|
125
|
+
public readonly blockQueue = Effect.runSync(Queue.unbounded<Option.Option<ContentBlock.Any>>());
|
|
139
126
|
|
|
140
|
-
/**
|
|
141
|
-
|
|
142
|
-
*/
|
|
143
|
-
public readonly streamEvent = this._parser.streamEvent;
|
|
127
|
+
/** Unparsed events from the underlying generation stream. */
|
|
128
|
+
public readonly eventQueue = Effect.runSync(Queue.unbounded<AiResponse.Part>());
|
|
144
129
|
|
|
145
|
-
/**
|
|
146
|
-
|
|
147
|
-
*/
|
|
148
|
-
public readonly userMessage = new Event<Message>();
|
|
130
|
+
/** Prevents concurrent execution of session. */
|
|
131
|
+
private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
|
|
149
132
|
|
|
150
|
-
/**
|
|
151
|
-
|
|
152
|
-
* Triggered by the model.
|
|
153
|
-
*/
|
|
154
|
-
public readonly statusReport = new Event<AgentStatus>();
|
|
133
|
+
/** Pending messages (incl. the current user request). */
|
|
134
|
+
private _pending: DataType.Message[] = [];
|
|
155
135
|
|
|
156
|
-
/**
|
|
157
|
-
|
|
158
|
-
*/
|
|
159
|
-
public readonly done = new Event<void>();
|
|
136
|
+
/** Prior history from queue. */
|
|
137
|
+
private _history: DataType.Message[] = [];
|
|
160
138
|
|
|
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
|
-
}
|
|
139
|
+
constructor(private readonly _options: AiSessionOptions = {}) {}
|
|
178
140
|
|
|
179
141
|
/**
|
|
180
142
|
* Runs the AI model loop interacting with tools and artifacts.
|
|
181
|
-
* @param options - The session options.
|
|
182
143
|
* @returns The messages generated by the session, including the user's prompt.
|
|
183
144
|
*/
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
let error: Error | undefined;
|
|
214
|
-
|
|
215
|
-
const requiredArtifactIds = new Set<string>(options.requiredArtifactIds ?? []);
|
|
216
|
-
try {
|
|
217
|
-
let more = false;
|
|
145
|
+
// TODO(dmaretskyi): Toolkit context doesn't get added to the effect type.
|
|
146
|
+
run = <Tools extends AiTool.Any>(
|
|
147
|
+
params: SessionRunParams<Tools>,
|
|
148
|
+
): Effect.Effect<
|
|
149
|
+
DataType.Message[],
|
|
150
|
+
AiAssistantError | AiInputPreprocessingError | AiToolNotFoundError | AiError.AiError,
|
|
151
|
+
AiLanguageModel.AiLanguageModel | ToolResolverService | ToolExecutionService | AiTool.ToHandler<Tools>
|
|
152
|
+
> =>
|
|
153
|
+
Effect.gen(this, function* () {
|
|
154
|
+
const observer = params.observer ?? GenerationObserver.noop();
|
|
155
|
+
|
|
156
|
+
// Create toolkit.
|
|
157
|
+
const toolkit: AiToolkit.ToHandler<Tools> = yield* createToolkit(params);
|
|
158
|
+
|
|
159
|
+
// Generate system prompt.
|
|
160
|
+
// TODO(budon): Dynamically resolve template variables.
|
|
161
|
+
const system = yield* formatSystemPrompt(params);
|
|
162
|
+
console.log(system);
|
|
163
|
+
|
|
164
|
+
// Generate user prompt.
|
|
165
|
+
const promptMessages = yield* formatUserPrompt(params);
|
|
166
|
+
yield* this.messageQueue.offer(promptMessages);
|
|
167
|
+
yield* observer.onMessage(promptMessages);
|
|
168
|
+
|
|
169
|
+
this._history = [...(params.history ?? [])];
|
|
170
|
+
this._pending = [promptMessages];
|
|
171
|
+
|
|
172
|
+
// Potential tool-use loop.
|
|
218
173
|
do {
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
...(await Promise.all(options.tools.map((toolId) => options.toolResolver.resolve(toolId)))),
|
|
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),
|
|
229
|
-
);
|
|
230
|
-
|
|
231
|
-
log('request', {
|
|
174
|
+
log.info('request', {
|
|
175
|
+
prompt: promptMessages,
|
|
176
|
+
system: { snippet: [system.slice(0, 32), '...', system.slice(-32)].join(''), length: system.length },
|
|
232
177
|
pending: this._pending.length,
|
|
233
178
|
history: this._history.length,
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
// Open request stream.
|
|
238
|
-
this._stream = await options.client.execStream({
|
|
239
|
-
...(options.generationOptions ?? {}),
|
|
240
|
-
// TODO(burdon): Rename messages or separate history/message.
|
|
241
|
-
history: [...this._history, ...this._pending],
|
|
242
|
-
tools,
|
|
243
|
-
systemPrompt:
|
|
244
|
-
options.systemPrompt ??
|
|
245
|
-
createBaseInstructions({
|
|
246
|
-
availableArtifacts: [...requiredArtifactIds],
|
|
247
|
-
operationModel: this._options.operationModel,
|
|
248
|
-
}),
|
|
179
|
+
objects: params.objects?.length ?? 0,
|
|
180
|
+
blueprints: params.blueprints?.length ?? 0,
|
|
181
|
+
toolkit: Object.values(toolkit.tools).map((tool: AiTool.Any) => tool.name),
|
|
249
182
|
});
|
|
250
183
|
|
|
251
|
-
//
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
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
|
-
}
|
|
280
|
-
}
|
|
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
|
-
|
|
294
|
-
if (error) {
|
|
295
|
-
throw error;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
return this._pending;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
async runStructured<S extends Schema.Schema.AnyNoContext>(
|
|
302
|
-
schema: S,
|
|
303
|
-
options: SessionRunOptions,
|
|
304
|
-
): Promise<Schema.Schema.Type<S>> {
|
|
305
|
-
const parser = structuredOutputParser(schema);
|
|
306
|
-
const result = await this.run({
|
|
307
|
-
...options,
|
|
308
|
-
executableTools: [...(options.executableTools ?? []), parser.tool],
|
|
309
|
-
});
|
|
310
|
-
return parser.getResult(result);
|
|
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
|
-
});
|
|
349
|
-
}
|
|
184
|
+
// Generate the prompt and make request.
|
|
185
|
+
const prompt = yield* AiPreprocessor.preprocessAiInput([...this._history, ...this._pending]);
|
|
186
|
+
const blocks = yield* AiLanguageModel.streamText({
|
|
187
|
+
prompt,
|
|
188
|
+
system,
|
|
189
|
+
toolkit,
|
|
190
|
+
// TODO(burdon): Despite this flag, the model still calls tools.
|
|
191
|
+
// Flag is only used in generateText (not streamText); patch and submit bug.
|
|
192
|
+
// https://github.com/Effect-TS/effect/blob/main/packages/ai/ai/src/AiLanguageModel.ts#L401
|
|
193
|
+
disableToolCallResolution: true,
|
|
194
|
+
}).pipe(
|
|
195
|
+
AiParser.parseResponse({
|
|
196
|
+
onBlock: (block) =>
|
|
197
|
+
Effect.all([this.blockQueue.offer(Option.some(block)), observer.onBlock(block)], { discard: true }),
|
|
198
|
+
onPart: (part) => Effect.all([this.eventQueue.offer(part), observer.onPart(part)], { discard: true }),
|
|
199
|
+
}),
|
|
200
|
+
Stream.runCollect,
|
|
201
|
+
Effect.map(Chunk.toArray),
|
|
202
|
+
);
|
|
350
203
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
})),
|
|
204
|
+
// Signal to stream consumers that message blocks are complete.
|
|
205
|
+
// Allows for coordination between the block and message queues
|
|
206
|
+
// to prevent the streaming blocks from being rendered twice when the message is produced.
|
|
207
|
+
// TODO(wittjosiah): The block queue should probably be drained at this point in the case that there is no consumer.
|
|
208
|
+
yield* this.blockQueue.offer(Option.none());
|
|
209
|
+
|
|
210
|
+
// Create response message.
|
|
211
|
+
const response = Obj.make(DataType.Message, {
|
|
212
|
+
created: new Date().toISOString(),
|
|
213
|
+
sender: { role: 'assistant' },
|
|
214
|
+
blocks,
|
|
363
215
|
});
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
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
|
-
);
|
|
216
|
+
this._pending.push(response);
|
|
217
|
+
yield* this.messageQueue.offer(response);
|
|
218
|
+
yield* observer.onMessage(response);
|
|
219
|
+
|
|
220
|
+
// Parse response for tool calls.
|
|
221
|
+
const toolCalls = getToolCalls(response);
|
|
222
|
+
if (toolCalls.length === 0) {
|
|
223
|
+
break;
|
|
390
224
|
}
|
|
391
225
|
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
private _createPlanningTool(options: SessionRunOptions): ExecutableTool {
|
|
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(', ')}`);
|
|
430
|
-
}
|
|
226
|
+
// TODO(burdon): Report errors to user; with proposed actions.
|
|
227
|
+
const toolResults = yield* callTools(toolkit, toolCalls);
|
|
228
|
+
const toolResultsMessage = Obj.make(DataType.Message, {
|
|
229
|
+
created: new Date().toISOString(),
|
|
230
|
+
sender: { role: 'user' },
|
|
231
|
+
blocks: toolResults,
|
|
232
|
+
});
|
|
431
233
|
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
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);
|
|
478
|
-
}
|
|
234
|
+
this._pending.push(toolResultsMessage);
|
|
235
|
+
yield* this.messageQueue.offer(toolResultsMessage);
|
|
236
|
+
yield* observer.onMessage(toolResultsMessage);
|
|
237
|
+
} while (true);
|
|
479
238
|
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
239
|
+
// Signals to stream consumers that the session has completed and no more messages are coming.
|
|
240
|
+
yield* Queue.shutdown(this.messageQueue);
|
|
241
|
+
yield* Queue.shutdown(this.blockQueue);
|
|
242
|
+
yield* Queue.shutdown(this.eventQueue);
|
|
484
243
|
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
244
|
+
log('done', { pending: this._pending.length });
|
|
245
|
+
return this._pending;
|
|
246
|
+
}).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));
|
|
488
247
|
|
|
489
|
-
|
|
490
|
-
|
|
248
|
+
// TODO(burdon): Implement.
|
|
249
|
+
async runStructured<S extends Schema.Schema.AnyNoContext>(
|
|
250
|
+
_schema: S,
|
|
251
|
+
_options: SessionRunParams<AiTool.Any>,
|
|
252
|
+
): Promise<Schema.Schema.Type<S>> {
|
|
253
|
+
return todo();
|
|
254
|
+
// const parser = structuredOutputParser(schema);
|
|
255
|
+
// const result = await this.run({
|
|
256
|
+
// ...options,
|
|
257
|
+
// executableTools: [...(options.executableTools ?? []), parser.tool],
|
|
258
|
+
// });
|
|
259
|
+
// return parser.getResult(result);
|
|
491
260
|
}
|
|
492
261
|
}
|
|
493
262
|
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
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> => {
|
|
553
|
-
const artifactIds = new Map<ObjectId, ObjectVersion>();
|
|
554
|
-
for (const message of messages) {
|
|
555
|
-
for (const block of message.content) {
|
|
556
|
-
if (block.type === 'json' && block.disposition === VersionPin.DISPOSITION) {
|
|
557
|
-
const pin = VersionPin.pipe(Schema.decodeOption)(JSON.parse(block.json)).pipe(Option.getOrUndefined);
|
|
558
|
-
if (!pin) {
|
|
559
|
-
continue;
|
|
560
|
-
}
|
|
561
|
-
artifactIds.set(pin.objectId, pin.version);
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
return artifactIds;
|
|
567
|
-
};
|
|
568
|
-
|
|
569
|
-
const createArtifactUpdateBlock = (
|
|
570
|
-
artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,
|
|
571
|
-
): MessageContentBlock => {
|
|
572
|
-
return {
|
|
573
|
-
type: 'text',
|
|
574
|
-
disposition: 'artifact-update',
|
|
575
|
-
text: `
|
|
576
|
-
The following artifacts have been updated since the last message:
|
|
577
|
-
${[...artifactDiff.entries()]
|
|
578
|
-
.map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `\n${diff}` : ''}</changed-artifact>`)
|
|
579
|
-
.join('\n')}
|
|
580
|
-
`,
|
|
581
|
-
};
|
|
582
|
-
};
|
|
263
|
+
/**
|
|
264
|
+
* Build a combined toolkit from the blueprint tools and the provided toolkit.
|
|
265
|
+
*/
|
|
266
|
+
const createToolkit = <Tools extends AiTool.Any>({
|
|
267
|
+
toolkit,
|
|
268
|
+
blueprints = [],
|
|
269
|
+
}: Pick<SessionRunParams<Tools>, 'toolkit' | 'blueprints'>) =>
|
|
270
|
+
Effect.gen(function* () {
|
|
271
|
+
const blueprintToolkit = yield* ToolResolverService.resolveToolkit(blueprints.flatMap(({ tools }) => tools));
|
|
272
|
+
const blueprintToolkitHandler: Context.Context<AiTool.ToHandler<AiTool.Any>> = yield* blueprintToolkit.toContext(
|
|
273
|
+
ToolExecutionService.handlersFor(blueprintToolkit),
|
|
274
|
+
);
|
|
275
|
+
|
|
276
|
+
return yield* AiToolkit.merge(...[toolkit, blueprintToolkit].filter(isNotFalsy)).pipe(
|
|
277
|
+
Effect.provide(blueprintToolkitHandler),
|
|
278
|
+
) as Effect.Effect<AiToolkit.ToHandler<any>, never, AiTool.ToHandler<Tools>>;
|
|
279
|
+
});
|