@dxos/assistant 0.8.3 → 0.8.4-main.1068cf700f
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/neutral/chunk-J5LGTIGS.mjs +10 -0
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +7 -0
- package/dist/lib/neutral/chunk-ZPC54VRM.mjs +596 -0
- package/dist/lib/neutral/chunk-ZPC54VRM.mjs.map +7 -0
- package/dist/lib/neutral/extraction/index.mjs +225 -0
- package/dist/lib/neutral/extraction/index.mjs.map +7 -0
- package/dist/lib/neutral/index.mjs +929 -0
- package/dist/lib/neutral/index.mjs.map +7 -0
- package/dist/lib/neutral/meta.json +1 -0
- package/dist/lib/neutral/testing/index.mjs +38 -0
- package/dist/lib/neutral/testing/index.mjs.map +7 -0
- package/dist/types/src/conversation/context.d.ts +138 -0
- package/dist/types/src/conversation/context.d.ts.map +1 -0
- package/dist/types/src/conversation/context.test.d.ts +2 -0
- package/dist/types/src/conversation/context.test.d.ts.map +1 -0
- package/dist/types/src/conversation/conversation.d.ts +66 -0
- package/dist/types/src/conversation/conversation.d.ts.map +1 -0
- package/dist/types/src/conversation/conversation.test.d.ts +2 -0
- package/dist/types/src/conversation/conversation.test.d.ts.map +1 -0
- package/dist/types/src/conversation/index.d.ts +3 -0
- package/dist/types/src/conversation/index.d.ts.map +1 -0
- package/dist/types/src/diff.d.ts +17 -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 +67 -0
- package/dist/types/src/errors.d.ts.map +1 -0
- package/dist/types/src/execution-graph.d.ts +85 -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 +279 -140
- 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 +345 -212
- package/dist/types/src/extraction/extraction.d.ts.map +1 -1
- package/dist/types/src/extraction/quotes.d.ts +3 -3
- 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/functions.test.d.ts +2 -0
- package/dist/types/src/functions.test.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +6 -3
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/session/GenericToolkit.d.ts +107 -0
- package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
- 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 +12 -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 +5 -0
- package/dist/types/src/session/index.d.ts.map +1 -1
- package/dist/types/src/session/observer.d.ts +23 -0
- package/dist/types/src/session/observer.d.ts.map +1 -0
- package/dist/types/src/session/session.d.ts +41 -246
- package/dist/types/src/session/session.d.ts.map +1 -1
- package/dist/types/src/session/toolkit.d.ts +14 -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/testing/index.d.ts +1 -2
- package/dist/types/src/testing/index.d.ts.map +1 -1
- package/dist/types/src/testing/layer.d.ts +22 -0
- package/dist/types/src/testing/layer.d.ts.map +1 -0
- package/dist/types/src/types/artifact.d.ts +28 -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 +58 -38
- package/src/conversation/context.test.ts +46 -0
- package/src/conversation/context.ts +330 -0
- package/src/conversation/conversation.test.ts +65 -0
- package/src/conversation/conversation.ts +203 -0
- package/src/conversation/index.ts +6 -0
- package/src/diff.test.ts +74 -0
- package/src/diff.ts +93 -0
- package/src/errors.ts +15 -0
- package/src/execution-graph.test.ts +740 -0
- package/src/execution-graph.ts +509 -0
- package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +14 -25
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +48 -51
- package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +23 -22
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +43 -41
- package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
- package/src/extraction/extraction-ner-function/named-entity-recognition.ts +3 -1
- package/src/extraction/extraction.ts +10 -9
- package/src/extraction/quotes.test.ts +3 -3
- package/src/extraction/quotes.ts +6 -7
- package/src/functions/index.ts +5 -0
- package/src/functions/services.ts +187 -0
- package/src/functions.conversations.json +1 -0
- package/src/functions.test.ts +74 -0
- package/src/index.ts +6 -3
- package/src/session/GenericToolkit.ts +160 -0
- package/src/session/artifact-diff.ts +41 -0
- package/src/session/error-handling.ts +41 -0
- package/src/session/format.test.ts +124 -0
- package/src/session/format.ts +143 -0
- package/src/session/index.ts +6 -0
- package/src/session/observer.ts +61 -0
- package/src/session/session.conversations.json +1 -0
- package/src/session/session.test.ts +106 -173
- package/src/session/session.ts +181 -495
- package/src/session/toolkit.ts +39 -0
- package/src/session/version-pin.ts +12 -12
- package/src/templates/index.ts +5 -0
- package/src/templates/instructions/format.tpl +57 -0
- package/src/templates/instructions/system.tpl +48 -0
- package/src/templates/system.ts +41 -0
- package/src/testing/index.ts +2 -8
- package/src/testing/layer.ts +84 -0
- package/src/types/artifact.ts +89 -0
- package/src/types/index.ts +5 -0
- package/src/typings.d.ts +5 -0
- package/dist/lib/browser/index.mjs +0 -2158
- package/dist/lib/browser/index.mjs.map +0 -7
- package/dist/lib/browser/meta.json +0 -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/lib/node-esm/index.mjs +0 -2160
- package/dist/lib/node-esm/index.mjs.map +0 -7
- package/dist/lib/node-esm/meta.json +0 -1
- package/dist/types/bin/chat.d.ts +0 -2
- package/dist/types/bin/chat.d.ts.map +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/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/summarization/summarization.test.d.ts +0 -2
- package/dist/types/src/summarization/summarization.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/types.d.ts +0 -3
- package/dist/types/src/types.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/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 -89
- package/src/session/version-pin.test.ts +0 -26
- package/src/summarization/summarization.test.ts +0 -221
- 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/typedefs.d.ts +0 -8
- package/src/types.ts +0 -8
- /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
package/src/session/session.ts
CHANGED
|
@@ -2,33 +2,59 @@
|
|
|
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
|
-
|
|
17
|
-
type MessageContentBlock,
|
|
18
|
-
MixedStreamParser,
|
|
19
|
-
ToolResult,
|
|
20
|
-
createTool,
|
|
21
|
-
type ExecutableTool,
|
|
15
|
+
AiParser,
|
|
16
|
+
AiPreprocessor,
|
|
17
|
+
type AiToolNotFoundError,
|
|
18
|
+
type PromptPreprocessingError,
|
|
19
|
+
type ToolExecutionService,
|
|
20
|
+
type ToolResolverService,
|
|
21
|
+
callTool,
|
|
22
|
+
getToolCalls,
|
|
23
|
+
withoutToolCallParising,
|
|
22
24
|
} from '@dxos/ai';
|
|
23
|
-
import { type
|
|
24
|
-
import {
|
|
25
|
+
import { type Blueprint } from '@dxos/blueprints';
|
|
26
|
+
import { todo } from '@dxos/debug';
|
|
25
27
|
import { Obj } from '@dxos/echo';
|
|
26
|
-
import {
|
|
27
|
-
import { create, type ObjectId } from '@dxos/echo-schema';
|
|
28
|
-
import { invariant } from '@dxos/invariant';
|
|
28
|
+
import { type FunctionInvocationService, TracingService } from '@dxos/functions';
|
|
29
29
|
import { log } from '@dxos/log';
|
|
30
|
+
import { Message } from '@dxos/types';
|
|
30
31
|
|
|
31
|
-
import {
|
|
32
|
+
import { type AiAssistantError } from '../errors';
|
|
33
|
+
|
|
34
|
+
import { formatSystemPrompt, formatUserPrompt } from './format';
|
|
35
|
+
import { GenerationObserver } from './observer';
|
|
36
|
+
|
|
37
|
+
export type AiSessionRunError = AiError.AiError | PromptPreprocessingError | AiToolNotFoundError | AiAssistantError;
|
|
38
|
+
|
|
39
|
+
export type AiSessionRunRequirements =
|
|
40
|
+
| LanguageModel.LanguageModel
|
|
41
|
+
| ToolExecutionService
|
|
42
|
+
| ToolResolverService
|
|
43
|
+
| TracingService
|
|
44
|
+
| FunctionInvocationService;
|
|
45
|
+
|
|
46
|
+
export type AiSessionOptions = {};
|
|
47
|
+
|
|
48
|
+
export type AiSessionRunProps<Tools extends Record<string, Tool.Any>> = {
|
|
49
|
+
prompt: string;
|
|
50
|
+
// TODO(wittjosiah): Rename to systemPrompt.
|
|
51
|
+
system?: string;
|
|
52
|
+
history?: Message.Message[];
|
|
53
|
+
objects?: Obj.Unknown[];
|
|
54
|
+
blueprints?: readonly Blueprint.Blueprint[];
|
|
55
|
+
toolkit?: Toolkit.WithHandler<Tools>;
|
|
56
|
+
observer?: GenerationObserver<Tools>;
|
|
57
|
+
};
|
|
32
58
|
|
|
33
59
|
/**
|
|
34
60
|
* Contains message history, tools, current context.
|
|
@@ -36,514 +62,174 @@ import { VersionPin } from './version-pin';
|
|
|
36
62
|
* It makes requests to the model, its a state machine.
|
|
37
63
|
* It keeps track of the current goal.
|
|
38
64
|
* It manages the context window.
|
|
39
|
-
* Tracks the success criteria of reaching the goal, exposing metrics (stretch)
|
|
65
|
+
* Tracks the success criteria of reaching the goal, exposing metrics (stretch).
|
|
40
66
|
* Could be run locally in the app or remotely.
|
|
41
67
|
* Could be personal or shared.
|
|
42
68
|
*/
|
|
69
|
+
export class AiSession {
|
|
70
|
+
/** Prevents concurrent execution of session. */
|
|
71
|
+
private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
|
|
43
72
|
|
|
44
|
-
/**
|
|
45
|
-
|
|
46
|
-
|
|
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'>;
|
|
73
|
+
/** Message history from queue. */
|
|
74
|
+
// TODO(burdon): Evolve into supporting a git-like graph of messages.
|
|
75
|
+
private _history: Message.Message[] = [];
|
|
75
76
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
systemPrompt?: string;
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Pre-require artifacts.
|
|
82
|
-
*/
|
|
83
|
-
requiredArtifactIds?: string[];
|
|
77
|
+
/** Pending messages for this session (incl. the current prompt). */
|
|
78
|
+
private _pending: Message.Message[] = [];
|
|
84
79
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
artifactDiffResolver?: ArtifactDiffResolver;
|
|
89
|
-
};
|
|
80
|
+
private _started = 0;
|
|
81
|
+
private _ended = 0;
|
|
82
|
+
private _toolCalls = 0;
|
|
90
83
|
|
|
91
|
-
|
|
84
|
+
constructor(private readonly _options: AiSessionOptions = {}) {}
|
|
92
85
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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();
|
|
107
|
-
|
|
108
|
-
/** Pending messages (incl. the current user request). */
|
|
109
|
-
private _pending: Message[] = [];
|
|
110
|
-
|
|
111
|
-
/** Current streaming response. */
|
|
112
|
-
private _stream: GenerationStream | undefined;
|
|
113
|
-
|
|
114
|
-
/** Prior history from queue. */
|
|
115
|
-
private _history: Message[] = [];
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* New message.
|
|
119
|
-
*/
|
|
120
|
-
public readonly message = this._parser.message;
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Complete block added to Message.
|
|
124
|
-
*/
|
|
125
|
-
public readonly block = this._parser.block;
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
* Update partial block (while streaming).
|
|
129
|
-
*/
|
|
130
|
-
public readonly update = this._parser.update;
|
|
131
|
-
|
|
132
|
-
public readonly streamEvent = this._parser.streamEvent;
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* User prompt or tool result.
|
|
136
|
-
*/
|
|
137
|
-
public readonly userMessage = new Event<Message>();
|
|
138
|
-
|
|
139
|
-
/**
|
|
140
|
-
* Agent self-reporting its status.
|
|
141
|
-
*/
|
|
142
|
-
public readonly statusReport = new Event<AgentStatus>();
|
|
143
|
-
|
|
144
|
-
public readonly toolStatusReport = new Event<{ message: Message; status: AgentStatus }>();
|
|
86
|
+
get duration(): number {
|
|
87
|
+
return this._ended - this._started;
|
|
88
|
+
}
|
|
145
89
|
|
|
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
|
-
});
|
|
90
|
+
get toolCalls(): number {
|
|
91
|
+
return this._toolCalls;
|
|
156
92
|
}
|
|
157
93
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);
|
|
180
|
-
}
|
|
94
|
+
run = <Tools extends Record<string, Tool.Any>>({
|
|
95
|
+
prompt,
|
|
96
|
+
system: systemTemplate,
|
|
97
|
+
history = [],
|
|
98
|
+
objects = [],
|
|
99
|
+
blueprints = [],
|
|
100
|
+
toolkit,
|
|
101
|
+
observer = GenerationObserver.noop(),
|
|
102
|
+
}: AiSessionRunProps<Tools>): Effect.Effect<Message.Message[], AiSessionRunError, AiSessionRunRequirements> =>
|
|
103
|
+
Effect.gen(this, function* () {
|
|
104
|
+
this._started = Date.now();
|
|
105
|
+
this._history = [...history];
|
|
106
|
+
this._pending = [];
|
|
107
|
+
const pending = this._pending;
|
|
108
|
+
|
|
109
|
+
const submitMessage = Effect.fnUntraced(function* (message: Message.Message) {
|
|
110
|
+
pending.push(message);
|
|
111
|
+
yield* observer.onMessage(message);
|
|
112
|
+
yield* TracingService.emitConverationMessage(message);
|
|
113
|
+
return message;
|
|
114
|
+
});
|
|
181
115
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
this._stream = undefined;
|
|
116
|
+
// Submit the prompt.
|
|
117
|
+
// TODO(burdon): Remove if cancelled?
|
|
118
|
+
const promptMessage = yield* submitMessage(yield* formatUserPrompt({ prompt, history }));
|
|
186
119
|
|
|
187
|
-
|
|
120
|
+
// Generate system and prompt messages.
|
|
121
|
+
const system = yield* formatSystemPrompt({ system: systemTemplate, blueprints, objects }).pipe(Effect.orDie);
|
|
188
122
|
|
|
189
|
-
|
|
190
|
-
try {
|
|
191
|
-
let more = false;
|
|
123
|
+
// Tool call loop.
|
|
192
124
|
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
125
|
log('request', {
|
|
126
|
+
prompt: promptMessage,
|
|
127
|
+
system: { snippet: createSnippet(system), length: system.length },
|
|
202
128
|
pending: this._pending.length,
|
|
203
129
|
history: this._history.length,
|
|
204
|
-
|
|
130
|
+
objects: objects?.length ?? 0,
|
|
205
131
|
});
|
|
206
132
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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
|
-
}),
|
|
133
|
+
const prompt = yield* AiPreprocessor.preprocessPrompt([...this._history, ...this._pending], {
|
|
134
|
+
system,
|
|
135
|
+
cacheControl: 'ephemeral',
|
|
219
136
|
});
|
|
220
137
|
|
|
221
|
-
//
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
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
|
-
}
|
|
262
|
-
|
|
263
|
-
if (error) {
|
|
264
|
-
throw error;
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
return this._pending;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
async runStructured<S extends Schema.Schema.AnyNoContext>(
|
|
271
|
-
schema: S,
|
|
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[] = [];
|
|
288
|
-
|
|
289
|
-
if (artifactDiffResolver) {
|
|
290
|
-
const versions = gatherObjectVersions(history);
|
|
291
|
-
|
|
292
|
-
const artifactDiff = await artifactDiffResolver(
|
|
293
|
-
Array.from(versions.entries()).map(([id, version]) => ({ id, lastVersion: version })),
|
|
294
|
-
);
|
|
138
|
+
// Execute the stream request.
|
|
139
|
+
const blocks = yield* LanguageModel.streamText({
|
|
140
|
+
prompt,
|
|
141
|
+
toolkit,
|
|
142
|
+
disableToolCallResolution: true,
|
|
143
|
+
}).pipe(
|
|
144
|
+
// Disable tool call parsing so that we can handle parameter schema errors on a per-tool call basis.
|
|
145
|
+
withoutToolCallParising,
|
|
146
|
+
// TOOD(dmaretskyi): Error mapping.
|
|
147
|
+
AiParser.parseResponse({
|
|
148
|
+
onBegin: () => observer.onBegin(),
|
|
149
|
+
onBlock: (block) => observer.onBlock(block),
|
|
150
|
+
onPart: (part) => observer.onPart(part),
|
|
151
|
+
onEnd: (summary) => observer.onEnd(summary),
|
|
152
|
+
}),
|
|
153
|
+
Stream.runCollect,
|
|
154
|
+
Effect.map(Chunk.toArray),
|
|
155
|
+
);
|
|
295
156
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
157
|
+
// Create the response message.
|
|
158
|
+
const response = yield* submitMessage(
|
|
159
|
+
Obj.make(Message.Message, {
|
|
160
|
+
created: new Date().toISOString(),
|
|
161
|
+
sender: { role: 'assistant' },
|
|
162
|
+
blocks,
|
|
163
|
+
}),
|
|
164
|
+
);
|
|
300
165
|
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
166
|
+
// Parse the response for tool calls.
|
|
167
|
+
const toolCalls = getToolCalls(response);
|
|
168
|
+
if (toolCalls.length === 0) {
|
|
169
|
+
break;
|
|
170
|
+
} else if (!toolkit) {
|
|
171
|
+
throw new Error('No toolkit provided'); // TODO(burdon): Throw user error?
|
|
305
172
|
}
|
|
306
173
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
private _createQueryArtifactsTool(artifacts: ArtifactDefinition[]): ExecutableTool {
|
|
321
|
-
return createTool('system', {
|
|
322
|
-
name: 'query_artifact_definitions',
|
|
323
|
-
description: 'Query the available artifact definitions',
|
|
324
|
-
schema: Schema.Struct({}),
|
|
325
|
-
execute: async () => {
|
|
326
|
-
return ToolResult.Success({
|
|
327
|
-
artifactDefinitions: artifacts.map((artifact) => ({
|
|
328
|
-
id: artifact.id,
|
|
329
|
-
name: artifact.name,
|
|
330
|
-
description: artifact.description,
|
|
331
|
-
})),
|
|
332
|
-
});
|
|
333
|
-
},
|
|
334
|
-
});
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
private _createRequireTool(
|
|
338
|
-
artifacts: ArtifactDefinition[],
|
|
339
|
-
onRequire: (artifactDefinitionIds: readonly string[]) => void,
|
|
340
|
-
): ExecutableTool {
|
|
341
|
-
return createTool('system', {
|
|
342
|
-
name: 'require_artifact_definitions',
|
|
343
|
-
description:
|
|
344
|
-
'Require the use of specific artifact definitions. This will allow the model to interact with artifact definitions and use their tools.',
|
|
345
|
-
schema: Schema.Struct({
|
|
346
|
-
artifactDefinitionIds: Schema.Array(Schema.String).annotations({
|
|
347
|
-
description: 'The ids of the artifact definitions to require',
|
|
348
|
-
examples: [['artifact:dxos.org/example/Test']],
|
|
349
|
-
}),
|
|
350
|
-
}),
|
|
351
|
-
execute: async ({ artifactDefinitionIds }) => {
|
|
352
|
-
const missingArtifactDefinitionIds = artifactDefinitionIds.filter(
|
|
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(', ')}`,
|
|
174
|
+
// Execute the tool calls.
|
|
175
|
+
// TODO(burdon): Retry errors? Write result when each completes individually?
|
|
176
|
+
const toolResults = yield* Effect.forEach(toolCalls, (toolCall) => {
|
|
177
|
+
return callTool(toolkit, toolCall).pipe(
|
|
178
|
+
Effect.provide(
|
|
179
|
+
TracingService.layerSubframe((context) => ({
|
|
180
|
+
...context,
|
|
181
|
+
parentMessage: response.id,
|
|
182
|
+
toolCallId: toolCall.toolCallId,
|
|
183
|
+
})),
|
|
184
|
+
),
|
|
358
185
|
);
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
onRequire(artifactDefinitionIds);
|
|
362
|
-
|
|
363
|
-
return ToolResult.Success({});
|
|
364
|
-
},
|
|
365
|
-
});
|
|
366
|
-
}
|
|
186
|
+
});
|
|
367
187
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
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
|
-
}),
|
|
188
|
+
// Add to queue and continue loop.
|
|
189
|
+
// TODO(wittjosiah): Sometimes tool error results are added to the queue before the tool agent statuses.
|
|
190
|
+
// This results in a broken execution graph.
|
|
191
|
+
yield* submitMessage(
|
|
192
|
+
Obj.make(Message.Message, {
|
|
193
|
+
created: new Date().toISOString(),
|
|
194
|
+
sender: { role: 'tool' },
|
|
195
|
+
blocks: toolResults,
|
|
390
196
|
}),
|
|
391
|
-
)
|
|
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(', ')}`);
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
const stepResults: any[] = [];
|
|
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);
|
|
445
|
-
}
|
|
197
|
+
);
|
|
446
198
|
|
|
447
|
-
|
|
448
|
-
}
|
|
449
|
-
});
|
|
450
|
-
}
|
|
199
|
+
this._toolCalls++;
|
|
200
|
+
} while (true);
|
|
451
201
|
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
202
|
+
this._ended = Date.now();
|
|
203
|
+
log('done', { pending: this._pending.length, duration: this.duration, tools: this._toolCalls });
|
|
204
|
+
return this._pending;
|
|
205
|
+
}).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));
|
|
455
206
|
|
|
456
|
-
|
|
457
|
-
|
|
207
|
+
/**
|
|
208
|
+
* @deprecated
|
|
209
|
+
*/
|
|
210
|
+
// TODO(burdon): Implement or remove.
|
|
211
|
+
async runStructured<S extends Schema.Schema.AnyNoContext>(
|
|
212
|
+
_schema: S,
|
|
213
|
+
_options: AiSessionRunProps<any>,
|
|
214
|
+
): Promise<Schema.Schema.Type<S>> {
|
|
215
|
+
return todo();
|
|
216
|
+
// const parser = structuredOutputParser(schema);
|
|
217
|
+
// const result = await this.run({
|
|
218
|
+
// ...options,
|
|
219
|
+
// executableTools: [...(options.executableTools ?? []), parser.tool],
|
|
220
|
+
// });
|
|
221
|
+
// return parser.getResult(result);
|
|
458
222
|
}
|
|
459
223
|
}
|
|
460
224
|
|
|
461
|
-
|
|
462
|
-
|
|
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> => {
|
|
520
|
-
const artifactIds = new Map<ObjectId, ObjectVersion>();
|
|
521
|
-
for (const message of messages) {
|
|
522
|
-
for (const block of message.content) {
|
|
523
|
-
if (block.type === 'json' && block.disposition === VersionPin.DISPOSITION) {
|
|
524
|
-
const pin = VersionPin.pipe(Schema.decodeOption)(JSON.parse(block.json)).pipe(Option.getOrUndefined);
|
|
525
|
-
if (!pin) {
|
|
526
|
-
continue;
|
|
527
|
-
}
|
|
528
|
-
artifactIds.set(pin.objectId, pin.version);
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
return artifactIds;
|
|
534
|
-
};
|
|
225
|
+
const createSnippet = (text: string, len = 32) =>
|
|
226
|
+
text.length <= len * 2 ? text : [text.slice(0, len), '...', text.slice(-len)].join('');
|
|
535
227
|
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
The following artifacts have been updated since the last message:
|
|
544
|
-
${Array.from(artifactDiff.entries())
|
|
545
|
-
.map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `\n${diff}` : ''}</changed-artifact>`)
|
|
546
|
-
.join('\n')}
|
|
547
|
-
`,
|
|
548
|
-
};
|
|
228
|
+
// TODO(dmaretskyi): Extract as a general util.
|
|
229
|
+
const logDump = (message: string, data: unknown) => {
|
|
230
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
231
|
+
const { writeFileSync } = require('node:fs');
|
|
232
|
+
const path = `/tmp/log-data-${Date.now()}.json`;
|
|
233
|
+
writeFileSync(path, JSON.stringify(data, null, 2));
|
|
234
|
+
log.info(message, { path });
|
|
549
235
|
};
|