@dxos/assistant 0.8.3-staging.0fa589b → 0.8.4-main.28f8d3d

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.
Files changed (152) hide show
  1. package/dist/lib/browser/chunk-6WRGDEMH.mjs +89 -0
  2. package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-NZGGCEF3.mjs +341 -0
  4. package/dist/lib/browser/chunk-NZGGCEF3.mjs.map +7 -0
  5. package/dist/lib/browser/extraction/index.mjs +269 -0
  6. package/dist/lib/browser/extraction/index.mjs.map +7 -0
  7. package/dist/lib/browser/index.mjs +306 -2110
  8. package/dist/lib/browser/index.mjs.map +4 -4
  9. package/dist/lib/browser/meta.json +1 -1
  10. package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +13 -0
  11. package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs.map +7 -0
  12. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +91 -0
  13. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +7 -0
  14. package/dist/lib/node-esm/chunk-XOOPGSGW.mjs +343 -0
  15. package/dist/lib/node-esm/chunk-XOOPGSGW.mjs.map +7 -0
  16. package/dist/lib/node-esm/extraction/index.mjs +270 -0
  17. package/dist/lib/node-esm/extraction/index.mjs.map +7 -0
  18. package/dist/lib/node-esm/index.mjs +305 -2110
  19. package/dist/lib/node-esm/index.mjs.map +4 -4
  20. package/dist/lib/node-esm/meta.json +1 -1
  21. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +14 -0
  22. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs.map +7 -0
  23. package/dist/types/src/conversation/context.d.ts +90 -0
  24. package/dist/types/src/conversation/context.d.ts.map +1 -0
  25. package/dist/types/src/conversation/conversation.d.ts +50 -0
  26. package/dist/types/src/conversation/conversation.d.ts.map +1 -0
  27. package/dist/types/src/conversation/index.d.ts +3 -0
  28. package/dist/types/src/conversation/index.d.ts.map +1 -0
  29. package/dist/types/src/errors.d.ts +39 -0
  30. package/dist/types/src/errors.d.ts.map +1 -0
  31. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  32. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +151 -53
  33. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  34. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts +1 -1
  35. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  36. package/dist/types/src/extraction/extraction.d.ts +106 -44
  37. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  38. package/dist/types/src/functions/index.d.ts +2 -0
  39. package/dist/types/src/functions/index.d.ts.map +1 -0
  40. package/dist/types/src/functions/services.d.ts +7 -0
  41. package/dist/types/src/functions/services.d.ts.map +1 -0
  42. package/dist/types/src/index.d.ts +4 -3
  43. package/dist/types/src/index.d.ts.map +1 -1
  44. package/dist/types/src/session/artifact-diff.d.ts +27 -0
  45. package/dist/types/src/session/artifact-diff.d.ts.map +1 -0
  46. package/dist/types/src/session/format.d.ts +168 -0
  47. package/dist/types/src/session/format.d.ts.map +1 -0
  48. package/dist/types/src/session/format.test.d.ts +2 -0
  49. package/dist/types/src/session/format.test.d.ts.map +1 -0
  50. package/dist/types/src/session/index.d.ts +1 -0
  51. package/dist/types/src/session/index.d.ts.map +1 -1
  52. package/dist/types/src/session/session.d.ts +125 -219
  53. package/dist/types/src/session/session.d.ts.map +1 -1
  54. package/dist/types/src/session/version-pin.d.ts +4 -4
  55. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  56. package/dist/types/src/templates/index.d.ts +2 -0
  57. package/dist/types/src/templates/index.d.ts.map +1 -0
  58. package/dist/types/src/templates/system.d.ts +22 -0
  59. package/dist/types/src/templates/system.d.ts.map +1 -0
  60. package/dist/types/src/types.d.ts +13 -0
  61. package/dist/types/src/types.d.ts.map +1 -1
  62. package/dist/types/tsconfig.tsbuildinfo +1 -1
  63. package/package.json +46 -31
  64. package/src/conversation/context.ts +133 -0
  65. package/src/conversation/conversation.ts +125 -0
  66. package/src/conversation/index.ts +6 -0
  67. package/src/errors.ts +10 -0
  68. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +7 -18
  69. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +23 -17
  70. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +4 -3
  71. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +7 -4
  72. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +2 -2
  73. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +1 -1
  74. package/src/extraction/quotes.test.ts +1 -1
  75. package/src/extraction/quotes.ts +1 -1
  76. package/src/functions/index.ts +5 -0
  77. package/src/functions/services.ts +114 -0
  78. package/src/index.ts +4 -3
  79. package/src/session/__snapshots__/session.test.ts.snap +32 -0
  80. package/src/session/artifact-diff.ts +37 -0
  81. package/src/session/format.test.ts +60 -0
  82. package/src/session/format.ts +139 -0
  83. package/src/session/index.ts +1 -0
  84. package/src/session/session.test.ts +95 -19
  85. package/src/session/session.ts +224 -494
  86. package/src/session/version-pin.test.ts +2 -21
  87. package/src/session/version-pin.ts +9 -9
  88. package/src/summarization/summarization.test.ts +82 -106
  89. package/src/templates/format.tpl +55 -0
  90. package/src/templates/index.ts +5 -0
  91. package/src/templates/system.tpl +47 -0
  92. package/src/templates/system.ts +32 -0
  93. package/src/types.ts +45 -1
  94. package/src/typings.d.ts +5 -0
  95. package/dist/lib/node/index.cjs +0 -2178
  96. package/dist/lib/node/index.cjs.map +0 -7
  97. package/dist/lib/node/meta.json +0 -1
  98. package/dist/types/bin/chat.d.ts +0 -2
  99. package/dist/types/bin/chat.d.ts.map +0 -1
  100. package/dist/types/src/blueprint/ai.test.d.ts +0 -2
  101. package/dist/types/src/blueprint/ai.test.d.ts.map +0 -1
  102. package/dist/types/src/blueprint/blueprint.d.ts +0 -55
  103. package/dist/types/src/blueprint/blueprint.d.ts.map +0 -1
  104. package/dist/types/src/blueprint/blueprint.test.d.ts +0 -2
  105. package/dist/types/src/blueprint/blueprint.test.d.ts.map +0 -1
  106. package/dist/types/src/blueprint/index.d.ts +0 -4
  107. package/dist/types/src/blueprint/index.d.ts.map +0 -1
  108. package/dist/types/src/blueprint/logger.d.ts +0 -25
  109. package/dist/types/src/blueprint/logger.d.ts.map +0 -1
  110. package/dist/types/src/blueprint/machine.d.ts +0 -143
  111. package/dist/types/src/blueprint/machine.d.ts.map +0 -1
  112. package/dist/types/src/blueprint/test-data.d.ts +0 -3
  113. package/dist/types/src/blueprint/test-data.d.ts.map +0 -1
  114. package/dist/types/src/research/exa.d.ts +0 -7
  115. package/dist/types/src/research/exa.d.ts.map +0 -1
  116. package/dist/types/src/research/graph.d.ts +0 -41
  117. package/dist/types/src/research/graph.d.ts.map +0 -1
  118. package/dist/types/src/research/graph.test.d.ts +0 -2
  119. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  120. package/dist/types/src/research/index.d.ts +0 -4
  121. package/dist/types/src/research/index.d.ts.map +0 -1
  122. package/dist/types/src/research/research.d.ts +0 -10
  123. package/dist/types/src/research/research.d.ts.map +0 -1
  124. package/dist/types/src/research/research.test.d.ts +0 -2
  125. package/dist/types/src/research/research.test.d.ts.map +0 -1
  126. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  127. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  128. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  129. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  130. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  131. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  132. package/dist/types/src/testing/index.d.ts +0 -3
  133. package/dist/types/src/testing/index.d.ts.map +0 -1
  134. package/src/blueprint/ai.test.ts +0 -156
  135. package/src/blueprint/blueprint.test.ts +0 -151
  136. package/src/blueprint/blueprint.ts +0 -75
  137. package/src/blueprint/index.ts +0 -7
  138. package/src/blueprint/logger.ts +0 -155
  139. package/src/blueprint/machine.ts +0 -251
  140. package/src/blueprint/test-data.ts +0 -55
  141. package/src/research/exa.ts +0 -100
  142. package/src/research/graph.test.ts +0 -15
  143. package/src/research/graph.ts +0 -337
  144. package/src/research/index.ts +0 -7
  145. package/src/research/instructions-research.tpl +0 -97
  146. package/src/research/research.test.ts +0 -190
  147. package/src/research/research.ts +0 -89
  148. package/src/testing/exa-search-1748337321991.ts +0 -131
  149. package/src/testing/exa-search-1748337331526.ts +0 -144
  150. package/src/testing/exa-search-1748337344119.ts +0 -133
  151. package/src/testing/index.ts +0 -11
  152. package/src/typedefs.d.ts +0 -8
@@ -2,548 +2,278 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Option, Schema } from 'effect';
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
- AgentStatusReport,
9
- isToolUse,
10
- runTools,
11
- type AgentStatus,
12
- structuredOutputParser,
13
- type AiServiceClient,
14
- type GenerationStream,
15
- type GenerateRequest,
16
- Message,
17
- type MessageContentBlock,
18
- MixedStreamParser,
19
- ToolResult,
20
- createTool,
21
- type ExecutableTool,
9
+ type AiInputPreprocessingError,
10
+ AiParser,
11
+ AiPreprocessor,
12
+ type AiToolNotFoundError,
13
+ type ConsolePrinter,
14
+ ToolExecutionService,
15
+ ToolResolverService,
16
+ callTools,
17
+ getToolCalls,
22
18
  } from '@dxos/ai';
23
- import { type ArtifactDefinition } from '@dxos/artifact';
24
- import { Event, synchronized } from '@dxos/async';
19
+ import { type Blueprint } from '@dxos/blueprints';
20
+ import { todo } from '@dxos/debug';
25
21
  import { Obj } from '@dxos/echo';
26
- import { ObjectVersion } from '@dxos/echo-db';
27
- import { create, type ObjectId } from '@dxos/echo-schema';
28
- import { invariant } from '@dxos/invariant';
29
22
  import { log } from '@dxos/log';
23
+ import { type ContentBlock, DataType } from '@dxos/schema';
24
+ import { isNotFalsy } from '@dxos/util';
30
25
 
31
- import { VersionPin } from './version-pin';
26
+ import { type AiAssistantError } from '../errors';
32
27
 
33
- /**
34
- * Contains message history, tools, current context.
35
- * Current context means the state of the app, time of day, and other contextual information.
36
- * It makes requests to the model, its a state machine.
37
- * It keeps track of the current goal.
38
- * It manages the context window.
39
- * Tracks the success criteria of reaching the goal, exposing metrics (stretch)
40
- * Could be run locally in the app or remotely.
41
- * Could be personal or shared.
42
- */
28
+ import { formatSystemPrompt, formatUserPrompt } from './format';
29
+
30
+ export type AiSessionOptions = {};
43
31
 
44
32
  /**
45
- * Resolves artifact ids to their versions.
46
- * Used to give the model a sense of the changes to the artifacts made by users during the conversation.
47
- * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,
48
- * a diff is inserted into the conversation.
33
+ * Live observer of the generation process.
49
34
  */
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
-
35
+ export interface GenerationObserver {
65
36
  /**
66
- * Non-artifact specific tools.
37
+ * Unparsed content block parts from the model.
67
38
  */
68
- tools: ExecutableTool[];
69
-
70
- history: Message[];
71
-
72
- prompt: string;
73
-
74
- generationOptions?: Pick<GenerateRequest, 'model'>;
75
-
76
- extensions?: ToolContextExtensions;
77
-
78
- systemPrompt?: string;
39
+ onPart: (part: AiResponse.Part) => Effect.Effect<void>;
79
40
 
80
41
  /**
81
- * Pre-require artifacts.
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
- requiredArtifactIds?: string[];
51
+ onBlock: (block: ContentBlock.Any) => Effect.Effect<void>;
84
52
 
85
53
  /**
86
- * @see ArtifactDiffResolver
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.
87
56
  */
88
- artifactDiffResolver?: ArtifactDiffResolver;
89
- };
57
+ onMessage: (message: DataType.Message) => Effect.Effect<void>;
58
+ }
90
59
 
91
- type OperationModel = 'planning' | 'importing' | 'configured';
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
+ }),
70
+
71
+ noop: () => GenerationObserver.make(),
92
72
 
93
- export type AiSessionOptions = {
94
73
  /**
95
- * Determines the agent's handling of the artifacts definitions:
96
- *
97
- * - `planning`: The model will create a plan with required artifacts for each step.
98
- * - `importing`: The model can query registry and only pull in the artifacts that are required to complete the task.
99
- * - `configured`: The available artifacts are pre-selected and the model cannot select additional artifacts.
74
+ * Debug printer to be used in unit-tests and browser devtools.
100
75
  */
101
- operationModel: OperationModel;
102
- };
103
-
104
- export class AISession {
105
- /** SSE stream parser. */
106
- private readonly _parser = new MixedStreamParser();
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
+ });
107
94
 
108
- /** Pending messages (incl. the current user request). */
109
- private _pending: Message[] = [];
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
+ };
110
104
 
111
- /** Current streaming response. */
112
- private _stream: GenerationStream | undefined;
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>());
113
118
 
114
- /** Prior history from queue. */
115
- private _history: Message[] = [];
119
+ // TODO(dmaretskyi): Remove the queues and convert everything to observer.
116
120
 
117
121
  /**
118
- * New message.
122
+ * Blocks streaming from the model during the session.
123
+ * @deprecated Use `observer.onBlock` instead.
119
124
  */
120
- public readonly message = this._parser.message;
125
+ public readonly blockQueue = Effect.runSync(Queue.unbounded<Option.Option<ContentBlock.Any>>());
121
126
 
122
- /**
123
- * Complete block added to Message.
124
- */
125
- public readonly block = this._parser.block;
127
+ /** Unparsed events from the underlying generation stream. */
128
+ public readonly eventQueue = Effect.runSync(Queue.unbounded<AiResponse.Part>());
126
129
 
127
- /**
128
- * Update partial block (while streaming).
129
- */
130
- public readonly update = this._parser.update;
130
+ /** Prevents concurrent execution of session. */
131
+ private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
131
132
 
132
- public readonly streamEvent = this._parser.streamEvent;
133
+ /** Pending messages (incl. the current user request). */
134
+ private _pending: DataType.Message[] = [];
133
135
 
134
- /**
135
- * User prompt or tool result.
136
- */
137
- public readonly userMessage = new Event<Message>();
136
+ /** Prior history from queue. */
137
+ private _history: DataType.Message[] = [];
138
+
139
+ constructor(private readonly _options: AiSessionOptions = {}) {}
138
140
 
139
141
  /**
140
- * Agent self-reporting its status.
142
+ * Runs the AI model loop interacting with tools and artifacts.
143
+ * @returns The messages generated by the session, including the user's prompt.
141
144
  */
142
- public readonly statusReport = new Event<AgentStatus>();
143
-
144
- public readonly toolStatusReport = new Event<{ message: Message; status: AgentStatus }>();
145
-
146
- constructor(private readonly _options: AiSessionOptions) {
147
- // Message complete.
148
- this._parser.message.on((message) => {
149
- this._pending.push(message);
150
- });
151
- this._parser.block.on((block) => {
152
- if (block.type === 'text' && block.disposition === 'status') {
153
- this.statusReport.emit(create(AgentStatusReport, { message: block.text }));
154
- }
155
- });
156
- }
157
-
158
- @synchronized
159
- async run(options: SessionRunOptions): Promise<Message[]> {
160
- const systemTools: ExecutableTool[] = [];
161
- switch (this._options.operationModel) {
162
- case 'planning':
163
- systemTools.push(this._createQueryArtifactsTool(options.artifacts), this._createPlanningTool(options));
164
- break;
165
- case 'importing':
166
- systemTools.push(
167
- this._createQueryArtifactsTool(options.artifacts),
168
- this._createRequireTool(options.artifacts, (artifactDefinitionIds) => {
169
- for (const artifactDefinitionId of artifactDefinitionIds) {
170
- requiredArtifactIds.add(artifactDefinitionId);
171
- }
172
- }),
173
- );
174
- break;
175
- case 'configured':
176
- // no system tools
177
- break;
178
- default:
179
- throw new TypeError(`Invalid operation model: ${this._options.operationModel}`);
180
- }
181
-
182
- this._history = [...options.history];
183
- this._pending = [await this._formatUserPrompt(options.artifactDiffResolver, options.prompt, options.history)];
184
- this.userMessage.emit(this._pending.at(-1)!);
185
- this._stream = undefined;
186
-
187
- let error: Error | undefined;
188
-
189
- const requiredArtifactIds = new Set<string>(options.requiredArtifactIds ?? []);
190
- try {
191
- 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.
192
173
  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
- log('request', {
174
+ log.info('request', {
175
+ prompt: promptMessages,
176
+ system: { snippet: [system.slice(0, 32), '...', system.slice(-32)].join(''), length: system.length },
202
177
  pending: this._pending.length,
203
178
  history: this._history.length,
204
- tools: tools.map((tool) => tool.name),
179
+ objects: params.objects?.length ?? 0,
180
+ blueprints: params.blueprints?.length ?? 0,
181
+ toolkit: Object.values(toolkit.tools).map((tool: AiTool.Any) => tool.name),
205
182
  });
206
183
 
207
- // Open request stream.
208
- this._stream = await options.client.execStream({
209
- ...(options.generationOptions ?? {}),
210
- // TODO(burdon): Rename messages or separate history/message.
211
- history: [...this._history, ...this._pending],
212
- tools,
213
- systemPrompt:
214
- options.systemPrompt ??
215
- createBaseInstructions({
216
- availableArtifacts: Array.from(requiredArtifactIds),
217
- operationModel: this._options.operationModel,
218
- }),
219
- });
220
-
221
- // Wait until complete.
222
- await this._parser.parse(this._stream);
223
- await this._stream.complete();
224
-
225
- // Add messages.
226
- log('response', { pending: this._pending });
227
-
228
- // Resolve tool use locally.
229
- more = false;
230
- const message = this._pending.at(-1);
231
- invariant(message);
232
- if (isToolUse(message)) {
233
- log('tool request...');
234
- const response = await runTools({
235
- message: this._pending.at(-1)!,
236
- tools,
237
- extensions: options.extensions ?? {},
238
- reportStatus: (status) => this._onToolStatusReport(message, status),
239
- });
240
-
241
- log('tool response', { response });
242
- switch (response.type) {
243
- case 'continue': {
244
- this._pending = [...this._pending, response.message];
245
- this.userMessage.emit(response.message);
246
- more = true;
247
- break;
248
- }
249
- }
250
- }
251
- } while (more);
252
- } catch (err) {
253
- log.catch(err);
254
- if (err instanceof Error && err.message.includes('Overloaded')) {
255
- error = new AIServiecOverloadedError('AI service overloaded', { cause: err } as any); // TODO(dmaretskyi): Schema errors cant have cause
256
- } else {
257
- error = new Error('AI service error', { cause: err });
258
- }
259
- } finally {
260
- this._stream = undefined;
261
- }
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
- );
295
-
296
- log.info('vision', {
297
- artifactDiff,
298
- versions,
299
- });
300
-
301
- for (const [id, { version }] of [...artifactDiff.entries()]) {
302
- if (ObjectVersion.equals(version, versions.get(id)!)) {
303
- artifactDiff.delete(id);
304
- continue;
305
- }
306
-
307
- prelude.push(VersionPin.createBlock(VersionPin.make({ objectId: id, version })));
308
- }
309
- if (artifactDiff.size > 0) {
310
- prelude.push(createArtifactUpdateBlock(artifactDiff));
311
- }
312
- }
313
-
314
- return Obj.make(Message, {
315
- role: 'user',
316
- content: [...prelude, { type: 'text', text: prompt }],
317
- });
318
- }
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
+ );
319
203
 
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
- })),
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,
332
215
  });
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(', ')}`,
358
- );
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;
359
224
  }
360
225
 
361
- onRequire(artifactDefinitionIds);
362
-
363
- return ToolResult.Success({});
364
- },
365
- });
366
- }
367
-
368
- private _createPlanningTool(options: SessionRunOptions): ExecutableTool {
369
- return createTool('system', {
370
- name: 'create_plan',
371
- description:
372
- 'Create a plan. Make sure that each step is independent and can be executed solely on the data returned by the previous step. The steps only share the data that is specified in the plan.',
373
- schema: Schema.Struct({
374
- goal: Schema.String.annotations({ description: 'The goal that the plan will achieve.' }),
375
- steps: Schema.Array(
376
- Schema.Struct({
377
- action: Schema.String.annotations({
378
- description: 'Complete, detailed action to perform.',
379
- }),
380
- input: Schema.String.annotations({
381
- description: 'The required input data for this step. First step must not require any data.',
382
- }),
383
- output: Schema.String.annotations({
384
- description: 'The output data from this step. This is passed to the next step as input.',
385
- }),
386
- requiredArtifactIds: Schema.Array(Schema.String).annotations({
387
- description: 'The ids of the artifacts required to perform this step.',
388
- examples: [['artifact:dxos.org/example/Test']],
389
- }),
390
- }),
391
- ).annotations({ description: 'Steps' }),
392
- }),
393
- execute: async ({ goal, steps }) => {
394
- const missingArtifactIds = steps
395
- .flatMap((step) => step.requiredArtifactIds)
396
- .filter((artifactId) => !options.artifacts.some((artifact) => artifact.id === artifactId));
397
- if (missingArtifactIds.length > 0) {
398
- return ToolResult.Error(`One or more artifact ids are invalid: ${missingArtifactIds.join(', ')}`);
399
- }
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
+ });
400
233
 
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
- }
234
+ this._pending.push(toolResultsMessage);
235
+ yield* this.messageQueue.offer(toolResultsMessage);
236
+ yield* observer.onMessage(toolResultsMessage);
237
+ } while (true);
446
238
 
447
- return ToolResult.Success({ stepResults });
448
- },
449
- });
450
- }
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);
451
243
 
452
- private _onToolStatusReport(message: Message, status: AgentStatus): void {
453
- this.toolStatusReport.emit({ message, status });
454
- }
244
+ log('done', { pending: this._pending.length });
245
+ return this._pending;
246
+ }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));
455
247
 
456
- abort(): void {
457
- this._stream?.abort();
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);
458
260
  }
459
261
  }
460
262
 
461
- // TODO(burdon): Use handlebars template with effect-schema input.
462
- const createBaseInstructions = ({
463
- availableArtifacts,
464
- operationModel,
465
- }: {
466
- availableArtifacts: string[];
467
- operationModel: OperationModel;
468
- }) => `
469
- You are a friendly, advanced AI assistant capable of creating and managing artifacts from available data and tools.
470
- Your task is to process user commands and questions and decide how best to respond.
471
- In some cases, you will need to create or reference data objects called artifacts.
472
-
473
- Follow these guidelines carefully:
474
-
475
- Decision-making:
476
-
477
- - Analyze the structure and type of the content in the user's message.
478
-
479
-
480
- ${
481
- operationModel === 'planning'
482
- ? `
483
- - Can you complete the task using the available artifacts?
484
- - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
485
- - Identify which artifacts are relevant to the user's request.
486
- - Break down the user's request into a step-by-step plan that you will use to execute the user's request, the plan items should include artifacts which will be used to perform the actions.
487
- `
488
- : ''
489
- }
490
- ${
491
- operationModel === 'importing'
492
- ? `
493
- - Can you complete the task using the available artifacts?
494
- - If you can't complete the task using the available artifacts, query the list of available artifacts using the appropriate tool.
495
- - Identify which artifacts are relevant to the user's request.
496
- - Are the required artifacts already available?
497
- - If not, select which artifact(s) will be the most relevant and require them using the require_artifacts tool.
498
- - The require'd artifact tools will be available for use after require.
499
- `
500
- : ''
501
- }
502
- ${
503
- operationModel === 'configured'
504
- ? `
505
- - Select the most relevant artifact(s) to complete the task.
506
- - Call the appropriate tool to use the artifact(s).
507
- `
508
- : ''
509
- }
510
-
511
- ${availableArtifacts.length > 0 ? `Artifacts already in context: ${availableArtifacts.join('\n')}` : ''}
512
- `;
513
-
514
- export class AIServiecOverloadedError extends Schema.TaggedError<AIServiecOverloadedError>()(
515
- 'AIServiecOverloadedError',
516
- {},
517
- ) {}
518
-
519
- const gatherObjectVersions = (messages: Message[]): Map<ObjectId, ObjectVersion> => {
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
- };
535
-
536
- const createArtifactUpdateBlock = (
537
- artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,
538
- ): MessageContentBlock => {
539
- return {
540
- type: 'text',
541
- disposition: 'artifact-update',
542
- text: `
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
- };
549
- };
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
+ });