@dxos/assistant 0.8.4-main.3eb6e50203 → 0.8.4-main.3fbcb4aa9b
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/lib/neutral/extraction/index.mjs +31 -54
- package/dist/lib/neutral/extraction/index.mjs.map +4 -4
- package/dist/lib/neutral/index.mjs +1003 -198
- package/dist/lib/neutral/index.mjs.map +4 -4
- package/dist/lib/neutral/meta.json +1 -1
- package/dist/types/src/conversation/context.d.ts +41 -23
- package/dist/types/src/conversation/context.d.ts.map +1 -1
- package/dist/types/src/conversation/index.d.ts +1 -1
- package/dist/types/src/conversation/index.d.ts.map +1 -1
- package/dist/types/src/conversation/session.d.ts +73 -0
- package/dist/types/src/conversation/session.d.ts.map +1 -0
- package/dist/types/src/diff.d.ts.map +1 -1
- package/dist/types/src/errors.d.ts +12 -12
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/execution-graph.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction-ner-function/index.d.ts +0 -1
- package/dist/types/src/extraction/extraction-ner-function/index.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction-ner-function/named-entity-recognition.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction.d.ts +876 -158
- package/dist/types/src/extraction/extraction.d.ts.map +1 -1
- package/dist/types/src/extraction/index.d.ts +0 -1
- package/dist/types/src/extraction/index.d.ts.map +1 -1
- package/dist/types/src/extraction/quotes.d.ts.map +1 -1
- package/dist/types/src/functions/services.d.ts +14 -16
- package/dist/types/src/functions/services.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
- package/dist/types/src/session/error-handling.d.ts.map +1 -1
- package/dist/types/src/session/format.d.ts +6 -3
- package/dist/types/src/session/format.d.ts.map +1 -1
- package/dist/types/src/session/index.d.ts +1 -2
- package/dist/types/src/session/index.d.ts.map +1 -1
- package/dist/types/src/session/observer.d.ts.map +1 -1
- package/dist/types/src/session/request.d.ts +104 -0
- package/dist/types/src/session/request.d.ts.map +1 -0
- package/dist/types/src/session/toolkit.d.ts +8 -6
- package/dist/types/src/session/toolkit.d.ts.map +1 -1
- package/dist/types/src/templates/system.d.ts +1 -2
- package/dist/types/src/templates/system.d.ts.map +1 -1
- package/dist/types/src/tracing.d.ts +233 -0
- package/dist/types/src/tracing.d.ts.map +1 -0
- package/dist/types/src/types/artifact.d.ts +5 -5
- package/dist/types/src/types/artifact.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +24 -39
- package/src/conversation/context.test.ts +19 -13
- package/src/conversation/context.ts +133 -60
- package/src/conversation/index.ts +1 -1
- package/src/conversation/session.ts +323 -0
- package/src/diff.test.ts +3 -3
- package/src/execution-graph.test.ts +2 -2
- package/src/execution-graph.ts +18 -8
- package/src/extraction/extraction-ner-function/index.ts +0 -1
- package/src/extraction/extraction.ts +38 -10
- package/src/extraction/index.ts +0 -1
- package/src/functions/services.ts +82 -55
- package/src/index.ts +1 -0
- package/src/session/format.ts +14 -10
- package/src/session/index.ts +1 -3
- package/src/session/observer.ts +3 -2
- package/src/session/request.ts +347 -0
- package/src/session/toolkit.ts +21 -13
- package/src/templates/instructions/system.tpl +50 -2
- package/src/templates/system.ts +7 -6
- package/src/tracing.ts +57 -0
- package/src/types/artifact.ts +5 -5
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs +0 -10
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +0 -7
- package/dist/lib/neutral/chunk-QBD6NQJK.mjs +0 -604
- package/dist/lib/neutral/chunk-QBD6NQJK.mjs.map +0 -7
- package/dist/lib/neutral/testing/index.mjs +0 -38
- package/dist/lib/neutral/testing/index.mjs.map +0 -7
- package/dist/types/src/conversation/conversation.d.ts +0 -66
- package/dist/types/src/conversation/conversation.d.ts.map +0 -1
- package/dist/types/src/conversation/conversation.test.d.ts +0 -2
- package/dist/types/src/conversation/conversation.test.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +0 -4
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts +0 -2
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.test.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-llm-function/index.d.ts +0 -2
- package/dist/types/src/extraction/extraction-llm-function/index.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +0 -347
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts.map +0 -1
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts +0 -2
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.test.d.ts.map +0 -1
- package/dist/types/src/functions.test.d.ts +0 -2
- package/dist/types/src/functions.test.d.ts.map +0 -1
- package/dist/types/src/session/GenericToolkit.d.ts +0 -107
- package/dist/types/src/session/GenericToolkit.d.ts.map +0 -1
- package/dist/types/src/session/format.test.d.ts +0 -2
- package/dist/types/src/session/format.test.d.ts.map +0 -1
- package/dist/types/src/session/session.d.ts +0 -61
- package/dist/types/src/session/session.d.ts.map +0 -1
- package/dist/types/src/session/session.test.d.ts +0 -2
- package/dist/types/src/session/session.test.d.ts.map +0 -1
- package/dist/types/src/testing/index.d.ts +0 -2
- package/dist/types/src/testing/index.d.ts.map +0 -1
- package/dist/types/src/testing/layer.d.ts +0 -22
- package/dist/types/src/testing/layer.d.ts.map +0 -1
- package/src/conversation/conversation.test.ts +0 -65
- package/src/conversation/conversation.ts +0 -210
- package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +0 -84
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +0 -62
- package/src/extraction/extraction-llm-function/index.ts +0 -5
- package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +0 -116
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +0 -56
- package/src/functions.conversations.json +0 -1
- package/src/functions.test.ts +0 -74
- package/src/session/GenericToolkit.ts +0 -160
- package/src/session/format.test.ts +0 -124
- package/src/session/session.conversations.json +0 -1
- package/src/session/session.test.ts +0 -163
- package/src/session/session.ts +0 -251
- package/src/testing/index.ts +0 -5
- package/src/testing/layer.ts +0 -84
package/README.md
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
# @dxos/assistant
|
|
2
|
+
|
|
2
3
|
Natural language interface to DXOS.
|
|
3
4
|
|
|
4
5
|
Communicate with your DXOS applications through conversations using advanced LLM capabilities. This package provides a flexible system for building AI assistants that can help users interact with and control DXOS apps.
|
|
@@ -1,15 +1,13 @@
|
|
|
1
|
-
import "../chunk-J5LGTIGS.mjs";
|
|
2
|
-
|
|
3
1
|
// src/extraction/extraction.ts
|
|
4
2
|
import * as Schema from "effect/Schema";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
3
|
+
import { Operation } from "@dxos/compute";
|
|
4
|
+
import { Obj } from "@dxos/echo";
|
|
7
5
|
import { log } from "@dxos/log";
|
|
8
6
|
import { Message } from "@dxos/types";
|
|
9
|
-
var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction.ts";
|
|
7
|
+
var __dxlog_file = "/__w/dxos/dxos/packages/core/compute/assistant/src/extraction/extraction.ts";
|
|
10
8
|
var ExtractionInput = Schema.Struct({
|
|
11
9
|
message: Message.Message,
|
|
12
|
-
objects: Schema.optional(Schema.Array(
|
|
10
|
+
objects: Schema.optional(Schema.Array(Obj.Unknown)),
|
|
13
11
|
options: Schema.optional(Schema.Struct({
|
|
14
12
|
timeout: Schema.optional(Schema.Number),
|
|
15
13
|
fallbackToRaw: Schema.optional(Schema.Boolean)
|
|
@@ -19,23 +17,34 @@ var ExtractionOutput = Schema.Struct({
|
|
|
19
17
|
message: Message.Message,
|
|
20
18
|
timeElapsed: Schema.Number
|
|
21
19
|
});
|
|
20
|
+
var extractionAnthropicFunction = Operation.make({
|
|
21
|
+
meta: {
|
|
22
|
+
key: "org.dxos.function.extraction.anthropic",
|
|
23
|
+
name: "Entity Extraction (Anthropic)",
|
|
24
|
+
description: "Extract entities from transcript using Anthropic LLM."
|
|
25
|
+
},
|
|
26
|
+
input: ExtractionInput,
|
|
27
|
+
output: ExtractionOutput
|
|
28
|
+
});
|
|
29
|
+
var extractionNerFunction = Operation.make({
|
|
30
|
+
meta: {
|
|
31
|
+
key: "org.dxos.function.extraction.ner",
|
|
32
|
+
name: "Entity Extraction (NER)",
|
|
33
|
+
description: "Extract entities from transcript using Named Entity Recognition."
|
|
34
|
+
},
|
|
35
|
+
input: ExtractionInput,
|
|
36
|
+
output: ExtractionOutput
|
|
37
|
+
});
|
|
22
38
|
var processTranscriptMessage = async (params) => {
|
|
23
39
|
try {
|
|
24
40
|
if (params.options?.timeout && params.options.timeout > 0) {
|
|
25
|
-
return await asyncTimeout(params.executor.invoke(params.function, params.input), params.options.timeout);
|
|
26
41
|
} else {
|
|
27
|
-
return await params.executor.invoke(params.function, params.input);
|
|
28
42
|
}
|
|
29
43
|
} catch (error) {
|
|
30
44
|
if (params.options?.fallbackToRaw) {
|
|
31
45
|
log.warn("failed to process message, falling back to raw text", {
|
|
32
46
|
error
|
|
33
|
-
}, {
|
|
34
|
-
F: __dxlog_file,
|
|
35
|
-
L: 67,
|
|
36
|
-
S: void 0,
|
|
37
|
-
C: (f, a) => f(...a)
|
|
38
|
-
});
|
|
47
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 57, S: void 0 });
|
|
39
48
|
return {
|
|
40
49
|
message: params.input.message,
|
|
41
50
|
timeElapsed: 0
|
|
@@ -44,48 +53,21 @@ var processTranscriptMessage = async (params) => {
|
|
|
44
53
|
throw error;
|
|
45
54
|
}
|
|
46
55
|
}
|
|
56
|
+
return {
|
|
57
|
+
message: params.input.message,
|
|
58
|
+
timeElapsed: 0
|
|
59
|
+
};
|
|
47
60
|
};
|
|
48
61
|
|
|
49
|
-
// src/extraction/extraction-llm-function/extraction-llm-function.ts
|
|
50
|
-
import { defineFunction } from "@dxos/functions";
|
|
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
62
|
// src/extraction/extraction-ner-function/named-entity-recognition.ts
|
|
76
63
|
import { pipeline } from "@xenova/transformers";
|
|
77
64
|
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";
|
|
65
|
+
var __dxlog_file2 = "/__w/dxos/dxos/packages/core/compute/assistant/src/extraction/extraction-ner-function/named-entity-recognition.ts";
|
|
79
66
|
var _ner;
|
|
80
67
|
var getNer = () => {
|
|
81
68
|
if (!_ner) {
|
|
82
69
|
_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
|
-
});
|
|
70
|
+
log2.info("NER model is ready", void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 14, S: void 0 });
|
|
89
71
|
return ner;
|
|
90
72
|
});
|
|
91
73
|
}
|
|
@@ -160,7 +142,7 @@ import { Filter, Query } from "@dxos/echo";
|
|
|
160
142
|
import { ObjectId } from "@dxos/keys";
|
|
161
143
|
import { DXN } from "@dxos/keys";
|
|
162
144
|
import { log as log3 } from "@dxos/log";
|
|
163
|
-
var __dxlog_file3 = "/__w/dxos/dxos/packages/core/assistant/src/extraction/quotes.ts";
|
|
145
|
+
var __dxlog_file3 = "/__w/dxos/dxos/packages/core/compute/assistant/src/extraction/quotes.ts";
|
|
164
146
|
var ReferencedQuotes = Schema2.Struct({
|
|
165
147
|
references: Schema2.Array(Schema2.Struct({
|
|
166
148
|
id: Schema2.String,
|
|
@@ -181,12 +163,7 @@ var findQuotes = async (quotes, db) => {
|
|
|
181
163
|
log3.info("found quotes in vector index", {
|
|
182
164
|
objects,
|
|
183
165
|
quote
|
|
184
|
-
}, {
|
|
185
|
-
F: __dxlog_file3,
|
|
186
|
-
L: 34,
|
|
187
|
-
S: void 0,
|
|
188
|
-
C: (f, a) => f(...a)
|
|
189
|
-
});
|
|
166
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file3, L: 26, S: void 0 });
|
|
190
167
|
return objects.length > 0 ? [
|
|
191
168
|
{
|
|
192
169
|
id: objects[0].id.toString(),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../../src/extraction/extraction.ts", "../../../../src/extraction/extraction-
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { asyncTimeout } from '@dxos/async';\nimport { Type } from '@dxos/echo';\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(Type.Obj)),\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 ProcessTranscriptMessageProps = {\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: ProcessTranscriptMessageProps): 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(Database.Service);\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 { type Database, Filter, Query } from '@dxos/echo';\nimport { ObjectId } from '@dxos/keys';\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: Database.Database): 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": "
|
|
6
|
-
"names": ["Schema", "
|
|
3
|
+
"sources": ["../../../../src/extraction/extraction.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 { Operation } from '@dxos/compute';\nimport { Obj } from '@dxos/echo';\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(Obj.Unknown)),\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 ProcessTranscriptMessageProps = {\n input: ExtractionInput;\n function: Operation.Definition<ExtractionInput, ExtractionOutput>;\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 = Operation.Definition<ExtractionInput, ExtractionOutput>;\n\n/**\n * Placeholder for Anthropic-based entity extraction.\n * Implementation is currently disabled pending restoration of extraction logic.\n */\nexport const extractionAnthropicFunction = Operation.make({\n meta: {\n key: 'org.dxos.function.extraction.anthropic',\n name: 'Entity Extraction (Anthropic)',\n description: 'Extract entities from transcript using Anthropic LLM.',\n },\n input: ExtractionInput,\n output: ExtractionOutput,\n});\n\n/**\n * Placeholder for NER-based entity extraction.\n * Implementation is currently disabled pending restoration of extraction logic.\n */\nexport const extractionNerFunction = Operation.make({\n meta: {\n key: 'org.dxos.function.extraction.ner',\n name: 'Entity Extraction (NER)',\n description: 'Extract entities from transcript using Named Entity Recognition.',\n },\n input: ExtractionInput,\n output: ExtractionOutput,\n});\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: ProcessTranscriptMessageProps): 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 // TODO(dmaretskyi): Restore extraction logic.\n return { message: params.input.message, timeElapsed: 0 };\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 { type Database, Filter, Query } from '@dxos/echo';\nimport { ObjectId } from '@dxos/keys';\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: Database.Database): 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,SAAS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ExtractionInput", "objects", "Array", "options", "optional", "Number", "fallbackToRaw", "timeElapsed", "key", "name", "description", "input", "output", "params", "timeout", "error", "message", "pipeline", "log", "_ner", "ner", "__dxlog_file", "entities", "text", "tokenGroups", "createTokenGroups", "combinedEntities", "canBeCombined", "prevToken", "currentToken", "currentState", "prevEntity", "entity", "currentEntity", "prevState", "token", "push", "lastTokenGroup", "score", "reduce", "index", "group", "at", "word", "start", "end", "combinedToken", "Schema", "Filter", "Query", "ObjectId", "DXN", "log", "__dxlog_file", "ReferencedQuotes", "String", "pipe", "description", "query", "select", "run", "info", "objects", "quote", "id", "toString", "text"]
|
|
7
7
|
}
|