@dxos/assistant 0.8.4-main.84f28bd → 0.8.4-main.ae835ea
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-4VIJTKPM.mjs +354 -0
- package/dist/lib/browser/chunk-4VIJTKPM.mjs.map +7 -0
- package/dist/lib/browser/chunk-UB26N5UF.mjs +89 -0
- package/dist/lib/browser/chunk-UB26N5UF.mjs.map +7 -0
- package/dist/lib/browser/extraction/index.mjs +272 -0
- package/dist/lib/browser/extraction/index.mjs.map +7 -0
- package/dist/lib/browser/index.mjs +754 -1873
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs +13 -0
- package/dist/lib/browser/named-entity-recognition-QPYHML66.mjs.map +7 -0
- package/dist/lib/node-esm/chunk-AUUC7II4.mjs +356 -0
- package/dist/lib/node-esm/chunk-AUUC7II4.mjs.map +7 -0
- package/dist/lib/node-esm/chunk-BCFXTNSK.mjs +91 -0
- package/dist/lib/node-esm/chunk-BCFXTNSK.mjs.map +7 -0
- package/dist/lib/node-esm/extraction/index.mjs +273 -0
- package/dist/lib/node-esm/extraction/index.mjs.map +7 -0
- package/dist/lib/node-esm/index.mjs +754 -1874
- 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-2HDF46YX.mjs +14 -0
- package/dist/lib/node-esm/named-entity-recognition-2HDF46YX.mjs.map +7 -0
- package/dist/types/src/conversation/context.d.ts +103 -0
- package/dist/types/src/conversation/context.d.ts.map +1 -0
- package/dist/types/src/conversation/conversation.d.ts +29 -32
- 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/diff.d.ts +15 -0
- package/dist/types/src/diff.d.ts.map +1 -0
- package/dist/types/src/diff.test.d.ts +2 -0
- package/dist/types/src/diff.test.d.ts.map +1 -0
- package/dist/types/src/errors.d.ts +75 -0
- package/dist/types/src/errors.d.ts.map +1 -0
- package/dist/types/src/execution-graph.d.ts +82 -0
- package/dist/types/src/execution-graph.d.ts.map +1 -0
- package/dist/types/src/execution-graph.test.d.ts +2 -0
- package/dist/types/src/execution-graph.test.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
- 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 +210 -73
- 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 +264 -166
- package/dist/types/src/extraction/extraction.d.ts.map +1 -1
- package/dist/types/src/extraction/quotes.d.ts +1 -1
- package/dist/types/src/extraction/quotes.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 +19 -0
- package/dist/types/src/functions/services.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +5 -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/error-handling.d.ts +4 -0
- package/dist/types/src/session/error-handling.d.ts.map +1 -0
- package/dist/types/src/session/format.d.ts +186 -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 +3 -0
- package/dist/types/src/session/index.d.ts.map +1 -1
- package/dist/types/src/session/observer.d.ts +22 -0
- package/dist/types/src/session/observer.d.ts.map +1 -0
- package/dist/types/src/session/session.d.ts +36 -268
- package/dist/types/src/session/session.d.ts.map +1 -1
- package/dist/types/src/session/toolkit.d.ts +15 -0
- package/dist/types/src/session/toolkit.d.ts.map +1 -0
- package/dist/types/src/session/version-pin.d.ts +5 -5
- 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 +18 -0
- package/dist/types/src/templates/system.d.ts.map +1 -0
- package/dist/types/src/types/artifact.d.ts +16 -0
- package/dist/types/src/types/artifact.d.ts.map +1 -0
- package/dist/types/src/types/index.d.ts +2 -0
- package/dist/types/src/types/index.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +46 -26
- package/src/conversation/context.ts +186 -0
- package/src/conversation/conversation.ts +101 -76
- package/src/conversation/index.ts +1 -0
- package/src/diff.test.ts +43 -0
- package/src/diff.ts +84 -0
- package/src/errors.ts +15 -0
- package/src/execution-graph.test.ts +738 -0
- package/src/execution-graph.ts +500 -0
- package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +13 -24
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +28 -22
- package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +9 -9
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +18 -8
- package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +4 -3
- package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
- package/src/extraction/extraction.ts +2 -2
- package/src/extraction/quotes.test.ts +3 -3
- package/src/extraction/quotes.ts +4 -4
- package/src/functions/index.ts +5 -0
- package/src/functions/services.ts +158 -0
- package/src/index.ts +5 -5
- package/src/session/artifact-diff.ts +41 -0
- package/src/session/error-handling.ts +41 -0
- package/src/session/format.test.ts +60 -0
- package/src/session/format.ts +142 -0
- package/src/session/index.ts +3 -0
- package/src/session/observer.ts +59 -0
- package/src/session/session.conversations.json +1 -0
- package/src/session/session.test.ts +88 -214
- package/src/session/session.ts +170 -539
- package/src/session/toolkit.ts +48 -0
- package/src/session/version-pin.ts +10 -10
- package/src/summarization/summarization.test.ts +87 -106
- package/src/templates/format.tpl +60 -0
- package/src/templates/index.ts +5 -0
- package/src/templates/system.tpl +48 -0
- package/src/templates/system.ts +41 -0
- package/src/types/artifact.ts +52 -0
- package/src/types/index.ts +5 -0
- 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/session/version-pin.test.d.ts +0 -2
- package/dist/types/src/session/version-pin.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/dist/types/src/types.d.ts +0 -3
- package/dist/types/src/types.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/binder.ts +0 -101
- 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/session/version-pin.test.ts +0 -26
- 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/types.ts +0 -8
package/src/session/session.ts
CHANGED
|
@@ -2,35 +2,57 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import type * as AiError from '@effect/ai/AiError';
|
|
6
|
+
import * as LanguageModel from '@effect/ai/LanguageModel';
|
|
7
|
+
import type * as Tool from '@effect/ai/Tool';
|
|
8
|
+
import type * as Toolkit from '@effect/ai/Toolkit';
|
|
9
|
+
import * as Chunk from 'effect/Chunk';
|
|
10
|
+
import * as Effect from 'effect/Effect';
|
|
11
|
+
import type * as Schema from 'effect/Schema';
|
|
12
|
+
import * as Stream from 'effect/Stream';
|
|
6
13
|
|
|
7
14
|
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
type
|
|
12
|
-
|
|
13
|
-
type
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
Message,
|
|
17
|
-
type MessageContentBlock,
|
|
18
|
-
MixedStreamParser,
|
|
19
|
-
ToolResult,
|
|
20
|
-
createTool,
|
|
21
|
-
type ExecutableTool,
|
|
22
|
-
type ToolId,
|
|
23
|
-
type ToolResolver,
|
|
15
|
+
AiParser,
|
|
16
|
+
AiPreprocessor,
|
|
17
|
+
type AiToolNotFoundError,
|
|
18
|
+
type PromptPreprocessingError,
|
|
19
|
+
type ToolExecutionService,
|
|
20
|
+
type ToolResolverService,
|
|
21
|
+
callTool,
|
|
22
|
+
getToolCalls,
|
|
24
23
|
} from '@dxos/ai';
|
|
25
|
-
import { type
|
|
26
|
-
import {
|
|
24
|
+
import { type Blueprint } from '@dxos/blueprints';
|
|
25
|
+
import { todo } from '@dxos/debug';
|
|
27
26
|
import { Obj } from '@dxos/echo';
|
|
28
|
-
import {
|
|
29
|
-
import { create, type ObjectId } from '@dxos/echo-schema';
|
|
30
|
-
import { invariant } from '@dxos/invariant';
|
|
27
|
+
import { TracingService } from '@dxos/functions';
|
|
31
28
|
import { log } from '@dxos/log';
|
|
29
|
+
import { DataType } from '@dxos/schema';
|
|
32
30
|
|
|
33
|
-
import {
|
|
31
|
+
import { type AiAssistantError } from '../errors';
|
|
32
|
+
|
|
33
|
+
import { formatSystemPrompt, formatUserPrompt } from './format';
|
|
34
|
+
import { GenerationObserver } from './observer';
|
|
35
|
+
|
|
36
|
+
export type AiSessionRunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;
|
|
37
|
+
|
|
38
|
+
export type AiSessionRunRequirements =
|
|
39
|
+
| LanguageModel.LanguageModel
|
|
40
|
+
| ToolExecutionService
|
|
41
|
+
| ToolResolverService
|
|
42
|
+
| TracingService;
|
|
43
|
+
|
|
44
|
+
export type AiSessionRunParams<Tools extends Record<string, Tool.Any>> = {
|
|
45
|
+
prompt: string;
|
|
46
|
+
// TODO(wittjosiah): Rename to systemPrompt.
|
|
47
|
+
system?: string;
|
|
48
|
+
history?: DataType.Message[];
|
|
49
|
+
objects?: Obj.Any[];
|
|
50
|
+
blueprints?: Blueprint.Blueprint[];
|
|
51
|
+
toolkit?: Toolkit.WithHandler<Tools>;
|
|
52
|
+
observer?: GenerationObserver;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export type AiSessionOptions = {};
|
|
34
56
|
|
|
35
57
|
/**
|
|
36
58
|
* Contains message history, tools, current context.
|
|
@@ -38,545 +60,154 @@ import { VersionPin } from './version-pin';
|
|
|
38
60
|
* It makes requests to the model, its a state machine.
|
|
39
61
|
* It keeps track of the current goal.
|
|
40
62
|
* It manages the context window.
|
|
41
|
-
* Tracks the success criteria of reaching the goal, exposing metrics (stretch)
|
|
63
|
+
* Tracks the success criteria of reaching the goal, exposing metrics (stretch).
|
|
42
64
|
* Could be run locally in the app or remotely.
|
|
43
65
|
* Could be personal or shared.
|
|
44
66
|
*/
|
|
67
|
+
export class AiSession {
|
|
68
|
+
/** Prevents concurrent execution of session. */
|
|
69
|
+
private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
|
|
70
|
+
|
|
71
|
+
/** Message history from queue. */
|
|
72
|
+
// TODO(burdon): Evolve into supporting a git-like graph of messages.
|
|
73
|
+
private _history: DataType.Message[] = [];
|
|
74
|
+
|
|
75
|
+
/** Pending messages for this session (incl. the current prompt). */
|
|
76
|
+
private _pending: DataType.Message[] = [];
|
|
77
|
+
|
|
78
|
+
constructor(private readonly _options: AiSessionOptions = {}) {}
|
|
79
|
+
|
|
80
|
+
run = <Tools extends Record<string, Tool.Any>>({
|
|
81
|
+
prompt,
|
|
82
|
+
system: systemTemplate,
|
|
83
|
+
history = [],
|
|
84
|
+
objects = [],
|
|
85
|
+
blueprints = [],
|
|
86
|
+
toolkit,
|
|
87
|
+
observer = GenerationObserver.noop(),
|
|
88
|
+
}: AiSessionRunParams<Tools>): Effect.Effect<DataType.Message[], AiSessionRunError, AiSessionRunRequirements> =>
|
|
89
|
+
Effect.gen(this, function* () {
|
|
90
|
+
this._history = [...history];
|
|
91
|
+
this._pending = [];
|
|
92
|
+
const pending = this._pending;
|
|
93
|
+
|
|
94
|
+
const submitMessage = Effect.fnUntraced(function* (message: DataType.Message) {
|
|
95
|
+
pending.push(message);
|
|
96
|
+
yield* observer.onMessage(message);
|
|
97
|
+
yield* TracingService.emitConverationMessage(message);
|
|
98
|
+
return message;
|
|
99
|
+
});
|
|
45
100
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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();
|
|
115
|
-
|
|
116
|
-
/** Pending messages (incl. the current user request). */
|
|
117
|
-
private _pending: Message[] = [];
|
|
118
|
-
|
|
119
|
-
/** Current streaming response. */
|
|
120
|
-
private _stream: GenerationStream | undefined;
|
|
121
|
-
|
|
122
|
-
/** Prior history from queue. */
|
|
123
|
-
private _history: Message[] = [];
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* New message.
|
|
127
|
-
*/
|
|
128
|
-
public readonly message = this._parser.message;
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
* Complete block added to Message.
|
|
132
|
-
*/
|
|
133
|
-
public readonly block = this._parser.block;
|
|
134
|
-
|
|
135
|
-
/**
|
|
136
|
-
* Update partial block (while streaming).
|
|
137
|
-
*/
|
|
138
|
-
public readonly update = this._parser.update;
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* Unparsed events from the underlying generation stream.
|
|
142
|
-
*/
|
|
143
|
-
public readonly streamEvent = this._parser.streamEvent;
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* User prompt or tool result.
|
|
147
|
-
*/
|
|
148
|
-
public readonly userMessage = new Event<Message>();
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* Agent self-reporting its status.
|
|
152
|
-
* Triggered by the model.
|
|
153
|
-
*/
|
|
154
|
-
public readonly statusReport = new Event<AgentStatus>();
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Emits when the session is done.
|
|
158
|
-
*/
|
|
159
|
-
public readonly done = new Event<void>();
|
|
160
|
-
|
|
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
|
-
}
|
|
178
|
-
|
|
179
|
-
/**
|
|
180
|
-
* Runs the AI model loop interacting with tools and artifacts.
|
|
181
|
-
* @param options - The session options.
|
|
182
|
-
* @returns The messages generated by the session, including the user's prompt.
|
|
183
|
-
*/
|
|
184
|
-
@synchronized
|
|
185
|
-
async run(options: SessionRunOptions): Promise<Message[]> {
|
|
186
|
-
const systemTools: ExecutableTool[] = [];
|
|
187
|
-
switch (this._options.operationModel) {
|
|
188
|
-
case 'planning':
|
|
189
|
-
systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createPlanningTool(options));
|
|
190
|
-
break;
|
|
191
|
-
case 'importing':
|
|
192
|
-
systemTools.push(
|
|
193
|
-
this._createQueryArtifactsTool(options.artifacts),
|
|
194
|
-
this._createRequireTool(options.artifacts, (artifactDefinitionIds) => {
|
|
195
|
-
for (const artifactDefinitionId of artifactDefinitionIds) {
|
|
196
|
-
requiredArtifactIds.add(artifactDefinitionId);
|
|
197
|
-
}
|
|
198
|
-
}),
|
|
199
|
-
);
|
|
200
|
-
break;
|
|
201
|
-
case 'configured':
|
|
202
|
-
// no system tools
|
|
203
|
-
break;
|
|
204
|
-
default:
|
|
205
|
-
throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
this._history = [...options.history];
|
|
209
|
-
this._pending = [await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)];
|
|
210
|
-
this.userMessage.emit(this._pending.at(-1)!);
|
|
211
|
-
this._stream = undefined;
|
|
101
|
+
// Submit the prompt.
|
|
102
|
+
// TODO(burdon): Remove if cancelled?
|
|
103
|
+
const promptMessage = yield* submitMessage(yield* formatUserPrompt({ prompt, history }));
|
|
212
104
|
|
|
213
|
-
|
|
105
|
+
// Generate system and prompt messages.
|
|
106
|
+
const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects });
|
|
214
107
|
|
|
215
|
-
|
|
216
|
-
try {
|
|
217
|
-
let more = false;
|
|
108
|
+
// Tool call loop.
|
|
218
109
|
do {
|
|
219
|
-
const tools: ExecutableTool[] = pipe(
|
|
220
|
-
[
|
|
221
|
-
...systemTools,
|
|
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
110
|
log('request', {
|
|
111
|
+
prompt: promptMessage,
|
|
112
|
+
system: { snippet: createSnippet(system), length: system.length },
|
|
232
113
|
pending: this._pending.length,
|
|
233
114
|
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
|
-
}),
|
|
115
|
+
objects: objects?.length ?? 0,
|
|
249
116
|
});
|
|
250
117
|
|
|
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
|
-
);
|
|
118
|
+
const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], { system });
|
|
119
|
+
|
|
120
|
+
// Execute the stream request.
|
|
121
|
+
// logDump('prompt', Prompt.Prompt.pipe(Schema.encodeSync)(prompt));
|
|
122
|
+
const blocks = yield* LanguageModel.streamText({
|
|
123
|
+
prompt,
|
|
124
|
+
toolkit,
|
|
125
|
+
disableToolCallResolution: true,
|
|
126
|
+
}).pipe(
|
|
127
|
+
// TOOD(dmaretskyi): Error mapping.
|
|
128
|
+
AiParser.parseResponse({
|
|
129
|
+
onBegin: () => observer.onBegin(),
|
|
130
|
+
onBlock: (block) => observer.onBlock(block),
|
|
131
|
+
onPart: (part) => observer.onPart(part),
|
|
132
|
+
onEnd: (summary) => observer.onEnd(summary),
|
|
133
|
+
}),
|
|
134
|
+
Stream.runCollect,
|
|
135
|
+
Effect.map(Chunk.toArray),
|
|
136
|
+
);
|
|
326
137
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
138
|
+
// Create the response message.
|
|
139
|
+
const response = yield* submitMessage(
|
|
140
|
+
Obj.make(DataType.Message, {
|
|
141
|
+
created: new Date().toISOString(),
|
|
142
|
+
sender: { role: 'assistant' },
|
|
143
|
+
blocks,
|
|
144
|
+
}),
|
|
145
|
+
);
|
|
331
146
|
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
147
|
+
// Parse the response for tool calls.
|
|
148
|
+
const toolCalls = getToolCalls(response);
|
|
149
|
+
if (toolCalls.length === 0) {
|
|
150
|
+
break;
|
|
151
|
+
} else if (!toolkit) {
|
|
152
|
+
throw new Error('No toolkit provided'); // TODO(burdon): Throw user error?
|
|
336
153
|
}
|
|
337
154
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
private _createQueryArtifactsTool(artifacts: ArtifactDefinition[]): ExecutableTool {
|
|
352
|
-
return createTool('system', {
|
|
353
|
-
name: 'query_artifact_definitions',
|
|
354
|
-
description: 'Query the available artifact definitions',
|
|
355
|
-
schema: Schema.Struct({}),
|
|
356
|
-
execute: async () => {
|
|
357
|
-
return ToolResult.Success({
|
|
358
|
-
artifactDefinitions: artifacts.map((artifact) => ({
|
|
359
|
-
id: artifact.id,
|
|
360
|
-
name: artifact.name,
|
|
361
|
-
description: artifact.description,
|
|
362
|
-
})),
|
|
363
|
-
});
|
|
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(', ')}`,
|
|
155
|
+
// Execute the tool calls.
|
|
156
|
+
// TODO(burdon): Retry errors? Write result when each completes individually?
|
|
157
|
+
const toolResults = yield* Effect.forEach(toolCalls, (toolCall) => {
|
|
158
|
+
return callTool(toolkit, toolCall).pipe(
|
|
159
|
+
Effect.provide(
|
|
160
|
+
TracingService.layerSubframe((context) => ({
|
|
161
|
+
...context,
|
|
162
|
+
parentMessage: response.id,
|
|
163
|
+
toolCallId: toolCall.toolCallId,
|
|
164
|
+
})),
|
|
165
|
+
),
|
|
389
166
|
);
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
onRequire(artifactDefinitionIds);
|
|
393
|
-
|
|
394
|
-
return ToolResult.Success({});
|
|
395
|
-
},
|
|
396
|
-
});
|
|
397
|
-
}
|
|
167
|
+
});
|
|
398
168
|
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
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
|
-
}),
|
|
169
|
+
// Add to queue and continue loop.
|
|
170
|
+
// TODO(wittjosiah): Sometimes tool error results are added to the queue before the tool agent statuses.
|
|
171
|
+
// This results in a broken execution graph.
|
|
172
|
+
yield* submitMessage(
|
|
173
|
+
Obj.make(DataType.Message, {
|
|
174
|
+
created: new Date().toISOString(),
|
|
175
|
+
sender: { role: 'tool' },
|
|
176
|
+
blocks: toolResults,
|
|
421
177
|
}),
|
|
422
|
-
)
|
|
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
|
-
}
|
|
431
|
-
|
|
432
|
-
const stepResults: any[] = [];
|
|
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);
|
|
478
|
-
}
|
|
479
|
-
|
|
480
|
-
return ToolResult.Success({ stepResults });
|
|
481
|
-
},
|
|
482
|
-
});
|
|
483
|
-
}
|
|
178
|
+
);
|
|
179
|
+
} while (true);
|
|
484
180
|
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
181
|
+
log('done', { pending: this._pending.length });
|
|
182
|
+
return this._pending;
|
|
183
|
+
}).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));
|
|
488
184
|
|
|
489
|
-
|
|
490
|
-
|
|
185
|
+
/**
|
|
186
|
+
* @deprecated
|
|
187
|
+
*/
|
|
188
|
+
// TODO(burdon): Implement or remove.
|
|
189
|
+
async runStructured<S extends Schema.Schema.AnyNoContext>(
|
|
190
|
+
_schema: S,
|
|
191
|
+
_options: AiSessionRunParams<any>,
|
|
192
|
+
): Promise<Schema.Schema.Type<S>> {
|
|
193
|
+
return todo();
|
|
194
|
+
// const parser = structuredOutputParser(schema);
|
|
195
|
+
// const result = await this.run({
|
|
196
|
+
// ...options,
|
|
197
|
+
// executableTools: [...(options.executableTools ?? []), parser.tool],
|
|
198
|
+
// });
|
|
199
|
+
// return parser.getResult(result);
|
|
491
200
|
}
|
|
492
201
|
}
|
|
493
202
|
|
|
494
|
-
|
|
495
|
-
|
|
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> => {
|
|
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
|
-
};
|
|
203
|
+
const createSnippet = (text: string, len = 32) =>
|
|
204
|
+
text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');
|
|
568
205
|
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
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
|
-
};
|
|
206
|
+
// TODO(dmaretskyi): Extract as a general util.
|
|
207
|
+
const logDump = (message: string, data: unknown) => {
|
|
208
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
209
|
+
const { writeFileSync } = require('node:fs');
|
|
210
|
+
const path = `/tmp/log-data-${Date.now()}.json`;
|
|
211
|
+
writeFileSync(path, JSON.stringify(data, null, 2));
|
|
212
|
+
log.info(message, { path });
|
|
582
213
|
};
|