@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.
- package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
- package/dist/lib/browser/extraction/index.mjs +121 -165
- package/dist/lib/browser/extraction/index.mjs.map +4 -4
- package/dist/lib/browser/index.mjs +1097 -161
- package/dist/lib/browser/index.mjs.map +4 -4
- package/dist/lib/browser/meta.json +1 -1
- package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
- package/dist/lib/node-esm/extraction/index.mjs +121 -165
- package/dist/lib/node-esm/extraction/index.mjs.map +4 -4
- package/dist/lib/node-esm/index.mjs +1097 -161
- package/dist/lib/node-esm/index.mjs.map +4 -4
- package/dist/lib/node-esm/meta.json +1 -1
- package/dist/types/src/conversation/context.d.ts +23 -10
- package/dist/types/src/conversation/context.d.ts.map +1 -1
- package/dist/types/src/conversation/conversation.d.ts +22 -31
- package/dist/types/src/conversation/conversation.d.ts.map +1 -1
- package/dist/types/src/diff.d.ts +15 -0
- package/dist/types/src/diff.d.ts.map +1 -0
- package/dist/types/src/diff.test.d.ts +2 -0
- package/dist/types/src/diff.test.d.ts.map +1 -0
- package/dist/types/src/errors.d.ts +45 -13
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/execution-graph.d.ts +85 -0
- package/dist/types/src/execution-graph.d.ts.map +1 -0
- package/dist/types/src/execution-graph.test.d.ts +2 -0
- package/dist/types/src/execution-graph.test.d.ts.map +1 -0
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts +1 -1
- package/dist/types/src/extraction/extraction-llm-function/extraction-llm-function.d.ts.map +1 -1
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.d.ts +82 -43
- package/dist/types/src/extraction/extraction-ner-function/extraction-ner-function.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 +262 -225
- package/dist/types/src/extraction/extraction.d.ts.map +1 -1
- package/dist/types/src/extraction/quotes.d.ts +1 -1
- package/dist/types/src/extraction/quotes.d.ts.map +1 -1
- package/dist/types/src/functions/services.d.ts +18 -5
- package/dist/types/src/functions/services.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +3 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/session/GenericToolkit.d.ts +84 -0
- package/dist/types/src/session/GenericToolkit.d.ts.map +1 -0
- package/dist/types/src/session/artifact-diff.d.ts +2 -2
- package/dist/types/src/session/artifact-diff.d.ts.map +1 -1
- package/dist/types/src/session/error-handling.d.ts +4 -0
- package/dist/types/src/session/error-handling.d.ts.map +1 -0
- package/dist/types/src/session/format.d.ts +5 -161
- package/dist/types/src/session/format.d.ts.map +1 -1
- package/dist/types/src/session/index.d.ts +3 -0
- package/dist/types/src/session/index.d.ts.map +1 -1
- package/dist/types/src/session/observer.d.ts +22 -0
- package/dist/types/src/session/observer.d.ts.map +1 -0
- package/dist/types/src/session/session.d.ts +22 -138
- package/dist/types/src/session/session.d.ts.map +1 -1
- package/dist/types/src/session/toolkit.d.ts +15 -0
- package/dist/types/src/session/toolkit.d.ts.map +1 -0
- package/dist/types/src/session/version-pin.d.ts +3 -3
- package/dist/types/src/session/version-pin.d.ts.map +1 -1
- package/dist/types/src/templates/system.d.ts +8 -12
- package/dist/types/src/templates/system.d.ts.map +1 -1
- package/dist/types/src/types/artifact.d.ts +20 -0
- package/dist/types/src/types/artifact.d.ts.map +1 -0
- package/dist/types/src/types/index.d.ts +2 -0
- package/dist/types/src/types/index.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +29 -31
- package/src/conversation/context.ts +75 -22
- package/src/conversation/conversation.ts +80 -77
- package/src/diff.test.ts +43 -0
- package/src/diff.ts +84 -0
- package/src/errors.ts +6 -1
- package/src/execution-graph.test.ts +740 -0
- package/src/execution-graph.ts +509 -0
- package/src/extraction/extraction-llm-function/extraction-llm-function.test.ts +9 -9
- package/src/extraction/extraction-llm-function/extraction-llm-function.ts +47 -56
- package/src/extraction/extraction-ner-function/extraction-ner-function.test.ts +16 -16
- package/src/extraction/extraction-ner-function/extraction-ner-function.ts +42 -43
- package/src/extraction/extraction-ner-function/named-entity-recognition.test.ts +12 -6
- package/src/extraction/extraction-ner-function/named-entity-recognition.ts +2 -0
- package/src/extraction/extraction.ts +7 -6
- package/src/extraction/quotes.test.ts +2 -2
- package/src/extraction/quotes.ts +3 -3
- package/src/functions/services.ts +104 -56
- package/src/index.ts +3 -1
- package/src/session/GenericToolkit.ts +130 -0
- package/src/session/artifact-diff.ts +8 -4
- package/src/session/error-handling.ts +41 -0
- package/src/session/format.test.ts +5 -4
- package/src/session/format.ts +27 -22
- package/src/session/index.ts +4 -0
- package/src/session/observer.ts +59 -0
- package/src/session/session.conversations.json +1 -0
- package/src/session/session.test.ts +35 -191
- package/src/session/session.ts +119 -185
- package/src/session/toolkit.ts +48 -0
- package/src/session/version-pin.ts +4 -5
- package/src/templates/{format.tpl → instructions/format.tpl} +8 -2
- package/src/templates/{system.tpl → instructions/system.tpl} +15 -14
- package/src/templates/system.ts +25 -16
- package/src/{types.ts → types/artifact.ts} +22 -3
- package/src/types/index.ts +5 -0
- package/dist/lib/browser/chunk-6WRGDEMH.mjs +0 -89
- package/dist/lib/browser/chunk-6WRGDEMH.mjs.map +0 -7
- package/dist/lib/browser/chunk-NZGGCEF3.mjs +0 -341
- package/dist/lib/browser/chunk-NZGGCEF3.mjs.map +0 -7
- package/dist/lib/browser/named-entity-recognition-O46UTCLR.mjs +0 -13
- package/dist/lib/node-esm/chunk-3UU5V4FS.mjs +0 -91
- package/dist/lib/node-esm/chunk-3UU5V4FS.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-XOOPGSGW.mjs +0 -343
- package/dist/lib/node-esm/chunk-XOOPGSGW.mjs.map +0 -7
- package/dist/lib/node-esm/named-entity-recognition-W4VMRCH6.mjs +0 -14
- package/dist/types/src/session/version-pin.test.d.ts +0 -2
- package/dist/types/src/session/version-pin.test.d.ts.map +0 -1
- package/dist/types/src/summarization/summarization.test.d.ts +0 -2
- package/dist/types/src/summarization/summarization.test.d.ts.map +0 -1
- package/dist/types/src/types.d.ts +0 -16
- package/dist/types/src/types.d.ts.map +0 -1
- package/src/session/__snapshots__/session.test.ts.snap +0 -32
- package/src/session/version-pin.test.ts +0 -7
- package/src/summarization/summarization.test.ts +0 -197
- /package/dist/lib/browser/{named-entity-recognition-O46UTCLR.mjs.map → chunk-J5LGTIGS.mjs.map} +0 -0
- /package/dist/lib/node-esm/{named-entity-recognition-W4VMRCH6.mjs.map → chunk-HSLMI22Q.mjs.map} +0 -0
- /package/src/extraction/extraction-llm-function/{instructions.tpl → transcription-instructions.tpl} +0 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2025 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import type * as Tool from '@effect/ai/Tool';
|
|
6
|
+
import * as Toolkit from '@effect/ai/Toolkit';
|
|
7
|
+
import type * as Context from 'effect/Context';
|
|
8
|
+
import * as Effect from 'effect/Effect';
|
|
9
|
+
|
|
10
|
+
import { type AiToolNotFoundError, ToolExecutionService, type ToolId, ToolResolverService } from '@dxos/ai';
|
|
11
|
+
import { type Blueprint } from '@dxos/blueprints';
|
|
12
|
+
import { isTruthy } from '@dxos/util';
|
|
13
|
+
|
|
14
|
+
export type ToolkitParams<Tools extends Record<string, Tool.Any>> = {
|
|
15
|
+
toolkit?: Toolkit.Toolkit<Tools>;
|
|
16
|
+
toolIds?: ToolId[];
|
|
17
|
+
blueprints?: Blueprint.Blueprint[];
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Build a combined toolkit from the blueprint tools and the provided toolkit.
|
|
22
|
+
*/
|
|
23
|
+
export const createToolkit = <Tools extends Record<string, Tool.Any> = {}>({
|
|
24
|
+
toolkit: toolkitParam,
|
|
25
|
+
toolIds = [],
|
|
26
|
+
blueprints = [],
|
|
27
|
+
}: ToolkitParams<Tools>): Effect.Effect<
|
|
28
|
+
Toolkit.WithHandler<any>,
|
|
29
|
+
AiToolNotFoundError,
|
|
30
|
+
ToolResolverService | ToolExecutionService | Tool.HandlersFor<Tools>
|
|
31
|
+
> =>
|
|
32
|
+
Effect.gen(function* () {
|
|
33
|
+
const blueprintToolkit = yield* ToolResolverService.resolveToolkit([
|
|
34
|
+
...blueprints.flatMap(({ tools }) => tools),
|
|
35
|
+
...toolIds,
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
const blueprintToolkitHandler: Context.Context<Tool.HandlersFor<any>> = yield* blueprintToolkit.toContext(
|
|
39
|
+
ToolExecutionService.handlersFor(blueprintToolkit),
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
const toolkit = Toolkit.merge(...[toolkitParam, blueprintToolkit].filter(isTruthy));
|
|
43
|
+
return yield* toolkit.pipe(Effect.provide(blueprintToolkitHandler)) as any as Effect.Effect<
|
|
44
|
+
Toolkit.WithHandler<any>,
|
|
45
|
+
never,
|
|
46
|
+
Tool.HandlersFor<Tools>
|
|
47
|
+
>;
|
|
48
|
+
});
|
|
@@ -2,12 +2,11 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import * as Schema from 'effect/Schema';
|
|
6
6
|
|
|
7
|
-
import { type
|
|
8
|
-
import { getVersion } from '@dxos/echo-db';
|
|
9
|
-
import { type
|
|
10
|
-
import { type ContentBlock } from '@dxos/schema';
|
|
7
|
+
import { type AnyEchoObject, ObjectId } from '@dxos/echo/internal';
|
|
8
|
+
import { type ObjectVersion, getVersion } from '@dxos/echo-db';
|
|
9
|
+
import { type ContentBlock } from '@dxos/types';
|
|
11
10
|
|
|
12
11
|
// TODO(dmaretskyi): Extract.
|
|
13
12
|
const ObjectVersionSchema = Schema.Unknown as Schema.Schema<ObjectVersion>;
|
|
@@ -23,6 +23,7 @@ The <typename> element is the type of the object.
|
|
|
23
23
|
It is very important to respond in the correct format.
|
|
24
24
|
You response must be valid Markdown.
|
|
25
25
|
In some cases you should respond with well-formed XML tags along with the content.
|
|
26
|
+
Code snippets should use 2-space indents.
|
|
26
27
|
|
|
27
28
|
{{#if cot}}
|
|
28
29
|
Before responding, explain your reasoning and include your detailed chain-of-thought enclosed in a <cot> tag.
|
|
@@ -42,8 +43,9 @@ You can reply with a block reference for objects if you have the DXN. For exampl
|
|
|
42
43
|
|
|
43
44
|
### Suggestions
|
|
44
45
|
|
|
45
|
-
Each suggestion must in the form of a proposed action enclosed in a <
|
|
46
|
-
Example: <
|
|
46
|
+
Each suggestion must in the form of a proposed action enclosed in a <suggestion> tag.
|
|
47
|
+
Example: <suggestion>Show on a map</suggestion>
|
|
48
|
+
Do not use bullets when listing suggestions.
|
|
47
49
|
|
|
48
50
|
### Multiple choice questions
|
|
49
51
|
|
|
@@ -53,3 +55,7 @@ Example: <select><option>Yes</option><option>No</option></select>
|
|
|
53
55
|
## Toolkit
|
|
54
56
|
|
|
55
57
|
If the user asks for a list of tools, then just emit a single self-closing <toolkit/> tag instead of listing the tools.
|
|
58
|
+
|
|
59
|
+
## Context
|
|
60
|
+
|
|
61
|
+
The current date and time is {{DATETIME}}.
|
|
@@ -1,17 +1,15 @@
|
|
|
1
1
|
{{! System Prompt }}
|
|
2
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
|
|
6
|
-
In your initial greeting state your name and make some suggestions based on the current context objects.
|
|
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 inside of 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
|
+
- You are an advanced AI assistant capable of creating and managing artifacts from provided data and tools.
|
|
8
|
+
- Your task is to process user commands and questions and decide how best to respond.
|
|
9
|
+
- In general be concise and direct.
|
|
10
|
+
- Follow all instructions carefully.
|
|
7
11
|
|
|
8
|
-
|
|
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:
|
|
12
|
+
## Planning
|
|
15
13
|
|
|
16
14
|
- Analyze the structure and type of the content in the user's message.
|
|
17
15
|
- Determine if you complete the task using the available blueprint definitions?
|
|
@@ -27,7 +25,7 @@ Include the following steps:
|
|
|
27
25
|
- Call the show tool to show the artifact to the user.
|
|
28
26
|
- 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
27
|
|
|
30
|
-
|
|
28
|
+
## Blueprints and Artifacts
|
|
31
29
|
|
|
32
30
|
- Determine if the interaction involves an artifact. Prefer artifacts for tables, lists, spreadsheets, kanbans, games, images, and other structured data.
|
|
33
31
|
- Determine if the user is explicitly talking about creating a new artifact, or wants to use an existing artifact.
|
|
@@ -35,13 +33,16 @@ Include the following steps:
|
|
|
35
33
|
- If you decide to create an artifact, call the associated tool to create the artifact.
|
|
36
34
|
- Artifacts are stored in the database. Tools are used to create and query artifacts.
|
|
37
35
|
- If you are unsure about creating an artifact ask the user for clarification.
|
|
38
|
-
|
|
39
36
|
- Artifacts are mutable objects that can change over the course of the conversation.
|
|
40
37
|
- 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
38
|
- You must never generate the id of the artifact; only recall the ids that are already in the history.
|
|
42
39
|
- Artifacts are created by requiring the specific artifact using the require_artifact tool and creating it by calling the associated tool.
|
|
43
|
-
|
|
44
40
|
- You can add suggested actions at the end of your response.
|
|
45
41
|
- 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
42
|
- Suggested actions must be in the form of a user instruction that you can follow.
|
|
47
43
|
- Suggested actions could include actions that create artifacts.
|
|
44
|
+
- After creating an artifact use a tool to add it to the chat context.
|
|
45
|
+
|
|
46
|
+
## Context
|
|
47
|
+
|
|
48
|
+
Today is {{DATETIME}}.
|
package/src/templates/system.ts
CHANGED
|
@@ -2,31 +2,40 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import defaultsDeep from 'lodash.defaultsdeep';
|
|
6
6
|
|
|
7
|
-
import
|
|
8
|
-
import
|
|
7
|
+
import { type ModelCapabilities } from '@dxos/ai';
|
|
8
|
+
import { Template } from '@dxos/blueprints';
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
* Emit chain-of-thought inside <cot> tag.
|
|
13
|
-
* Should be `false` for models with built-in reasoning: Claude, deepseek, o1.
|
|
14
|
-
*/
|
|
15
|
-
cot?: boolean;
|
|
10
|
+
import FORMAT from './instructions/format.tpl?raw';
|
|
11
|
+
import SYSTEM from './instructions/system.tpl?raw';
|
|
16
12
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
13
|
+
/**
|
|
14
|
+
* System template variables.
|
|
15
|
+
*/
|
|
16
|
+
export type SystemPromptOptions = ModelCapabilities & {
|
|
17
|
+
DATETIME: string;
|
|
21
18
|
};
|
|
22
19
|
|
|
23
20
|
/**
|
|
24
21
|
* Base system prompt.
|
|
25
22
|
* NOTE: This contains protocol instructions that can not be dynamically edited.
|
|
26
23
|
*/
|
|
27
|
-
export const createSystemPrompt = (options:
|
|
24
|
+
export const createSystemPrompt = (options: Partial<SystemPromptOptions> = {}) =>
|
|
25
|
+
Template.process<SystemPromptOptions>(
|
|
26
|
+
FORMAT,
|
|
27
|
+
defaultsDeep(options, {
|
|
28
|
+
DATETIME: new Date().toISOString(),
|
|
29
|
+
}),
|
|
30
|
+
);
|
|
28
31
|
|
|
29
32
|
export const templates = {
|
|
30
|
-
|
|
31
|
-
system: Template.make({
|
|
33
|
+
/** Editable system prompt.*/
|
|
34
|
+
system: Template.make({
|
|
35
|
+
/**
|
|
36
|
+
* NOTE: We are forbidden from accessing randomness at model level in cloudflare, so we have to have pre-generated ids.
|
|
37
|
+
*/
|
|
38
|
+
id: '01K2J2FZWH39F55CS7B26GP1Q3',
|
|
39
|
+
source: SYSTEM,
|
|
40
|
+
}),
|
|
32
41
|
};
|
|
@@ -2,9 +2,12 @@
|
|
|
2
2
|
// Copyright 2025 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import
|
|
5
|
+
import type * as Effect from 'effect/Effect';
|
|
6
|
+
import * as Schema from 'effect/Schema';
|
|
6
7
|
|
|
7
|
-
import { type
|
|
8
|
+
import { type ObjectNotFoundError, type Type } from '@dxos/echo';
|
|
9
|
+
import { type ObjectId } from '@dxos/echo/internal';
|
|
10
|
+
import { DatabaseService } from '@dxos/echo-db';
|
|
8
11
|
import { DXN, LOCAL_SPACE_TAG, type SpaceId } from '@dxos/keys';
|
|
9
12
|
import { trim } from '@dxos/util';
|
|
10
13
|
|
|
@@ -17,10 +20,15 @@ export const createArtifactElement = (id: ObjectId) => `<artifact id=${id} />`;
|
|
|
17
20
|
* A model-friendly way to reference an object.
|
|
18
21
|
* Supports vairous formats that will be normalized to a DXN.
|
|
19
22
|
*/
|
|
20
|
-
// TODO(burdon): Rename
|
|
23
|
+
// TODO(burdon): Rename RefFromLLM?
|
|
21
24
|
export const ArtifactId: Schema.Schema<string> & {
|
|
22
25
|
toDXN: (reference: ArtifactId, owningSpaceId?: SpaceId) => DXN;
|
|
26
|
+
resolve: <S extends Type.Obj.Any | Type.Relation.Any>(
|
|
27
|
+
schema: S,
|
|
28
|
+
ref: ArtifactId,
|
|
29
|
+
) => Effect.Effect<Schema.Schema.Type<S>, ObjectNotFoundError, DatabaseService>;
|
|
23
30
|
} = class extends Schema.String.annotations({
|
|
31
|
+
// TODO(dmaretskyi): This section gets overriden.
|
|
24
32
|
description: trim`
|
|
25
33
|
The ID of the referenced object. Formats accepted:
|
|
26
34
|
- DXN (dxn:echo:@:XXXXX). DXNs can be prepended with an @ symbol for compatibility with in-text references.
|
|
@@ -47,6 +55,17 @@ export const ArtifactId: Schema.Schema<string> & {
|
|
|
47
55
|
throw new Error(`Unable to parse object reference: ${reference}`);
|
|
48
56
|
}
|
|
49
57
|
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Resolves an artifact ID to an object.
|
|
61
|
+
*/
|
|
62
|
+
static resolve<S extends Type.Obj.Any | Type.Relation.Any>(
|
|
63
|
+
schema: S,
|
|
64
|
+
ref: ArtifactId,
|
|
65
|
+
): Effect.Effect<Schema.Schema.Type<S>, ObjectNotFoundError, DatabaseService> {
|
|
66
|
+
const dxn = ArtifactId.toDXN(ref);
|
|
67
|
+
return DatabaseService.resolve(dxn, schema);
|
|
68
|
+
}
|
|
50
69
|
};
|
|
51
70
|
|
|
52
71
|
export type ArtifactId = Schema.Schema.Type<typeof ArtifactId>;
|
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
// src/extraction/extraction-ner-function/named-entity-recognition.ts
|
|
2
|
-
import { pipeline } from "@xenova/transformers";
|
|
3
|
-
import { log } from "@dxos/log";
|
|
4
|
-
var __dxlog_file = "/__w/dxos/dxos/packages/core/assistant/src/extraction/extraction-ner-function/named-entity-recognition.ts";
|
|
5
|
-
var _ner;
|
|
6
|
-
var getNer = () => {
|
|
7
|
-
if (!_ner) {
|
|
8
|
-
_ner = pipeline("ner", "Xenova/bert-base-NER").then((ner) => {
|
|
9
|
-
log.info("NER model is ready", void 0, {
|
|
10
|
-
F: __dxlog_file,
|
|
11
|
-
L: 23,
|
|
12
|
-
S: void 0,
|
|
13
|
-
C: (f, a) => f(...a)
|
|
14
|
-
});
|
|
15
|
-
return ner;
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
return _ner;
|
|
19
|
-
};
|
|
20
|
-
var extractFullEntities = async (text) => {
|
|
21
|
-
const ner = await getNer();
|
|
22
|
-
const entities = await ner(text);
|
|
23
|
-
const tokenGroups = createTokenGroups(entities);
|
|
24
|
-
const combinedEntities = tokenGroups.map(combineNerTokens);
|
|
25
|
-
return combinedEntities;
|
|
26
|
-
};
|
|
27
|
-
var createTokenGroups = (tokens) => {
|
|
28
|
-
const tokenGroups = [];
|
|
29
|
-
const canBeCombined = (prevToken, currentToken) => {
|
|
30
|
-
const [currentState, currentEntity] = currentToken.entity.split("-");
|
|
31
|
-
const [prevState, prevEntity] = prevToken.entity.split("-");
|
|
32
|
-
if (prevEntity !== currentEntity) {
|
|
33
|
-
return false;
|
|
34
|
-
}
|
|
35
|
-
if (prevState === "O") {
|
|
36
|
-
return false;
|
|
37
|
-
}
|
|
38
|
-
if (currentState === "I") {
|
|
39
|
-
return true;
|
|
40
|
-
}
|
|
41
|
-
if ((prevState === "B" || prevState === "I") && currentState === "B") {
|
|
42
|
-
return currentToken.word.startsWith("#");
|
|
43
|
-
}
|
|
44
|
-
return false;
|
|
45
|
-
};
|
|
46
|
-
for (const token of tokens) {
|
|
47
|
-
if (tokenGroups.length === 0) {
|
|
48
|
-
tokenGroups.push([
|
|
49
|
-
token
|
|
50
|
-
]);
|
|
51
|
-
continue;
|
|
52
|
-
}
|
|
53
|
-
const lastTokenGroup = tokenGroups.at(-1);
|
|
54
|
-
if (canBeCombined(lastTokenGroup.at(-1), token)) {
|
|
55
|
-
lastTokenGroup.push(token);
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
tokenGroups.push([
|
|
59
|
-
token
|
|
60
|
-
]);
|
|
61
|
-
}
|
|
62
|
-
return tokenGroups;
|
|
63
|
-
};
|
|
64
|
-
var combineNerTokens = (group) => {
|
|
65
|
-
const combinedToken = {
|
|
66
|
-
entity: group.at(0).entity.split("-")[1],
|
|
67
|
-
score: group.reduce((acc, token) => acc + token.score, 0) / group.length,
|
|
68
|
-
index: group.at(0).index,
|
|
69
|
-
word: group.at(0).word,
|
|
70
|
-
start: group.at(0).start,
|
|
71
|
-
end: group.at(-1).end
|
|
72
|
-
};
|
|
73
|
-
for (const token of group.slice(1)) {
|
|
74
|
-
if (token.word.startsWith("#")) {
|
|
75
|
-
combinedToken.word += token.word.replace(/^#+/, "");
|
|
76
|
-
} else {
|
|
77
|
-
combinedToken.word += " " + token.word;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return combinedToken;
|
|
81
|
-
};
|
|
82
|
-
|
|
83
|
-
export {
|
|
84
|
-
getNer,
|
|
85
|
-
extractFullEntities,
|
|
86
|
-
createTokenGroups,
|
|
87
|
-
combineNerTokens
|
|
88
|
-
};
|
|
89
|
-
//# sourceMappingURL=chunk-6WRGDEMH.mjs.map
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/extraction/extraction-ner-function/named-entity-recognition.ts"],
|
|
4
|
-
"sourcesContent": ["//\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 * 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 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"],
|
|
5
|
-
"mappings": ";AAIA,SAIEA,gBACK;AAEP,SAASC,WAAW;;AAEpB,IAAIC;AAMG,IAAMC,SAAS,MAAA;AACpB,MAAI,CAACD,MAAM;AACTA,WAAOF,SAAS,OAAO,sBAAA,EAAwBI,KAAK,CAACC,QAAAA;AACnDJ,UAAIK,KAAK,sBAAA,QAAA;;;;;;AACT,aAAOD;IACT,CAAA;EACF;AACA,SAAOH;AACT;AAKO,IAAMK,sBAAsB,OAAOC,SAAAA;AACxC,QAAMH,MAAM,MAAMF,OAAAA;AAClB,QAAMM,WAAY,MAAMJ,IAAIG,IAAAA;AAC5B,QAAME,cAAcC,kBAAkBF,QAAAA;AACtC,QAAMG,mBAAmBF,YAAYG,IAAIC,gBAAAA;AACzC,SAAOF;AACT;AAEO,IAAMD,oBAAoB,CAACI,WAAAA;AAChC,QAAML,cAA6C,CAAA;AAEnD,QAAMM,gBAAgB,CAACC,WAAsCC,iBAAAA;AAC3D,UAAM,CAACC,cAAcC,aAAAA,IAAiBF,aAAaG,OAAOC,MAAM,GAAA;AAChE,UAAM,CAACC,WAAWC,UAAAA,IAAcP,UAAUI,OAAOC,MAAM,GAAA;AACvD,QAAIE,eAAeJ,eAAe;AAChC,aAAO;IACT;AACA,QAAIG,cAAc,KAAK;AACrB,aAAO;IACT;AACA,QAAIJ,iBAAiB,KAAK;AACxB,aAAO;IACT;AACA,SAAKI,cAAc,OAAOA,cAAc,QAAQJ,iBAAiB,KAAK;AACpE,aAAOD,aAAaO,KAAKC,WAAW,GAAA;IACtC;AACA,WAAO;EACT;AAEA,aAAWC,SAASZ,QAAQ;AAC1B,QAAIL,YAAYkB,WAAW,GAAG;AAC5BlB,kBAAYmB,KAAK;QAACF;OAAM;AACxB;IACF;AACA,UAAMG,iBAAiBpB,YAAYqB,GAAG,EAAC;AACvC,QAAIf,cAAcc,eAAeC,GAAG,EAAC,GAAKJ,KAAAA,GAAQ;AAChDG,qBAAeD,KAAKF,KAAAA;AACpB;IACF;AACAjB,gBAAYmB,KAAK;MAACF;KAAM;EAC1B;AAEA,SAAOjB;AACT;AAEO,IAAMI,mBAAmB,CAACkB,UAAAA;AAC/B,QAAMC,gBAA2C;IAC/CZ,QAAQW,MAAMD,GAAG,CAAA,EAAIV,OAAOC,MAAM,GAAA,EAAK,CAAA;IACvCY,OAAOF,MAAMG,OAAO,CAACC,KAAKT,UAAUS,MAAMT,MAAMO,OAAO,CAAA,IAAKF,MAAMJ;IAClES,OAAOL,MAAMD,GAAG,CAAA,EAAIM;IACpBZ,MAAMO,MAAMD,GAAG,CAAA,EAAIN;IACnBa,OAAON,MAAMD,GAAG,CAAA,EAAIO;IACpBC,KAAKP,MAAMD,GAAG,EAAC,EAAIQ;EACrB;AAEA,aAAWZ,SAASK,MAAMQ,MAAM,CAAA,GAAI;AAClC,QAAIb,MAAMF,KAAKC,WAAW,GAAA,GAAM;AAC9BO,oBAAcR,QAAQE,MAAMF,KAAKgB,QAAQ,OAAO,EAAA;IAClD,OAAO;AACLR,oBAAcR,QAAQ,MAAME,MAAMF;IACpC;EACF;AAEA,SAAOQ;AACT;",
|
|
6
|
-
"names": ["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"]
|
|
7
|
-
}
|