@dxos/assistant 0.8.4-main.fd6878d → 0.8.4-main.fffef41

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 (122) hide show
  1. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  2. package/dist/lib/browser/extraction/index.mjs +121 -165
  3. package/dist/lib/browser/extraction/index.mjs.map +4 -4
  4. package/dist/lib/browser/index.mjs +1097 -161
  5. package/dist/lib/browser/index.mjs.map +4 -4
  6. package/dist/lib/browser/meta.json +1 -1
  7. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  8. package/dist/lib/node-esm/extraction/index.mjs +121 -165
  9. package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
  10. package/dist/lib/node-esm/index.mjs +1097 -161
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/types/src/conversation/context.d.ts +23 -10
  14. package/dist/types/src/conversation/context.d.ts.map +1 -1
  15. package/dist/types/src/conversation/conversation.d.ts +22 -31
  16. package/dist/types/src/conversation/conversation.d.ts.map +1 -1
  17. package/dist/types/src/diff.d.ts +15 -0
  18. package/dist/types/src/diff.d.ts.map +1 -0
  19. package/dist/types/src/diff.test.d.ts +2 -0
  20. package/dist/types/src/diff.test.d.ts.map +1 -0
  21. package/dist/types/src/errors.d.ts +45 -13
  22. package/dist/types/src/errors.d.ts.map +1 -1
  23. package/dist/types/src/execution-graph.d.ts +85 -0
  24. package/dist/types/src/execution-graph.d.ts.map +1 -0
  25. package/dist/types/src/execution-graph.test.d.ts +2 -0
  26. package/dist/types/src/execution-graph.test.d.ts.map +1 -0
  27. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
  28. package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
  29. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +82 -43
  30. package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +1 -1
  31. package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
  32. package/dist/types/src/extraction/extraction.d.ts +262 -225
  33. package/dist/types/src/extraction/extraction.d.ts.map +1 -1
  34. package/dist/types/src/extraction/quotes.d.ts +1 -1
  35. package/dist/types/src/extraction/quotes.d.ts.map +1 -1
  36. package/dist/types/src/functions/services.d.ts +18 -5
  37. package/dist/types/src/functions/services.d.ts.map +1 -1
  38. package/dist/types/src/index.d.ts +3 -1
  39. package/dist/types/src/index.d.ts.map +1 -1
  40. package/dist/types/src/session/GenericToolkit.d.ts +84 -0
  41. package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
  42. package/dist/types/src/session/artifact-diff.d.ts +2 -2
  43. package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
  44. package/dist/types/src/session/error-handling.d.ts +4 -0
  45. package/dist/types/src/session/error-handling.d.ts.map +1 -0
  46. package/dist/types/src/session/format.d.ts +5 -161
  47. package/dist/types/src/session/format.d.ts.map +1 -1
  48. package/dist/types/src/session/index.d.ts +3 -0
  49. package/dist/types/src/session/index.d.ts.map +1 -1
  50. package/dist/types/src/session/observer.d.ts +22 -0
  51. package/dist/types/src/session/observer.d.ts.map +1 -0
  52. package/dist/types/src/session/session.d.ts +22 -138
  53. package/dist/types/src/session/session.d.ts.map +1 -1
  54. package/dist/types/src/session/toolkit.d.ts +15 -0
  55. package/dist/types/src/session/toolkit.d.ts.map +1 -0
  56. package/dist/types/src/session/version-pin.d.ts +3 -3
  57. package/dist/types/src/session/version-pin.d.ts.map +1 -1
  58. package/dist/types/src/templates/system.d.ts +8 -12
  59. package/dist/types/src/templates/system.d.ts.map +1 -1
  60. package/dist/types/src/types/artifact.d.ts +20 -0
  61. package/dist/types/src/types/artifact.d.ts.map +1 -0
  62. package/dist/types/src/types/index.d.ts +2 -0
  63. package/dist/types/src/types/index.d.ts.map +1 -0
  64. package/dist/types/tsconfig.tsbuildinfo +1 -1
  65. package/package.json +29 -31
  66. package/src/conversation/context.ts +75 -22
  67. package/src/conversation/conversation.ts +80 -77
  68. package/src/diff.test.ts +43 -0
  69. package/src/diff.ts +84 -0
  70. package/src/errors.ts +6 -1
  71. package/src/execution-graph.test.ts +740 -0
  72. package/src/execution-graph.ts +509 -0
  73. package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +9 -9
  74. package/src/extraction/extraction-llm-function/extraction-llm-function.ts +47 -56
  75. package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +16 -16
  76. package/src/extraction/extraction-ner-function/extraction-ner-function.ts +42 -43
  77. package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
  78. package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
  79. package/src/extraction/extraction.ts +7 -6
  80. package/src/extraction/quotes.test.ts +2 -2
  81. package/src/extraction/quotes.ts +3 -3
  82. package/src/functions/services.ts +104 -56
  83. package/src/index.ts +3 -1
  84. package/src/session/GenericToolkit.ts +130 -0
  85. package/src/session/artifact-diff.ts +8 -4
  86. package/src/session/error-handling.ts +41 -0
  87. package/src/session/format.test.ts +5 -4
  88. package/src/session/format.ts +27 -22
  89. package/src/session/index.ts +4 -0
  90. package/src/session/observer.ts +59 -0
  91. package/src/session/session.conversations.json +1 -0
  92. package/src/session/session.test.ts +35 -191
  93. package/src/session/session.ts +119 -185
  94. package/src/session/toolkit.ts +48 -0
  95. package/src/session/version-pin.ts +4 -5
  96. package/src/templates/{format.tpl → instructions/format.tpl} +8 -2
  97. package/src/templates/{system.tpl → instructions/system.tpl} +15 -14
  98. package/src/templates/system.ts +25 -16
  99. package/src/{types.ts → types/artifact.ts} +22 -3
  100. package/src/types/index.ts +5 -0
  101. package/dist/lib/browser/chunk-6WRGDEMH.mjs +0 -89
  102. package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +0 -7
  103. package/dist/lib/browser/chunk-NZGGCEF3.mjs +0 -341
  104. package/dist/lib/browser/chunk-NZGGCEF3.mjs.map +0 -7
  105. package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +0 -13
  106. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +0 -91
  107. package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +0 -7
  108. package/dist/lib/node-esm/chunk-XOOPGSGW.mjs +0 -343
  109. package/dist/lib/node-esm/chunk-XOOPGSGW.mjs.map +0 -7
  110. package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +0 -14
  111. package/dist/types/src/session/version-pin.test.d.ts +0 -2
  112. package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
  113. package/dist/types/src/summarization/summarization.test.d.ts +0 -2
  114. package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
  115. package/dist/types/src/types.d.ts +0 -16
  116. package/dist/types/src/types.d.ts.map +0 -1
  117. package/src/session/__snapshots__/session.test.ts.snap +0 -32
  118. package/src/session/version-pin.test.ts +0 -7
  119. package/src/summarization/summarization.test.ts +0 -197
  120. /package/dist/lib/browser/{named-entity-recognition-O46UTCLR.mjs.map → chunk-J5LGTIGS.mjs.map} +0 -0
  121. /package/dist/lib/node-esm/{named-entity-recognition-W4VMRCH6.mjs.map → chunk-HSLMI22Q.mjs.map} +0 -0
  122. /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
@@ -0,0 +1,10 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ export {
8
+ __export
9
+ };
10
+ //# sourceMappingURL=chunk-J5LGTIGS.mjs.map
@@ -1,22 +1,14 @@
1
- import {
2
- AiSession
3
- } from "../chunk-NZGGCEF3.mjs";
4
- import {
5
- combineNerTokens,
6
- createTokenGroups,
7
- extractFullEntities,
8
- getNer
9
- } from "../chunk-6WRGDEMH.mjs";
1
+ import "../chunk-J5LGTIGS.mjs";
10
2
 
11
3
  // src/extraction/extraction.ts
12
- import { Schema } from "effect";
4
+ import * as Schema from "effect/Schema";
13
5
  import { asyncTimeout } from "@dxos/async";
14
- import { Expando } from "@dxos/echo-schema";
6
+ import { Expando } from "@dxos/echo/internal";
15
7
  import { log } from "@dxos/log";
16
- import { DataType } from "@dxos/schema";
8
+ import { Message } from "@dxos/types";
17
9
  var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction.ts";
18
10
  var ExtractionInput = Schema.Struct({
19
- message: DataType.Message,
11
+ message: Message.Message,
20
12
  objects: Schema.optional(Schema.Array(Expando)),
21
13
  options: Schema.optional(Schema.Struct({
22
14
  timeout: Schema.optional(Schema.Number),
@@ -24,7 +16,7 @@ var ExtractionInput = Schema.Struct({
24
16
  }))
25
17
  });
26
18
  var ExtractionOutput = Schema.Struct({
27
- message: DataType.Message,
19
+ message: Message.Message,
28
20
  timeElapsed: Schema.Number
29
21
  });
30
22
  var processTranscriptMessage = async (params) => {
@@ -40,7 +32,7 @@ var processTranscriptMessage = async (params) => {
40
32
  error
41
33
  }, {
42
34
  F: __dxlog_file,
43
- L: 66,
35
+ L: 67,
44
36
  S: void 0,
45
37
  C: (f, a) => f(...a)
46
38
  });
@@ -55,19 +47,120 @@ var processTranscriptMessage = async (params) => {
55
47
  };
56
48
 
57
49
  // src/extraction/extraction-llm-function/extraction-llm-function.ts
58
- import { AiService, ToolRegistry } from "@dxos/ai";
59
- import { Obj } from "@dxos/echo";
60
- import { create } from "@dxos/echo-schema";
61
50
  import { defineFunction } from "@dxos/functions";
62
- import { DataType as DataType2 } from "@dxos/schema";
51
+ var extractionAnthropicFunction = defineFunction({
52
+ key: "dxos.org/function/extraction/extract-entities",
53
+ name: "Extract Entities",
54
+ description: "Extract entities from the transcript message and add them to the message.",
55
+ inputSchema: ExtractionInput,
56
+ outputSchema: ExtractionOutput,
57
+ handler: async ({ data: { message, objects }, context }) => {
58
+ throw new Error("not implemented");
59
+ }
60
+ });
61
+
62
+ // src/extraction/extraction-ner-function/extraction-ner-function.ts
63
+ import { defineFunction as defineFunction2 } from "@dxos/functions";
64
+ var extractionNerFunction = defineFunction2({
65
+ key: "dxos.org/function/extraction/extract-entities",
66
+ name: "Extract Entities",
67
+ description: "Extracts named entities from a text",
68
+ inputSchema: ExtractionInput,
69
+ outputSchema: ExtractionOutput,
70
+ handler: async ({ data: { message, options }, context }) => {
71
+ throw new Error("not implemented");
72
+ }
73
+ });
74
+
75
+ // src/extraction/extraction-ner-function/named-entity-recognition.ts
76
+ import { pipeline } from "@xenova/transformers";
77
+ import { log as log2 } from "@dxos/log";
78
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-ner-function/named-entity-recognition.ts";
79
+ var _ner;
80
+ var getNer = () => {
81
+ if (!_ner) {
82
+ _ner = pipeline("ner", "Xenova/bert-base-NER").then((ner) => {
83
+ log2.info("NER model is ready", void 0, {
84
+ F: __dxlog_file2,
85
+ L: 24,
86
+ S: void 0,
87
+ C: (f, a) => f(...a)
88
+ });
89
+ return ner;
90
+ });
91
+ }
92
+ return _ner;
93
+ };
94
+ var extractFullEntities = async (text) => {
95
+ const ner = await getNer();
96
+ const entities = await ner(text);
97
+ const tokenGroups = createTokenGroups(entities);
98
+ const combinedEntities = tokenGroups.map(combineNerTokens);
99
+ return combinedEntities;
100
+ };
101
+ var createTokenGroups = (tokens) => {
102
+ const tokenGroups = [];
103
+ const canBeCombined = (prevToken, currentToken) => {
104
+ const [currentState, currentEntity] = currentToken.entity.split("-");
105
+ const [prevState, prevEntity] = prevToken.entity.split("-");
106
+ if (prevEntity !== currentEntity) {
107
+ return false;
108
+ }
109
+ if (prevState === "O") {
110
+ return false;
111
+ }
112
+ if (currentState === "I") {
113
+ return true;
114
+ }
115
+ if ((prevState === "B" || prevState === "I") && currentState === "B") {
116
+ return currentToken.word.startsWith("#");
117
+ }
118
+ return false;
119
+ };
120
+ for (const token of tokens) {
121
+ if (tokenGroups.length === 0) {
122
+ tokenGroups.push([
123
+ token
124
+ ]);
125
+ continue;
126
+ }
127
+ const lastTokenGroup = tokenGroups.at(-1);
128
+ if (canBeCombined(lastTokenGroup.at(-1), token)) {
129
+ lastTokenGroup.push(token);
130
+ continue;
131
+ }
132
+ tokenGroups.push([
133
+ token
134
+ ]);
135
+ }
136
+ return tokenGroups;
137
+ };
138
+ var combineNerTokens = (group) => {
139
+ const combinedToken = {
140
+ entity: group.at(0).entity.split("-")[1],
141
+ score: group.reduce((acc, token) => acc + token.score, 0) / group.length,
142
+ index: group.at(0).index,
143
+ word: group.at(0).word,
144
+ start: group.at(0).start,
145
+ end: group.at(-1).end
146
+ };
147
+ for (const token of group.slice(1)) {
148
+ if (token.word.startsWith("#")) {
149
+ combinedToken.word += token.word.replace(/^#+/, "");
150
+ } else {
151
+ combinedToken.word += " " + token.word;
152
+ }
153
+ }
154
+ return combinedToken;
155
+ };
63
156
 
64
157
  // src/extraction/quotes.ts
65
- import { Schema as Schema2 } from "effect";
158
+ import * as Schema2 from "effect/Schema";
66
159
  import { Filter, Query } from "@dxos/echo";
67
- import { ObjectId } from "@dxos/echo-schema";
160
+ import { ObjectId } from "@dxos/echo/internal";
68
161
  import { DXN } from "@dxos/keys";
69
- import { log as log2 } from "@dxos/log";
70
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/assistant/src/extraction/quotes.ts";
162
+ import { log as log3 } from "@dxos/log";
163
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/extraction/quotes.ts";
71
164
  var ReferencedQuotes = Schema2.Struct({
72
165
  references: Schema2.Array(Schema2.Struct({
73
166
  id: Schema2.String,
@@ -85,11 +178,11 @@ var findQuotes = async (quotes, db) => {
85
178
  const { objects } = await db.query(Query.select(Filter.text(quote, {
86
179
  type: "vector"
87
180
  }))).run();
88
- log2.info("found quotes in vector index", {
181
+ log3.info("found quotes in vector index", {
89
182
  objects,
90
183
  quote
91
184
  }, {
92
- F: __dxlog_file2,
185
+ F: __dxlog_file3,
93
186
  L: 35,
94
187
  S: void 0,
95
188
  C: (f, a) => f(...a)
@@ -111,147 +204,10 @@ var insertReferences = (text, quotes) => {
111
204
  continue;
112
205
  }
113
206
  const regex = new RegExp(quote.quote.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "gi");
114
- text = text.replace(regex, `[${quote.quote}][${DXN.fromLocalObjectId(quote.id).toString()}]`);
207
+ text = text.replace(regex, `[${quote.quote}](${DXN.fromLocalObjectId(quote.id).toString()})`);
115
208
  }
116
209
  return text;
117
210
  };
118
-
119
- // raw-loader:./instructions.tpl?raw
120
- var instructions_default = 'You are an AI assistant specialized in processing and enhancing transcripts with contextual information.\nYour task is to analyze a given transcript and extract references to the context objects.\n\nThe context and transcript are provided in the user message in `context` and `transcript` XML tags.\n\nHere are your instructions:\n\n1. Read the transcript and context information provided above.\n\n2. Process each segment of the transcript separately.\n\n3. For each segment:\n a. Analyze the content and identify relevant information from the context.\n b. Extract a number of references to the context objects that are mentioned in the segment.\n c. Output the references in the format `{ "quote": "earnings report", "id": "01JT0JP9AX0XKGZX4MV4B69VT6" }`.\n d. If there are no references, just output an empty array.\n\n4. Maintain the exact order and structure of the original transcript segments.\n\nOutput Format:\nYou have been provided with a tool that specifies output format\n\nRemember:\n- Only quote the text that is in the transcript.\n- Analyze each segment carefully before processing it.\n- Only reference objects that appear in the context and exactly by their id, If the object is not in the context, do not insert a reference. \n\nNow, process the transcript and context provided below according to these instructions.';
121
-
122
- // src/extraction/extraction-llm-function/extraction-llm-function.ts
123
- var extractionAnthropicFn = defineFunction({
124
- description: "Extract entities from the transcript message and add them to the message.",
125
- inputSchema: ExtractionInput,
126
- outputSchema: ExtractionOutput,
127
- handler: async ({ data: { message, objects }, context }) => {
128
- const startTime = performance.now();
129
- const ai = context.getService(AiService.AiService);
130
- const session = new AiSession({
131
- operationModel: "configured"
132
- });
133
- const result = await session.runStructured(ReferencedQuotes, {
134
- generationOptions: {
135
- model: "@anthropic/claude-3-5-haiku-20241022"
136
- },
137
- client: ai.client,
138
- systemPrompt: instructions_default,
139
- history: [
140
- Obj.make(DataType2.Message, {
141
- created: (/* @__PURE__ */ new Date()).toISOString(),
142
- sender: {
143
- role: "user"
144
- },
145
- blocks: [
146
- {
147
- _tag: "text",
148
- text: `<context>${JSON.stringify(objects)}</context>`
149
- },
150
- {
151
- _tag: "text",
152
- text: `<transcript>${JSON.stringify(message.blocks)}</transcript>`
153
- }
154
- ]
155
- })
156
- ],
157
- artifacts: [],
158
- prompt: "",
159
- tools: [],
160
- toolResolver: new ToolRegistry([])
161
- });
162
- return {
163
- message: create(DataType2.Message, {
164
- ...message,
165
- blocks: message.blocks.map((block, i) => block._tag !== "transcript" ? block : {
166
- ...block,
167
- text: insertReferences(block.text, result)
168
- })
169
- }),
170
- timeElapsed: performance.now() - startTime
171
- };
172
- }
173
- });
174
-
175
- // src/extraction/extraction-ner-function/extraction-ner-function.ts
176
- import { asyncTimeout as asyncTimeout2 } from "@dxos/async";
177
- import { create as create2 } from "@dxos/echo-schema";
178
- import { DatabaseService, defineFunction as defineFunction2 } from "@dxos/functions";
179
- import { invariant } from "@dxos/invariant";
180
- import { log as log3 } from "@dxos/log";
181
- import { DataType as DataType3 } from "@dxos/schema";
182
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-ner-function/extraction-ner-function.ts";
183
- var extractionNerFn = defineFunction2({
184
- description: "Extracts named entities from a text",
185
- inputSchema: ExtractionInput,
186
- outputSchema: ExtractionOutput,
187
- handler: async ({ data: { message, options }, context }) => {
188
- log3.info("input", {
189
- message,
190
- options
191
- }, {
192
- F: __dxlog_file3,
193
- L: 24,
194
- S: void 0,
195
- C: (f, a) => f(...a)
196
- });
197
- const startTime = performance.now();
198
- const { db } = context.getService(DatabaseService);
199
- const { extractFullEntities: extractFullEntities2 } = await import("../named-entity-recognition-O46UTCLR.mjs");
200
- const entitiesPromise = Promise.all(message.blocks.map(async (block) => {
201
- invariant(block._tag === "transcript" || block._tag === "text", "Block must have text", {
202
- F: __dxlog_file3,
203
- L: 31,
204
- S: void 0,
205
- A: [
206
- "block._tag === 'transcript' || block._tag === 'text'",
207
- "'Block must have text'"
208
- ]
209
- });
210
- return extractFullEntities2(block.text);
211
- })).then((entities2) => entities2.flat());
212
- const entities = options?.timeout ? await asyncTimeout2(entitiesPromise, options.timeout) : await entitiesPromise;
213
- log3.info("entities", {
214
- entities
215
- }, {
216
- F: __dxlog_file3,
217
- L: 36,
218
- S: void 0,
219
- C: (f, a) => f(...a)
220
- });
221
- const quoteReferences = await findQuotes(entities.map((entity) => entity.word), db);
222
- const blocksWithReferences = message.blocks.map((block, i) => {
223
- invariant(block._tag === "transcript" || block._tag === "text", "Block must have text", {
224
- F: __dxlog_file3,
225
- L: 42,
226
- S: void 0,
227
- A: [
228
- "block._tag === 'transcript' || block._tag === 'text'",
229
- "'Block must have text'"
230
- ]
231
- });
232
- return {
233
- ...block,
234
- text: insertReferences(block._tag, quoteReferences)
235
- };
236
- });
237
- const messageWithReferences = create2(DataType3.Message, {
238
- ...message,
239
- blocks: blocksWithReferences
240
- });
241
- log3.info("output", {
242
- messageWithReferences
243
- }, {
244
- F: __dxlog_file3,
245
- L: 50,
246
- S: void 0,
247
- C: (f, a) => f(...a)
248
- });
249
- return {
250
- message: messageWithReferences,
251
- timeElapsed: performance.now() - startTime
252
- };
253
- }
254
- });
255
211
  export {
256
212
  ExtractionInput,
257
213
  ExtractionOutput,
@@ -259,8 +215,8 @@ export {
259
215
  combineNerTokens,
260
216
  createTokenGroups,
261
217
  extractFullEntities,
262
- extractionAnthropicFn,
263
- extractionNerFn,
218
+ extractionAnthropicFunction,
219
+ extractionNerFunction,
264
220
  findQuotes,
265
221
  getNer,
266
222
  insertReferences,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../src/extraction/extraction.ts", "../../../../src/extraction/extraction-llm-function/extraction-llm-function.ts", "../../../../src/extraction/quotes.ts", "raw-loader:./instructions.tpl?raw", "../../../../src/extraction/extraction-ner-function/extraction-ner-function.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { asyncTimeout } from '@dxos/async';\nimport { Expando } from '@dxos/echo-schema';\nimport { type FunctionDefinition, type FunctionExecutor } from '@dxos/functions';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nexport const ExtractionInput = Schema.Struct({\n message: DataType.Message,\n objects: Schema.optional(Schema.Array(Expando)),\n options: Schema.optional(\n Schema.Struct({\n timeout: Schema.optional(Schema.Number),\n fallbackToRaw: Schema.optional(Schema.Boolean),\n }),\n ),\n});\nexport interface ExtractionInput extends Schema.Schema.Type<typeof ExtractionInput> {}\n\nexport const ExtractionOutput = Schema.Struct({\n message: DataType.Message,\n timeElapsed: Schema.Number,\n});\nexport interface ExtractionOutput extends Schema.Schema.Type<typeof ExtractionOutput> {}\n\nexport type ProcessTranscriptMessageParams = {\n input: ExtractionInput;\n function: FunctionDefinition<ExtractionInput, ExtractionOutput>;\n executor: FunctionExecutor;\n\n options?: {\n /**\n * Timeout for the entity extraction.\n */\n timeout?: number;\n\n /**\n * Fallback to raw text if the entity extraction fails.\n * Otherwise the function will throw an error.\n * @default false\n */\n fallbackToRaw?: boolean;\n };\n};\n\nexport type ExtractionFunction = FunctionDefinition<ExtractionInput, ExtractionOutput>;\n\n/**\n * Extract entities from the transcript message and add them to the message.\n */\n// TODO(dmaretskyi): Move context to a vector search index.\nexport const processTranscriptMessage = async (params: ProcessTranscriptMessageParams): Promise<ExtractionOutput> => {\n try {\n if (params.options?.timeout && params.options.timeout > 0) {\n return await asyncTimeout(params.executor.invoke(params.function, params.input), params.options.timeout);\n } else {\n return await params.executor.invoke(params.function, params.input);\n }\n } catch (error) {\n if (params.options?.fallbackToRaw) {\n log.warn('failed to process message, falling back to raw text', { error });\n return {\n message: params.input.message,\n timeElapsed: 0,\n };\n } else {\n throw error;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\n// ISSUE(burdon): defineFunction\n// @ts-nocheck\n\nimport { AiService, ToolRegistry } from '@dxos/ai';\nimport { Obj } from '@dxos/echo';\nimport { create } from '@dxos/echo-schema';\nimport { type FunctionDefinition, defineFunction } from '@dxos/functions';\nimport { type ContentBlock, DataType } from '@dxos/schema';\n\nimport { AiSession } from '../../session';\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\nimport { ReferencedQuotes, insertReferences } from '../quotes';\n\nimport PROMPT from './instructions.tpl?raw';\n\nexport const extractionAnthropicFn: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({\n description: 'Extract entities from the transcript message and add them to the message.',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, objects }, context }) => {\n const startTime = performance.now();\n const ai = context.getService(AiService.AiService);\n const session = new AiSession({ operationModel: 'configured' });\n const result = await session.runStructured(ReferencedQuotes, {\n generationOptions: {\n model: '@anthropic/claude-3-5-haiku-20241022',\n },\n client: ai.client,\n systemPrompt: PROMPT,\n history: [\n Obj.make(DataType.Message, {\n created: new Date().toISOString(),\n sender: { role: 'user' },\n blocks: [\n {\n _tag: 'text',\n text: `<context>${JSON.stringify(objects)}</context>`,\n } satisfies ContentBlock.Text,\n {\n _tag: 'text',\n text: `<transcript>${JSON.stringify(message.blocks)}</transcript>`,\n } satisfies ContentBlock.Text,\n ],\n }),\n ],\n artifacts: [],\n prompt: '',\n tools: [],\n toolResolver: new ToolRegistry([]),\n } as any); // TODO(burdon): Rewrite test.\n\n return {\n message: create(DataType.Message, {\n ...message,\n blocks: message.blocks.map((block, i) =>\n block._tag !== 'transcript'\n ? block\n : {\n ...block,\n text: insertReferences(block.text, result),\n },\n ),\n }),\n timeElapsed: performance.now() - startTime,\n };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { Filter, Query } from '@dxos/echo';\nimport { type EchoDatabase } from '@dxos/echo-db';\nimport { ObjectId } from '@dxos/echo-schema';\nimport { DXN } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nexport const ReferencedQuotes = Schema.Struct({\n references: Schema.Array(\n Schema.Struct({\n id: Schema.String,\n quote: Schema.String, // TODO(burdon): Quote?\n }),\n )\n .pipe(Schema.mutable)\n .annotations({\n // TODO(burdon): Does this description make sense?\n description: `\n The references to the context objects that are mentioned in the transcript. \n Quote should match the original transcript text exactly, while id is the id of the context object.\n `,\n }),\n});\nexport type ReferencedQuotes = Schema.Schema.Type<typeof ReferencedQuotes>;\n\nexport const findQuotes = async (quotes: string[], db: EchoDatabase): Promise<ReferencedQuotes> => {\n const references = await Promise.all(\n quotes.map(async (quote) => {\n const { objects } = await db.query(Query.select(Filter.text(quote, { type: 'vector' }))).run();\n log.info('found quotes in vector index', { objects, quote });\n return objects.length > 0 ? [{ id: objects[0].id.toString(), quote }] : [];\n }),\n );\n return { references: references.flat() };\n};\n\n/**\n * Finds and replaces all quotes with DXNs references.\n */\n// TODO(dmaretskyi): Lookup and verifiy ids from provided context.\nexport const insertReferences = (text: string, quotes: ReferencedQuotes) => {\n for (const quote of quotes.references) {\n if (!ObjectId.isValid(quote.id)) {\n continue;\n }\n\n // Use a case-insensitive regular expression to replace the quote.\n const regex = new RegExp(quote.quote.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi');\n text = text.replace(regex, `[${quote.quote}][${DXN.fromLocalObjectId(quote.id).toString()}]`);\n }\n\n return text;\n};\n", "You are an AI assistant specialized in processing and enhancing transcripts with contextual information.\nYour task is to analyze a given transcript and extract references to the context objects.\n\nThe context and transcript are provided in the user message in `context` and `transcript` XML tags.\n\nHere are your instructions:\n\n1. Read the transcript and context information provided above.\n\n2. Process each segment of the transcript separately.\n\n3. For each segment:\n a. Analyze the content and identify relevant information from the context.\n b. Extract a number of references to the context objects that are mentioned in the segment.\n c. Output the references in the format `{ \"quote\": \"earnings report\", \"id\": \"01JT0JP9AX0XKGZX4MV4B69VT6\" }`.\n d. If there are no references, just output an empty array.\n\n4. Maintain the exact order and structure of the original transcript segments.\n\nOutput Format:\nYou have been provided with a tool that specifies output format\n\nRemember:\n- Only quote the text that is in the transcript.\n- Analyze each segment carefully before processing it.\n- Only reference objects that appear in the context and exactly by their id, If the object is not in the context, do not insert a reference. \n\nNow, process the transcript and context provided below according to these instructions.", "//\n// Copyright 2025 DXOS.org\n//\n\n// ISSUE(burdon): defineFunction\n// @ts-nocheck\n\nimport { asyncTimeout } from '@dxos/async';\nimport { create } from '@dxos/echo-schema';\nimport { DatabaseService, defineFunction } from '@dxos/functions';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { DataType } from '@dxos/schema';\n\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\nimport { findQuotes, insertReferences } from '../quotes';\n\n// TODO(mykola): Make it use vector index to query objects and not pass objects as input.\nexport const extractionNerFn = defineFunction({\n description: 'Extracts named entities from a text',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, options }, context }) => {\n log.info('input', { message, options });\n const startTime = performance.now();\n const { db } = context.getService(DatabaseService);\n const { extractFullEntities } = await import('./named-entity-recognition');\n\n const entitiesPromise = Promise.all(\n message.blocks.map(async (block) => {\n invariant(block._tag === 'transcript' || block._tag === 'text', 'Block must have text');\n return extractFullEntities(block.text);\n }),\n ).then((entities) => entities.flat());\n const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;\n log.info('entities', { entities });\n const quoteReferences = await findQuotes(\n entities.map((entity) => entity.word),\n db,\n );\n const blocksWithReferences = message.blocks.map((block, i) => {\n invariant(block._tag === 'transcript' || block._tag === 'text', 'Block must have text');\n return { ...block, text: insertReferences(block._tag, quoteReferences) };\n });\n const messageWithReferences = create(DataType.Message, {\n ...message,\n blocks: blocksWithReferences,\n });\n\n log.info('output', { messageWithReferences });\n\n return {\n message: messageWithReferences,\n timeElapsed: performance.now() - startTime,\n };\n },\n});\n"],
5
- "mappings": ";;;;;;;;;;;AAIA,SAASA,cAA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struct", "message", "Message", "objects", "optional", "Array", "options", "timeout", "Number", "fallbackToRaw", "Boolean", "ExtractionOutput", "timeElapsed", "processTranscriptMessage", "params", "executor", "invoke", "function", "input", "error", "warn", "AiService", "ToolRegistry", "Obj", "create", "defineFunction", "DataType", "Schema", "Filter", "Query", "ObjectId", "DXN", "log", "ReferencedQuotes", "Struct", "references", "Array", "id", "String", "quote", "pipe", "mutable", "annotations", "description", "findQuotes", "quotes", "db", "Promise", "all", "map", "objects", "query", "select", "text", "type", "run", "info", "length", "toString", "flat", "insertReferences", "isValid", "regex", "RegExp", "replace", "fromLocalObjectId", "extractionAnthropicFn", "defineFunction", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "objects", "context", "startTime", "performance", "now", "ai", "getService", "AiService", "session", "AiSession", "operationModel", "result", "runStructured", "ReferencedQuotes", "generationOptions", "model", "client", "systemPrompt", "PROMPT", "history", "Obj", "make", "DataType", "Message", "created", "Date", "toISOString", "sender", "role", "blocks", "_tag", "text", "JSON", "stringify", "artifacts", "prompt", "tools", "toolResolver", "ToolRegistry", "create", "map", "block", "i", "insertReferences", "timeElapsed", "asyncTimeout", "create", "DatabaseService", "defineFunction", "invariant", "log", "DataType", "extractionNerFn", "defineFunction", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "options", "context", "log", "info", "startTime", "performance", "now", "db", "getService", "DatabaseService", "extractFullEntities", "entitiesPromise", "Promise", "all", "blocks", "map", "block", "invariant", "_tag", "text", "then", "entities", "flat", "timeout", "asyncTimeout", "quoteReferences", "findQuotes", "entity", "word", "blocksWithReferences", "i", "insertReferences", "messageWithReferences", "create", "DataType", "Message", "timeElapsed"]
3
+ "sources": ["../../../../src/extraction/extraction.ts", "../../../../src/extraction/extraction-llm-function/extraction-llm-function.ts", "../../../../src/extraction/extraction-ner-function/extraction-ner-function.ts", "../../../../src/extraction/extraction-ner-function/named-entity-recognition.ts", "../../../../src/extraction/quotes.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { asyncTimeout } from '@dxos/async';\nimport { Expando } from '@dxos/echo/internal';\nimport { type FunctionDefinition } from '@dxos/functions';\nimport { type FunctionExecutor } from '@dxos/functions-runtime';\nimport { log } from '@dxos/log';\nimport { Message } from '@dxos/types';\n\nexport const ExtractionInput = Schema.Struct({\n message: Message.Message,\n objects: Schema.optional(Schema.Array(Expando)),\n options: Schema.optional(\n Schema.Struct({\n timeout: Schema.optional(Schema.Number),\n fallbackToRaw: Schema.optional(Schema.Boolean),\n }),\n ),\n});\nexport interface ExtractionInput extends Schema.Schema.Type<typeof ExtractionInput> {}\n\nexport const ExtractionOutput = Schema.Struct({\n message: Message.Message,\n timeElapsed: Schema.Number,\n});\nexport interface ExtractionOutput extends Schema.Schema.Type<typeof ExtractionOutput> {}\n\nexport type ProcessTranscriptMessageParams = {\n input: ExtractionInput;\n function: FunctionDefinition<ExtractionInput, ExtractionOutput>;\n executor: FunctionExecutor;\n\n options?: {\n /**\n * Timeout for the entity extraction.\n */\n timeout?: number;\n\n /**\n * Fallback to raw text if the entity extraction fails.\n * Otherwise the function will throw an error.\n * @default false\n */\n fallbackToRaw?: boolean;\n };\n};\n\nexport type ExtractionFunction = FunctionDefinition<ExtractionInput, ExtractionOutput>;\n\n/**\n * Extract entities from the transcript message and add them to the message.\n */\n// TODO(dmaretskyi): Move context to a vector search index.\nexport const processTranscriptMessage = async (params: ProcessTranscriptMessageParams): Promise<ExtractionOutput> => {\n try {\n if (params.options?.timeout && params.options.timeout > 0) {\n return await asyncTimeout(params.executor.invoke(params.function, params.input), params.options.timeout);\n } else {\n return await params.executor.invoke(params.function, params.input);\n }\n } catch (error) {\n if (params.options?.fallbackToRaw) {\n log.warn('failed to process message, falling back to raw text', { error });\n return {\n message: params.input.message,\n timeElapsed: 0,\n };\n } else {\n throw error;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type FunctionDefinition, defineFunction } from '@dxos/functions';\n\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\n\nexport const extractionAnthropicFunction: FunctionDefinition<ExtractionInput, ExtractionOutput> = defineFunction({\n key: 'dxos.org/function/extraction/extract-entities',\n name: 'Extract Entities',\n description: 'Extract entities from the transcript message and add them to the message.',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, objects }, context }) => {\n throw new Error('not implemented');\n // const startTime = performance.now();\n // const ai = context.getService(AiService.AiService);\n // const session = new AiSession({ operationModel: 'configured' });\n // const result = await session.runStructured(ReferencedQuotes, {\n // generationOptions: {\n // model: '@anthropic/claude-3-5-haiku-20241022',\n // },\n // client: ai.client,\n // systemPrompt: PROMPT,\n // history: [\n // Obj.make(DataType.Message.Message, {\n // created: new Date().toISOString(),\n // sender: { role: 'user' },\n // blocks: [\n // {\n // _tag: 'text',\n // text: `<context>${JSON.stringify(objects)}</context>`,\n // } satisfies DataType.ContentBlock.Text,\n // {\n // _tag: 'text',\n // text: `<transcript>${JSON.stringify(message.blocks)}</transcript>`,\n // } satisfies DataType.ContentBlock.Text,\n // ],\n // }),\n // ],\n // artifacts: [],\n // prompt: '',\n // tools: [],\n // } as any); // TODO(burdon): Rewrite test.\n\n // return {\n // timeElapsed: performance.now() - startTime,\n // message: create(DataType.Message.Message, {\n // ...message,\n // blocks: message.blocks.map((block) =>\n // block._tag !== 'transcript'\n // ? block\n // : {\n // ...block,\n // text: insertReferences(block.text, result),\n // },\n // ),\n // }),\n // };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { defineFunction } from '@dxos/functions';\n\nimport { ExtractionInput, ExtractionOutput } from '../extraction';\n\n/**\n * Named Entity Recognition model\n */\n// TODO(mykola): Make it use vector index to query objects and not pass objects as input.\nexport const extractionNerFunction = defineFunction({\n key: 'dxos.org/function/extraction/extract-entities',\n name: 'Extract Entities',\n description: 'Extracts named entities from a text',\n inputSchema: ExtractionInput,\n outputSchema: ExtractionOutput,\n handler: async ({ data: { message, options }, context }) => {\n throw new Error('not implemented');\n // log.info('input', { message, options });\n // const startTime = performance.now();\n // const { db } = context.getService(DatabaseService);\n // const { extractFullEntities } = await import('./named-entity-recognition');\n\n // const entitiesPromise = Promise.all(\n // message.blocks.map(async (block) => {\n // invariant(block._tag === 'transcript' || block._tag === 'text');\n // return extractFullEntities(block.text);\n // }),\n // ).then((entities) => entities.flat());\n // const entities = options?.timeout ? await asyncTimeout(entitiesPromise, options.timeout) : await entitiesPromise;\n\n // log.info('entities', { entities });\n // const quoteReferences = await findQuotes(\n // entities.map((entity) => entity.word),\n // db,\n // );\n\n // const blocksWithReferences = message.blocks.map((block) => {\n // invariant(block._tag === 'transcript' || block._tag === 'text');\n // return { ...block, text: insertReferences(block._tag, quoteReferences) };\n // });\n\n // const messageWithReferences = create(Message.Message, {\n // ...message,\n // blocks: blocksWithReferences,\n // });\n\n // log.info('output', { messageWithReferences });\n // return {\n // message: messageWithReferences,\n // timeElapsed: performance.now() - startTime,\n // };\n },\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport {\n type TokenClassificationOutput,\n type TokenClassificationPipelineType,\n type TokenClassificationSingle,\n pipeline,\n} from '@xenova/transformers';\n\nimport { log } from '@dxos/log';\n\nlet _ner: Promise<TokenClassificationPipelineType>;\n\n/**\n * Named Entity Recognition pipeline.\n * Initializes the pipeline on first call.\n * @returns The singleton promise that resolves to a token classification pipeline.\n */\nexport const getNer = () => {\n if (!_ner) {\n _ner = pipeline('ner', 'Xenova/bert-base-NER').then((ner) => {\n log.info('NER model is ready');\n return ner;\n });\n }\n\n return _ner;\n};\n\n/**\n * Extracts entities from text using the named entity recognition pipeline and does simple grouping of tokens.\n */\nexport const extractFullEntities = async (text: string): Promise<TokenClassificationSingle[]> => {\n const ner = await getNer();\n const entities = (await ner(text)) as TokenClassificationOutput;\n const tokenGroups = createTokenGroups(entities);\n const combinedEntities = tokenGroups.map(combineNerTokens);\n return combinedEntities;\n};\n\nexport const createTokenGroups = (tokens: TokenClassificationSingle[]): TokenClassificationSingle[][] => {\n const tokenGroups: TokenClassificationSingle[][] = [];\n\n const canBeCombined = (prevToken: TokenClassificationSingle, currentToken: TokenClassificationSingle) => {\n const [currentState, currentEntity] = currentToken.entity.split('-'); // B, I, O\n const [prevState, prevEntity] = prevToken.entity.split('-'); // B, I, O\n if (prevEntity !== currentEntity) {\n return false;\n }\n if (prevState === 'O') {\n return false;\n }\n if (currentState === 'I') {\n return true;\n }\n if ((prevState === 'B' || prevState === 'I') && currentState === 'B') {\n return currentToken.word.startsWith('#');\n }\n return false;\n };\n\n for (const token of tokens) {\n if (tokenGroups.length === 0) {\n tokenGroups.push([token]);\n continue;\n }\n const lastTokenGroup = tokenGroups.at(-1)!;\n if (canBeCombined(lastTokenGroup.at(-1)!, token)) {\n lastTokenGroup.push(token);\n continue;\n }\n tokenGroups.push([token]);\n }\n\n return tokenGroups;\n};\n\nexport const combineNerTokens = (group: TokenClassificationSingle[]): TokenClassificationSingle => {\n const combinedToken: TokenClassificationSingle = {\n entity: group.at(0)!.entity.split('-')[1],\n score: group.reduce((acc, token) => acc + token.score, 0) / group.length,\n index: group.at(0)!.index,\n word: group.at(0)!.word,\n start: group.at(0)!.start,\n end: group.at(-1)!.end,\n };\n\n for (const token of group.slice(1)) {\n if (token.word.startsWith('#')) {\n combinedToken.word += token.word.replace(/^#+/, '');\n } else {\n combinedToken.word += ' ' + token.word;\n }\n }\n\n return combinedToken;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Filter, Query } from '@dxos/echo';\nimport { ObjectId } from '@dxos/echo/internal';\nimport { type EchoDatabase } from '@dxos/echo-db';\nimport { DXN } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nexport const ReferencedQuotes = Schema.Struct({\n references: Schema.Array(\n Schema.Struct({\n id: Schema.String,\n quote: Schema.String, // TODO(burdon): Quote?\n }),\n )\n .pipe(Schema.mutable)\n .annotations({\n // TODO(burdon): Does this description make sense?\n description: `\n The references to the context objects that are mentioned in the transcript. \n Quote should match the original transcript text exactly, while id is the id of the context object.\n `,\n }),\n});\nexport type ReferencedQuotes = Schema.Schema.Type<typeof ReferencedQuotes>;\n\nexport const findQuotes = async (quotes: string[], db: EchoDatabase): Promise<ReferencedQuotes> => {\n const references = await Promise.all(\n quotes.map(async (quote) => {\n const { objects } = await db.query(Query.select(Filter.text(quote, { type: 'vector' }))).run();\n log.info('found quotes in vector index', { objects, quote });\n return objects.length > 0 ? [{ id: objects[0].id.toString(), quote }] : [];\n }),\n );\n return { references: references.flat() };\n};\n\n/**\n * Finds and replaces all quotes with DXNs references.\n */\n// TODO(dmaretskyi): Lookup and verifiy ids from provided context.\nexport const insertReferences = (text: string, quotes: ReferencedQuotes) => {\n for (const quote of quotes.references) {\n if (!ObjectId.isValid(quote.id)) {\n continue;\n }\n\n // Use a case-insensitive regular expression to replace the quote.\n const regex = new RegExp(quote.quote.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), 'gi');\n text = text.replace(regex, `[${quote.quote}](${DXN.fromLocalObjectId(quote.id).toString()})`);\n }\n\n return text;\n};\n"],
5
+ "mappings": ";;;AAIA,YAAYA,YAAY;AAExB,SAASC,oBAAoB;AAC7B,SAASC,eAAe;AAGxB,SAASC,WAAW;AACpB,SAASC,eAAe;;AAEjB,IAAMC,kBAAyBC,cAAO;EAC3CC,SAASH,QAAQA;EACjBI,SAAgBC,gBAAgBC,aAAMR,OAAAA,CAAAA;EACtCS,SAAgBF,gBACPH,cAAO;IACZM,SAAgBH,gBAAgBI,aAAM;IACtCC,eAAsBL,gBAAgBM,cAAO;EAC/C,CAAA,CAAA;AAEJ,CAAA;AAGO,IAAMC,mBAA0BV,cAAO;EAC5CC,SAASH,QAAQA;EACjBa,aAAoBJ;AACtB,CAAA;AA6BO,IAAMK,2BAA2B,OAAOC,WAAAA;AAC7C,MAAI;AACF,QAAIA,OAAOR,SAASC,WA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AAY;AACrC,QAAI,CAACL,SAAS+B,QAAQtB,MAAMF,EAAE,GAAG;AAC/B;IACF;AAGA,UAAMyB,QAAQ,IAAIC,OAAOxB,MAAMA,MAAMyB,QAAQ,uBAAuB,MAAA,GAAS,IAAA;AAC7EX,WAAOA,KAAKW,QAAQF,OAAO,IAAIvB,MAAMA,KAAK,KAAKR,IAAIkC,kBAAkB1B,MAAMF,EAAE,EAAEqB,SAAQ,CAAA,GAAK;EAC9F;AAEA,SAAOL;AACT;",
6
+ "names": ["Schema", "asyncTimeout", "Expando", "log", "Message", "ExtractionInput", "Struct", "message", "objects", "optional", "Array", "options", "timeout", "Number", "fallbackToRaw", "Boolean", "ExtractionOutput", "timeElapsed", "processTranscriptMessage", "params", "executor", "invoke", "function", "input", "error", "warn", "defineFunction", "extractionAnthropicFunction", "defineFunction", "key", "name", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "objects", "context", "Error", "defineFunction", "extractionNerFunction", "defineFunction", "key", "name", "description", "inputSchema", "ExtractionInput", "outputSchema", "ExtractionOutput", "handler", "data", "message", "options", "context", "Error", "pipeline", "log", "_ner", "getNer", "then", "ner", "info", "extractFullEntities", "text", "entities", "tokenGroups", "createTokenGroups", "combinedEntities", "map", "combineNerTokens", "tokens", "canBeCombined", "prevToken", "currentToken", "currentState", "currentEntity", "entity", "split", "prevState", "prevEntity", "word", "startsWith", "token", "length", "push", "lastTokenGroup", "at", "group", "combinedToken", "score", "reduce", "acc", "index", "start", "end", "slice", "replace", "Schema", "Filter", "Query", "ObjectId", "DXN", "log", "ReferencedQuotes", "Struct", "references", "Array", "id", "String", "quote", "pipe", "mutable", "annotations", "description", "findQuotes", "quotes", "db", "Promise", "all", "map", "objects", "query", "select", "text", "type", "run", "info", "length", "toString", "flat", "insertReferences", "isValid", "regex", "RegExp", "replace", "fromLocalObjectId"]
7
7
  }