@anvia/graph 1.0.8 → 1.0.10
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 +27 -0
- package/dist/{chunk-N3CKMOPE.js → chunk-S2QTQGBS.js} +3 -2
- package/dist/chunk-S2QTQGBS.js.map +1 -0
- package/dist/{explore-9jm2c1mG.d.ts → explore-BIGzT6El.d.ts} +45 -1
- package/dist/explore.d.ts +1 -1
- package/dist/explore.js +1 -1
- package/dist/index.d.ts +52 -5
- package/dist/index.js +252 -60
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunk-N3CKMOPE.js.map +0 -1
package/README.md
CHANGED
|
@@ -47,9 +47,26 @@ const ingestion = await ingestGraphText({
|
|
|
47
47
|
},
|
|
48
48
|
conflict: "error",
|
|
49
49
|
orphanEntities: "delete",
|
|
50
|
+
factConflicts: {
|
|
51
|
+
entity: {
|
|
52
|
+
properties: {
|
|
53
|
+
summary: "prefer-longest",
|
|
54
|
+
aliases: "union",
|
|
55
|
+
confidence: "max",
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
},
|
|
50
59
|
});
|
|
51
60
|
```
|
|
52
61
|
|
|
62
|
+
Extraction conflicts and stored-graph write conflicts are separate policies. `factConflicts`
|
|
63
|
+
resolves disagreements between chunks before persistence; `conflict` controls collisions with facts
|
|
64
|
+
already stored by the graph adapter. Extraction rejects disagreements by default. Built-in
|
|
65
|
+
property strategies include `prefer-first`, `prefer-last`, `prefer-defined`, `prefer-longest`,
|
|
66
|
+
`union`, `max`, and `min`; a custom resolver receives structured candidate and source chunk data.
|
|
67
|
+
Conflict errors and resolved warnings include the fact type, stable key, parsed identity, property,
|
|
68
|
+
candidate values, and source chunk IDs. Resolved disagreements are returned in `warnings`.
|
|
69
|
+
|
|
53
70
|
Use `ingestGraphDocuments()` for a batch. Both functions extract facts, embed chunks and entities,
|
|
54
71
|
and atomically replace each source document in the managed graph. Existing graph registrations are
|
|
55
72
|
read-only and are rejected as ingestion targets by TypeScript.
|
|
@@ -61,6 +78,12 @@ reuse the chunk embeddings without another model call:
|
|
|
61
78
|
await vectorStore.upsert({ documents: ingestion.vectorDocuments });
|
|
62
79
|
```
|
|
63
80
|
|
|
81
|
+
Every ingestion result includes a `receipt` with document, entity, relationship, and vector IDs,
|
|
82
|
+
the graph write counts, warnings, an optional caller-supplied `revision`, and vector-stage status.
|
|
83
|
+
Use `ingestGraphTextToStores()` or `ingestGraphDocumentsToStores()` to write the graph followed by
|
|
84
|
+
the vector store. If the second stage fails, `GraphIngestionStageError` exposes a receipt with a
|
|
85
|
+
completed graph stage and failed vector stage for queue reconciliation.
|
|
86
|
+
|
|
64
87
|
The graph and vector writes are separate transactions. Applications that require cross-store
|
|
65
88
|
reconciliation should persist their own ingestion status and retry the incomplete write. Advanced
|
|
66
89
|
callers can use `prepareGraphDocuments()` to run chunking, extraction, and embedding without writing,
|
|
@@ -105,6 +128,7 @@ Adapters implementing `GraphExplorer` expose a portable, bounded view for visual
|
|
|
105
128
|
const overview = await graph.explore({
|
|
106
129
|
mode: "overview",
|
|
107
130
|
nodeTypes: ["Product"],
|
|
131
|
+
includeProvenance: true,
|
|
108
132
|
maxNodes: 100,
|
|
109
133
|
maxRelationships: 200,
|
|
110
134
|
});
|
|
@@ -120,3 +144,6 @@ const neighborhood = await graph.explore({
|
|
|
120
144
|
Explorer IDs are opaque and provider-specific. They are intended for follow-up expansion within the
|
|
121
145
|
same graph, not persistence or cross-provider migration. Adapters cap overview and expansion requests,
|
|
122
146
|
return truncation metadata, and omit reserved Anvia properties such as stored embeddings.
|
|
147
|
+
|
|
148
|
+
When `includeProvenance` is true, supported adapters attach source `documentIds` and `chunkIds` to
|
|
149
|
+
nodes and relationships.
|
|
@@ -23,7 +23,8 @@ function resolveGraphExploreOptions(schema, options) {
|
|
|
23
23
|
defaultMaxRelationships,
|
|
24
24
|
maximumRelationships,
|
|
25
25
|
"maxRelationships"
|
|
26
|
-
)
|
|
26
|
+
),
|
|
27
|
+
includeProvenance: options.includeProvenance ?? false
|
|
27
28
|
};
|
|
28
29
|
if (options.abortSignal !== void 0) base.abortSignal = options.abortSignal;
|
|
29
30
|
if (options.mode === "overview") {
|
|
@@ -82,4 +83,4 @@ function boundedInteger(value, fallback, maximum, label) {
|
|
|
82
83
|
export {
|
|
83
84
|
resolveGraphExploreOptions
|
|
84
85
|
};
|
|
85
|
-
//# sourceMappingURL=chunk-
|
|
86
|
+
//# sourceMappingURL=chunk-S2QTQGBS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/explore.ts"],"sourcesContent":["import type { GraphExploreDirection, GraphExploreOptions, GraphSchemaLike } from \"./types.js\";\n\nconst defaultMaxNodes = 100;\nconst maximumNodes = 500;\nconst defaultMaxRelationships = 200;\nconst maximumRelationships = 1_000;\nconst defaultMaxDepth = 1;\nconst maximumDepth = 4;\nconst maximumRoots = 20;\n\ntype ResolvedGraphExploreBase = Readonly<{\n nodeTypes: readonly string[];\n relationships: readonly string[];\n maxNodes: number;\n maxRelationships: number;\n includeProvenance: boolean;\n abortSignal?: AbortSignal | undefined;\n}>;\n\nexport type ResolvedGraphExploreOverviewOptions = ResolvedGraphExploreBase &\n Readonly<{ mode: \"overview\" }>;\n\nexport type ResolvedGraphExploreExpandOptions = ResolvedGraphExploreBase &\n Readonly<{\n mode: \"expand\";\n nodeIds: readonly string[];\n direction: GraphExploreDirection;\n maxDepth: number;\n }>;\n\nexport type ResolvedGraphExploreOptions =\n | ResolvedGraphExploreOverviewOptions\n | ResolvedGraphExploreExpandOptions;\n\nexport function resolveGraphExploreOptions<Schema extends GraphSchemaLike>(\n schema: Schema,\n options: GraphExploreOptions<Schema>,\n): ResolvedGraphExploreOptions {\n const nodeTypes = resolveNames(options.nodeTypes, Object.keys(schema.nodes), \"node type\");\n const relationships = resolveNames(\n options.relationships,\n Object.keys(schema.relationships),\n \"relationship type\",\n true,\n );\n const base: {\n nodeTypes: string[];\n relationships: string[];\n maxNodes: number;\n maxRelationships: number;\n includeProvenance: boolean;\n abortSignal?: AbortSignal | undefined;\n } = {\n nodeTypes,\n relationships,\n maxNodes: boundedInteger(options.maxNodes, defaultMaxNodes, maximumNodes, \"maxNodes\"),\n maxRelationships: boundedInteger(\n options.maxRelationships,\n defaultMaxRelationships,\n maximumRelationships,\n \"maxRelationships\",\n ),\n includeProvenance: options.includeProvenance ?? false,\n };\n if (options.abortSignal !== undefined) base.abortSignal = options.abortSignal;\n if (options.mode === \"overview\") {\n return { ...base, mode: \"overview\" };\n }\n const nodeIds = uniqueNonEmptyStrings(options.nodeIds, \"node id\");\n if (nodeIds.length === 0) {\n throw new TypeError(\"Graph expansion requires at least one node id.\");\n }\n if (nodeIds.length > maximumRoots) {\n throw new RangeError(`Graph expansion accepts at most ${maximumRoots} root nodes.`);\n }\n const direction = options.direction ?? \"both\";\n if (direction !== \"outgoing\" && direction !== \"incoming\" && direction !== \"both\") {\n throw new TypeError(\"Graph expansion direction must be outgoing, incoming, or both.\");\n }\n return {\n ...base,\n mode: \"expand\",\n nodeIds,\n direction,\n maxDepth: boundedInteger(options.maxDepth, defaultMaxDepth, maximumDepth, \"maxDepth\"),\n };\n}\n\nfunction resolveNames(\n selected: readonly string[] | undefined,\n available: readonly string[],\n label: string,\n allowEmpty = false,\n): string[] {\n const values = selected === undefined ? [...available] : uniqueNonEmptyStrings(selected, label);\n if (!allowEmpty && values.length === 0) {\n throw new TypeError(`Graph exploration requires at least one ${label}.`);\n }\n const known = new Set(available);\n for (const value of values) {\n if (!known.has(value))\n throw new TypeError(`Graph exploration references unknown ${label} ${value}.`);\n }\n return values;\n}\n\nfunction uniqueNonEmptyStrings(values: readonly string[], label: string): string[] {\n const unique = new Set<string>();\n for (const value of values) {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`Graph ${label} must be a non-empty string.`);\n }\n if (unique.has(value)) throw new TypeError(`Duplicate graph ${label}: ${value}.`);\n unique.add(value);\n }\n return [...unique];\n}\n\nfunction boundedInteger(\n value: number | undefined,\n fallback: number,\n maximum: number,\n label: string,\n): number {\n const resolved = value ?? fallback;\n if (!Number.isSafeInteger(resolved) || resolved < 1 || resolved > maximum) {\n throw new RangeError(`Graph exploration ${label} must be between 1 and ${maximum}.`);\n }\n return resolved;\n}\n"],"mappings":";AAEA,IAAM,kBAAkB;AACxB,IAAM,eAAe;AACrB,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAC7B,IAAM,kBAAkB;AACxB,IAAM,eAAe;AACrB,IAAM,eAAe;AA0Bd,SAAS,2BACd,QACA,SAC6B;AAC7B,QAAM,YAAY,aAAa,QAAQ,WAAW,OAAO,KAAK,OAAO,KAAK,GAAG,WAAW;AACxF,QAAM,gBAAgB;AAAA,IACpB,QAAQ;AAAA,IACR,OAAO,KAAK,OAAO,aAAa;AAAA,IAChC;AAAA,IACA;AAAA,EACF;AACA,QAAM,OAOF;AAAA,IACF;AAAA,IACA;AAAA,IACA,UAAU,eAAe,QAAQ,UAAU,iBAAiB,cAAc,UAAU;AAAA,IACpF,kBAAkB;AAAA,MAChB,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,mBAAmB,QAAQ,qBAAqB;AAAA,EAClD;AACA,MAAI,QAAQ,gBAAgB,OAAW,MAAK,cAAc,QAAQ;AAClE,MAAI,QAAQ,SAAS,YAAY;AAC/B,WAAO,EAAE,GAAG,MAAM,MAAM,WAAW;AAAA,EACrC;AACA,QAAM,UAAU,sBAAsB,QAAQ,SAAS,SAAS;AAChE,MAAI,QAAQ,WAAW,GAAG;AACxB,UAAM,IAAI,UAAU,gDAAgD;AAAA,EACtE;AACA,MAAI,QAAQ,SAAS,cAAc;AACjC,UAAM,IAAI,WAAW,mCAAmC,YAAY,cAAc;AAAA,EACpF;AACA,QAAM,YAAY,QAAQ,aAAa;AACvC,MAAI,cAAc,cAAc,cAAc,cAAc,cAAc,QAAQ;AAChF,UAAM,IAAI,UAAU,gEAA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phRelationship<Schema>[];
|
|
60
60
|
mentions: readonly GraphMention[];
|
|
61
61
|
}>;
|
|
62
|
+
type GraphFactKind = "entity" | "relationship";
|
|
63
|
+
type GraphFactConflictCandidate = Readonly<{
|
|
64
|
+
chunkId: string;
|
|
65
|
+
properties: GraphProperties;
|
|
66
|
+
value: GraphPropertyValue | undefined;
|
|
67
|
+
}>;
|
|
68
|
+
type GraphFactPropertyConflict = Readonly<{
|
|
69
|
+
code: "GRAPH_FACT_CONFLICT";
|
|
70
|
+
kind: GraphFactKind;
|
|
71
|
+
key: string;
|
|
72
|
+
type: string;
|
|
73
|
+
identity: GraphNodeIdentity;
|
|
74
|
+
property: string;
|
|
75
|
+
candidates: readonly GraphFactConflictCandidate[];
|
|
76
|
+
sourceChunkIds: readonly string[];
|
|
77
|
+
}>;
|
|
78
|
+
type GraphFactPropertyConflictResolver = (conflict: GraphFactPropertyConflict) => GraphPropertyValue | undefined;
|
|
79
|
+
type GraphFactPropertyConflictStrategy = "reject" | "prefer-first" | "prefer-last" | "prefer-defined" | "prefer-longest" | "union" | "max" | "min" | GraphFactPropertyConflictResolver;
|
|
80
|
+
type GraphFactConflictPolicy = Readonly<{
|
|
81
|
+
default?: GraphFactPropertyConflictStrategy | undefined;
|
|
82
|
+
properties?: Readonly<Record<string, GraphFactPropertyConflictStrategy>> | undefined;
|
|
83
|
+
resolve?: GraphFactPropertyConflictResolver | undefined;
|
|
84
|
+
}>;
|
|
85
|
+
type GraphFactConflictOptions = Readonly<{
|
|
86
|
+
entity?: GraphFactConflictPolicy | undefined;
|
|
87
|
+
relationship?: GraphFactConflictPolicy | undefined;
|
|
88
|
+
}>;
|
|
89
|
+
type GraphFactConflictWarning = Omit<GraphFactPropertyConflict, "code"> & Readonly<{
|
|
90
|
+
code: "GRAPH_FACT_CONFLICT_RESOLVED";
|
|
91
|
+
strategy: string;
|
|
92
|
+
resolvedValue: GraphPropertyValue | undefined;
|
|
93
|
+
}>;
|
|
94
|
+
type GraphExtractionWarning = GraphFactConflictWarning;
|
|
62
95
|
type GraphChunk<Metadata extends GraphProperties = GraphProperties> = Readonly<{
|
|
63
96
|
id: string;
|
|
64
97
|
documentId: string;
|
|
@@ -78,10 +111,12 @@ type ExtractGraphFactsOptions<Schema extends GraphSchemaLike, Model extends Comp
|
|
|
78
111
|
retries?: RetrySetting | undefined;
|
|
79
112
|
concurrency?: number | undefined;
|
|
80
113
|
abortSignal?: AbortSignal | undefined;
|
|
114
|
+
conflicts?: GraphFactConflictOptions | undefined;
|
|
81
115
|
}>;
|
|
82
116
|
type ExtractGraphFactsResult<Schema extends GraphSchemaLike> = Readonly<{
|
|
83
117
|
output: GraphFacts<Schema>;
|
|
84
118
|
usage: Usage;
|
|
119
|
+
warnings: readonly GraphExtractionWarning[];
|
|
85
120
|
}>;
|
|
86
121
|
type GraphVectorSearchOptions = Readonly<{
|
|
87
122
|
type: "vector";
|
|
@@ -169,6 +204,7 @@ type GraphExploreOverviewOptions<Schema extends GraphSchemaLike> = Readonly<{
|
|
|
169
204
|
mode: "overview";
|
|
170
205
|
nodeTypes?: readonly (keyof Schema["nodes"] & string)[] | undefined;
|
|
171
206
|
relationships?: readonly (keyof Schema["relationships"] & string)[] | undefined;
|
|
207
|
+
includeProvenance?: boolean | undefined;
|
|
172
208
|
maxNodes?: number | undefined;
|
|
173
209
|
maxRelationships?: number | undefined;
|
|
174
210
|
abortSignal?: AbortSignal | undefined;
|
|
@@ -178,6 +214,7 @@ type GraphExploreExpandOptions<Schema extends GraphSchemaLike> = Readonly<{
|
|
|
178
214
|
nodeIds: readonly string[];
|
|
179
215
|
nodeTypes?: readonly (keyof Schema["nodes"] & string)[] | undefined;
|
|
180
216
|
relationships?: readonly (keyof Schema["relationships"] & string)[] | undefined;
|
|
217
|
+
includeProvenance?: boolean | undefined;
|
|
181
218
|
direction?: GraphExploreDirection | undefined;
|
|
182
219
|
maxDepth?: number | undefined;
|
|
183
220
|
maxNodes?: number | undefined;
|
|
@@ -191,6 +228,7 @@ type GraphExploreNode = Readonly<{
|
|
|
191
228
|
type: string;
|
|
192
229
|
identity: GraphNodeIdentity;
|
|
193
230
|
properties: GraphProperties;
|
|
231
|
+
provenance?: GraphExploreProvenance | undefined;
|
|
194
232
|
}>;
|
|
195
233
|
type GraphExploreRelationship = Readonly<{
|
|
196
234
|
id: string;
|
|
@@ -199,6 +237,11 @@ type GraphExploreRelationship = Readonly<{
|
|
|
199
237
|
from: string;
|
|
200
238
|
to: string;
|
|
201
239
|
properties: GraphProperties;
|
|
240
|
+
provenance?: GraphExploreProvenance | undefined;
|
|
241
|
+
}>;
|
|
242
|
+
type GraphExploreProvenance = Readonly<{
|
|
243
|
+
documentIds: readonly string[];
|
|
244
|
+
chunkIds: readonly string[];
|
|
202
245
|
}>;
|
|
203
246
|
type GraphExploreResult = Readonly<{
|
|
204
247
|
nodes: readonly GraphExploreNode[];
|
|
@@ -260,6 +303,7 @@ type ResolvedGraphExploreBase = Readonly<{
|
|
|
260
303
|
relationships: readonly string[];
|
|
261
304
|
maxNodes: number;
|
|
262
305
|
maxRelationships: number;
|
|
306
|
+
includeProvenance: boolean;
|
|
263
307
|
abortSignal?: AbortSignal | undefined;
|
|
264
308
|
}>;
|
|
265
309
|
type ResolvedGraphExploreOverviewOptions = ResolvedGraphExploreBase & Readonly<{
|
|
@@ -274,4 +318,4 @@ type ResolvedGraphExploreExpandOptions = ResolvedGraphExploreBase & Readonly<{
|
|
|
274
318
|
type ResolvedGraphExploreOptions = ResolvedGraphExploreOverviewOptions | ResolvedGraphExploreExpandOptions;
|
|
275
319
|
declare function resolveGraphExploreOptions<Schema extends GraphSchemaLike>(schema: Schema, options: GraphExploreOptions<Schema>): ResolvedGraphExploreOptions;
|
|
276
320
|
|
|
277
|
-
export { type
|
|
321
|
+
export { type GraphSearchOptions as $, type GraphEvidence as A, type GraphEvidenceCapability as B, type CreateGraphSearchToolOptions as C, type GraphEvidenceFor as D, type ExtractGraphFactsOptions as E, type GraphEvidenceOptions as F, type GraphNodeIdentity as G, type GraphExploreDirection as H, type GraphExploreExpandOptions as I, type GraphExploreNode as J, type GraphExploreOptions as K, type GraphExploreOverviewOptions as L, type GraphExploreProvenance as M, type GraphExploreRelationship as N, type GraphExploreResult as O, type GraphExplorer as P, type GraphFactConflictPolicy as Q, type GraphFactConflictWarning as R, type GraphFactKind as S, type GraphFactPropertyConflictResolver as T, type GraphFactPropertyConflictStrategy as U, type GraphFacts as V, type GraphHybridSearchOptions as W, type GraphNodeDefinition as X, type GraphPropertyPrimitive as Y, type GraphRelationshipDefinition as Z, type GraphRetrieveOptions as _, type GraphFactConflictCandidate as a, type GraphTraversalOptions as a0, type GraphVectorSearchOptions as a1, type ReplaceGraphDocumentsOptions as a2, type ResolvedGraphExploreExpandOptions as a3, type ResolvedGraphExploreOptions as a4, type ResolvedGraphExploreOverviewOptions as a5, resolveGraphExploreOptions as a6, type GraphFactPropertyConflict as b, type GraphSchemaLike as c, type ExtractGraphFactsResult as d, type GraphWriteResult as e, type GraphExtractionWarning as f, type GraphEntity as g, type GraphFactConflictOptions as h, type GraphDocumentWriter as i, type GraphWriteConflict as j, type GraphOrphanEntityPolicy as k, type GraphDocument as l, type GraphChunk as m, type GraphRelationship as n, type GraphMention as o, type GraphSchemaOptions as p, type GraphSchema as q, type GraphProperties as r, type GraphPropertyValue as s, type GraphContextRetriever as t, type GraphSearchTool as u, type GraphChangeCounts as v, type GraphContext as w, type GraphContextNode as x, type GraphContextRelationship as y, type GraphContextSeed as z };
|
package/dist/explore.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { a3 as ResolvedGraphExploreExpandOptions, a4 as ResolvedGraphExploreOptions, a5 as ResolvedGraphExploreOverviewOptions, a6 as resolveGraphExploreOptions } from './explore-BIGzT6El.js';
|
|
2
2
|
import '@anvia/core';
|
|
3
3
|
import '@anvia/core/embeddings';
|
|
4
4
|
import '@anvia/core/tool';
|
package/dist/explore.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,16 +1,23 @@
|
|
|
1
1
|
import * as _anvia_core from '@anvia/core';
|
|
2
|
-
import { CompletionModel, RetrySetting, Usage } from '@anvia/core';
|
|
3
|
-
import { G as
|
|
4
|
-
export {
|
|
2
|
+
import { JsonObject, CompletionModel, RetrySetting, Usage } from '@anvia/core';
|
|
3
|
+
import { G as GraphNodeIdentity, a as GraphFactConflictCandidate, b as GraphFactPropertyConflict, c as GraphSchemaLike, E as ExtractGraphFactsOptions, d as ExtractGraphFactsResult, e as GraphWriteResult, f as GraphExtractionWarning, g as GraphEntity, h as GraphFactConflictOptions, i as GraphDocumentWriter, j as GraphWriteConflict, k as GraphOrphanEntityPolicy, l as GraphDocument, m as GraphChunk, n as GraphRelationship, o as GraphMention, p as GraphSchemaOptions, q as GraphSchema, r as GraphProperties, s as GraphPropertyValue, t as GraphContextRetriever, C as CreateGraphSearchToolOptions, u as GraphSearchTool } from './explore-BIGzT6El.js';
|
|
4
|
+
export { v as GraphChangeCounts, w as GraphContext, x as GraphContextNode, y as GraphContextRelationship, z as GraphContextSeed, A as GraphEvidence, B as GraphEvidenceCapability, D as GraphEvidenceFor, F as GraphEvidenceOptions, H as GraphExploreDirection, I as GraphExploreExpandOptions, J as GraphExploreNode, K as GraphExploreOptions, L as GraphExploreOverviewOptions, M as GraphExploreProvenance, N as GraphExploreRelationship, O as GraphExploreResult, P as GraphExplorer, Q as GraphFactConflictPolicy, R as GraphFactConflictWarning, S as GraphFactKind, T as GraphFactPropertyConflictResolver, U as GraphFactPropertyConflictStrategy, V as GraphFacts, W as GraphHybridSearchOptions, X as GraphNodeDefinition, Y as GraphPropertyPrimitive, Z as GraphRelationshipDefinition, _ as GraphRetrieveOptions, $ as GraphSearchOptions, a0 as GraphTraversalOptions, a1 as GraphVectorSearchOptions, a2 as ReplaceGraphDocumentsOptions, a3 as ResolvedGraphExploreExpandOptions, a4 as ResolvedGraphExploreOptions, a5 as ResolvedGraphExploreOverviewOptions, a6 as resolveGraphExploreOptions } from './explore-BIGzT6El.js';
|
|
5
5
|
import { TextDocument, TextDocumentMetadata, TextDocumentChunkingOptions } from '@anvia/core/documents';
|
|
6
|
-
import {
|
|
6
|
+
import { EmbeddedDocument, EmbeddingModel } from '@anvia/core/embeddings';
|
|
7
7
|
import '@anvia/core/tool';
|
|
8
8
|
import 'zod';
|
|
9
9
|
|
|
10
10
|
declare function extractGraphFacts<Schema extends GraphSchemaLike, Model extends _anvia_core.CompletionModel>(options: ExtractGraphFactsOptions<Schema, Model>): Promise<ExtractGraphFactsResult<Schema>>;
|
|
11
11
|
declare class GraphFactConflictError extends Error {
|
|
12
|
+
readonly code: "GRAPH_FACT_CONFLICT";
|
|
13
|
+
readonly kind: "entity" | "relationship";
|
|
12
14
|
readonly factKey: string;
|
|
15
|
+
readonly type: string;
|
|
16
|
+
readonly identity: GraphNodeIdentity;
|
|
17
|
+
readonly property: string;
|
|
18
|
+
readonly candidates: readonly GraphFactConflictCandidate[];
|
|
13
19
|
readonly sourceChunkIds: readonly string[];
|
|
20
|
+
constructor(conflict: GraphFactPropertyConflict);
|
|
14
21
|
constructor(factKey: string, sourceChunkIds: readonly string[]);
|
|
15
22
|
}
|
|
16
23
|
|
|
@@ -27,6 +34,8 @@ type GraphPreparationOptions<Schema extends GraphSchemaLike, ExtractionModel ext
|
|
|
27
34
|
retries?: RetrySetting | undefined;
|
|
28
35
|
concurrency?: number | undefined;
|
|
29
36
|
abortSignal?: AbortSignal | undefined;
|
|
37
|
+
factConflicts?: GraphFactConflictOptions | undefined;
|
|
38
|
+
revision?: string | undefined;
|
|
30
39
|
}>;
|
|
31
40
|
type PrepareGraphDocumentsOptions<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel = CompletionModel> = GraphPreparationOptions<Schema, ExtractionModel>;
|
|
32
41
|
type IngestGraphDocumentsOptions<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel = CompletionModel> = Omit<GraphPreparationOptions<Schema, ExtractionModel>, "graph"> & Readonly<{
|
|
@@ -45,12 +54,50 @@ type PreparedGraphDocuments<Schema extends GraphSchemaLike> = Readonly<{
|
|
|
45
54
|
relationships: readonly GraphRelationship<Schema>[];
|
|
46
55
|
mentions: readonly GraphMention[];
|
|
47
56
|
usage: Usage;
|
|
57
|
+
warnings: readonly GraphExtractionWarning[];
|
|
48
58
|
}>;
|
|
49
59
|
type IngestGraphDocumentsResult<Schema extends GraphSchemaLike> = PreparedGraphDocuments<Schema> & Readonly<{
|
|
50
60
|
write: GraphWriteResult;
|
|
61
|
+
receipt: GraphIngestionReceipt;
|
|
51
62
|
}>;
|
|
63
|
+
type GraphIngestionReceipt = Readonly<{
|
|
64
|
+
documentIds: readonly string[];
|
|
65
|
+
revision?: string | undefined;
|
|
66
|
+
entityKeys: readonly string[];
|
|
67
|
+
relationshipKeys: readonly string[];
|
|
68
|
+
vectorDocumentIds: readonly string[];
|
|
69
|
+
graphWrite: Readonly<{
|
|
70
|
+
status: "completed";
|
|
71
|
+
result: GraphWriteResult;
|
|
72
|
+
}>;
|
|
73
|
+
vectorWrite: Readonly<{
|
|
74
|
+
status: "not-requested" | "completed" | "failed";
|
|
75
|
+
}>;
|
|
76
|
+
warnings: readonly GraphExtractionWarning[];
|
|
77
|
+
}>;
|
|
78
|
+
type GraphVectorWriter = Readonly<{
|
|
79
|
+
upsert(options: {
|
|
80
|
+
documents: Array<EmbeddedDocument<TextDocument<TextDocumentMetadata>, TextDocumentMetadata>>;
|
|
81
|
+
providerOptions?: JsonObject | undefined;
|
|
82
|
+
}): Promise<void>;
|
|
83
|
+
}>;
|
|
84
|
+
type IngestGraphDocumentsToStoresOptions<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel = CompletionModel> = IngestGraphDocumentsOptions<Schema, ExtractionModel> & Readonly<{
|
|
85
|
+
vectorStore: GraphVectorWriter;
|
|
86
|
+
vectorProviderOptions?: JsonObject | undefined;
|
|
87
|
+
}>;
|
|
88
|
+
type IngestGraphTextToStoresOptions<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel = CompletionModel> = Omit<IngestGraphDocumentsToStoresOptions<Schema, ExtractionModel>, "documents"> & Readonly<{
|
|
89
|
+
document: TextDocument<TextDocumentMetadata>;
|
|
90
|
+
}>;
|
|
91
|
+
declare class GraphIngestionStageError extends Error {
|
|
92
|
+
readonly receipt: GraphIngestionReceipt;
|
|
93
|
+
readonly code: "GRAPH_INGESTION_STAGE_FAILED";
|
|
94
|
+
readonly stage: "vector";
|
|
95
|
+
constructor(receipt: GraphIngestionReceipt, cause: unknown);
|
|
96
|
+
}
|
|
52
97
|
declare function ingestGraphText<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel>(options: IngestGraphTextOptions<Schema, ExtractionModel>): Promise<IngestGraphDocumentsResult<Schema>>;
|
|
53
98
|
declare function ingestGraphDocuments<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel>(options: IngestGraphDocumentsOptions<Schema, ExtractionModel>): Promise<IngestGraphDocumentsResult<Schema>>;
|
|
99
|
+
declare function ingestGraphTextToStores<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel>(options: IngestGraphTextToStoresOptions<Schema, ExtractionModel>): Promise<IngestGraphDocumentsResult<Schema>>;
|
|
100
|
+
declare function ingestGraphDocumentsToStores<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel>(options: IngestGraphDocumentsToStoresOptions<Schema, ExtractionModel>): Promise<IngestGraphDocumentsResult<Schema>>;
|
|
54
101
|
declare function prepareGraphDocuments<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel>(options: PrepareGraphDocumentsOptions<Schema, ExtractionModel>): Promise<PreparedGraphDocuments<Schema>>;
|
|
55
102
|
|
|
56
103
|
declare const graphReservedPropertyPrefix = "__anvia_";
|
|
@@ -66,4 +113,4 @@ declare function assertGraphPropertyName(value: string): void;
|
|
|
66
113
|
|
|
67
114
|
declare function createGraphSearchTool<Schema extends GraphSchemaLike, Retriever extends GraphContextRetriever<Schema>>(options: CreateGraphSearchToolOptions<Schema, Retriever>): GraphSearchTool;
|
|
68
115
|
|
|
69
|
-
export { CreateGraphSearchToolOptions, ExtractGraphFactsOptions, ExtractGraphFactsResult, GraphChunk, GraphContextRetriever, GraphDocument, GraphDocumentWriter, GraphEntity, GraphFactConflictError, GraphMention, GraphOrphanEntityPolicy, GraphProperties, GraphPropertyValue, GraphRelationship, GraphSchema, GraphSchemaLike, GraphSchemaOptions, GraphSearchTool, GraphWriteConflict, GraphWriteResult, type IngestGraphDocumentsOptions, type IngestGraphDocumentsResult, type IngestGraphTextOptions, type PrepareGraphDocumentsOptions, type PreparedGraphDocuments, assertGraphName, assertGraphPropertyName, createGraphSearchTool, defineGraphSchema, extractGraphFacts, freezeGraphSchema, graphReservedPropertyPrefix, ingestGraphDocuments, ingestGraphText, parseGraphProperties, parseGraphPropertyValue, prepareGraphDocuments, validateGraphSchemaOptions };
|
|
116
|
+
export { CreateGraphSearchToolOptions, ExtractGraphFactsOptions, ExtractGraphFactsResult, GraphChunk, GraphContextRetriever, GraphDocument, GraphDocumentWriter, GraphEntity, GraphExtractionWarning, GraphFactConflictCandidate, GraphFactConflictError, GraphFactConflictOptions, GraphFactPropertyConflict, type GraphIngestionReceipt, GraphIngestionStageError, GraphMention, GraphNodeIdentity, GraphOrphanEntityPolicy, GraphProperties, GraphPropertyValue, GraphRelationship, GraphSchema, GraphSchemaLike, GraphSchemaOptions, GraphSearchTool, type GraphVectorWriter, GraphWriteConflict, GraphWriteResult, type IngestGraphDocumentsOptions, type IngestGraphDocumentsResult, type IngestGraphDocumentsToStoresOptions, type IngestGraphTextOptions, type IngestGraphTextToStoresOptions, type PrepareGraphDocumentsOptions, type PreparedGraphDocuments, assertGraphName, assertGraphPropertyName, createGraphSearchTool, defineGraphSchema, extractGraphFacts, freezeGraphSchema, graphReservedPropertyPrefix, ingestGraphDocuments, ingestGraphDocumentsToStores, ingestGraphText, ingestGraphTextToStores, parseGraphProperties, parseGraphPropertyValue, prepareGraphDocuments, validateGraphSchemaOptions };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveGraphExploreOptions
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-S2QTQGBS.js";
|
|
4
4
|
|
|
5
5
|
// src/extract.ts
|
|
6
6
|
import { Usage } from "@anvia/core";
|
|
@@ -217,7 +217,7 @@ async function extractGraphFacts(options) {
|
|
|
217
217
|
}
|
|
218
218
|
);
|
|
219
219
|
return {
|
|
220
|
-
|
|
220
|
+
...normalizeFacts(options.schema, extractions, options.conflicts),
|
|
221
221
|
usage: extractions.reduce((usage, item) => Usage.add(usage, item.usage), Usage.empty())
|
|
222
222
|
};
|
|
223
223
|
}
|
|
@@ -259,9 +259,9 @@ ${relationships}`,
|
|
|
259
259
|
extra
|
|
260
260
|
].filter((part) => part !== void 0 && part.length > 0).join("\n\n");
|
|
261
261
|
}
|
|
262
|
-
function normalizeFacts(schema, extractions) {
|
|
263
|
-
const
|
|
264
|
-
const
|
|
262
|
+
function normalizeFacts(schema, extractions, conflicts) {
|
|
263
|
+
const entityCandidates = /* @__PURE__ */ new Map();
|
|
264
|
+
const relationshipCandidates = /* @__PURE__ */ new Map();
|
|
265
265
|
const mentions = /* @__PURE__ */ new Map();
|
|
266
266
|
for (const extraction of extractions) {
|
|
267
267
|
const refs = /* @__PURE__ */ new Map();
|
|
@@ -277,32 +277,15 @@ function normalizeFacts(schema, extractions) {
|
|
|
277
277
|
);
|
|
278
278
|
const identity = identityFromProperties(definition.identity, properties2, raw.type);
|
|
279
279
|
const key = `${raw.type}:${stableObject(identity)}`;
|
|
280
|
-
const
|
|
281
|
-
const next = {
|
|
280
|
+
const candidate = {
|
|
282
281
|
key,
|
|
283
282
|
type: raw.type,
|
|
284
283
|
identity,
|
|
285
284
|
properties: properties2,
|
|
286
|
-
|
|
285
|
+
chunkId: extraction.chunkId
|
|
287
286
|
};
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
refs.set(raw.ref, next);
|
|
291
|
-
} else {
|
|
292
|
-
assertSameProperties(
|
|
293
|
-
current.properties,
|
|
294
|
-
properties2,
|
|
295
|
-
key,
|
|
296
|
-
current.sourceChunkIds,
|
|
297
|
-
extraction.chunkId
|
|
298
|
-
);
|
|
299
|
-
const merged = {
|
|
300
|
-
...current,
|
|
301
|
-
sourceChunkIds: [...current.sourceChunkIds, extraction.chunkId]
|
|
302
|
-
};
|
|
303
|
-
entities.set(key, merged);
|
|
304
|
-
refs.set(raw.ref, merged);
|
|
305
|
-
}
|
|
287
|
+
appendCandidate(entityCandidates, key, candidate);
|
|
288
|
+
refs.set(raw.ref, candidate);
|
|
306
289
|
mentions.set(`${extraction.chunkId}\0${key}`, {
|
|
307
290
|
chunkId: extraction.chunkId,
|
|
308
291
|
entityKey: key
|
|
@@ -331,37 +314,170 @@ function normalizeFacts(schema, extractions) {
|
|
|
331
314
|
);
|
|
332
315
|
const identity = identityFromProperties(definition.identity ?? [], properties2, raw.type);
|
|
333
316
|
const key = `${raw.type}:${from.key}->${to.key}:${stableObject(identity)}`;
|
|
334
|
-
|
|
335
|
-
const next = {
|
|
317
|
+
appendCandidate(relationshipCandidates, key, {
|
|
336
318
|
key,
|
|
337
319
|
type: raw.type,
|
|
338
320
|
from: from.key,
|
|
339
321
|
to: to.key,
|
|
322
|
+
identity,
|
|
340
323
|
properties: properties2,
|
|
341
|
-
|
|
342
|
-
};
|
|
343
|
-
if (current === void 0) relationships.set(key, next);
|
|
344
|
-
else {
|
|
345
|
-
assertSameProperties(
|
|
346
|
-
current.properties,
|
|
347
|
-
properties2,
|
|
348
|
-
key,
|
|
349
|
-
current.sourceChunkIds,
|
|
350
|
-
extraction.chunkId
|
|
351
|
-
);
|
|
352
|
-
relationships.set(key, {
|
|
353
|
-
...current,
|
|
354
|
-
sourceChunkIds: [...current.sourceChunkIds, extraction.chunkId]
|
|
355
|
-
});
|
|
356
|
-
}
|
|
324
|
+
chunkId: extraction.chunkId
|
|
325
|
+
});
|
|
357
326
|
}
|
|
358
327
|
}
|
|
328
|
+
const warnings = [];
|
|
329
|
+
const entities = [...entityCandidates.values()].map((candidates) => {
|
|
330
|
+
const first = requiredCandidate(candidates);
|
|
331
|
+
const definition = schema.nodes[first.type];
|
|
332
|
+
if (definition === void 0) throw new TypeError(`Unknown graph entity type: ${first.type}`);
|
|
333
|
+
const properties2 = parseGraphProperties(
|
|
334
|
+
definition.properties.parse(
|
|
335
|
+
resolveFactProperties(
|
|
336
|
+
"entity",
|
|
337
|
+
first.key,
|
|
338
|
+
first.type,
|
|
339
|
+
first.identity,
|
|
340
|
+
candidates,
|
|
341
|
+
conflicts?.entity,
|
|
342
|
+
warnings
|
|
343
|
+
)
|
|
344
|
+
),
|
|
345
|
+
`entity ${first.type}`
|
|
346
|
+
);
|
|
347
|
+
return {
|
|
348
|
+
key: first.key,
|
|
349
|
+
type: first.type,
|
|
350
|
+
identity: first.identity,
|
|
351
|
+
properties: properties2,
|
|
352
|
+
sourceChunkIds: uniqueChunkIds(candidates)
|
|
353
|
+
};
|
|
354
|
+
});
|
|
355
|
+
const relationships = [...relationshipCandidates.values()].map((candidates) => {
|
|
356
|
+
const first = requiredCandidate(candidates);
|
|
357
|
+
const definition = schema.relationships[first.type];
|
|
358
|
+
if (definition === void 0) {
|
|
359
|
+
throw new TypeError(`Unknown graph relationship type: ${first.type}`);
|
|
360
|
+
}
|
|
361
|
+
const properties2 = parseGraphProperties(
|
|
362
|
+
definition.properties.parse(
|
|
363
|
+
resolveFactProperties(
|
|
364
|
+
"relationship",
|
|
365
|
+
first.key,
|
|
366
|
+
first.type,
|
|
367
|
+
first.identity,
|
|
368
|
+
candidates,
|
|
369
|
+
conflicts?.relationship,
|
|
370
|
+
warnings
|
|
371
|
+
)
|
|
372
|
+
),
|
|
373
|
+
`relationship ${first.type}`
|
|
374
|
+
);
|
|
375
|
+
return {
|
|
376
|
+
key: first.key,
|
|
377
|
+
type: first.type,
|
|
378
|
+
from: first.from,
|
|
379
|
+
to: first.to,
|
|
380
|
+
properties: properties2,
|
|
381
|
+
sourceChunkIds: uniqueChunkIds(candidates)
|
|
382
|
+
};
|
|
383
|
+
});
|
|
359
384
|
return {
|
|
360
|
-
entities: [...
|
|
361
|
-
|
|
362
|
-
mentions: [...mentions.values()]
|
|
385
|
+
output: { entities, relationships, mentions: [...mentions.values()] },
|
|
386
|
+
warnings
|
|
363
387
|
};
|
|
364
388
|
}
|
|
389
|
+
function appendCandidate(candidates, key, candidate) {
|
|
390
|
+
const current = candidates.get(key);
|
|
391
|
+
if (current === void 0) candidates.set(key, [candidate]);
|
|
392
|
+
else current.push(candidate);
|
|
393
|
+
}
|
|
394
|
+
function requiredCandidate(candidates) {
|
|
395
|
+
const candidate = candidates[0];
|
|
396
|
+
if (candidate === void 0) throw new TypeError("Graph fact candidate group cannot be empty.");
|
|
397
|
+
return candidate;
|
|
398
|
+
}
|
|
399
|
+
function uniqueChunkIds(candidates) {
|
|
400
|
+
return [...new Set(candidates.map((candidate) => candidate.chunkId))];
|
|
401
|
+
}
|
|
402
|
+
function resolveFactProperties(kind, key, type, identity, candidates, policy, warnings) {
|
|
403
|
+
const propertyNames = [
|
|
404
|
+
...new Set(candidates.flatMap((candidate) => Object.keys(candidate.properties)))
|
|
405
|
+
].sort();
|
|
406
|
+
const properties2 = {};
|
|
407
|
+
for (const property of propertyNames) {
|
|
408
|
+
const propertyCandidates = candidates.map((candidate) => ({
|
|
409
|
+
chunkId: candidate.chunkId,
|
|
410
|
+
properties: candidate.properties,
|
|
411
|
+
value: candidate.properties[property]
|
|
412
|
+
}));
|
|
413
|
+
const firstValue = propertyCandidates[0]?.value;
|
|
414
|
+
if (propertyCandidates.every(
|
|
415
|
+
(candidate) => stableValue(candidate.value) === stableValue(firstValue)
|
|
416
|
+
)) {
|
|
417
|
+
if (firstValue !== void 0) properties2[property] = firstValue;
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
const conflict = {
|
|
421
|
+
code: "GRAPH_FACT_CONFLICT",
|
|
422
|
+
kind,
|
|
423
|
+
key,
|
|
424
|
+
type,
|
|
425
|
+
identity,
|
|
426
|
+
property,
|
|
427
|
+
candidates: propertyCandidates,
|
|
428
|
+
sourceChunkIds: uniqueChunkIds(propertyCandidates)
|
|
429
|
+
};
|
|
430
|
+
const strategy = policy?.properties?.[property] ?? policy?.resolve ?? policy?.default ?? "reject";
|
|
431
|
+
if (strategy === "reject") throw new GraphFactConflictError(conflict);
|
|
432
|
+
const resolvedValue = validateResolvedValue(
|
|
433
|
+
resolvePropertyConflict(strategy, conflict),
|
|
434
|
+
conflict
|
|
435
|
+
);
|
|
436
|
+
if (resolvedValue !== void 0) properties2[property] = resolvedValue;
|
|
437
|
+
warnings.push({
|
|
438
|
+
...conflict,
|
|
439
|
+
code: "GRAPH_FACT_CONFLICT_RESOLVED",
|
|
440
|
+
strategy: typeof strategy === "function" ? "custom" : strategy,
|
|
441
|
+
resolvedValue
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
return properties2;
|
|
445
|
+
}
|
|
446
|
+
function resolvePropertyConflict(strategy, conflict) {
|
|
447
|
+
if (typeof strategy === "function") {
|
|
448
|
+
return strategy(conflict);
|
|
449
|
+
}
|
|
450
|
+
const values = conflict.candidates.map((candidate) => candidate.value);
|
|
451
|
+
if (strategy === "prefer-first") return values[0];
|
|
452
|
+
if (strategy === "prefer-last") return values.at(-1);
|
|
453
|
+
if (strategy === "prefer-defined") return values.find((value) => value !== void 0);
|
|
454
|
+
if (strategy === "prefer-longest") {
|
|
455
|
+
const strings = definedValues(values, "string", conflict, strategy);
|
|
456
|
+
return strings.reduce((longest, value) => value.length > longest.length ? value : longest);
|
|
457
|
+
}
|
|
458
|
+
if (strategy === "union") {
|
|
459
|
+
const arrays = values.filter((value) => value !== void 0);
|
|
460
|
+
if (!arrays.every(Array.isArray)) throw incompatibleStrategy(conflict, strategy);
|
|
461
|
+
return [...new Set(arrays.flat())];
|
|
462
|
+
}
|
|
463
|
+
const numbers = definedValues(values, "number", conflict, strategy);
|
|
464
|
+
return strategy === "max" ? Math.max(...numbers) : Math.min(...numbers);
|
|
465
|
+
}
|
|
466
|
+
function definedValues(values, type, conflict, strategy) {
|
|
467
|
+
const defined = values.filter((value) => value !== void 0);
|
|
468
|
+
if (defined.length === 0 || !defined.every((value) => typeof value === type)) {
|
|
469
|
+
throw incompatibleStrategy(conflict, strategy);
|
|
470
|
+
}
|
|
471
|
+
return defined;
|
|
472
|
+
}
|
|
473
|
+
function validateResolvedValue(value, conflict) {
|
|
474
|
+
return value === void 0 ? void 0 : parseGraphPropertyValue(value, `Resolved graph fact ${conflict.key}.${conflict.property}`);
|
|
475
|
+
}
|
|
476
|
+
function incompatibleStrategy(conflict, strategy) {
|
|
477
|
+
return new TypeError(
|
|
478
|
+
`Graph fact conflict strategy ${strategy} is incompatible with ${conflict.key}.${conflict.property}.`
|
|
479
|
+
);
|
|
480
|
+
}
|
|
365
481
|
function identityFromProperties(keys, properties2, type) {
|
|
366
482
|
const identity = {};
|
|
367
483
|
for (const key of keys) {
|
|
@@ -378,22 +494,41 @@ function stableObject(value) {
|
|
|
378
494
|
Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)))
|
|
379
495
|
);
|
|
380
496
|
}
|
|
381
|
-
function
|
|
382
|
-
|
|
383
|
-
throw new GraphFactConflictError(key, [...sourceChunkIds, nextChunkId]);
|
|
384
|
-
}
|
|
497
|
+
function stableValue(value) {
|
|
498
|
+
return value === void 0 ? "undefined" : stableObject({ value });
|
|
385
499
|
}
|
|
386
500
|
var GraphFactConflictError = class extends Error {
|
|
387
|
-
|
|
501
|
+
code = "GRAPH_FACT_CONFLICT";
|
|
502
|
+
kind;
|
|
503
|
+
factKey;
|
|
504
|
+
type;
|
|
505
|
+
identity;
|
|
506
|
+
property;
|
|
507
|
+
candidates;
|
|
508
|
+
sourceChunkIds;
|
|
509
|
+
constructor(conflictOrKey, legacyChunkIds = []) {
|
|
510
|
+
const conflict = typeof conflictOrKey === "string" ? {
|
|
511
|
+
code: "GRAPH_FACT_CONFLICT",
|
|
512
|
+
kind: "entity",
|
|
513
|
+
key: conflictOrKey,
|
|
514
|
+
type: conflictOrKey.split(":", 1)[0] ?? "unknown",
|
|
515
|
+
identity: {},
|
|
516
|
+
property: "unknown",
|
|
517
|
+
candidates: [],
|
|
518
|
+
sourceChunkIds: legacyChunkIds
|
|
519
|
+
} : conflictOrKey;
|
|
388
520
|
super(
|
|
389
|
-
`Conflicting graph fact ${
|
|
521
|
+
`Conflicting graph fact ${conflict.key}.${conflict.property} was extracted from chunks ${conflict.sourceChunkIds.join(", ")}.`
|
|
390
522
|
);
|
|
391
|
-
this.factKey = factKey;
|
|
392
|
-
this.sourceChunkIds = sourceChunkIds;
|
|
393
523
|
this.name = "GraphFactConflictError";
|
|
524
|
+
this.kind = conflict.kind;
|
|
525
|
+
this.factKey = conflict.key;
|
|
526
|
+
this.type = conflict.type;
|
|
527
|
+
this.identity = conflict.identity;
|
|
528
|
+
this.property = conflict.property;
|
|
529
|
+
this.candidates = conflict.candidates;
|
|
530
|
+
this.sourceChunkIds = conflict.sourceChunkIds;
|
|
394
531
|
}
|
|
395
|
-
factKey;
|
|
396
|
-
sourceChunkIds;
|
|
397
532
|
};
|
|
398
533
|
function assertConcurrency(value) {
|
|
399
534
|
if (value !== void 0 && (!Number.isSafeInteger(value) || value < 1)) {
|
|
@@ -426,6 +561,16 @@ import {
|
|
|
426
561
|
chunkTextDocuments
|
|
427
562
|
} from "@anvia/core/documents";
|
|
428
563
|
import { embedDocuments } from "@anvia/core/embeddings";
|
|
564
|
+
var GraphIngestionStageError = class extends Error {
|
|
565
|
+
constructor(receipt, cause) {
|
|
566
|
+
super("Graph ingestion completed, but the vector write failed.", { cause });
|
|
567
|
+
this.receipt = receipt;
|
|
568
|
+
this.name = "GraphIngestionStageError";
|
|
569
|
+
}
|
|
570
|
+
receipt;
|
|
571
|
+
code = "GRAPH_INGESTION_STAGE_FAILED";
|
|
572
|
+
stage = "vector";
|
|
573
|
+
};
|
|
429
574
|
async function ingestGraphText(options) {
|
|
430
575
|
return ingestGraphDocuments({
|
|
431
576
|
graph: options.graph,
|
|
@@ -438,6 +583,8 @@ async function ingestGraphText(options) {
|
|
|
438
583
|
retries: options.retries,
|
|
439
584
|
concurrency: options.concurrency,
|
|
440
585
|
abortSignal: options.abortSignal,
|
|
586
|
+
factConflicts: options.factConflicts,
|
|
587
|
+
revision: options.revision,
|
|
441
588
|
conflict: options.conflict,
|
|
442
589
|
orphanEntities: options.orphanEntities
|
|
443
590
|
});
|
|
@@ -454,9 +601,37 @@ async function ingestGraphDocuments(options) {
|
|
|
454
601
|
orphanEntities: options.orphanEntities,
|
|
455
602
|
abortSignal: options.abortSignal
|
|
456
603
|
});
|
|
457
|
-
return {
|
|
604
|
+
return {
|
|
605
|
+
...prepared,
|
|
606
|
+
write,
|
|
607
|
+
receipt: ingestionReceipt(prepared, write, options.revision, "not-requested")
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
async function ingestGraphTextToStores(options) {
|
|
611
|
+
return ingestGraphDocumentsToStores({ ...options, documents: [options.document] });
|
|
612
|
+
}
|
|
613
|
+
async function ingestGraphDocumentsToStores(options) {
|
|
614
|
+
const result = await ingestGraphDocuments(options);
|
|
615
|
+
try {
|
|
616
|
+
await options.vectorStore.upsert({
|
|
617
|
+
documents: [...result.vectorDocuments],
|
|
618
|
+
providerOptions: options.vectorProviderOptions
|
|
619
|
+
});
|
|
620
|
+
} catch (error) {
|
|
621
|
+
throw new GraphIngestionStageError(
|
|
622
|
+
{ ...result.receipt, vectorWrite: { status: "failed" } },
|
|
623
|
+
error
|
|
624
|
+
);
|
|
625
|
+
}
|
|
626
|
+
return {
|
|
627
|
+
...result,
|
|
628
|
+
receipt: { ...result.receipt, vectorWrite: { status: "completed" } }
|
|
629
|
+
};
|
|
458
630
|
}
|
|
459
631
|
async function prepareGraphDocuments(options) {
|
|
632
|
+
if (options.revision !== void 0 && options.revision.trim().length === 0) {
|
|
633
|
+
throw new TypeError("Graph ingestion revision must be a non-empty string.");
|
|
634
|
+
}
|
|
460
635
|
validatePortableMetadata(options.documents);
|
|
461
636
|
const chunks = chunkTextDocuments({
|
|
462
637
|
documents: options.documents,
|
|
@@ -471,7 +646,8 @@ async function prepareGraphDocuments(options) {
|
|
|
471
646
|
instructions: options.instructions,
|
|
472
647
|
retries: options.retries,
|
|
473
648
|
concurrency: options.concurrency,
|
|
474
|
-
abortSignal: options.abortSignal
|
|
649
|
+
abortSignal: options.abortSignal,
|
|
650
|
+
conflicts: options.factConflicts
|
|
475
651
|
}),
|
|
476
652
|
embedDocuments({
|
|
477
653
|
model: options.embeddingModel,
|
|
@@ -501,7 +677,20 @@ async function prepareGraphDocuments(options) {
|
|
|
501
677
|
entities: embeddedEntities.documents,
|
|
502
678
|
relationships: facts.output.relationships,
|
|
503
679
|
mentions: facts.output.mentions,
|
|
504
|
-
usage: facts.usage
|
|
680
|
+
usage: facts.usage,
|
|
681
|
+
warnings: facts.warnings
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
function ingestionReceipt(prepared, write, revision, vectorStatus) {
|
|
685
|
+
return {
|
|
686
|
+
documentIds: prepared.documents.map((document) => document.id),
|
|
687
|
+
...revision === void 0 ? {} : { revision },
|
|
688
|
+
entityKeys: prepared.entities.map((entity) => entity.id),
|
|
689
|
+
relationshipKeys: prepared.relationships.map((relationship) => relationship.key),
|
|
690
|
+
vectorDocumentIds: prepared.vectorDocuments.map((document) => document.id),
|
|
691
|
+
graphWrite: { status: "completed", result: write },
|
|
692
|
+
vectorWrite: { status: vectorStatus },
|
|
693
|
+
warnings: prepared.warnings
|
|
505
694
|
};
|
|
506
695
|
}
|
|
507
696
|
function validatePortableMetadata(documents) {
|
|
@@ -654,6 +843,7 @@ function createGraphSearchTool(options) {
|
|
|
654
843
|
}
|
|
655
844
|
export {
|
|
656
845
|
GraphFactConflictError,
|
|
846
|
+
GraphIngestionStageError,
|
|
657
847
|
assertGraphName,
|
|
658
848
|
assertGraphPropertyName,
|
|
659
849
|
createGraphSearchTool,
|
|
@@ -662,7 +852,9 @@ export {
|
|
|
662
852
|
freezeGraphSchema,
|
|
663
853
|
graphReservedPropertyPrefix,
|
|
664
854
|
ingestGraphDocuments,
|
|
855
|
+
ingestGraphDocumentsToStores,
|
|
665
856
|
ingestGraphText,
|
|
857
|
+
ingestGraphTextToStores,
|
|
666
858
|
parseGraphProperties,
|
|
667
859
|
parseGraphPropertyValue,
|
|
668
860
|
prepareGraphDocuments,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/extract.ts","../src/schema.ts","../src/ingest.ts","../src/tool.ts"],"sourcesContent":["import { Usage } from \"@anvia/core\";\nimport { extract } from \"@anvia/core/extractor\";\nimport { z } from \"zod\";\nimport { parseGraphProperties } from \"./schema.js\";\nimport type {\n ExtractGraphFactsOptions,\n ExtractGraphFactsResult,\n GraphEntity,\n GraphFacts,\n GraphMention,\n GraphNodeIdentity,\n GraphProperties,\n GraphRelationship,\n GraphSchemaLike,\n} from \"./types.js\";\n\ntype RawEntity = { ref: string; type: string; properties: Record<string, unknown> };\ntype RawRelationship = {\n type: string;\n from: string;\n to: string;\n properties: Record<string, unknown>;\n};\ntype RawChunkFacts = { entities: RawEntity[]; relationships: RawRelationship[] };\ntype ChunkExtraction = { chunkId: string; output: RawChunkFacts; usage: Usage };\n\nexport async function extractGraphFacts<\n Schema extends GraphSchemaLike,\n Model extends import(\"@anvia/core\").CompletionModel,\n>(options: ExtractGraphFactsOptions<Schema, Model>): Promise<ExtractGraphFactsResult<Schema>> {\n assertConcurrency(options.concurrency);\n throwIfAborted(options.abortSignal);\n const ids = new Set<string>();\n for (const chunk of options.chunks) {\n if (ids.has(chunk.id)) throw new TypeError(`Duplicate graph chunk id: ${chunk.id}`);\n ids.add(chunk.id);\n if (typeof chunk.text !== \"string\") {\n throw new TypeError(`Graph chunk ${chunk.id} text must be a string.`);\n }\n }\n\n const outputSchema = extractionSchema(options.schema);\n const instructions = graphInstructions(options.schema, options.instructions);\n const extractions = await mapConcurrent(\n options.chunks,\n options.concurrency ?? 1,\n async (chunk): Promise<ChunkExtraction> => {\n throwIfAborted(options.abortSignal);\n const result = await extract({\n model: options.model,\n text: chunk.text,\n outputSchema,\n instructions,\n retries: options.retries,\n abortSignal: options.abortSignal,\n });\n return { chunkId: chunk.id, output: result.output as RawChunkFacts, usage: result.usage };\n },\n );\n return {\n output: normalizeFacts(options.schema, extractions),\n usage: extractions.reduce((usage, item) => Usage.add(usage, item.usage), Usage.empty()),\n };\n}\n\nfunction extractionSchema(schema: GraphSchemaLike): z.ZodType<RawChunkFacts> {\n const entities = Object.entries(schema.nodes).map(([type, definition]) =>\n z.object({ ref: z.string().min(1), type: z.literal(type), properties: definition.properties }),\n );\n const relationships = Object.entries(schema.relationships).map(([type, definition]) =>\n z.object({\n type: z.literal(type),\n from: z.string().min(1),\n to: z.string().min(1),\n properties: definition.properties,\n }),\n );\n return z.object({\n entities: z.array(union(entities, z.never())),\n relationships: z.array(union(relationships, z.never())),\n }) as unknown as z.ZodType<RawChunkFacts>;\n}\n\nfunction union(items: z.ZodType[], empty: z.ZodType): z.ZodType {\n if (items.length === 0) return empty;\n if (items.length === 1) return items[0] as z.ZodType;\n return z.union(items as [z.ZodType, z.ZodType, ...z.ZodType[]]);\n}\n\nfunction graphInstructions(schema: GraphSchemaLike, extra: string | undefined): string {\n const nodes = Object.entries(schema.nodes)\n .map(([type, definition]) => `- ${type}: ${definition.description}`)\n .join(\"\\n\");\n const relationships = Object.entries(schema.relationships)\n .map(\n ([type, definition]) =>\n `- ${type}: ${definition.from} -> ${definition.to}. ${definition.description}`,\n )\n .join(\"\\n\");\n return [\n \"Extract only facts directly supported by the source text.\",\n \"Give every extracted entity a unique local ref and use those refs as relationship endpoints.\",\n \"Do not invent entity or relationship types outside the declared schema.\",\n `Node types:\\n${nodes}`,\n relationships.length === 0\n ? \"No relationship types are allowed.\"\n : `Relationship types:\\n${relationships}`,\n extra,\n ]\n .filter((part): part is string => part !== undefined && part.length > 0)\n .join(\"\\n\\n\");\n}\n\nfunction normalizeFacts<Schema extends GraphSchemaLike>(\n schema: Schema,\n extractions: readonly ChunkExtraction[],\n): GraphFacts<Schema> {\n const entities = new Map<string, GraphEntity<Schema>>();\n const relationships = new Map<string, GraphRelationship<Schema>>();\n const mentions = new Map<string, GraphMention>();\n\n for (const extraction of extractions) {\n const refs = new Map<string, GraphEntity<Schema>>();\n for (const raw of extraction.output.entities) {\n if (refs.has(raw.ref)) {\n throw new TypeError(`Duplicate entity ref ${raw.ref} in chunk ${extraction.chunkId}.`);\n }\n const definition = schema.nodes[raw.type];\n if (definition === undefined) throw new TypeError(`Unknown graph entity type: ${raw.type}`);\n const properties = parseGraphProperties(\n definition.properties.parse(raw.properties),\n `entity ${raw.type}`,\n );\n const identity = identityFromProperties(definition.identity, properties, raw.type);\n const key = `${raw.type}:${stableObject(identity)}`;\n const current = entities.get(key);\n const next = {\n key,\n type: raw.type,\n identity,\n properties,\n sourceChunkIds: [extraction.chunkId],\n } as unknown as GraphEntity<Schema>;\n if (current === undefined) {\n entities.set(key, next);\n refs.set(raw.ref, next);\n } else {\n assertSameProperties(\n current.properties,\n properties,\n key,\n current.sourceChunkIds,\n extraction.chunkId,\n );\n const merged = {\n ...current,\n sourceChunkIds: [...current.sourceChunkIds, extraction.chunkId],\n } as GraphEntity<Schema>;\n entities.set(key, merged);\n refs.set(raw.ref, merged);\n }\n mentions.set(`${extraction.chunkId}\\u0000${key}`, {\n chunkId: extraction.chunkId,\n entityKey: key,\n });\n }\n\n for (const raw of extraction.output.relationships) {\n const definition = schema.relationships[raw.type];\n if (definition === undefined) {\n throw new TypeError(`Unknown graph relationship type: ${raw.type}`);\n }\n const from = refs.get(raw.from);\n const to = refs.get(raw.to);\n if (from === undefined || to === undefined) {\n throw new TypeError(\n `Relationship ${raw.type} in chunk ${extraction.chunkId} references an unknown entity ref.`,\n );\n }\n if (from.type !== definition.from || to.type !== definition.to) {\n throw new TypeError(\n `Relationship ${raw.type} has invalid endpoint types ${from.type} -> ${to.type}.`,\n );\n }\n const properties = parseGraphProperties(\n definition.properties.parse(raw.properties),\n `relationship ${raw.type}`,\n );\n const identity = identityFromProperties(definition.identity ?? [], properties, raw.type);\n const key = `${raw.type}:${from.key}->${to.key}:${stableObject(identity)}`;\n const current = relationships.get(key);\n const next = {\n key,\n type: raw.type,\n from: from.key,\n to: to.key,\n properties,\n sourceChunkIds: [extraction.chunkId],\n } as unknown as GraphRelationship<Schema>;\n if (current === undefined) relationships.set(key, next);\n else {\n assertSameProperties(\n current.properties,\n properties,\n key,\n current.sourceChunkIds,\n extraction.chunkId,\n );\n relationships.set(key, {\n ...current,\n sourceChunkIds: [...current.sourceChunkIds, extraction.chunkId],\n } as GraphRelationship<Schema>);\n }\n }\n }\n return {\n entities: [...entities.values()],\n relationships: [...relationships.values()],\n mentions: [...mentions.values()],\n };\n}\n\nfunction identityFromProperties(\n keys: readonly string[],\n properties: GraphProperties,\n type: string,\n): GraphNodeIdentity {\n const identity: Record<string, string | number | boolean> = {};\n for (const key of keys) {\n const value = properties[key];\n if (\n value === undefined ||\n !(typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\")\n ) {\n throw new TypeError(`Identity property ${key} for ${type} must be a primitive value.`);\n }\n identity[key] = value;\n }\n return identity;\n}\n\nfunction stableObject(value: Readonly<Record<string, unknown>>): string {\n return JSON.stringify(\n Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right))),\n );\n}\n\nfunction assertSameProperties(\n left: GraphProperties,\n right: GraphProperties,\n key: string,\n sourceChunkIds: readonly string[],\n nextChunkId: string,\n): void {\n if (stableObject(left) !== stableObject(right)) {\n throw new GraphFactConflictError(key, [...sourceChunkIds, nextChunkId]);\n }\n}\n\nexport class GraphFactConflictError extends Error {\n constructor(\n readonly factKey: string,\n readonly sourceChunkIds: readonly string[],\n ) {\n super(\n `Conflicting graph fact ${factKey} was extracted from chunks ${sourceChunkIds.join(\", \")}.`,\n );\n this.name = \"GraphFactConflictError\";\n }\n}\n\nfunction assertConcurrency(value: number | undefined): void {\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {\n throw new RangeError(\"Graph extraction concurrency must be a positive safe integer.\");\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted !== true) return;\n if (signal.reason instanceof Error) throw signal.reason;\n throw new DOMException(\"The operation was aborted.\", \"AbortError\");\n}\n\nasync function mapConcurrent<Input, Output>(\n values: readonly Input[],\n concurrency: number,\n run: (value: Input) => Promise<Output>,\n): Promise<Output[]> {\n const output = Array<Output>(values.length);\n let cursor = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, values.length) }, async () => {\n for (;;) {\n const index = cursor;\n cursor += 1;\n if (index >= values.length) return;\n output[index] = await run(values[index] as Input);\n }\n }),\n );\n return output;\n}\n","import { z } from \"zod\";\nimport type {\n GraphProperties,\n GraphPropertyPrimitive,\n GraphPropertyValue,\n GraphSchema,\n GraphSchemaOptions,\n} from \"./types.js\";\n\nexport const graphReservedPropertyPrefix = \"__anvia_\";\n\nexport function defineGraphSchema<const Options extends GraphSchemaOptions>(\n options: Options,\n): GraphSchema<Options> {\n validateGraphSchemaOptions(options);\n return freezeGraphSchema(options, \"graph-schema\");\n}\n\nexport function validateGraphSchemaOptions(options: GraphSchemaOptions): void {\n if (Object.keys(options.nodes).length === 0) {\n throw new TypeError(\"A graph schema requires at least one node type.\");\n }\n for (const [type, definition] of Object.entries(options.nodes)) {\n assertGraphName(type, \"node type\");\n assertDescription(definition.description, `node ${type}`);\n if (!(definition.properties instanceof z.ZodObject)) {\n throw new TypeError(`Properties for node ${type} must be a Zod object schema.`);\n }\n assertExactPropertySchema(definition.properties, `node ${type}`);\n if (\n definition.identity.length === 0 ||\n new Set(definition.identity).size !== definition.identity.length\n ) {\n throw new TypeError(`Node ${type} must declare unique identity properties.`);\n }\n for (const property of definition.identity) {\n assertGraphPropertyName(property);\n if (!(property in definition.properties.shape)) {\n throw new TypeError(`Identity property ${property} is not declared by node ${type}.`);\n }\n }\n for (const property of Object.keys(definition.properties.shape)) {\n assertGraphPropertyName(property);\n }\n }\n for (const [type, definition] of Object.entries(options.relationships)) {\n assertGraphName(type, \"relationship type\");\n assertDescription(definition.description, `relationship ${type}`);\n if (!(definition.from in options.nodes) || !(definition.to in options.nodes)) {\n throw new TypeError(`Relationship ${type} references an unknown endpoint type.`);\n }\n if (!(definition.properties instanceof z.ZodObject)) {\n throw new TypeError(`Properties for relationship ${type} must be a Zod object schema.`);\n }\n assertExactPropertySchema(definition.properties, `relationship ${type}`);\n const identity = definition.identity ?? [];\n if (new Set(identity).size !== identity.length) {\n throw new TypeError(`Relationship ${type} contains duplicate identity properties.`);\n }\n for (const property of Object.keys(definition.properties.shape)) {\n assertGraphPropertyName(property);\n }\n for (const property of identity) {\n if (!(property in definition.properties.shape)) {\n throw new TypeError(\n `Identity property ${property} is not declared by relationship ${type}.`,\n );\n }\n }\n }\n}\n\nexport function freezeGraphSchema<\n const Options extends GraphSchemaOptions,\n const Kind extends string,\n>(options: Options, kind: Kind): Readonly<Options & { kind: Kind }> {\n const nodes = Object.fromEntries(\n Object.entries(options.nodes).map(([type, definition]) => [\n type,\n Object.freeze({ ...definition, identity: Object.freeze([...definition.identity]) }),\n ]),\n );\n const relationships = Object.fromEntries(\n Object.entries(options.relationships).map(([type, definition]) => {\n const copy = { ...definition };\n if (definition.identity !== undefined) {\n Object.assign(copy, { identity: Object.freeze([...definition.identity]) });\n }\n return [type, Object.freeze(copy)];\n }),\n );\n return Object.freeze({\n nodes: Object.freeze(nodes),\n relationships: Object.freeze(relationships),\n kind,\n }) as Readonly<Options & { kind: Kind }>;\n}\n\nexport function parseGraphProperties(value: unknown, label: string): GraphProperties {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} must be an object of graph property values.`);\n }\n const output: Record<string, GraphPropertyValue> = {};\n for (const [key, item] of Object.entries(value)) {\n assertGraphPropertyName(key);\n output[key] = parseGraphPropertyValue(item, `${label}.${key}`);\n }\n return output;\n}\n\nexport function parseGraphPropertyValue(value: unknown, label: string): GraphPropertyValue {\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new TypeError(`${label} must be finite.`);\n if (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n throw new TypeError(`${label} must be a safe integer.`);\n }\n return value;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) return [];\n const parsed = value.map((item, index) => parsePrimitive(item, `${label}[${index}]`));\n const type = typeof parsed[0];\n if (!parsed.every((item) => typeof item === type)) {\n throw new TypeError(`${label} must be a homogeneous array.`);\n }\n return parsed as GraphPropertyValue;\n }\n throw new TypeError(`${label} is not a supported graph property value.`);\n}\n\nexport function assertGraphName(value: string, label: string): void {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string.`);\n }\n}\n\nexport function assertGraphPropertyName(value: string): void {\n assertGraphName(value, \"graph property name\");\n if (value.startsWith(graphReservedPropertyPrefix)) {\n throw new TypeError(\n `Graph property names beginning with ${graphReservedPropertyPrefix} are reserved.`,\n );\n }\n}\n\nfunction parsePrimitive(value: unknown, label: string): GraphPropertyPrimitive {\n const parsed = parseGraphPropertyValue(value, label);\n if (typeof parsed === \"string\" || typeof parsed === \"number\" || typeof parsed === \"boolean\") {\n return parsed;\n }\n throw new TypeError(`${label} must be a primitive property value.`);\n}\n\nfunction assertDescription(value: string, label: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`${label} requires a non-empty description.`);\n }\n}\n\nfunction assertExactPropertySchema(schema: z.ZodObject<z.ZodRawShape>, label: string): void {\n const definition = schema._zod.def;\n if (!(definition.catchall instanceof z.ZodNever)) {\n throw new TypeError(`${label} properties must use a strict Zod object schema.`);\n }\n for (const [property, propertySchema] of Object.entries(schema.shape)) {\n assertNonEffectfulSchema(propertySchema, `${label} property ${property}`, new Set());\n }\n}\n\nfunction assertNonEffectfulSchema(value: unknown, label: string, visited: Set<z.ZodType>): void {\n if (!(value instanceof z.ZodType)) throw new TypeError(`${label} must be a Zod schema.`);\n if (visited.has(value)) return;\n visited.add(value);\n const definition = value._zod.def as unknown as Record<string, unknown>;\n const type = definition.type;\n if (\n definition.coerce === true ||\n type === \"default\" ||\n type === \"prefault\" ||\n type === \"catch\" ||\n type === \"transform\" ||\n type === \"pipe\"\n ) {\n throw new TypeError(\n `${label} must not coerce, default, transform, preprocess, or catch values.`,\n );\n }\n const checks = definition.checks;\n if (\n Array.isArray(checks) &&\n checks.some((check) => {\n if (typeof check !== \"object\" || check === null) return false;\n return (check as { _zod?: { def?: { check?: unknown } } })._zod?.def?.check === \"overwrite\";\n })\n ) {\n throw new TypeError(`${label} must not normalize or overwrite values.`);\n }\n for (const child of schemaChildren(definition)) assertNonEffectfulSchema(child, label, visited);\n}\n\nfunction schemaChildren(definition: Record<string, unknown>): z.ZodType[] {\n const children: z.ZodType[] = [];\n for (const key of [\"innerType\", \"element\", \"left\", \"right\", \"rest\", \"keyType\", \"valueType\"]) {\n const value = definition[key];\n if (value instanceof z.ZodType) children.push(value);\n }\n for (const key of [\"options\", \"items\"]) {\n const value = definition[key];\n if (Array.isArray(value)) {\n for (const item of value) if (item instanceof z.ZodType) children.push(item);\n }\n }\n return children;\n}\n","import type { CompletionModel, RetrySetting, Usage } from \"@anvia/core\";\nimport {\n chunkTextDocuments,\n type TextDocument,\n type TextDocumentChunk,\n type TextDocumentChunkingOptions,\n type TextDocumentMetadata,\n} from \"@anvia/core/documents\";\nimport { embedDocuments, type EmbeddedDocument, type EmbeddingModel } from \"@anvia/core/embeddings\";\nimport { extractGraphFacts } from \"./extract.js\";\nimport { parseGraphProperties } from \"./schema.js\";\nimport type {\n GraphChunk,\n GraphDocument,\n GraphDocumentWriter,\n GraphEntity,\n GraphMention,\n GraphOrphanEntityPolicy,\n GraphProperties,\n GraphRelationship,\n GraphSchemaLike,\n GraphWriteConflict,\n GraphWriteResult,\n} from \"./types.js\";\n\ntype GraphPreparationOptions<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel,\n> = Readonly<{\n graph: Readonly<{ schema: Schema }>;\n documents: readonly TextDocument<TextDocumentMetadata>[];\n extractionModel: ExtractionModel;\n embeddingModel: EmbeddingModel;\n chunking?: TextDocumentChunkingOptions | undefined;\n entityText?: ((entity: GraphEntity<Schema>) => string) | undefined;\n instructions?: string | undefined;\n retries?: RetrySetting | undefined;\n concurrency?: number | undefined;\n abortSignal?: AbortSignal | undefined;\n}>;\n\nexport type PrepareGraphDocumentsOptions<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel = CompletionModel,\n> = GraphPreparationOptions<Schema, ExtractionModel>;\n\nexport type IngestGraphDocumentsOptions<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel = CompletionModel,\n> = Omit<GraphPreparationOptions<Schema, ExtractionModel>, \"graph\"> &\n Readonly<{\n graph: GraphDocumentWriter<Schema>;\n conflict: GraphWriteConflict;\n orphanEntities: GraphOrphanEntityPolicy;\n }>;\n\nexport type IngestGraphTextOptions<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel = CompletionModel,\n> = Omit<IngestGraphDocumentsOptions<Schema, ExtractionModel>, \"documents\"> &\n Readonly<{ document: TextDocument<TextDocumentMetadata> }>;\n\nexport type PreparedGraphDocuments<Schema extends GraphSchemaLike> = Readonly<{\n documents: readonly GraphDocument[];\n chunks: readonly EmbeddedDocument<GraphChunk<TextDocumentMetadata>, TextDocumentMetadata>[];\n vectorDocuments: readonly EmbeddedDocument<\n TextDocument<TextDocumentMetadata>,\n TextDocumentMetadata\n >[];\n entities: readonly EmbeddedDocument<GraphEntity<Schema>>[];\n relationships: readonly GraphRelationship<Schema>[];\n mentions: readonly GraphMention[];\n usage: Usage;\n}>;\n\nexport type IngestGraphDocumentsResult<Schema extends GraphSchemaLike> =\n PreparedGraphDocuments<Schema> & Readonly<{ write: GraphWriteResult }>;\n\nexport async function ingestGraphText<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel,\n>(\n options: IngestGraphTextOptions<Schema, ExtractionModel>,\n): Promise<IngestGraphDocumentsResult<Schema>> {\n return ingestGraphDocuments({\n graph: options.graph,\n documents: [options.document],\n extractionModel: options.extractionModel,\n embeddingModel: options.embeddingModel,\n chunking: options.chunking,\n entityText: options.entityText,\n instructions: options.instructions,\n retries: options.retries,\n concurrency: options.concurrency,\n abortSignal: options.abortSignal,\n conflict: options.conflict,\n orphanEntities: options.orphanEntities,\n });\n}\n\nexport async function ingestGraphDocuments<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel,\n>(\n options: IngestGraphDocumentsOptions<Schema, ExtractionModel>,\n): Promise<IngestGraphDocumentsResult<Schema>> {\n const prepared = await prepareGraphDocuments(options);\n const write = await options.graph.replaceDocuments({\n documents: prepared.documents,\n chunks: prepared.chunks,\n entities: prepared.entities,\n relationships: prepared.relationships,\n mentions: prepared.mentions,\n conflict: options.conflict,\n orphanEntities: options.orphanEntities,\n abortSignal: options.abortSignal,\n });\n return { ...prepared, write };\n}\n\nexport async function prepareGraphDocuments<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel,\n>(\n options: PrepareGraphDocumentsOptions<Schema, ExtractionModel>,\n): Promise<PreparedGraphDocuments<Schema>> {\n validatePortableMetadata(options.documents);\n const chunks = chunkTextDocuments({\n documents: options.documents,\n chunking: options.chunking,\n });\n const graphChunks: GraphChunk<TextDocumentMetadata>[] = chunks.map((chunk) => graphChunk(chunk));\n const [facts, embeddedChunks] = await Promise.all([\n extractGraphFacts({\n model: options.extractionModel,\n schema: options.graph.schema,\n chunks: graphChunks,\n instructions: options.instructions,\n retries: options.retries,\n concurrency: options.concurrency,\n abortSignal: options.abortSignal,\n }),\n embedDocuments({\n model: options.embeddingModel,\n documents: graphChunks,\n id: (chunk) => chunk.id,\n content: (chunk) => chunk.text,\n metadata: (chunk) => chunk.metadata,\n retries: options.retries,\n concurrency: options.concurrency,\n abortSignal: options.abortSignal,\n }),\n ]);\n const embeddedEntities = await embedDocuments({\n model: options.embeddingModel,\n documents: [...facts.output.entities],\n id: (entity) => entity.key,\n content: options.entityText ?? defaultGraphEntityText,\n retries: options.retries,\n concurrency: options.concurrency,\n abortSignal: options.abortSignal,\n });\n const vectorDocuments = groupVectorDocuments(options.documents, embeddedChunks.documents);\n return {\n documents: options.documents.map((document) => graphDocument(document)),\n chunks: embeddedChunks.documents,\n vectorDocuments,\n entities: embeddedEntities.documents,\n relationships: facts.output.relationships,\n mentions: facts.output.mentions,\n usage: facts.usage,\n };\n}\n\nfunction validatePortableMetadata(documents: readonly TextDocument<TextDocumentMetadata>[]): void {\n for (const document of documents) {\n if (document.metadata === undefined) {\n continue;\n }\n const metadata = parseGraphProperties(\n document.metadata,\n `Text document ${document.id} metadata`,\n );\n for (const [key, value] of Object.entries(metadata)) {\n if (Array.isArray(value)) {\n throw new TypeError(\n `Text document ${document.id} metadata.${key} must be a portable primitive value`,\n );\n }\n }\n }\n}\n\nfunction groupVectorDocuments(\n documents: readonly TextDocument<TextDocumentMetadata>[],\n chunks: readonly EmbeddedDocument<GraphChunk<TextDocumentMetadata>, TextDocumentMetadata>[],\n): readonly EmbeddedDocument<TextDocument<TextDocumentMetadata>, TextDocumentMetadata>[] {\n const chunksByDocument = new Map<\n string,\n EmbeddedDocument<GraphChunk<TextDocumentMetadata>, TextDocumentMetadata>[]\n >();\n for (const chunk of chunks) {\n const documentChunks = chunksByDocument.get(chunk.document.documentId);\n if (documentChunks === undefined) {\n chunksByDocument.set(chunk.document.documentId, [chunk]);\n } else {\n documentChunks.push(chunk);\n }\n }\n return documents.map((document) => {\n const documentChunks = chunksByDocument.get(document.id);\n if (documentChunks === undefined) {\n throw new TypeError(`Text document ${document.id} has no embedded graph chunks`);\n }\n const embeddedDocument: EmbeddedDocument<\n TextDocument<TextDocumentMetadata>,\n TextDocumentMetadata\n > = {\n id: document.id,\n document,\n embeddings: documentChunks.flatMap((chunk) => chunk.embeddings),\n };\n if (document.metadata !== undefined) {\n embeddedDocument.metadata = document.metadata;\n }\n return embeddedDocument;\n });\n}\n\nfunction graphDocument(document: TextDocument<TextDocumentMetadata>): GraphDocument {\n if (document.metadata === undefined) {\n return { id: document.id };\n }\n return { id: document.id, properties: document.metadata };\n}\n\nfunction graphChunk(\n chunk: TextDocumentChunk<TextDocumentMetadata>,\n): GraphChunk<TextDocumentMetadata> {\n if (chunk.metadata === undefined) {\n return {\n id: chunk.id,\n documentId: chunk.documentId,\n index: chunk.index,\n text: chunk.text,\n };\n }\n return {\n id: chunk.id,\n documentId: chunk.documentId,\n index: chunk.index,\n text: chunk.text,\n metadata: chunk.metadata,\n };\n}\n\nfunction defaultGraphEntityText(entity: GraphEntity<GraphSchemaLike>): string {\n const properties = Object.entries(entity.properties)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, value]) => `${key}: ${formatGraphProperty(value)}`)\n .join(\"\\n\");\n return properties.length === 0 ? entity.type : `${entity.type}\\n${properties}`;\n}\n\nfunction formatGraphProperty(value: GraphProperties[string]): string {\n if (Array.isArray(value)) {\n return value.join(\", \");\n }\n return String(value);\n}\n","import { createTool } from \"@anvia/core/tool\";\nimport { z } from \"zod\";\nimport type {\n CreateGraphSearchToolOptions,\n GraphContextRetriever,\n GraphSchemaLike,\n GraphSearchTool,\n} from \"./types.js\";\n\nconst primitive = z.union([z.string(), z.number().finite(), z.boolean()]);\nconst propertyValue = z.union([\n primitive,\n z.array(z.string()),\n z.array(z.number().finite()),\n z.array(z.boolean()),\n]);\nconst properties = z.record(z.string(), propertyValue);\nconst contextSchema = z.object({\n seeds: z.array(\n z.object({\n key: z.string(),\n type: z.string(),\n score: z.number().finite(),\n properties,\n sourceChunkIds: z.array(z.string()),\n }),\n ),\n nodes: z.array(\n z.object({\n key: z.string(),\n type: z.string(),\n identity: z.record(z.string(), primitive),\n properties,\n sourceChunkIds: z.array(z.string()),\n }),\n ),\n relationships: z.array(\n z.object({\n key: z.string(),\n type: z.string(),\n from: z.string(),\n to: z.string(),\n properties,\n sourceChunkIds: z.array(z.string()),\n }),\n ),\n evidence: z.array(\n z.object({\n chunkId: z.string(),\n documentId: z.string(),\n index: z.number().int(),\n text: z.string(),\n metadata: properties,\n }),\n ),\n});\n\nexport function createGraphSearchTool<\n Schema extends GraphSchemaLike,\n Retriever extends GraphContextRetriever<Schema>,\n>(options: CreateGraphSearchToolOptions<Schema, Retriever>): GraphSearchTool {\n return createTool({\n name: options.name,\n description: options.description,\n inputSchema: z.object({\n query: z.string().min(1).describe(\"The question or concept to search for in the graph.\"),\n }),\n outputSchema: contextSchema,\n execute: async ({ query }, context) =>\n (await options.graph.retrieve({\n model: options.model,\n query,\n search: options.search,\n traversal: options.traversal,\n evidence: options.evidence,\n retries: options.retries,\n abortSignal: context.abortSignal,\n })) as unknown as z.input<typeof contextSchema>,\n }) as unknown as GraphSearchTool;\n}\n"],"mappings":";;;;;AAAA,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,KAAAA,UAAS;;;ACFlB,SAAS,SAAS;AASX,IAAM,8BAA8B;AAEpC,SAAS,kBACd,SACsB;AACtB,6BAA2B,OAAO;AAClC,SAAO,kBAAkB,SAAS,cAAc;AAClD;AAEO,SAAS,2BAA2B,SAAmC;AAC5E,MAAI,OAAO,KAAK,QAAQ,KAAK,EAAE,WAAW,GAAG;AAC3C,UAAM,IAAI,UAAU,iDAAiD;AAAA,EACvE;AACA,aAAW,CAAC,MAAM,UAAU,KAAK,OAAO,QAAQ,QAAQ,KAAK,GAAG;AAC9D,oBAAgB,MAAM,WAAW;AACjC,sBAAkB,WAAW,aAAa,QAAQ,IAAI,EAAE;AACxD,QAAI,EAAE,WAAW,sBAAsB,EAAE,YAAY;AACnD,YAAM,IAAI,UAAU,uBAAuB,IAAI,+BAA+B;AAAA,IAChF;AACA,8BAA0B,WAAW,YAAY,QAAQ,IAAI,EAAE;AAC/D,Q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A,MACf,UAAUA,GAAE,OAAOA,GAAE,OAAO,GAAG,SAAS;AAAA,MACxC;AAAA,MACA,gBAAgBA,GAAE,MAAMA,GAAE,OAAO,CAAC;AAAA,IACpC,CAAC;AAAA,EACH;AAAA,EACA,eAAeA,GAAE;AAAA,IACfA,GAAE,OAAO;AAAA,MACP,KAAKA,GAAE,OAAO;AAAA,MACd,MAAMA,GAAE,OAAO;AAAA,MACf,MAAMA,GAAE,OAAO;AAAA,MACf,IAAIA,GAAE,OAAO;AAAA,MACb;AAAA,MACA,gBAAgBA,GAAE,MAAMA,GAAE,OAAO,CAAC;AAAA,IACpC,CAAC;AAAA,EACH;AAAA,EACA,UAAUA,GAAE;AAAA,IACVA,GAAE,OAAO;AAAA,MACP,SAASA,GAAE,OAAO;AAAA,MAClB,YAAYA,GAAE,OAAO;AAAA,MACrB,OAAOA,GAAE,OAAO,EAAE,IAAI;AAAA,MACtB,MAAMA,GAAE,OAAO;AAAA,MACf,UAAU;AAAA,IACZ,CAAC;AAAA,EACH;AACF,CAAC;AAEM,SAAS,sBAGd,SAA2E;AAC3E,SAAO,WAAW;AAAA,IAChB,MAAM,QAAQ;AAAA,IACd,aAAa,QAAQ;AAAA,IACrB,aAAaA,GAAE,OAAO;AAAA,MACpB,OAAOA,GAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,qDAAqD;AAAA,IACzF,CAAC;AAAA,IACD,cAAc;AAAA,IACd,SAAS,OAAO,EAAE,MAAM,GAAG,YACxB,MAAM,QAAQ,MAAM,SAAS;AAAA,MAC5B,OAAO,QAAQ;AAAA,MACf;AAAA,MACA,QAAQ,QAAQ;AAAA,MAChB,WAAW,QAAQ;AAAA,MACnB,UAAU,QAAQ;AAAA,MAClB,SAAS,QAAQ;AAAA,MACjB,aAAa,QAAQ;AAAA,IACvB,CAAC;AAAA,EACL,CAAC;AACH;","names":["z","z","properties","properties","z"]}
|
|
1
|
+
{"version":3,"sources":["../src/extract.ts","../src/schema.ts","../src/ingest.ts","../src/tool.ts"],"sourcesContent":["import { Usage } from \"@anvia/core\";\nimport { extract } from \"@anvia/core/extractor\";\nimport { z } from \"zod\";\nimport { parseGraphProperties, parseGraphPropertyValue } from \"./schema.js\";\nimport type {\n ExtractGraphFactsOptions,\n ExtractGraphFactsResult,\n GraphEntity,\n GraphExtractionWarning,\n GraphFactConflictCandidate,\n GraphFactConflictPolicy,\n GraphFactPropertyConflict,\n GraphFactPropertyConflictStrategy,\n GraphFacts,\n GraphMention,\n GraphNodeIdentity,\n GraphProperties,\n GraphPropertyValue,\n GraphRelationship,\n GraphSchemaLike,\n} from \"./types.js\";\n\ntype RawEntity = { ref: string; type: string; properties: Record<string, unknown> };\ntype RawRelationship = {\n type: string;\n from: string;\n to: string;\n properties: Record<string, unknown>;\n};\ntype RawChunkFacts = { entities: RawEntity[]; relationships: RawRelationship[] };\ntype ChunkExtraction = { chunkId: string; output: RawChunkFacts; usage: Usage };\ntype EntityCandidate = Readonly<{\n key: string;\n type: string;\n identity: GraphNodeIdentity;\n properties: GraphProperties;\n chunkId: string;\n}>;\ntype RelationshipCandidate = Readonly<{\n key: string;\n type: string;\n from: string;\n to: string;\n identity: GraphNodeIdentity;\n properties: GraphProperties;\n chunkId: string;\n}>;\n\nexport async function extractGraphFacts<\n Schema extends GraphSchemaLike,\n Model extends import(\"@anvia/core\").CompletionModel,\n>(options: ExtractGraphFactsOptions<Schema, Model>): Promise<ExtractGraphFactsResult<Schema>> {\n assertConcurrency(options.concurrency);\n throwIfAborted(options.abortSignal);\n const ids = new Set<string>();\n for (const chunk of options.chunks) {\n if (ids.has(chunk.id)) throw new TypeError(`Duplicate graph chunk id: ${chunk.id}`);\n ids.add(chunk.id);\n if (typeof chunk.text !== \"string\") {\n throw new TypeError(`Graph chunk ${chunk.id} text must be a string.`);\n }\n }\n\n const outputSchema = extractionSchema(options.schema);\n const instructions = graphInstructions(options.schema, options.instructions);\n const extractions = await mapConcurrent(\n options.chunks,\n options.concurrency ?? 1,\n async (chunk): Promise<ChunkExtraction> => {\n throwIfAborted(options.abortSignal);\n const result = await extract({\n model: options.model,\n text: chunk.text,\n outputSchema,\n instructions,\n retries: options.retries,\n abortSignal: options.abortSignal,\n });\n return { chunkId: chunk.id, output: result.output as RawChunkFacts, usage: result.usage };\n },\n );\n return {\n ...normalizeFacts(options.schema, extractions, options.conflicts),\n usage: extractions.reduce((usage, item) => Usage.add(usage, item.usage), Usage.empty()),\n };\n}\n\nfunction extractionSchema(schema: GraphSchemaLike): z.ZodType<RawChunkFacts> {\n const entities = Object.entries(schema.nodes).map(([type, definition]) =>\n z.object({ ref: z.string().min(1), type: z.literal(type), properties: definition.properties }),\n );\n const relationships = Object.entries(schema.relationships).map(([type, definition]) =>\n z.object({\n type: z.literal(type),\n from: z.string().min(1),\n to: z.string().min(1),\n properties: definition.properties,\n }),\n );\n return z.object({\n entities: z.array(union(entities, z.never())),\n relationships: z.array(union(relationships, z.never())),\n }) as unknown as z.ZodType<RawChunkFacts>;\n}\n\nfunction union(items: z.ZodType[], empty: z.ZodType): z.ZodType {\n if (items.length === 0) return empty;\n if (items.length === 1) return items[0] as z.ZodType;\n return z.union(items as [z.ZodType, z.ZodType, ...z.ZodType[]]);\n}\n\nfunction graphInstructions(schema: GraphSchemaLike, extra: string | undefined): string {\n const nodes = Object.entries(schema.nodes)\n .map(([type, definition]) => `- ${type}: ${definition.description}`)\n .join(\"\\n\");\n const relationships = Object.entries(schema.relationships)\n .map(\n ([type, definition]) =>\n `- ${type}: ${definition.from} -> ${definition.to}. ${definition.description}`,\n )\n .join(\"\\n\");\n return [\n \"Extract only facts directly supported by the source text.\",\n \"Give every extracted entity a unique local ref and use those refs as relationship endpoints.\",\n \"Do not invent entity or relationship types outside the declared schema.\",\n `Node types:\\n${nodes}`,\n relationships.length === 0\n ? \"No relationship types are allowed.\"\n : `Relationship types:\\n${relationships}`,\n extra,\n ]\n .filter((part): part is string => part !== undefined && part.length > 0)\n .join(\"\\n\\n\");\n}\n\nfunction normalizeFacts<Schema extends GraphSchemaLike>(\n schema: Schema,\n extractions: readonly ChunkExtraction[],\n conflicts: ExtractGraphFactsOptions<Schema, import(\"@anvia/core\").CompletionModel>[\"conflicts\"],\n): Readonly<{ output: GraphFacts<Schema>; warnings: readonly GraphExtractionWarning[] }> {\n const entityCandidates = new Map<string, EntityCandidate[]>();\n const relationshipCandidates = new Map<string, RelationshipCandidate[]>();\n const mentions = new Map<string, GraphMention>();\n\n for (const extraction of extractions) {\n const refs = new Map<string, EntityCandidate>();\n for (const raw of extraction.output.entities) {\n if (refs.has(raw.ref)) {\n throw new TypeError(`Duplicate entity ref ${raw.ref} in chunk ${extraction.chunkId}.`);\n }\n const definition = schema.nodes[raw.type];\n if (definition === undefined) throw new TypeError(`Unknown graph entity type: ${raw.type}`);\n const properties = parseGraphProperties(\n definition.properties.parse(raw.properties),\n `entity ${raw.type}`,\n );\n const identity = identityFromProperties(definition.identity, properties, raw.type);\n const key = `${raw.type}:${stableObject(identity)}`;\n const candidate: EntityCandidate = {\n key,\n type: raw.type,\n identity,\n properties,\n chunkId: extraction.chunkId,\n };\n appendCandidate(entityCandidates, key, candidate);\n refs.set(raw.ref, candidate);\n mentions.set(`${extraction.chunkId}\\u0000${key}`, {\n chunkId: extraction.chunkId,\n entityKey: key,\n });\n }\n\n for (const raw of extraction.output.relationships) {\n const definition = schema.relationships[raw.type];\n if (definition === undefined) {\n throw new TypeError(`Unknown graph relationship type: ${raw.type}`);\n }\n const from = refs.get(raw.from);\n const to = refs.get(raw.to);\n if (from === undefined || to === undefined) {\n throw new TypeError(\n `Relationship ${raw.type} in chunk ${extraction.chunkId} references an unknown entity ref.`,\n );\n }\n if (from.type !== definition.from || to.type !== definition.to) {\n throw new TypeError(\n `Relationship ${raw.type} has invalid endpoint types ${from.type} -> ${to.type}.`,\n );\n }\n const properties = parseGraphProperties(\n definition.properties.parse(raw.properties),\n `relationship ${raw.type}`,\n );\n const identity = identityFromProperties(definition.identity ?? [], properties, raw.type);\n const key = `${raw.type}:${from.key}->${to.key}:${stableObject(identity)}`;\n appendCandidate(relationshipCandidates, key, {\n key,\n type: raw.type,\n from: from.key,\n to: to.key,\n identity,\n properties,\n chunkId: extraction.chunkId,\n });\n }\n }\n const warnings: GraphExtractionWarning[] = [];\n const entities = [...entityCandidates.values()].map((candidates) => {\n const first = requiredCandidate(candidates);\n const definition = schema.nodes[first.type];\n if (definition === undefined) throw new TypeError(`Unknown graph entity type: ${first.type}`);\n const properties = parseGraphProperties(\n definition.properties.parse(\n resolveFactProperties(\n \"entity\",\n first.key,\n first.type,\n first.identity,\n candidates,\n conflicts?.entity,\n warnings,\n ),\n ),\n `entity ${first.type}`,\n );\n return {\n key: first.key,\n type: first.type,\n identity: first.identity,\n properties,\n sourceChunkIds: uniqueChunkIds(candidates),\n } as GraphEntity<Schema>;\n });\n const relationships = [...relationshipCandidates.values()].map((candidates) => {\n const first = requiredCandidate(candidates);\n const definition = schema.relationships[first.type];\n if (definition === undefined) {\n throw new TypeError(`Unknown graph relationship type: ${first.type}`);\n }\n const properties = parseGraphProperties(\n definition.properties.parse(\n resolveFactProperties(\n \"relationship\",\n first.key,\n first.type,\n first.identity,\n candidates,\n conflicts?.relationship,\n warnings,\n ),\n ),\n `relationship ${first.type}`,\n );\n return {\n key: first.key,\n type: first.type,\n from: first.from,\n to: first.to,\n properties,\n sourceChunkIds: uniqueChunkIds(candidates),\n } as GraphRelationship<Schema>;\n });\n return {\n output: { entities, relationships, mentions: [...mentions.values()] },\n warnings,\n };\n}\n\nfunction appendCandidate<Candidate>(\n candidates: Map<string, Candidate[]>,\n key: string,\n candidate: Candidate,\n): void {\n const current = candidates.get(key);\n if (current === undefined) candidates.set(key, [candidate]);\n else current.push(candidate);\n}\n\nfunction requiredCandidate<Candidate>(candidates: readonly Candidate[]): Candidate {\n const candidate = candidates[0];\n if (candidate === undefined) throw new TypeError(\"Graph fact candidate group cannot be empty.\");\n return candidate;\n}\n\nfunction uniqueChunkIds(candidates: readonly { chunkId: string }[]): readonly string[] {\n return [...new Set(candidates.map((candidate) => candidate.chunkId))];\n}\n\nfunction resolveFactProperties(\n kind: \"entity\" | \"relationship\",\n key: string,\n type: string,\n identity: GraphNodeIdentity,\n candidates: readonly { chunkId: string; properties: GraphProperties }[],\n policy: GraphFactConflictPolicy | undefined,\n warnings: GraphExtractionWarning[],\n): GraphProperties {\n const propertyNames = [\n ...new Set(candidates.flatMap((candidate) => Object.keys(candidate.properties))),\n ].sort();\n const properties: Record<string, GraphPropertyValue> = {};\n for (const property of propertyNames) {\n const propertyCandidates: GraphFactConflictCandidate[] = candidates.map((candidate) => ({\n chunkId: candidate.chunkId,\n properties: candidate.properties,\n value: candidate.properties[property],\n }));\n const firstValue = propertyCandidates[0]?.value;\n if (\n propertyCandidates.every(\n (candidate) => stableValue(candidate.value) === stableValue(firstValue),\n )\n ) {\n if (firstValue !== undefined) properties[property] = firstValue;\n continue;\n }\n const conflict: GraphFactPropertyConflict = {\n code: \"GRAPH_FACT_CONFLICT\",\n kind,\n key,\n type,\n identity,\n property,\n candidates: propertyCandidates,\n sourceChunkIds: uniqueChunkIds(propertyCandidates),\n };\n const strategy =\n policy?.properties?.[property] ?? policy?.resolve ?? policy?.default ?? \"reject\";\n if (strategy === \"reject\") throw new GraphFactConflictError(conflict);\n const resolvedValue = validateResolvedValue(\n resolvePropertyConflict(strategy, conflict),\n conflict,\n );\n if (resolvedValue !== undefined) properties[property] = resolvedValue;\n warnings.push({\n ...conflict,\n code: \"GRAPH_FACT_CONFLICT_RESOLVED\",\n strategy: typeof strategy === \"function\" ? \"custom\" : strategy,\n resolvedValue,\n });\n }\n return properties;\n}\n\nfunction resolvePropertyConflict(\n strategy: Exclude<GraphFactPropertyConflictStrategy, \"reject\">,\n conflict: GraphFactPropertyConflict,\n): GraphPropertyValue | undefined {\n if (typeof strategy === \"function\") {\n return strategy(conflict);\n }\n const values = conflict.candidates.map((candidate) => candidate.value);\n if (strategy === \"prefer-first\") return values[0];\n if (strategy === \"prefer-last\") return values.at(-1);\n if (strategy === \"prefer-defined\") return values.find((value) => value !== undefined);\n if (strategy === \"prefer-longest\") {\n const strings = definedValues(values, \"string\", conflict, strategy);\n return strings.reduce((longest, value) => (value.length > longest.length ? value : longest));\n }\n if (strategy === \"union\") {\n const arrays = values.filter((value) => value !== undefined);\n if (!arrays.every(Array.isArray)) throw incompatibleStrategy(conflict, strategy);\n return [...new Set(arrays.flat())] as string[] | number[] | boolean[];\n }\n const numbers = definedValues(values, \"number\", conflict, strategy);\n return strategy === \"max\" ? Math.max(...numbers) : Math.min(...numbers);\n}\n\nfunction definedValues<Type extends \"string\" | \"number\">(\n values: readonly (GraphPropertyValue | undefined)[],\n type: Type,\n conflict: GraphFactPropertyConflict,\n strategy: string,\n): Type extends \"string\" ? string[] : number[] {\n const defined = values.filter((value) => value !== undefined);\n if (defined.length === 0 || !defined.every((value) => typeof value === type)) {\n throw incompatibleStrategy(conflict, strategy);\n }\n return defined as Type extends \"string\" ? string[] : number[];\n}\n\nfunction validateResolvedValue(\n value: GraphPropertyValue | undefined,\n conflict: GraphFactPropertyConflict,\n): GraphPropertyValue | undefined {\n return value === undefined\n ? undefined\n : parseGraphPropertyValue(value, `Resolved graph fact ${conflict.key}.${conflict.property}`);\n}\n\nfunction incompatibleStrategy(conflict: GraphFactPropertyConflict, strategy: string): TypeError {\n return new TypeError(\n `Graph fact conflict strategy ${strategy} is incompatible with ${conflict.key}.${conflict.property}.`,\n );\n}\n\nfunction identityFromProperties(\n keys: readonly string[],\n properties: GraphProperties,\n type: string,\n): GraphNodeIdentity {\n const identity: Record<string, string | number | boolean> = {};\n for (const key of keys) {\n const value = properties[key];\n if (\n value === undefined ||\n !(typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\")\n ) {\n throw new TypeError(`Identity property ${key} for ${type} must be a primitive value.`);\n }\n identity[key] = value;\n }\n return identity;\n}\n\nfunction stableObject(value: Readonly<Record<string, unknown>>): string {\n return JSON.stringify(\n Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right))),\n );\n}\n\nfunction stableValue(value: unknown): string {\n return value === undefined ? \"undefined\" : stableObject({ value });\n}\n\nexport class GraphFactConflictError extends Error {\n readonly code = \"GRAPH_FACT_CONFLICT\" as const;\n readonly kind: \"entity\" | \"relationship\";\n readonly factKey: string;\n readonly type: string;\n readonly identity: GraphNodeIdentity;\n readonly property: string;\n readonly candidates: readonly GraphFactConflictCandidate[];\n readonly sourceChunkIds: readonly string[];\n\n constructor(conflict: GraphFactPropertyConflict);\n constructor(factKey: string, sourceChunkIds: readonly string[]);\n constructor(\n conflictOrKey: GraphFactPropertyConflict | string,\n legacyChunkIds: readonly string[] = [],\n ) {\n const conflict =\n typeof conflictOrKey === \"string\"\n ? {\n code: \"GRAPH_FACT_CONFLICT\" as const,\n kind: \"entity\" as const,\n key: conflictOrKey,\n type: conflictOrKey.split(\":\", 1)[0] ?? \"unknown\",\n identity: {},\n property: \"unknown\",\n candidates: [],\n sourceChunkIds: legacyChunkIds,\n }\n : conflictOrKey;\n super(\n `Conflicting graph fact ${conflict.key}.${conflict.property} was extracted from chunks ${conflict.sourceChunkIds.join(\", \")}.`,\n );\n this.name = \"GraphFactConflictError\";\n this.kind = conflict.kind;\n this.factKey = conflict.key;\n this.type = conflict.type;\n this.identity = conflict.identity;\n this.property = conflict.property;\n this.candidates = conflict.candidates;\n this.sourceChunkIds = conflict.sourceChunkIds;\n }\n}\n\nfunction assertConcurrency(value: number | undefined): void {\n if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {\n throw new RangeError(\"Graph extraction concurrency must be a positive safe integer.\");\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted !== true) return;\n if (signal.reason instanceof Error) throw signal.reason;\n throw new DOMException(\"The operation was aborted.\", \"AbortError\");\n}\n\nasync function mapConcurrent<Input, Output>(\n values: readonly Input[],\n concurrency: number,\n run: (value: Input) => Promise<Output>,\n): Promise<Output[]> {\n const output = Array<Output>(values.length);\n let cursor = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, values.length) }, async () => {\n for (;;) {\n const index = cursor;\n cursor += 1;\n if (index >= values.length) return;\n output[index] = await run(values[index] as Input);\n }\n }),\n );\n return output;\n}\n","import { z } from \"zod\";\nimport type {\n GraphProperties,\n GraphPropertyPrimitive,\n GraphPropertyValue,\n GraphSchema,\n GraphSchemaOptions,\n} from \"./types.js\";\n\nexport const graphReservedPropertyPrefix = \"__anvia_\";\n\nexport function defineGraphSchema<const Options extends GraphSchemaOptions>(\n options: Options,\n): GraphSchema<Options> {\n validateGraphSchemaOptions(options);\n return freezeGraphSchema(options, \"graph-schema\");\n}\n\nexport function validateGraphSchemaOptions(options: GraphSchemaOptions): void {\n if (Object.keys(options.nodes).length === 0) {\n throw new TypeError(\"A graph schema requires at least one node type.\");\n }\n for (const [type, definition] of Object.entries(options.nodes)) {\n assertGraphName(type, \"node type\");\n assertDescription(definition.description, `node ${type}`);\n if (!(definition.properties instanceof z.ZodObject)) {\n throw new TypeError(`Properties for node ${type} must be a Zod object schema.`);\n }\n assertExactPropertySchema(definition.properties, `node ${type}`);\n if (\n definition.identity.length === 0 ||\n new Set(definition.identity).size !== definition.identity.length\n ) {\n throw new TypeError(`Node ${type} must declare unique identity properties.`);\n }\n for (const property of definition.identity) {\n assertGraphPropertyName(property);\n if (!(property in definition.properties.shape)) {\n throw new TypeError(`Identity property ${property} is not declared by node ${type}.`);\n }\n }\n for (const property of Object.keys(definition.properties.shape)) {\n assertGraphPropertyName(property);\n }\n }\n for (const [type, definition] of Object.entries(options.relationships)) {\n assertGraphName(type, \"relationship type\");\n assertDescription(definition.description, `relationship ${type}`);\n if (!(definition.from in options.nodes) || !(definition.to in options.nodes)) {\n throw new TypeError(`Relationship ${type} references an unknown endpoint type.`);\n }\n if (!(definition.properties instanceof z.ZodObject)) {\n throw new TypeError(`Properties for relationship ${type} must be a Zod object schema.`);\n }\n assertExactPropertySchema(definition.properties, `relationship ${type}`);\n const identity = definition.identity ?? [];\n if (new Set(identity).size !== identity.length) {\n throw new TypeError(`Relationship ${type} contains duplicate identity properties.`);\n }\n for (const property of Object.keys(definition.properties.shape)) {\n assertGraphPropertyName(property);\n }\n for (const property of identity) {\n if (!(property in definition.properties.shape)) {\n throw new TypeError(\n `Identity property ${property} is not declared by relationship ${type}.`,\n );\n }\n }\n }\n}\n\nexport function freezeGraphSchema<\n const Options extends GraphSchemaOptions,\n const Kind extends string,\n>(options: Options, kind: Kind): Readonly<Options & { kind: Kind }> {\n const nodes = Object.fromEntries(\n Object.entries(options.nodes).map(([type, definition]) => [\n type,\n Object.freeze({ ...definition, identity: Object.freeze([...definition.identity]) }),\n ]),\n );\n const relationships = Object.fromEntries(\n Object.entries(options.relationships).map(([type, definition]) => {\n const copy = { ...definition };\n if (definition.identity !== undefined) {\n Object.assign(copy, { identity: Object.freeze([...definition.identity]) });\n }\n return [type, Object.freeze(copy)];\n }),\n );\n return Object.freeze({\n nodes: Object.freeze(nodes),\n relationships: Object.freeze(relationships),\n kind,\n }) as Readonly<Options & { kind: Kind }>;\n}\n\nexport function parseGraphProperties(value: unknown, label: string): GraphProperties {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${label} must be an object of graph property values.`);\n }\n const output: Record<string, GraphPropertyValue> = {};\n for (const [key, item] of Object.entries(value)) {\n assertGraphPropertyName(key);\n output[key] = parseGraphPropertyValue(item, `${label}.${key}`);\n }\n return output;\n}\n\nexport function parseGraphPropertyValue(value: unknown, label: string): GraphPropertyValue {\n if (typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new TypeError(`${label} must be finite.`);\n if (Number.isInteger(value) && !Number.isSafeInteger(value)) {\n throw new TypeError(`${label} must be a safe integer.`);\n }\n return value;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) return [];\n const parsed = value.map((item, index) => parsePrimitive(item, `${label}[${index}]`));\n const type = typeof parsed[0];\n if (!parsed.every((item) => typeof item === type)) {\n throw new TypeError(`${label} must be a homogeneous array.`);\n }\n return parsed as GraphPropertyValue;\n }\n throw new TypeError(`${label} is not a supported graph property value.`);\n}\n\nexport function assertGraphName(value: string, label: string): void {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string.`);\n }\n}\n\nexport function assertGraphPropertyName(value: string): void {\n assertGraphName(value, \"graph property name\");\n if (value.startsWith(graphReservedPropertyPrefix)) {\n throw new TypeError(\n `Graph property names beginning with ${graphReservedPropertyPrefix} are reserved.`,\n );\n }\n}\n\nfunction parsePrimitive(value: unknown, label: string): GraphPropertyPrimitive {\n const parsed = parseGraphPropertyValue(value, label);\n if (typeof parsed === \"string\" || typeof parsed === \"number\" || typeof parsed === \"boolean\") {\n return parsed;\n }\n throw new TypeError(`${label} must be a primitive property value.`);\n}\n\nfunction assertDescription(value: string, label: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`${label} requires a non-empty description.`);\n }\n}\n\nfunction assertExactPropertySchema(schema: z.ZodObject<z.ZodRawShape>, label: string): void {\n const definition = schema._zod.def;\n if (!(definition.catchall instanceof z.ZodNever)) {\n throw new TypeError(`${label} properties must use a strict Zod object schema.`);\n }\n for (const [property, propertySchema] of Object.entries(schema.shape)) {\n assertNonEffectfulSchema(propertySchema, `${label} property ${property}`, new Set());\n }\n}\n\nfunction assertNonEffectfulSchema(value: unknown, label: string, visited: Set<z.ZodType>): void {\n if (!(value instanceof z.ZodType)) throw new TypeError(`${label} must be a Zod schema.`);\n if (visited.has(value)) return;\n visited.add(value);\n const definition = value._zod.def as unknown as Record<string, unknown>;\n const type = definition.type;\n if (\n definition.coerce === true ||\n type === \"default\" ||\n type === \"prefault\" ||\n type === \"catch\" ||\n type === \"transform\" ||\n type === \"pipe\"\n ) {\n throw new TypeError(\n `${label} must not coerce, default, transform, preprocess, or catch values.`,\n );\n }\n const checks = definition.checks;\n if (\n Array.isArray(checks) &&\n checks.some((check) => {\n if (typeof check !== \"object\" || check === null) return false;\n return (check as { _zod?: { def?: { check?: unknown } } })._zod?.def?.check === \"overwrite\";\n })\n ) {\n throw new TypeError(`${label} must not normalize or overwrite values.`);\n }\n for (const child of schemaChildren(definition)) assertNonEffectfulSchema(child, label, visited);\n}\n\nfunction schemaChildren(definition: Record<string, unknown>): z.ZodType[] {\n const children: z.ZodType[] = [];\n for (const key of [\"innerType\", \"element\", \"left\", \"right\", \"rest\", \"keyType\", \"valueType\"]) {\n const value = definition[key];\n if (value instanceof z.ZodType) children.push(value);\n }\n for (const key of [\"options\", \"items\"]) {\n const value = definition[key];\n if (Array.isArray(value)) {\n for (const item of value) if (item instanceof z.ZodType) children.push(item);\n }\n }\n return children;\n}\n","import type { CompletionModel, JsonObject, RetrySetting, Usage } from \"@anvia/core\";\nimport {\n chunkTextDocuments,\n type TextDocument,\n type TextDocumentChunk,\n type TextDocumentChunkingOptions,\n type TextDocumentMetadata,\n} from \"@anvia/core/documents\";\nimport { embedDocuments, type EmbeddedDocument, type EmbeddingModel } from \"@anvia/core/embeddings\";\nimport { extractGraphFacts } from \"./extract.js\";\nimport { parseGraphProperties } from \"./schema.js\";\nimport type {\n GraphChunk,\n GraphDocument,\n GraphDocumentWriter,\n GraphEntity,\n GraphExtractionWarning,\n GraphFactConflictOptions,\n GraphMention,\n GraphOrphanEntityPolicy,\n GraphProperties,\n GraphRelationship,\n GraphSchemaLike,\n GraphWriteConflict,\n GraphWriteResult,\n} from \"./types.js\";\n\ntype GraphPreparationOptions<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel,\n> = Readonly<{\n graph: Readonly<{ schema: Schema }>;\n documents: readonly TextDocument<TextDocumentMetadata>[];\n extractionModel: ExtractionModel;\n embeddingModel: EmbeddingModel;\n chunking?: TextDocumentChunkingOptions | undefined;\n entityText?: ((entity: GraphEntity<Schema>) => string) | undefined;\n instructions?: string | undefined;\n retries?: RetrySetting | undefined;\n concurrency?: number | undefined;\n abortSignal?: AbortSignal | undefined;\n factConflicts?: GraphFactConflictOptions | undefined;\n revision?: string | undefined;\n}>;\n\nexport type PrepareGraphDocumentsOptions<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel = CompletionModel,\n> = GraphPreparationOptions<Schema, ExtractionModel>;\n\nexport type IngestGraphDocumentsOptions<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel = CompletionModel,\n> = Omit<GraphPreparationOptions<Schema, ExtractionModel>, \"graph\"> &\n Readonly<{\n graph: GraphDocumentWriter<Schema>;\n conflict: GraphWriteConflict;\n orphanEntities: GraphOrphanEntityPolicy;\n }>;\n\nexport type IngestGraphTextOptions<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel = CompletionModel,\n> = Omit<IngestGraphDocumentsOptions<Schema, ExtractionModel>, \"documents\"> &\n Readonly<{ document: TextDocument<TextDocumentMetadata> }>;\n\nexport type PreparedGraphDocuments<Schema extends GraphSchemaLike> = Readonly<{\n documents: readonly GraphDocument[];\n chunks: readonly EmbeddedDocument<GraphChunk<TextDocumentMetadata>, TextDocumentMetadata>[];\n vectorDocuments: readonly EmbeddedDocument<\n TextDocument<TextDocumentMetadata>,\n TextDocumentMetadata\n >[];\n entities: readonly EmbeddedDocument<GraphEntity<Schema>>[];\n relationships: readonly GraphRelationship<Schema>[];\n mentions: readonly GraphMention[];\n usage: Usage;\n warnings: readonly GraphExtractionWarning[];\n}>;\n\nexport type IngestGraphDocumentsResult<Schema extends GraphSchemaLike> =\n PreparedGraphDocuments<Schema> &\n Readonly<{ write: GraphWriteResult; receipt: GraphIngestionReceipt }>;\n\nexport type GraphIngestionReceipt = Readonly<{\n documentIds: readonly string[];\n revision?: string | undefined;\n entityKeys: readonly string[];\n relationshipKeys: readonly string[];\n vectorDocumentIds: readonly string[];\n graphWrite: Readonly<{ status: \"completed\"; result: GraphWriteResult }>;\n vectorWrite: Readonly<{ status: \"not-requested\" | \"completed\" | \"failed\" }>;\n warnings: readonly GraphExtractionWarning[];\n}>;\n\nexport type GraphVectorWriter = Readonly<{\n upsert(options: {\n documents: Array<EmbeddedDocument<TextDocument<TextDocumentMetadata>, TextDocumentMetadata>>;\n providerOptions?: JsonObject | undefined;\n }): Promise<void>;\n}>;\n\nexport type IngestGraphDocumentsToStoresOptions<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel = CompletionModel,\n> = IngestGraphDocumentsOptions<Schema, ExtractionModel> &\n Readonly<{\n vectorStore: GraphVectorWriter;\n vectorProviderOptions?: JsonObject | undefined;\n }>;\n\nexport type IngestGraphTextToStoresOptions<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel = CompletionModel,\n> = Omit<IngestGraphDocumentsToStoresOptions<Schema, ExtractionModel>, \"documents\"> &\n Readonly<{ document: TextDocument<TextDocumentMetadata> }>;\n\nexport class GraphIngestionStageError extends Error {\n readonly code = \"GRAPH_INGESTION_STAGE_FAILED\" as const;\n readonly stage = \"vector\" as const;\n\n constructor(\n readonly receipt: GraphIngestionReceipt,\n cause: unknown,\n ) {\n super(\"Graph ingestion completed, but the vector write failed.\", { cause });\n this.name = \"GraphIngestionStageError\";\n }\n}\n\nexport async function ingestGraphText<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel,\n>(\n options: IngestGraphTextOptions<Schema, ExtractionModel>,\n): Promise<IngestGraphDocumentsResult<Schema>> {\n return ingestGraphDocuments({\n graph: options.graph,\n documents: [options.document],\n extractionModel: options.extractionModel,\n embeddingModel: options.embeddingModel,\n chunking: options.chunking,\n entityText: options.entityText,\n instructions: options.instructions,\n retries: options.retries,\n concurrency: options.concurrency,\n abortSignal: options.abortSignal,\n factConflicts: options.factConflicts,\n revision: options.revision,\n conflict: options.conflict,\n orphanEntities: options.orphanEntities,\n });\n}\n\nexport async function ingestGraphDocuments<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel,\n>(\n options: IngestGraphDocumentsOptions<Schema, ExtractionModel>,\n): Promise<IngestGraphDocumentsResult<Schema>> {\n const prepared = await prepareGraphDocuments(options);\n const write = await options.graph.replaceDocuments({\n documents: prepared.documents,\n chunks: prepared.chunks,\n entities: prepared.entities,\n relationships: prepared.relationships,\n mentions: prepared.mentions,\n conflict: options.conflict,\n orphanEntities: options.orphanEntities,\n abortSignal: options.abortSignal,\n });\n return {\n ...prepared,\n write,\n receipt: ingestionReceipt(prepared, write, options.revision, \"not-requested\"),\n };\n}\n\nexport async function ingestGraphTextToStores<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel,\n>(\n options: IngestGraphTextToStoresOptions<Schema, ExtractionModel>,\n): Promise<IngestGraphDocumentsResult<Schema>> {\n return ingestGraphDocumentsToStores({ ...options, documents: [options.document] });\n}\n\nexport async function ingestGraphDocumentsToStores<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel,\n>(\n options: IngestGraphDocumentsToStoresOptions<Schema, ExtractionModel>,\n): Promise<IngestGraphDocumentsResult<Schema>> {\n const result = await ingestGraphDocuments(options);\n try {\n await options.vectorStore.upsert({\n documents: [...result.vectorDocuments],\n providerOptions: options.vectorProviderOptions,\n });\n } catch (error) {\n throw new GraphIngestionStageError(\n { ...result.receipt, vectorWrite: { status: \"failed\" } },\n error,\n );\n }\n return {\n ...result,\n receipt: { ...result.receipt, vectorWrite: { status: \"completed\" } },\n };\n}\n\nexport async function prepareGraphDocuments<\n Schema extends GraphSchemaLike,\n ExtractionModel extends CompletionModel,\n>(\n options: PrepareGraphDocumentsOptions<Schema, ExtractionModel>,\n): Promise<PreparedGraphDocuments<Schema>> {\n if (options.revision !== undefined && options.revision.trim().length === 0) {\n throw new TypeError(\"Graph ingestion revision must be a non-empty string.\");\n }\n validatePortableMetadata(options.documents);\n const chunks = chunkTextDocuments({\n documents: options.documents,\n chunking: options.chunking,\n });\n const graphChunks: GraphChunk<TextDocumentMetadata>[] = chunks.map((chunk) => graphChunk(chunk));\n const [facts, embeddedChunks] = await Promise.all([\n extractGraphFacts({\n model: options.extractionModel,\n schema: options.graph.schema,\n chunks: graphChunks,\n instructions: options.instructions,\n retries: options.retries,\n concurrency: options.concurrency,\n abortSignal: options.abortSignal,\n conflicts: options.factConflicts,\n }),\n embedDocuments({\n model: options.embeddingModel,\n documents: graphChunks,\n id: (chunk) => chunk.id,\n content: (chunk) => chunk.text,\n metadata: (chunk) => chunk.metadata,\n retries: options.retries,\n concurrency: options.concurrency,\n abortSignal: options.abortSignal,\n }),\n ]);\n const embeddedEntities = await embedDocuments({\n model: options.embeddingModel,\n documents: [...facts.output.entities],\n id: (entity) => entity.key,\n content: options.entityText ?? defaultGraphEntityText,\n retries: options.retries,\n concurrency: options.concurrency,\n abortSignal: options.abortSignal,\n });\n const vectorDocuments = groupVectorDocuments(options.documents, embeddedChunks.documents);\n return {\n documents: options.documents.map((document) => graphDocument(document)),\n chunks: embeddedChunks.documents,\n vectorDocuments,\n entities: embeddedEntities.documents,\n relationships: facts.output.relationships,\n mentions: facts.output.mentions,\n usage: facts.usage,\n warnings: facts.warnings,\n };\n}\n\nfunction ingestionReceipt<Schema extends GraphSchemaLike>(\n prepared: PreparedGraphDocuments<Schema>,\n write: GraphWriteResult,\n revision: string | undefined,\n vectorStatus: GraphIngestionReceipt[\"vectorWrite\"][\"status\"],\n): GraphIngestionReceipt {\n return {\n documentIds: prepared.documents.map((document) => document.id),\n ...(revision === undefined ? {} : { revision }),\n entityKeys: prepared.entities.map((entity) => entity.id),\n relationshipKeys: prepared.relationships.map((relationship) => relationship.key),\n vectorDocumentIds: prepared.vectorDocuments.map((document) => document.id),\n graphWrite: { status: \"completed\", result: write },\n vectorWrite: { status: vectorStatus },\n warnings: prepared.warnings,\n };\n}\n\nfunction validatePortableMetadata(documents: readonly TextDocument<TextDocumentMetadata>[]): void {\n for (const document of documents) {\n if (document.metadata === undefined) {\n continue;\n }\n const metadata = parseGraphProperties(\n document.metadata,\n `Text document ${document.id} metadata`,\n );\n for (const [key, value] of Object.entries(metadata)) {\n if (Array.isArray(value)) {\n throw new TypeError(\n `Text document ${document.id} metadata.${key} must be a portable primitive value`,\n );\n }\n }\n }\n}\n\nfunction groupVectorDocuments(\n documents: readonly TextDocument<TextDocumentMetadata>[],\n chunks: readonly EmbeddedDocument<GraphChunk<TextDocumentMetadata>, TextDocumentMetadata>[],\n): readonly EmbeddedDocument<TextDocument<TextDocumentMetadata>, TextDocumentMetadata>[] {\n const chunksByDocument = new Map<\n string,\n EmbeddedDocument<GraphChunk<TextDocumentMetadata>, TextDocumentMetadata>[]\n >();\n for (const chunk of chunks) {\n const documentChunks = chunksByDocument.get(chunk.document.documentId);\n if (documentChunks === undefined) {\n chunksByDocument.set(chunk.document.documentId, [chunk]);\n } else {\n documentChunks.push(chunk);\n }\n }\n return documents.map((document) => {\n const documentChunks = chunksByDocument.get(document.id);\n if (documentChunks === undefined) {\n throw new TypeError(`Text document ${document.id} has no embedded graph chunks`);\n }\n const embeddedDocument: EmbeddedDocument<\n TextDocument<TextDocumentMetadata>,\n TextDocumentMetadata\n > = {\n id: document.id,\n document,\n embeddings: documentChunks.flatMap((chunk) => chunk.embeddings),\n };\n if (document.metadata !== undefined) {\n embeddedDocument.metadata = document.metadata;\n }\n return embeddedDocument;\n });\n}\n\nfunction graphDocument(document: TextDocument<TextDocumentMetadata>): GraphDocument {\n if (document.metadata === undefined) {\n return { id: document.id };\n }\n return { id: document.id, properties: document.metadata };\n}\n\nfunction graphChunk(\n chunk: TextDocumentChunk<TextDocumentMetadata>,\n): GraphChunk<TextDocumentMetadata> {\n if (chunk.metadata === undefined) {\n return {\n id: chunk.id,\n documentId: chunk.documentId,\n index: chunk.index,\n text: chunk.text,\n };\n }\n return {\n id: chunk.id,\n documentId: chunk.documentId,\n index: chunk.index,\n text: chunk.text,\n metadata: chunk.metadata,\n };\n}\n\nfunction defaultGraphEntityText(entity: GraphEntity<GraphSchemaLike>): string {\n const properties = Object.entries(entity.properties)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, value]) => `${key}: ${formatGraphProperty(value)}`)\n .join(\"\\n\");\n return properties.length === 0 ? entity.type : `${entity.type}\\n${properties}`;\n}\n\nfunction formatGraphProperty(value: GraphProperties[string]): string {\n if (Array.isArray(value)) {\n return value.join(\", \");\n }\n return String(value);\n}\n","import { createTool } from \"@anvia/core/tool\";\nimport { z } from \"zod\";\nimport type {\n CreateGraphSearchToolOptions,\n GraphContextRetriever,\n GraphSchemaLike,\n GraphSearchTool,\n} from \"./types.js\";\n\nconst primitive = z.union([z.string(), z.number().finite(), z.boolean()]);\nconst propertyValue = z.union([\n primitive,\n z.array(z.string()),\n z.array(z.number().finite()),\n z.array(z.boolean()),\n]);\nconst properties = z.record(z.string(), propertyValue);\nconst contextSchema = z.object({\n seeds: z.array(\n z.object({\n key: z.string(),\n type: z.string(),\n score: z.number().finite(),\n properties,\n sourceChunkIds: z.array(z.string()),\n }),\n ),\n nodes: z.array(\n z.object({\n key: z.string(),\n type: z.string(),\n identity: z.record(z.string(), primitive),\n properties,\n sourceChunkIds: z.array(z.string()),\n }),\n ),\n relationships: z.array(\n z.object({\n key: z.string(),\n type: z.string(),\n from: z.string(),\n to: z.string(),\n properties,\n sourceChunkIds: z.array(z.string()),\n }),\n ),\n evidence: z.array(\n z.object({\n chunkId: z.string(),\n documentId: z.string(),\n index: z.number().int(),\n text: z.string(),\n metadata: properties,\n }),\n ),\n});\n\nexport function createGraphSearchTool<\n Schema extends GraphSchemaLike,\n Retriever extends GraphContextRetriever<Schema>,\n>(options: CreateGraphSearchToolOptions<Schema, Retriever>): GraphSearchTool {\n return createTool({\n name: options.name,\n description: options.description,\n inputSchema: z.object({\n query: z.string().min(1).describe(\"The question or concept to search for in the graph.\"),\n }),\n outputSchema: contextSchema,\n execute: async ({ query }, context) =>\n (await options.graph.retrieve({\n model: options.model,\n query,\n search: options.search,\n traversal: options.traversal,\n evidence: options.evidence,\n retries: options.retries,\n abortSignal: context.abortSignal,\n })) as unknown as z.input<typeof contextSchema>,\n }) as unknown as GraphSearchTool;\n}\n"],"mappings":";;;;;AAAA,SAAS,aAAa;A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AC;AAAA,IACpC,CAAC;AAAA,EACH;AAAA,EACA,eAAeA,GAAE;AAAA,IACfA,GAAE,OAAO;AAAA,MACP,KAAKA,GAAE,OAAO;AAAA,MACd,MAAMA,GAAE,OAAO;AAAA,MACf,MAAMA,GAAE,OAAO;AAAA,MACf,IAAIA,GAAE,OAAO;AAAA,MACb;AAAA,MACA,gBAAgBA,GAAE,MAAMA,GAAE,OAAO,CAAC;AAAA,IACpC,CAAC;AAAA,EACH;AAAA,EACA,UAAUA,GAAE;AAAA,IACVA,GAAE,OAAO;AAAA,MACP,SAASA,GAAE,OAAO;AAAA,MAClB,YAAYA,GAAE,OAAO;AAAA,MACrB,OAAOA,GAAE,OAAO,EAAE,IAAI;AAAA,MACtB,MAAMA,GAAE,OAAO;AAAA,MACf,UAAU;AAAA,IACZ,CAAC;AAAA,EACH;AACF,CAAC;AAEM,SAAS,sBAGd,SAA2E;AAC3E,SAAO,WAAW;AAAA,IAChB,MAAM,QAAQ;AAAA,IACd,aAAa,QAAQ;AAAA,IACrB,aAAaA,GAAE,OAAO;AAAA,MACpB,OAAOA,GAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,qDAAqD;AAAA,IACzF,CAAC;AAAA,IACD,cAAc;AAAA,IACd,SAAS,OAAO,EAAE,MAAM,GAAG,YACxB,MAAM,QAAQ,MAAM,SAAS;AAAA,MAC5B,OAAO,QAAQ;AAAA,MACf;AAAA,MACA,QAAQ,QAAQ;AAAA,MAChB,WAAW,QAAQ;AAAA,MACnB,UAAU,QAAQ;AAAA,MAClB,SAAS,QAAQ;AAAA,MACjB,aAAa,QAAQ;AAAA,IACvB,CAAC;AAAA,EACL,CAAC;AACH;","names":["z","z","properties","properties","z"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anvia/graph",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.10",
|
|
4
4
|
"description": "Provider-neutral knowledge graph primitives for Anvia.",
|
|
5
5
|
"author": "anvia",
|
|
6
6
|
"maintainer": "Indra Zulfi",
|
|
@@ -37,10 +37,10 @@
|
|
|
37
37
|
"tsup": "^8.5.0",
|
|
38
38
|
"typescript": "^5.9.3",
|
|
39
39
|
"vitest": "^4.0.8",
|
|
40
|
-
"@anvia/core": "1.0.
|
|
40
|
+
"@anvia/core": "1.0.8"
|
|
41
41
|
},
|
|
42
42
|
"peerDependencies": {
|
|
43
|
-
"@anvia/core": "1.0.
|
|
43
|
+
"@anvia/core": "1.0.8"
|
|
44
44
|
},
|
|
45
45
|
"scripts": {
|
|
46
46
|
"build": "tsup src/index.ts src/explore.ts --format esm --dts --sourcemap --clean",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/explore.ts"],"sourcesContent":["import type { GraphExploreDirection, GraphExploreOptions, GraphSchemaLike } from \"./types.js\";\n\nconst defaultMaxNodes = 100;\nconst maximumNodes = 500;\nconst defaultMaxRelationships = 200;\nconst maximumRelationships = 1_000;\nconst defaultMaxDepth = 1;\nconst maximumDepth = 4;\nconst maximumRoots = 20;\n\ntype ResolvedGraphExploreBase = Readonly<{\n nodeTypes: readonly string[];\n relationships: readonly string[];\n maxNodes: number;\n maxRelationships: number;\n abortSignal?: AbortSignal | undefined;\n}>;\n\nexport type ResolvedGraphExploreOverviewOptions = ResolvedGraphExploreBase &\n Readonly<{ mode: \"overview\" }>;\n\nexport type ResolvedGraphExploreExpandOptions = ResolvedGraphExploreBase &\n Readonly<{\n mode: \"expand\";\n nodeIds: readonly string[];\n direction: GraphExploreDirection;\n maxDepth: number;\n }>;\n\nexport type ResolvedGraphExploreOptions =\n | ResolvedGraphExploreOverviewOptions\n | ResolvedGraphExploreExpandOptions;\n\nexport function resolveGraphExploreOptions<Schema extends GraphSchemaLike>(\n schema: Schema,\n options: GraphExploreOptions<Schema>,\n): ResolvedGraphExploreOptions {\n const nodeTypes = resolveNames(options.nodeTypes, Object.keys(schema.nodes), \"node type\");\n const relationships = resolveNames(\n options.relationships,\n Object.keys(schema.relationships),\n \"relationship type\",\n true,\n );\n const base: {\n nodeTypes: string[];\n relationships: string[];\n maxNodes: number;\n maxRelationships: number;\n abortSignal?: AbortSignal | undefined;\n } = {\n nodeTypes,\n relationships,\n maxNodes: boundedInteger(options.maxNodes, defaultMaxNodes, maximumNodes, \"maxNodes\"),\n maxRelationships: boundedInteger(\n options.maxRelationships,\n defaultMaxRelationships,\n maximumRelationships,\n \"maxRelationships\",\n ),\n };\n if (options.abortSignal !== undefined) base.abortSignal = options.abortSignal;\n if (options.mode === \"overview\") {\n return { ...base, mode: \"overview\" };\n }\n const nodeIds = uniqueNonEmptyStrings(options.nodeIds, \"node id\");\n if (nodeIds.length === 0) {\n throw new TypeError(\"Graph expansion requires at least one node id.\");\n }\n if (nodeIds.length > maximumRoots) {\n throw new RangeError(`Graph expansion accepts at most ${maximumRoots} root nodes.`);\n }\n const direction = options.direction ?? \"both\";\n if (direction !== \"outgoing\" && direction !== \"incoming\" && direction !== \"both\") {\n throw new TypeError(\"Graph expansion direction must be outgoing, incoming, or both.\");\n }\n return {\n ...base,\n mode: \"expand\",\n nodeIds,\n direction,\n maxDepth: boundedInteger(options.maxDepth, defaultMaxDepth, maximumDepth, \"maxDepth\"),\n };\n}\n\nfunction resolveNames(\n selected: readonly string[] | undefined,\n available: readonly string[],\n label: string,\n allowEmpty = false,\n): string[] {\n const values = selected === undefined ? [...available] : uniqueNonEmptyStrings(selected, label);\n if (!allowEmpty && values.length === 0) {\n throw new TypeError(`Graph exploration requires at least one ${label}.`);\n }\n const known = new Set(available);\n for (const value of values) {\n if (!known.has(value))\n throw new TypeError(`Graph exploration references unknown ${label} ${value}.`);\n }\n return values;\n}\n\nfunction uniqueNonEmptyStrings(values: readonly string[], label: string): string[] {\n const unique = new Set<string>();\n for (const value of values) {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`Graph ${label} must be a non-empty string.`);\n }\n if (unique.has(value)) throw new TypeError(`Duplicate graph ${label}: ${value}.`);\n unique.add(value);\n }\n return [...unique];\n}\n\nfunction boundedInteger(\n value: number | undefined,\n fallback: number,\n maximum: number,\n label: string,\n): number {\n const resolved = value ?? fallback;\n if (!Number.isSafeInteger(resolved) || resolved < 1 || resolved > maximum) {\n throw new RangeError(`Graph exploration ${label} must be between 1 and ${maximum}.`);\n }\n return resolved;\n}\n"],"mappings":";AAEA,IAAM,kBAAkB;AACxB,IAAM,eAAe;AACrB,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAC7B,IAAM,kBAAkB;AACxB,IAAM,eAAe;AACrB,IAAM,eAAe;AAyBd,SAAS,2BACd,QACA,SAC6B;AAC7B,QAAM,YAAY,aAAa,QAAQ,WAAW,OAAO,KAAK,OAAO,KAAK,GAAG,WAAW;AACxF,QAAM,gBAAgB;AAAA,IACpB,QAAQ;AAAA,IACR,OAAO,KAAK,OAAO,aAAa;AAAA,IAChC;AAAA,IACA;AAAA,EACF;AACA,QAAM,OAMF;AAAA,IACF;AAAA,IACA;AAAA,IACA,UAAU,eAAe,QAAQ,UAAU,iBAAiB,cAAc,UAAU;AAAA,IACpF,kBAAkB;AAAA,MAChB,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,gBAAgB,OAAW,MAAK,cAAc,QAAQ;AAClE,MAAI,QAAQ,SAAS,YAAY;AAC/B,WAAO,EAAE,GAAG,MAAM,MAAM,WAAW;AAAA,EACrC;AACA,QAAM,UAAU,sBAAsB,QAAQ,SAAS,SAAS;AAChE,MAAI,QAAQ,WAAW,GAAG;AACxB,UAAM,IAAI,UAAU,gDAAgD;AAAA,EACtE;AACA,MAAI,QAAQ,SAAS,cAAc;AACjC,UAAM,IAAI,WAAW,mCAAmC,YAAY,cAAc;AAAA,EACpF;AACA,QAAM,YAAY,QAAQ,aAAa;AACvC,MAAI,cAAc,cAAc,cAAc,cAAc,cAAc,QAAQ;AAChF,UAAM,IAAI,UAA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