@dxos/assistant 0.8.4-main.b97322e → 0.8.4-main.bc2380dfbc

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 (196) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +2 -1
  3. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  4. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +7 -0
  5. package/dist/lib/neutral/extraction/index.mjs +204 -0
  6. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  7. package/dist/lib/neutral/index.mjs +1755 -0
  8. package/dist/lib/neutral/index.mjs.map +7 -0
  9. package/dist/lib/neutral/meta.json +1 -0
  10. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  11. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  12. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  13. package/dist/types/src/extraction/extraction.d.ts +1066 -273
  14. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  15. package/dist/types/src/extraction/index.d.ts +0 -1
  16. package/dist/types/src/extraction/index.d.ts.map +1 -1
  17. package/dist/types/src/extraction/quotes.d.ts +3 -3
  18. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  19. package/dist/types/src/functions/services.d.ts +15 -4
  20. package/dist/types/src/functions/services.d.ts.map +1 -1
  21. package/dist/types/src/index.d.ts +2 -5
  22. package/dist/types/src/index.d.ts.map +1 -1
  23. package/dist/types/src/request/AiRequest.d.ts +104 -0
  24. package/dist/types/src/request/AiRequest.d.ts.map +1 -0
  25. package/dist/types/src/request/artifact-diff.d.ts +27 -0
  26. package/dist/types/src/request/artifact-diff.d.ts.map +1 -0
  27. package/dist/types/src/request/format.d.ts +15 -0
  28. package/dist/types/src/request/format.d.ts.map +1 -0
  29. package/dist/types/src/request/index.d.ts +4 -0
  30. package/dist/types/src/request/index.d.ts.map +1 -0
  31. package/dist/types/src/request/observer.d.ts +23 -0
  32. package/dist/types/src/request/observer.d.ts.map +1 -0
  33. package/dist/types/src/{session → request}/version-pin.d.ts +4 -4
  34. package/dist/types/src/request/version-pin.d.ts.map +1 -0
  35. package/dist/types/src/session/AiContext.d.ts +154 -0
  36. package/dist/types/src/session/AiContext.d.ts.map +1 -0
  37. package/dist/types/src/session/AiContext.test.d.ts +2 -0
  38. package/dist/types/src/session/AiContext.test.d.ts.map +1 -0
  39. package/dist/types/src/session/AiSession.d.ts +73 -0
  40. package/dist/types/src/session/AiSession.d.ts.map +1 -0
  41. package/dist/types/src/session/index.d.ts +3 -2
  42. package/dist/types/src/session/index.d.ts.map +1 -1
  43. package/dist/types/src/session/toolkit.d.ts +16 -0
  44. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  45. package/dist/types/src/templates/index.d.ts +1 -1
  46. package/dist/types/src/templates/system.d.ts +17 -0
  47. package/dist/types/src/templates/system.d.ts.map +1 -0
  48. package/dist/types/src/util/artifact.d.ts +27 -0
  49. package/dist/types/src/util/artifact.d.ts.map +1 -0
  50. package/dist/types/src/util/diff.d.ts +17 -0
  51. package/dist/types/src/util/diff.d.ts.map +1 -0
  52. package/dist/types/src/util/diff.test.d.ts +2 -0
  53. package/dist/types/src/util/diff.test.d.ts.map +1 -0
  54. package/dist/types/src/util/error-handling.d.ts +4 -0
  55. package/dist/types/src/util/error-handling.d.ts.map +1 -0
  56. package/dist/types/src/util/errors.d.ts +67 -0
  57. package/dist/types/src/util/errors.d.ts.map +1 -0
  58. package/dist/types/src/util/execution-graph.d.ts +85 -0
  59. package/dist/types/src/util/execution-graph.d.ts.map +1 -0
  60. package/dist/types/src/util/execution-graph.test.d.ts +2 -0
  61. package/dist/types/src/util/execution-graph.test.d.ts.map +1 -0
  62. package/dist/types/src/util/index.d.ts +7 -0
  63. package/dist/types/src/util/index.d.ts.map +1 -0
  64. package/dist/types/src/util/tracing.d.ts +233 -0
  65. package/dist/types/src/util/tracing.d.ts.map +1 -0
  66. package/dist/types/tsconfig.tsbuildinfo +1 -1
  67. package/package.json +42 -36
  68. package/src/extraction/extraction-ner-function/index.ts +0 -1
  69. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  70. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  71. package/src/extraction/extraction.ts +44 -15
  72. package/src/extraction/index.ts +0 -1
  73. package/src/extraction/quotes.test.ts +3 -3
  74. package/src/extraction/quotes.ts +6 -7
  75. package/src/functions/services.ts +173 -98
  76. package/src/index.ts +2 -5
  77. package/src/request/AiRequest.ts +348 -0
  78. package/src/request/artifact-diff.ts +41 -0
  79. package/src/request/format.ts +147 -0
  80. package/src/request/index.ts +8 -0
  81. package/src/request/observer.ts +62 -0
  82. package/src/{session → request}/version-pin.ts +8 -8
  83. package/src/session/AiContext.test.ts +53 -0
  84. package/src/session/AiContext.ts +403 -0
  85. package/src/session/AiSession.ts +324 -0
  86. package/src/session/index.ts +4 -2
  87. package/src/session/toolkit.ts +47 -0
  88. package/src/templates/index.ts +1 -1
  89. package/src/templates/instructions/format.tpl +57 -0
  90. package/src/templates/instructions/system.tpl +96 -0
  91. package/src/templates/system.ts +42 -0
  92. package/src/typings.d.ts +5 -0
  93. package/src/util/artifact.ts +88 -0
  94. package/src/util/diff.test.ts +74 -0
  95. package/src/util/diff.ts +93 -0
  96. package/src/util/error-handling.ts +42 -0
  97. package/src/util/errors.ts +15 -0
  98. package/src/util/execution-graph.test.ts +740 -0
  99. package/src/util/execution-graph.ts +519 -0
  100. package/src/util/index.ts +10 -0
  101. package/src/util/tracing.ts +57 -0
  102. package/dist/lib/browser/index.mjs +0 -1831
  103. package/dist/lib/browser/index.mjs.map +0 -7
  104. package/dist/lib/browser/meta.json +0 -1
  105. package/dist/lib/node-esm/index.mjs +0 -1833
  106. package/dist/lib/node-esm/index.mjs.map +0 -7
  107. package/dist/lib/node-esm/meta.json +0 -1
  108. package/dist/types/bin/chat.d.ts +0 -2
  109. package/dist/types/bin/chat.d.ts.map +0 -1
  110. package/dist/types/src/context/binder.d.ts +0 -34
  111. package/dist/types/src/context/binder.d.ts.map +0 -1
  112. package/dist/types/src/context/binding.d.ts +0 -56
  113. package/dist/types/src/context/binding.d.ts.map +0 -1
  114. package/dist/types/src/context/index.d.ts +0 -3
  115. package/dist/types/src/context/index.d.ts.map +0 -1
  116. package/dist/types/src/conversation/conversation.d.ts +0 -38
  117. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  118. package/dist/types/src/conversation/index.d.ts +0 -2
  119. package/dist/types/src/conversation/index.d.ts.map +0 -1
  120. package/dist/types/src/errors.d.ts +0 -38
  121. package/dist/types/src/errors.d.ts.map +0 -1
  122. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  123. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  124. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  125. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  126. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  127. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  128. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -302
  129. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  130. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  131. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  132. package/dist/types/src/research/exa.d.ts +0 -12
  133. package/dist/types/src/research/exa.d.ts.map +0 -1
  134. package/dist/types/src/research/graph.d.ts +0 -51
  135. package/dist/types/src/research/graph.d.ts.map +0 -1
  136. package/dist/types/src/research/graph.test.d.ts +0 -2
  137. package/dist/types/src/research/graph.test.d.ts.map +0 -1
  138. package/dist/types/src/research/index.d.ts +0 -4
  139. package/dist/types/src/research/index.d.ts.map +0 -1
  140. package/dist/types/src/research/research.d.ts +0 -10
  141. package/dist/types/src/research/research.d.ts.map +0 -1
  142. package/dist/types/src/research/research.test.d.ts +0 -2
  143. package/dist/types/src/research/research.test.d.ts.map +0 -1
  144. package/dist/types/src/session/session.d.ts +0 -260
  145. package/dist/types/src/session/session.d.ts.map +0 -1
  146. package/dist/types/src/session/session.test.d.ts +0 -2
  147. package/dist/types/src/session/session.test.d.ts.map +0 -1
  148. package/dist/types/src/session/version-pin.d.ts.map +0 -1
  149. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  150. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  151. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  152. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  153. package/dist/types/src/templates/prompt.d.ts +0 -30
  154. package/dist/types/src/templates/prompt.d.ts.map +0 -1
  155. package/dist/types/src/testing/exa-search-1748337321991.d.ts +0 -38
  156. package/dist/types/src/testing/exa-search-1748337321991.d.ts.map +0 -1
  157. package/dist/types/src/testing/exa-search-1748337331526.d.ts +0 -37
  158. package/dist/types/src/testing/exa-search-1748337331526.d.ts.map +0 -1
  159. package/dist/types/src/testing/exa-search-1748337344119.d.ts +0 -58
  160. package/dist/types/src/testing/exa-search-1748337344119.d.ts.map +0 -1
  161. package/dist/types/src/testing/index.d.ts +0 -3
  162. package/dist/types/src/testing/index.d.ts.map +0 -1
  163. package/dist/types/src/types.d.ts +0 -13
  164. package/dist/types/src/types.d.ts.map +0 -1
  165. package/src/context/binder.ts +0 -103
  166. package/src/context/binding.ts +0 -32
  167. package/src/context/index.ts +0 -6
  168. package/src/conversation/conversation.ts +0 -96
  169. package/src/conversation/index.ts +0 -5
  170. package/src/errors.ts +0 -10
  171. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -83
  172. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -70
  173. package/src/extraction/extraction-llm-function/index.ts +0 -5
  174. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -115
  175. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -57
  176. package/src/research/exa.ts +0 -97
  177. package/src/research/graph.test.ts +0 -64
  178. package/src/research/graph.ts +0 -369
  179. package/src/research/index.ts +0 -7
  180. package/src/research/instructions-research.tpl +0 -98
  181. package/src/research/research.test.ts +0 -190
  182. package/src/research/research.ts +0 -87
  183. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  184. package/src/session/session.test.ts +0 -310
  185. package/src/session/session.ts +0 -336
  186. package/src/session/version-pin.test.ts +0 -7
  187. package/src/summarization/summarization.test.ts +0 -208
  188. package/src/templates/assistant.tpl +0 -111
  189. package/src/templates/prompt.ts +0 -45
  190. package/src/testing/exa-search-1748337321991.ts +0 -131
  191. package/src/testing/exa-search-1748337331526.ts +0 -144
  192. package/src/testing/exa-search-1748337344119.ts +0 -133
  193. package/src/testing/index.ts +0 -11
  194. package/src/typedefs.d.ts +0 -8
  195. package/src/types.ts +0 -47
  196. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -1,336 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { AiLanguageModel, AiToolkit, type AiError, type AiResponse, type AiTool } from '@effect/ai';
6
- import { Chunk, Context, Effect, Option, pipe, Stream, type Schema } from 'effect';
7
- import { Array, String } from 'effect';
8
-
9
- import {
10
- AiParser,
11
- AiPreprocessor,
12
- getToolCalls,
13
- runTool,
14
- ToolExecutionService,
15
- ToolResolverService,
16
- type AgentStatus,
17
- type AiInputPreprocessingError,
18
- type AiToolNotFoundError,
19
- type GenerationStream,
20
- } from '@dxos/ai';
21
- import { Event } from '@dxos/async';
22
- import { type Blueprint } from '@dxos/blueprints';
23
- import { todo } from '@dxos/debug';
24
- import { Obj } from '@dxos/echo';
25
- import { ObjectVersion } from '@dxos/echo-db';
26
- import { type ObjectId } from '@dxos/echo-schema';
27
- import { DatabaseService } from '@dxos/functions';
28
- import { log } from '@dxos/log';
29
- import { DataType, type ContentBlock } from '@dxos/schema';
30
-
31
- import { AiAssistantError } from '../errors';
32
-
33
- export type AiSessionOptions = {};
34
-
35
- export type SessionRunOptions<Tools extends AiTool.Any> = {
36
- prompt: string;
37
- history: DataType.Message[];
38
- systemPrompt?: string;
39
- toolkit?: AiToolkit.AiToolkit<Tools>;
40
- blueprints?: Blueprint.Blueprint[];
41
- };
42
-
43
- /**
44
- * Contains message history, tools, current context.
45
- * Current context means the state of the app, time of day, and other contextual information.
46
- * It makes requests to the model, its a state machine.
47
- * It keeps track of the current goal.
48
- * It manages the context window.
49
- * Tracks the success criteria of reaching the goal, exposing metrics (stretch).
50
- * Could be run locally in the app or remotely.
51
- * Could be personal or shared.
52
- */
53
- export class AiSession {
54
- // TODO(burdon): Move to conversation.
55
- private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
56
-
57
- /** Pending messages (incl. the current user request). */
58
- private _pending: DataType.Message[] = [];
59
-
60
- /** Current streaming response. */
61
- private _stream: GenerationStream | undefined;
62
-
63
- /** Prior history from queue. */
64
- private _history: DataType.Message[] = [];
65
-
66
- /**
67
- * New message.
68
- */
69
- public readonly message = new Event<DataType.Message>();
70
-
71
- /**
72
- * Complete block added to Message.
73
- */
74
- public readonly block = new Event<ContentBlock.Any>();
75
-
76
- /**
77
- * Update partial block (while streaming).
78
- */
79
- public readonly update = new Event<ContentBlock.Any>();
80
-
81
- /**
82
- * Unparsed events from the underlying generation stream.
83
- */
84
- public readonly streamEvent = new Event<AiResponse.Part>();
85
-
86
- /**
87
- * User prompt or tool result.
88
- */
89
- public readonly userMessage = new Event<DataType.Message>();
90
-
91
- /**
92
- * Agent self-reporting its status.
93
- * Triggered by the model.
94
- */
95
- public readonly statusReport = new Event<AgentStatus>();
96
-
97
- /**
98
- * Emits when the session is done.
99
- */
100
- public readonly done = new Event<void>();
101
-
102
- constructor(private readonly _options: AiSessionOptions = {}) {}
103
-
104
- /**
105
- * Runs the AI model loop interacting with tools and artifacts.
106
- * @param options - The session options.
107
- * @returns The messages generated by the session, including the user's prompt.
108
- */
109
- // TODO(dmaretskyi): Toolkit context doesn't get added to the effect type.
110
- run = <Tools extends AiTool.Any>(
111
- options: SessionRunOptions<Tools>,
112
- ): Effect.Effect<
113
- DataType.Message[],
114
- AiAssistantError | AiInputPreprocessingError | AiToolNotFoundError | AiError.AiError,
115
- AiLanguageModel.AiLanguageModel | ToolResolverService | ToolExecutionService | AiTool.ToHandler<Tools>
116
- > =>
117
- Effect.gen(this, function* () {
118
- this._history = [...options.history];
119
-
120
- const promptMessages = yield* this._formatUserPrompt(options.prompt, options.history);
121
- this._pending = [promptMessages];
122
- this.userMessage.emit(promptMessages);
123
-
124
- // Potential tool use loop.
125
- do {
126
- log('request', {
127
- pending: this._pending.length,
128
- history: this._history.length,
129
- tools: (Object.values(options.toolkit?.tools ?? {}) as AiTool.Any[]).map((tool: AiTool.Any) => tool.name),
130
- });
131
-
132
- const prompt = yield* AiPreprocessor.preprocessAiInput([...this._history, ...this._pending]);
133
-
134
- const blueprints = options.blueprints ?? [];
135
-
136
- // Build system prompt from blueprint templates.
137
- // TODO(dmaretskyi): Loading BP from the Database should be done at the higher level. We need a type for the resolved blueprint.
138
- const systemPrompt = yield* pipe(
139
- blueprints,
140
- Effect.forEach((blueprint) => DatabaseService.loadRef(blueprint.instructions)),
141
- Effect.flatMap(Effect.forEach((template) => DatabaseService.loadRef(template.source))),
142
- Effect.map(Array.map((template) => `\n\n<blueprint>${template.content}</blueprint>`)),
143
- Effect.map(Array.reduce(options.systemPrompt ?? '', String.concat)),
144
- );
145
-
146
- // Build a combined toolkit from the blueprint tools and the provided toolkit.
147
- const blueprintToolkit = yield* ToolResolverService.resolveToolkit(blueprints.flatMap((bp) => bp.tools));
148
- const blueprintToolkitHandler: Context.Context<AiTool.ToHandler<AiTool.Any>> =
149
- yield* blueprintToolkit.toContext(yield* ToolExecutionService.handlersFor(blueprintToolkit));
150
- const toolkit = options.toolkit != null ? AiToolkit.merge(options.toolkit, blueprintToolkit) : blueprintToolkit;
151
- const toolkitWithBlueprintHandlers = yield* toolkit.pipe(
152
- Effect.provide(blueprintToolkitHandler) as any,
153
- ) as Effect.Effect<AiToolkit.ToHandler<any>, never, AiTool.ToHandler<Tools>>;
154
-
155
- log.info('run', {
156
- systemPrompt: [systemPrompt.slice(0, 32), '...', systemPrompt.slice(-32), systemPrompt.length].join(' '),
157
- tools: Object.keys(blueprintToolkit.tools),
158
- });
159
-
160
- const blocks = yield* AiLanguageModel.streamText({
161
- prompt,
162
- system: systemPrompt,
163
- toolkit: toolkitWithBlueprintHandlers,
164
- disableToolCallResolution: true,
165
- }).pipe(
166
- AiParser.parseGptStream({
167
- onBlock: (block) =>
168
- Effect.gen(this, function* () {
169
- if (block.pending) {
170
- this.update.emit(block);
171
- } else {
172
- this.block.emit(block);
173
- }
174
- }),
175
- onPart: (part) =>
176
- Effect.gen(this, function* () {
177
- this.streamEvent.emit(part);
178
- }),
179
- }),
180
- Stream.runCollect,
181
- Effect.map(Chunk.toArray),
182
- );
183
-
184
- const response = Obj.make(DataType.Message, {
185
- created: new Date().toISOString(),
186
- sender: { role: 'assistant' },
187
- blocks,
188
- });
189
- this._pending.push(response);
190
- this.message.emit(response);
191
-
192
- const toolCalls = getToolCalls(response);
193
- if (toolCalls.length === 0) {
194
- break;
195
- }
196
-
197
- const toolResults = yield* runTools(toolCalls, toolkitWithBlueprintHandlers as any);
198
- this._pending.push(
199
- Obj.make(DataType.Message, {
200
- created: new Date().toISOString(),
201
- sender: { role: 'user' },
202
- blocks: toolResults,
203
- }),
204
- );
205
- } while (true);
206
-
207
- return this._pending;
208
- }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));
209
-
210
- async runStructured<S extends Schema.Schema.AnyNoContext>(
211
- schema: S,
212
- options: SessionRunOptions<AiTool.Any>,
213
- ): Promise<Schema.Schema.Type<S>> {
214
- return todo();
215
- // const parser = structuredOutputParser(schema);
216
- // const result = await this.run({
217
- // ...options,
218
- // executableTools: [...(options.executableTools ?? []), parser.tool],
219
- // });
220
- // return parser.getResult(result);
221
- }
222
-
223
- private _formatUserPrompt = (prompt: string, history: DataType.Message[]) =>
224
- Effect.gen(function* () {
225
- const prelude: ContentBlock.Any[] = [];
226
-
227
- // TODO(dmaretskyi): Evaluate other approaches as `serviceOption` isn't represented in the type system.
228
- const artifactDiffResolver = yield* Effect.serviceOption(ArtifactDiffResolver);
229
- if (Option.isSome(artifactDiffResolver)) {
230
- const versions = gatherObjectVersions(history);
231
-
232
- const artifactDiff = yield* Effect.tryPromise({
233
- try: () =>
234
- artifactDiffResolver.value.resolve(
235
- [...versions.entries()].map(([id, version]) => ({ id, lastVersion: version })),
236
- ),
237
- catch: AiAssistantError.wrap('Artifact diff resolution error'),
238
- });
239
-
240
- log.info('vision', {
241
- artifactDiff,
242
- versions,
243
- });
244
-
245
- for (const [id, { version }] of [...artifactDiff.entries()]) {
246
- if (ObjectVersion.equals(version, versions.get(id)!)) {
247
- artifactDiff.delete(id);
248
- continue;
249
- }
250
-
251
- prelude.push({ _tag: 'anchor', objectId: id, version });
252
- }
253
- if (artifactDiff.size > 0) {
254
- prelude.push(createArtifactUpdateBlock(artifactDiff));
255
- }
256
- }
257
-
258
- return Obj.make(DataType.Message, {
259
- created: new Date().toISOString(),
260
- sender: { role: 'user' },
261
- blocks: [...prelude, { _tag: 'text', text: prompt }],
262
- });
263
- });
264
-
265
- abort(): void {
266
- this._stream?.abort();
267
- }
268
- }
269
-
270
- const gatherObjectVersions = (messages: DataType.Message[]): Map<ObjectId, ObjectVersion> => {
271
- const artifactIds = new Map<ObjectId, ObjectVersion>();
272
- for (const message of messages) {
273
- for (const block of message.blocks) {
274
- if (block._tag === 'anchor') {
275
- artifactIds.set(block.objectId, block.version as ObjectVersion);
276
- }
277
- }
278
- }
279
-
280
- return artifactIds;
281
- };
282
-
283
- const createArtifactUpdateBlock = (
284
- artifactDiff: Map<ObjectId, { version: ObjectVersion; diff?: string }>,
285
- ): ContentBlock.Any => {
286
- return {
287
- _tag: 'text',
288
- // TODO(dmaretskyi): Does this need to be a special content-block?
289
- disposition: 'artifact-update',
290
- text: `
291
- The following artifacts have been updated since the last message:
292
- ${[...artifactDiff.entries()]
293
- .map(([id, { diff }]) => `<changed-artifact id="${id}">${diff ? `\n${diff}` : ''}</changed-artifact>`)
294
- .join('\n')}
295
- `,
296
- };
297
- };
298
-
299
- /**
300
- * Resolves artifact ids to their versions.
301
- * Used to give the model a sense of the changes to the artifacts made by users during the conversation.
302
- * The artifacts versions are pinned in the history, and whenever the artifact changes in-between assistant's steps,
303
- * a diff is inserted into the conversation.
304
- *
305
- * Can be optionally provided to the session run call.
306
- */
307
- // TODO(dmaretskyi): Convert to Context.Reference
308
- export class ArtifactDiffResolver extends Context.Tag('ArtifactDiffResolver')<
309
- ArtifactDiffResolver,
310
- ArtifactDiffResolver.Service
311
- >() {}
312
-
313
- export namespace ArtifactDiffResolver {
314
- export type Service = {
315
- resolve: (artifacts: { id: ObjectId; lastVersion: ObjectVersion }[]) => Promise<
316
- Map<
317
- ObjectId,
318
- {
319
- version: ObjectVersion;
320
- diff?: string;
321
- }
322
- >
323
- >;
324
- };
325
- }
326
-
327
- const runTools: <Tools extends AiTool.Any>(
328
- toolCalls: ContentBlock.ToolCall[],
329
- toolkit: AiToolkit.AiToolkit<Tools>,
330
- ) => Effect.Effect<ContentBlock.ToolResult[], AiError.AiError, AiTool.ToHandler<Tools>> = Effect.fn('runTools')(
331
- function* (toolCalls, toolkit) {
332
- const toolkitWithHandlers = Effect.isEffect(toolkit) ? yield* toolkit : toolkit;
333
-
334
- return yield* Effect.forEach(toolCalls, (toolCall) => runTool(toolkitWithHandlers, toolCall));
335
- },
336
- );
@@ -1,7 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { describe } from 'vitest';
6
-
7
- describe('VersionPin', () => {});
@@ -1,208 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- // TODO(burdon): Fix.
6
- // @ts-nocheck
7
-
8
- import { pipe, Schema } from 'effect';
9
- import { beforeAll, describe, test } from 'vitest';
10
-
11
- import { AiService, MixedStreamParser } from '@dxos/ai';
12
- import { Obj } from '@dxos/echo';
13
- import { type EchoDatabase } from '@dxos/echo-db';
14
- import { EchoTestBuilder } from '@dxos/echo-db/testing';
15
- import { defineFunction, FunctionExecutor, ServiceContainer } from '@dxos/functions';
16
- import { type ContentBlock, DataType } from '@dxos/schema';
17
- import { createTestData } from '@dxos/schema/testing';
18
- import { trim } from '@dxos/util';
19
-
20
- const REMOTE_AI = true;
21
-
22
- const summarizationFn = defineFunction({
23
- description: 'Summarize a document',
24
- inputSchema: Schema.Struct({
25
- document: Schema.optional(DataType.Text),
26
- transcript: Schema.Array(DataType.Message),
27
- }),
28
- outputSchema: DataType.Text,
29
- handler: async ({ data: { document, transcript }, context }) => {
30
- const ai = context.getService(AiService);
31
- const result = await new MixedStreamParser().parse(
32
- await ai.client.execStream({
33
- model: '@anthropic/claude-3-5-haiku-20241022',
34
- // TODO(burdon): Factor out and test prompts.
35
- systemPrompt: trim`
36
- Your job is to summarize a meeting transcript.
37
- Transcript Summarizer updates an existing summary within <summary> tags with a new transcript that is placed in <transcript> tags.
38
- Transcript Summarizer updates only the relevant parts of the summary.
39
- If there's no summary, create a new one.
40
- Transcript Summarizer outputs only the summary texts and nothing else.
41
- Transcript Summarizer keeps the original summary structure.
42
- Transcript Summarizer keeps the unrelated parts of the summary untouched.
43
- The Transcript Summarizer errs on the side of being too verbose.
44
- The Transcript Summarizer outputs the entire update summary.
45
- The summary is formatted as hierarchical markdown bullet points with no headings.
46
- The hierarchical structure is deeply nested.
47
- The Transcript Summarizer formats the bullets with "-" symbol as prefix and two spaces indentation.
48
- The Transcript Summarizer knows that the content of transcript will be updated solely by its output.
49
- The Transcript Summarizer outputs only the summary text.
50
- `,
51
- history: [
52
- Obj.make(DataType.Message, {
53
- created: new Date().toISOString(),
54
- sender: { role: 'user' },
55
- blocks: [
56
- {
57
- _tag: 'text',
58
- text: trim`
59
- <transcript>
60
- ${JSON.stringify(transcript, null, 2)}
61
- </transcript>
62
- `,
63
- },
64
- ...(document != null && document.content.length > 0
65
- ? [
66
- {
67
- _tag: 'text',
68
- text: trim`
69
- <summary>
70
- ${document.content}
71
- </summary>
72
- `,
73
- } satisfies ContentBlock.Text,
74
- ]
75
- : []),
76
- ],
77
- }),
78
- ],
79
- }),
80
- );
81
- return Obj.make(DataType.Text, {
82
- content: pipe(result[0]?.blocks[0], (c) => (c?._tag === 'text' ? c.text : '')),
83
- });
84
- },
85
- });
86
-
87
- const refinementFn = defineFunction({
88
- description: 'Refine a summary',
89
- inputSchema: Schema.Struct({
90
- summaries: Schema.Array(DataType.Text),
91
- }),
92
- outputSchema: Schema.Struct({
93
- summary: DataType.Text,
94
- }),
95
- handler: async ({ data: { summaries }, context }) => {
96
- const ai = context.getService(AiService);
97
- const result = await new MixedStreamParser().parse(
98
- await ai.client.execStream({
99
- model: '@anthropic/claude-3-5-haiku-20241022',
100
- // TODO(burdon): Factor out and test prompts.
101
- systemPrompt: trim`
102
- You are a Transcript Summary Refiner.
103
- Transcript Summary Refiner works on a history of evolving summaries that were generated based on the transcript.
104
- The summaries are presented starting from the oldest to the newest.
105
- Each iteration of the summary contains a new part of the transcript.
106
- The Transcript Summary Refiner refines the summary based on the history of summaries.
107
- The Transcript Summary Refiner identifies any potential data lost between the iterations and adds its back to the output.
108
- The Transcript Summary Refiner updates the summary to be more structured.
109
- The Transcript Summary Refiner errs on the side of being too verbose.
110
- The Transcript Summary Refiner errs on keeping the original summary structure.
111
- The Transcript Summary Refiner outputs the entire update summary.
112
- The Transcript Summary is formatted as hierarchical markdown bullet points with no headings.
113
- The hierarchical structure is deeply nested.
114
- The Transcript Summary Refiner formats the bullets with "-" symbol as prefix and two spaces indentation.
115
- The Transcript Summary Refiner knows that the content of transcript will be updated solely by its output.
116
- The Transcript Summary Refiner outputs only the summary text.
117
- `,
118
- history: [
119
- Obj.make(DataType.Message, {
120
- created: new Date().toISOString(),
121
- sender: { role: 'user' },
122
- blocks: summaries.map(
123
- (summary) =>
124
- ({
125
- _tag: 'text',
126
- text: trim`
127
- <summary>
128
- ${summary.content}
129
- </summary>
130
- `,
131
- }) satisfies ContentBlock.Text,
132
- ),
133
- }),
134
- ],
135
- }),
136
- );
137
- return {
138
- summary: Obj.make(DataType.Text, {
139
- content: pipe(result[0]?.blocks[0], (c) => (c?._tag === 'text' ? c.text : '')),
140
- }),
141
- };
142
- },
143
- });
144
-
145
- describe.skip('Summarization', () => {
146
- let builder: EchoTestBuilder;
147
- let db: EchoDatabase;
148
- let executor: FunctionExecutor;
149
-
150
- // TODO(burdon): Rewrite test.
151
- beforeAll(async () => {
152
- // TODO(dmaretskyi): Helper to scaffold this from a config.
153
- builder = await new EchoTestBuilder().open();
154
- const { db: db1 } = await builder.createDatabase({ indexing: { vector: true } });
155
- db = db1;
156
- executor = new FunctionExecutor(
157
- new ServiceContainer().setServices({
158
- ai: todo(),
159
- database: {
160
- db,
161
- },
162
- }),
163
- );
164
- });
165
-
166
- test('keeps transcript outline', { timeout: 1000_000 }, async () => {
167
- const { transcriptMessages } = createTestData();
168
-
169
- const summary = Obj.make(DataType.Text, {
170
- content: '',
171
- });
172
-
173
- const summaries = [];
174
-
175
- for (let i = 0; i < transcriptMessages.length; i++) {
176
- const blocks = transcriptMessages.slice(Math.max(0, i - 2), i + 1);
177
- const result = await executor.invoke(summarizationFn, {
178
- document: summary,
179
- transcript: blocks,
180
- });
181
- summary.content = result.content;
182
- summaries.push(Obj.make(DataType.Text, { content: result.content }));
183
-
184
- console.log(blocks.at(-1));
185
- console.log();
186
- console.log('--------------------------------');
187
- console.log();
188
- console.log(summary.content);
189
- console.log();
190
-
191
- if (i % 3 === 0 && i > 0) {
192
- const history: any = summaries.slice(-5);
193
- const result = await executor.invoke(refinementFn, {
194
- summaries: history,
195
- });
196
- summary.content = result.summary.content;
197
- summaries.push(Obj.make(DataType.Text, { content: result.summary.content }));
198
-
199
- console.log('REFINED');
200
- console.log();
201
- console.log('--------------------------------');
202
- console.log();
203
- console.log(summary.content);
204
- console.log();
205
- }
206
- }
207
- });
208
- });
@@ -1,111 +0,0 @@
1
- {{! System Prompt }}
2
-
3
- You are a friendly, advanced AI assistant capable of creating and managing artifacts from available data and tools.
4
- Your task is to process user commands and questions and decide how best to respond.
5
- In some cases, you will need to create or reference data objects called artifacts.
6
-
7
- Follow these guidelines carefully:
8
-
9
- {{section}}. Decision-making:
10
-
11
- {{#if cot}}
12
- Before responding, explain your reasoning and include your detailed chain-of-thought in a <cot> tag.
13
- {{/if}}
14
-
15
- Include the following steps:
16
-
17
- - Analyze the structure and type of the content in the user's message.
18
- - Can you complete the task using the available artifact definitions?
19
- - If you can't complete the task using the available artifact definitions, query the list of available artifact definitions using the appropriate tool.
20
- - Identify which artifact definitions are relevant to the user's request.
21
- - Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.
22
- - Make a final decision on whether to create an artifact and explain your reasoning.
23
- - Are the required artifact definitions already available?
24
- - If not, select which artifact definition(s) will be the most relevant and require them using the require_artifact_definitions tool.
25
- - The require'd artifact tools will be available for use after require.
26
- - If creating an artifact, outline how you will structure it within the response.
27
- - Decide if the artifact needs to be shown to the user.
28
- - Call the show tool to show the artifact to the user.
29
- - If you ask the user a multiple choice question, then present each of the possible answers as concise text inside <option> tags inside a well formed <select> tag.
30
- - If you have suggestions for follow-up actions then present each action as text within a <suggest> tag.
31
- - Your reasoning must include: whether to use artifacts or not, to create one or query, whether to show the artifact to the user, and how to structure the response.
32
-
33
- If the user asks for a list of tools, then just emit a single self-closing <tool-list/> tag instead of listing the tools.The tag will be replaced with the list of tools when the response is rendered.
34
- Do not list the tools or artifacts in your response, only emit the tag.
35
- Do not mention the tag anywhere else in your response unless you are rendering a tool list.
36
-
37
- {{section}}. Artifacts:
38
-
39
- - Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.
40
- - Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.
41
- - If it is ambiguous, query for existing artifacts first and then decide.
42
- - If you decide to create an artifact, call the associated tool to create the artifact.
43
- - Artifacts are stored in the database. Tools are used to create and query artifacts.
44
- - If you are unsure about creating an artifact ask the user for clarification.
45
-
46
- {{#if artifacts}}
47
- {{section}}. Artifact Rules:
48
-
49
- - Artifacts are mutable objects that can change over the course of the conversation.
50
- - Always re-query the artifact using the tool (like query or inspect) to get the latest state of the artifact before answering the user.
51
- - You must never generate the id of the artifact; only recall the ids that are already in the history.
52
- - Artifacts are created by requiring the specific artifact using the require_artifact tool and creating it by calling the associated tool.
53
-
54
- {{section}}. Artifact Providers:
55
-
56
- {{#each artifacts}}
57
- - {{this}}
58
- {{/each}}
59
- {{/if}}
60
-
61
- {{#if associatedArtifact}}
62
- {{section}}. Associated artifact:
63
-
64
- The following ID and typename identify the artifact associated with this conversation.
65
- This conversation appears alongside the associated artifact as a peer, and the user is likely to make reference to and requests about it.
66
- You can interact with this artifact using tools.
67
-
68
- ID: {{associatedArtifact.id}}
69
- Typename: {{associatedArtifact.typename}}
70
- {{/if}}
71
-
72
- {{#if suggestions}}
73
- {{section}}. Suggested actions:
74
-
75
- - You can add suggested actions at the end of your response.
76
- - Suggested actions should be very concise and start with a verb and be phrased as a command to an agent -- not a question to the user.
77
- - Suggested actions must be in the form of a user instruction that you can follow.
78
- - Suggested actions could include actions that create artifacts.
79
- - Suggested actions must be enclosed in a <suggest> tag and on a separate line.
80
- Examples:
81
- <suggest>Show the data on a map.</suggest>
82
- <suggest>Create a kanban from the table.</suggest>
83
-
84
- - If you have asked a multiple choice question, then present each of the possible answers as concise text inside <option> tags inside a well formed <select> tag.
85
- Example:
86
- <select><option>Yes</option><option>No</option></select>
87
- {{/if}}
88
-
89
- {{section}}. Content proposals:
90
-
91
- You can propose content to add to associated artifacts. Enclose the content you are proposing to add in a <proposal> tag on a separate line.
92
- For example:
93
- <proposal>Apples add a delightful crunch and natural sweetness to salads</proposal>
94
-
95
- {{section}}. Output Formats:
96
-
97
- It is very important to respond in the correct format.
98
-
99
- {{#if cot}}
100
- - Your detailed chain-of-thought must be in the form of a markdown list enclosed in <cot> tags.
101
- - The <cot> tag should be the first thing in your response.
102
- {{/if}}
103
- - Suggested actions must be enclosed in a <suggest> tag and on a separate line.
104
- - Content proposals must be enclosed in a <proposal> tag and on a separate line.
105
-
106
- References:
107
-
108
- - Both user and you can reference external data in the markdown format: [label][URI].
109
- - If you get references back from a tool call, you can render them as is by preserving the ID literally.
110
-
111
- {{instructions}}