@dxos/assistant 0.8.4-main.fd6878d → 0.8.4-staging.60fe92afc8

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 (183) 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/extraction/index.mjs +208 -0
  5. package/dist/lib/neutral/extraction/index.mjs.map +7 -0
  6. package/dist/lib/neutral/index.mjs +1886 -0
  7. package/dist/lib/neutral/index.mjs.map +7 -0
  8. package/dist/lib/neutral/meta.json +1 -0
  9. package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
  10. package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
  11. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  12. package/dist/types/src/extraction/extraction.d.ts +1650 -281
  13. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  14. package/dist/types/src/extraction/index.d.ts +0 -1
  15. package/dist/types/src/extraction/index.d.ts.map +1 -1
  16. package/dist/types/src/extraction/quotes.d.ts +3 -3
  17. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  18. package/dist/types/src/functions/services.d.ts +16 -5
  19. package/dist/types/src/functions/services.d.ts.map +1 -1
  20. package/dist/types/src/index.d.ts +2 -3
  21. package/dist/types/src/index.d.ts.map +1 -1
  22. package/dist/types/src/request/AiRequest.d.ts +308 -0
  23. package/dist/types/src/request/AiRequest.d.ts.map +1 -0
  24. package/dist/types/src/{session → request}/artifact-diff.d.ts +5 -5
  25. package/dist/types/src/request/artifact-diff.d.ts.map +1 -0
  26. package/dist/types/src/request/format.d.ts +15 -0
  27. package/dist/types/src/request/format.d.ts.map +1 -0
  28. package/dist/types/src/request/index.d.ts +4 -0
  29. package/dist/types/src/request/index.d.ts.map +1 -0
  30. package/dist/types/src/request/observer.d.ts +23 -0
  31. package/dist/types/src/request/observer.d.ts.map +1 -0
  32. package/dist/types/src/{session → request}/version-pin.d.ts +6 -6
  33. package/dist/types/src/request/version-pin.d.ts.map +1 -0
  34. package/dist/types/src/session/AiContext.d.ts +178 -0
  35. package/dist/types/src/session/AiContext.d.ts.map +1 -0
  36. package/dist/types/src/session/AiContext.test.d.ts +2 -0
  37. package/dist/types/src/session/AiContext.test.d.ts.map +1 -0
  38. package/dist/types/src/session/AiSession.d.ts +79 -0
  39. package/dist/types/src/session/AiSession.d.ts.map +1 -0
  40. package/dist/types/src/session/AiSession.test.d.ts +2 -0
  41. package/dist/types/src/session/AiSession.test.d.ts.map +1 -0
  42. package/dist/types/src/session/SessionLink.d.ts +17 -0
  43. package/dist/types/src/session/SessionLink.d.ts.map +1 -0
  44. package/dist/types/src/session/SessionLoader.d.ts +15 -0
  45. package/dist/types/src/session/SessionLoader.d.ts.map +1 -0
  46. package/dist/types/src/session/SessionLoader.test.d.ts +2 -0
  47. package/dist/types/src/session/SessionLoader.test.d.ts.map +1 -0
  48. package/dist/types/src/session/index.d.ts +5 -3
  49. package/dist/types/src/session/index.d.ts.map +1 -1
  50. package/dist/types/src/session/toolkit.d.ts +16 -0
  51. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  52. package/dist/types/src/templates/system.d.ts +19 -14
  53. package/dist/types/src/templates/system.d.ts.map +1 -1
  54. package/dist/types/src/util/artifact.d.ts +18 -0
  55. package/dist/types/src/util/artifact.d.ts.map +1 -0
  56. package/dist/types/src/util/diff.d.ts +17 -0
  57. package/dist/types/src/util/diff.d.ts.map +1 -0
  58. package/dist/types/src/util/diff.test.d.ts +2 -0
  59. package/dist/types/src/util/diff.test.d.ts.map +1 -0
  60. package/dist/types/src/util/error-handling.d.ts +4 -0
  61. package/dist/types/src/util/error-handling.d.ts.map +1 -0
  62. package/dist/types/src/util/errors.d.ts +67 -0
  63. package/dist/types/src/util/errors.d.ts.map +1 -0
  64. package/dist/types/src/util/execution-graph.d.ts +85 -0
  65. package/dist/types/src/util/execution-graph.d.ts.map +1 -0
  66. package/dist/types/src/util/execution-graph.test.d.ts +2 -0
  67. package/dist/types/src/util/execution-graph.test.d.ts.map +1 -0
  68. package/dist/types/src/util/index.d.ts +7 -0
  69. package/dist/types/src/util/index.d.ts.map +1 -0
  70. package/dist/types/src/util/tracing.d.ts +296 -0
  71. package/dist/types/src/util/tracing.d.ts.map +1 -0
  72. package/dist/types/tsconfig.tsbuildinfo +1 -1
  73. package/package.json +37 -47
  74. package/src/extraction/extraction-ner-function/index.ts +0 -1
  75. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  76. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  77. package/src/extraction/extraction.ts +49 -19
  78. package/src/extraction/index.ts +0 -1
  79. package/src/extraction/quotes.test.ts +2 -2
  80. package/src/extraction/quotes.ts +7 -9
  81. package/src/functions/services.ts +180 -66
  82. package/src/index.ts +2 -3
  83. package/src/request/AiRequest.ts +387 -0
  84. package/src/{session → request}/artifact-diff.ts +10 -6
  85. package/src/{session → request}/format.ts +45 -37
  86. package/src/request/index.ts +8 -0
  87. package/src/request/observer.ts +62 -0
  88. package/src/{session → request}/version-pin.ts +8 -8
  89. package/src/session/AiContext.test.ts +49 -0
  90. package/src/session/AiContext.ts +420 -0
  91. package/src/session/AiSession.test.ts +111 -0
  92. package/src/session/AiSession.ts +328 -0
  93. package/src/session/SessionLink.ts +23 -0
  94. package/src/session/SessionLoader.test.ts +115 -0
  95. package/src/session/SessionLoader.ts +55 -0
  96. package/src/session/index.ts +6 -3
  97. package/src/session/toolkit.ts +47 -0
  98. package/src/templates/{format.tpl → instructions/format.tpl} +6 -4
  99. package/src/templates/instructions/system.tpl +96 -0
  100. package/src/templates/system.ts +26 -16
  101. package/src/util/artifact.ts +96 -0
  102. package/src/util/diff.test.ts +74 -0
  103. package/src/util/diff.ts +93 -0
  104. package/src/util/error-handling.ts +42 -0
  105. package/src/util/errors.ts +15 -0
  106. package/src/util/execution-graph.test.ts +740 -0
  107. package/src/util/execution-graph.ts +520 -0
  108. package/src/util/index.ts +10 -0
  109. package/src/util/tracing.ts +60 -0
  110. package/dist/lib/browser/chunk-6WRGDEMH.mjs +0 -89
  111. package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +0 -7
  112. package/dist/lib/browser/chunk-NZGGCEF3.mjs +0 -341
  113. package/dist/lib/browser/chunk-NZGGCEF3.mjs.map +0 -7
  114. package/dist/lib/browser/extraction/index.mjs +0 -269
  115. package/dist/lib/browser/extraction/index.mjs.map +0 -7
  116. package/dist/lib/browser/index.mjs +0 -354
  117. package/dist/lib/browser/index.mjs.map +0 -7
  118. package/dist/lib/browser/meta.json +0 -1
  119. package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +0 -13
  120. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +0 -91
  121. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +0 -7
  122. package/dist/lib/node-esm/chunk-XOOPGSGW.mjs +0 -343
  123. package/dist/lib/node-esm/chunk-XOOPGSGW.mjs.map +0 -7
  124. package/dist/lib/node-esm/extraction/index.mjs +0 -270
  125. package/dist/lib/node-esm/extraction/index.mjs.map +0 -7
  126. package/dist/lib/node-esm/index.mjs +0 -355
  127. package/dist/lib/node-esm/index.mjs.map +0 -7
  128. package/dist/lib/node-esm/meta.json +0 -1
  129. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +0 -14
  130. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs.map +0 -7
  131. package/dist/types/src/conversation/context.d.ts +0 -90
  132. package/dist/types/src/conversation/context.d.ts.map +0 -1
  133. package/dist/types/src/conversation/conversation.d.ts +0 -50
  134. package/dist/types/src/conversation/conversation.d.ts.map +0 -1
  135. package/dist/types/src/conversation/index.d.ts +0 -3
  136. package/dist/types/src/conversation/index.d.ts.map +0 -1
  137. package/dist/types/src/errors.d.ts +0 -39
  138. package/dist/types/src/errors.d.ts.map +0 -1
  139. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
  140. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
  141. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
  142. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
  143. package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
  144. package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
  145. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -306
  146. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
  147. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
  148. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
  149. package/dist/types/src/session/artifact-diff.d.ts.map +0 -1
  150. package/dist/types/src/session/format.d.ts +0 -168
  151. package/dist/types/src/session/format.d.ts.map +0 -1
  152. package/dist/types/src/session/format.test.d.ts +0 -2
  153. package/dist/types/src/session/format.test.d.ts.map +0 -1
  154. package/dist/types/src/session/session.d.ts +0 -167
  155. package/dist/types/src/session/session.d.ts.map +0 -1
  156. package/dist/types/src/session/session.test.d.ts +0 -2
  157. package/dist/types/src/session/session.test.d.ts.map +0 -1
  158. package/dist/types/src/session/version-pin.d.ts.map +0 -1
  159. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  160. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  161. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  162. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  163. package/dist/types/src/types.d.ts +0 -16
  164. package/dist/types/src/types.d.ts.map +0 -1
  165. package/src/conversation/context.ts +0 -133
  166. package/src/conversation/conversation.ts +0 -125
  167. package/src/conversation/index.ts +0 -6
  168. package/src/errors.ts +0 -10
  169. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
  170. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -71
  171. package/src/extraction/extraction-llm-function/index.ts +0 -5
  172. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -116
  173. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -57
  174. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  175. package/src/session/format.test.ts +0 -60
  176. package/src/session/session.test.ts +0 -305
  177. package/src/session/session.ts +0 -279
  178. package/src/session/version-pin.test.ts +0 -7
  179. package/src/summarization/summarization.test.ts +0 -197
  180. package/src/templates/system.tpl +0 -47
  181. package/src/types.ts +0 -52
  182. /package/dist/lib/{browser/named-entity-recognition-O46UTCLR.mjs.map → neutral/chunk-J5LGTIGS.mjs.map} +0 -0
  183. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -1,279 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
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';
7
-
8
- import {
9
- type AiInputPreprocessingError,
10
- AiParser,
11
- AiPreprocessor,
12
- type AiToolNotFoundError,
13
- type ConsolePrinter,
14
- ToolExecutionService,
15
- ToolResolverService,
16
- callTools,
17
- getToolCalls,
18
- } from '@dxos/ai';
19
- import { type Blueprint } from '@dxos/blueprints';
20
- import { todo } from '@dxos/debug';
21
- import { Obj } from '@dxos/echo';
22
- import { log } from '@dxos/log';
23
- import { type ContentBlock, DataType } from '@dxos/schema';
24
- import { isNotFalsy } from '@dxos/util';
25
-
26
- import { type AiAssistantError } from '../errors';
27
-
28
- import { formatSystemPrompt, formatUserPrompt } from './format';
29
-
30
- export type AiSessionOptions = {};
31
-
32
- /**
33
- * Live observer of the generation process.
34
- */
35
- export interface GenerationObserver {
36
- /**
37
- * Unparsed content block parts from the model.
38
- */
39
- onPart: (part: AiResponse.Part) => Effect.Effect<void>;
40
-
41
- /**
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!"}
50
- */
51
- onBlock: (block: ContentBlock.Any) => Effect.Effect<void>;
52
-
53
- /**
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.
56
- */
57
- onMessage: (message: DataType.Message) => Effect.Effect<void>;
58
- }
59
-
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(),
72
-
73
- /**
74
- * Debug printer to be used in unit-tests and browser devtools.
75
- */
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
- });
94
-
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
- };
104
-
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>());
118
-
119
- // TODO(dmaretskyi): Remove the queues and convert everything to observer.
120
-
121
- /**
122
- * Blocks streaming from the model during the session.
123
- * @deprecated Use `observer.onBlock` instead.
124
- */
125
- public readonly blockQueue = Effect.runSync(Queue.unbounded<Option.Option<ContentBlock.Any>>());
126
-
127
- /** Unparsed events from the underlying generation stream. */
128
- public readonly eventQueue = Effect.runSync(Queue.unbounded<AiResponse.Part>());
129
-
130
- /** Prevents concurrent execution of session. */
131
- private readonly _semaphore = Effect.runSync(Effect.makeSemaphore(1));
132
-
133
- /** Pending messages (incl. the current user request). */
134
- private _pending: DataType.Message[] = [];
135
-
136
- /** Prior history from queue. */
137
- private _history: DataType.Message[] = [];
138
-
139
- constructor(private readonly _options: AiSessionOptions = {}) {}
140
-
141
- /**
142
- * Runs the AI model loop interacting with tools and artifacts.
143
- * @returns The messages generated by the session, including the user's prompt.
144
- */
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.
173
- do {
174
- log.info('request', {
175
- prompt: promptMessages,
176
- system: { snippet: [system.slice(0, 32), '...', system.slice(-32)].join(''), length: system.length },
177
- pending: this._pending.length,
178
- history: this._history.length,
179
- objects: params.objects?.length ?? 0,
180
- blueprints: params.blueprints?.length ?? 0,
181
- toolkit: Object.values(toolkit.tools).map((tool: AiTool.Any) => tool.name),
182
- });
183
-
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
- );
203
-
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,
215
- });
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;
224
- }
225
-
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
- });
233
-
234
- this._pending.push(toolResultsMessage);
235
- yield* this.messageQueue.offer(toolResultsMessage);
236
- yield* observer.onMessage(toolResultsMessage);
237
- } while (true);
238
-
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);
243
-
244
- log('done', { pending: this._pending.length });
245
- return this._pending;
246
- }).pipe(this._semaphore.withPermits(1), Effect.withSpan('AiSession.run'));
247
-
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);
260
- }
261
- }
262
-
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
- });
@@ -1,7 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { describe } from 'vitest';
6
-
7
- describe('VersionPin', () => {});
@@ -1,197 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- // ISSUE(burdon): defineFunction
6
- // @ts-nocheck
7
-
8
- import { Schema, pipe } 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 { FunctionExecutor, ServiceContainer, defineFunction } 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 summarizationFn = defineFunction({
21
- description: 'Summarize a document',
22
- inputSchema: Schema.Struct({
23
- document: Schema.optional(DataType.Text),
24
- transcript: Schema.Array(DataType.Message),
25
- }),
26
- outputSchema: DataType.Text,
27
- handler: async ({ data: { document, transcript }, context }) => {
28
- const ai = context.getService(AiService.AiService);
29
- const result = await new MixedStreamParser().parse(
30
- await ai.client.execStream({
31
- model: '@anthropic/claude-3-5-haiku-20241022',
32
- // TODO(burdon): Factor out and test prompts.
33
- systemPrompt: trim`
34
- Your job is to summarize a meeting transcript.
35
- Transcript Summarizer updates an existing summary within <summary> tags with a new transcript that is placed in <transcript> tags.
36
- Transcript Summarizer updates only the relevant parts of the summary.
37
- If there's no summary, create a new one.
38
- Transcript Summarizer outputs only the summary texts and nothing else.
39
- Transcript Summarizer keeps the original summary structure.
40
- Transcript Summarizer keeps the unrelated parts of the summary untouched.
41
- The Transcript Summarizer errs on the side of being too verbose.
42
- The Transcript Summarizer outputs the entire update summary.
43
- The summary is formatted as hierarchical markdown bullet points with no headings.
44
- The hierarchical structure is deeply nested.
45
- The Transcript Summarizer formats the bullets with "-" symbol as prefix and two spaces indentation.
46
- The Transcript Summarizer knows that the content of transcript will be updated solely by its output.
47
- The Transcript Summarizer outputs only the summary text.
48
- `,
49
- history: [
50
- Obj.make(DataType.Message, {
51
- created: new Date().toISOString(),
52
- sender: { role: 'user' },
53
- blocks: [
54
- {
55
- _tag: 'text',
56
- text: trim`
57
- <transcript>
58
- ${JSON.stringify(transcript, null, 2)}
59
- </transcript>
60
- `,
61
- },
62
- ...(document != null && document.content.length > 0
63
- ? [
64
- {
65
- _tag: 'text',
66
- text: trim`
67
- <summary>
68
- ${document.content}
69
- </summary>
70
- `,
71
- } satisfies ContentBlock.Text,
72
- ]
73
- : []),
74
- ],
75
- }),
76
- ],
77
- }),
78
- );
79
-
80
- return DataType.makeText(pipe(result[0]?.blocks[0], (c) => (c?._tag === 'text' ? c.text : '')));
81
- },
82
- });
83
-
84
- const refinementFn = defineFunction({
85
- description: 'Refine a summary',
86
- inputSchema: Schema.Struct({
87
- summaries: Schema.Array(DataType.Text),
88
- }),
89
- outputSchema: Schema.Struct({
90
- summary: DataType.Text,
91
- }),
92
- handler: async ({ data: { summaries }, context }) => {
93
- const ai = context.getService(AiService.AiService);
94
- const result = await new MixedStreamParser().parse(
95
- await ai.client.execStream({
96
- model: '@anthropic/claude-3-5-haiku-20241022',
97
- // TODO(burdon): Factor out and test prompts.
98
- systemPrompt: trim`
99
- You are a Transcript Summary Refiner.
100
- Transcript Summary Refiner works on a history of evolving summaries that were generated based on the transcript.
101
- The summaries are presented starting from the oldest to the newest.
102
- Each iteration of the summary contains a new part of the transcript.
103
- The Transcript Summary Refiner refines the summary based on the history of summaries.
104
- The Transcript Summary Refiner identifies any potential data lost between the iterations and adds its back to the output.
105
- The Transcript Summary Refiner updates the summary to be more structured.
106
- The Transcript Summary Refiner errs on the side of being too verbose.
107
- The Transcript Summary Refiner errs on keeping the original summary structure.
108
- The Transcript Summary Refiner outputs the entire update summary.
109
- The Transcript Summary is formatted as hierarchical markdown bullet points with no headings.
110
- The hierarchical structure is deeply nested.
111
- The Transcript Summary Refiner formats the bullets with "-" symbol as prefix and two spaces indentation.
112
- The Transcript Summary Refiner knows that the content of transcript will be updated solely by its output.
113
- The Transcript Summary Refiner outputs only the summary text.
114
- `,
115
- history: [
116
- Obj.make(DataType.Message, {
117
- created: new Date().toISOString(),
118
- sender: { role: 'user' },
119
- blocks: summaries.map(
120
- (summary) =>
121
- ({
122
- _tag: 'text',
123
- text: trim`
124
- <summary>
125
- ${summary.content}
126
- </summary>
127
- `,
128
- }) satisfies ContentBlock.Text,
129
- ),
130
- }),
131
- ],
132
- }),
133
- );
134
- return {
135
- summary: DataType.makeText(pipe(result[0]?.blocks[0], (c) => (c?._tag === 'text' ? c.text : ''))),
136
- };
137
- },
138
- });
139
-
140
- describe.skip('Summarization', () => {
141
- let builder: EchoTestBuilder;
142
- let db: EchoDatabase;
143
- let executor: FunctionExecutor;
144
-
145
- // TODO(burdon): Rewrite test.
146
- beforeAll(async () => {
147
- // TODO(dmaretskyi): Helper to scaffold this from a config.
148
- builder = await new EchoTestBuilder().open();
149
- const { db: db1 } = await builder.createDatabase({ indexing: { vector: true } });
150
- db = db1;
151
- executor = new FunctionExecutor(
152
- new ServiceContainer().setServices({
153
- ai: todo(),
154
- database: {
155
- db,
156
- },
157
- }),
158
- );
159
- });
160
-
161
- test('keeps transcript outline', { timeout: 1000_000 }, async () => {
162
- const { transcriptMessages } = createTestData();
163
-
164
- const summary = DataType.makeText();
165
-
166
- const summaries = [];
167
-
168
- for (let i = 0; i < transcriptMessages.length; i++) {
169
- const blocks = transcriptMessages.slice(Math.max(0, i - 2), i + 1);
170
- const result = await executor.invoke(summarizationFn, {
171
- document: summary,
172
- transcript: blocks,
173
- });
174
- summary.content = result.content;
175
- summaries.push(DataType.makeText(result.content));
176
-
177
- console.log(blocks.at(-1));
178
- console.log();
179
- console.log(summary.content);
180
- console.log();
181
-
182
- if (i % 3 === 0 && i > 0) {
183
- const history: any = summaries.slice(-5);
184
- const result = await executor.invoke(refinementFn, {
185
- summaries: history,
186
- });
187
- summary.content = result.summary.content;
188
- summaries.push(DataType.makeText(result.summary.content));
189
-
190
- console.log('REFINED');
191
- console.log();
192
- console.log(summary.content);
193
- console.log();
194
- }
195
- }
196
- });
197
- });
@@ -1,47 +0,0 @@
1
- {{! System Prompt }}
2
-
3
- You are a helpful assistant called Kai.
4
- Your name is Kai and you are powered by different language models.
5
- You were created by DXOS and operate in Composer and on the DXOS EDGE network.
6
- In your initial greeting state your name and make some suggestions based on the current context objects.
7
-
8
- You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.
9
- Your task is to process user commands and questions and decide how best to respond.
10
- In general be concise and direct.
11
-
12
- Follow these guidelines carefully:
13
-
14
- Include the following steps:
15
-
16
- - Analyze the structure and type of the content in the user's message.
17
- - Determine if you complete the task using the available blueprint definitions?
18
- - If you can't complete the task using the available blueprint definitions, query the list of available blueprint definitions using the appropriate tool.
19
- - Identify which blueprint definitions are relevant to the user's request.
20
- - Evaluate the potential benefits of creating an artifact vs. normal processing for each identified element.
21
- - Make a final decision on whether to create an artifact and explain your reasoning.
22
- - Are the required blueprint definitions already available?
23
- - If not, select which blueprint definition(s) will be the most relevant and require them using the require_artifact_definitions tool.
24
- - The require'd artifact tools will be available for use after require.
25
- - If creating an artifact, outline how you will structure it within the response.
26
- - Decide if the artifact needs to be shown to the user.
27
- - Call the show tool to show the artifact to the user.
28
- - 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.
29
-
30
- # Blueprints
31
-
32
- - Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.
33
- - Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.
34
- - If it is ambiguous, query for existing artifacts first and then decide.
35
- - If you decide to create an artifact, call the associated tool to create the artifact.
36
- - Artifacts are stored in the database. Tools are used to create and query artifacts.
37
- - If you are unsure about creating an artifact ask the user for clarification.
38
-
39
- - Artifacts are mutable objects that can change over the course of the conversation.
40
- - Always re-query the artifact using the tool (like query or inspect) to get the latest state of the artifact before answering the user.
41
- - You must never generate the id of the artifact; only recall the ids that are already in the history.
42
- - Artifacts are created by requiring the specific artifact using the require_artifact tool and creating it by calling the associated tool.
43
-
44
- - You can add suggested actions at the end of your response.
45
- - 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.
46
- - Suggested actions must be in the form of a user instruction that you can follow.
47
- - Suggested actions could include actions that create artifacts.
package/src/types.ts DELETED
@@ -1,52 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Schema } from 'effect';
6
-
7
- import { type ObjectId } from '@dxos/echo-schema';
8
- import { DXN, LOCAL_SPACE_TAG, type SpaceId } from '@dxos/keys';
9
- import { trim } from '@dxos/util';
10
-
11
- /**
12
- * @deprecated
13
- */
14
- export const createArtifactElement = (id: ObjectId) => `<artifact id=${id} />`;
15
-
16
- /**
17
- * A model-friendly way to reference an object.
18
- * Supports vairous formats that will be normalized to a DXN.
19
- */
20
- // TODO(burdon): Rename ObjectReference?
21
- export const ArtifactId: Schema.Schema<string> & {
22
- toDXN: (reference: ArtifactId, owningSpaceId?: SpaceId) => DXN;
23
- } = class extends Schema.String.annotations({
24
- description: trim`
25
- The ID of the referenced object. Formats accepted:
26
- - DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.
27
- - space ID, object ID tuple (spaceID:objectID)
28
- - Only object ID that is assumed to be in the current space (XXXXX)
29
- `,
30
- examples: ['dxn:echo:@:XXXXX', '@dxn:echo:@:XXXXX', 'spaceID:objectID', 'XXXXX'],
31
- }) {
32
- static toDXN(reference: ArtifactId, owningSpaceId?: SpaceId): DXN {
33
- // Allow @dxn: prefix for compatibility with in-text references.
34
- if (reference.startsWith('@dxn:')) {
35
- return DXN.parse(reference.slice(1));
36
- } else if (reference.startsWith('dxn:')) {
37
- return DXN.parse(reference);
38
- } else if (/^[A-Z0-9]+:[A-Z0-9]+$/.test(reference)) {
39
- const [spaceId, objectId] = reference.split(':');
40
- // This is a workaround because the current Filter API doesn't work with fully qualified Echo DXNs.
41
- // We check if the space ID is the same as the owning space and then use LOCAL_SPACE_TAG for local references.
42
- // TODO(dmaretskyi): Fix this in the Echo and Filter API to properly handle fully qualified DXNs.
43
- return new DXN(DXN.kind.ECHO, [spaceId === owningSpaceId ? LOCAL_SPACE_TAG : spaceId, objectId]);
44
- } else if (/^[A-Z0-9]+$/.test(reference)) {
45
- return DXN.fromLocalObjectId(reference);
46
- } else {
47
- throw new Error(`Unable to parse object reference: ${reference}`);
48
- }
49
- }
50
- };
51
-
52
- export type ArtifactId = Schema.Schema.Type<typeof ArtifactId>;