@anvia/graph 1.0.3 → 1.0.4
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 +43 -0
- package/dist/{explore-B2BuWiSK.d.ts → explore-9jm2c1mG.d.ts} +18 -2
- package/dist/explore.d.ts +1 -1
- package/dist/index.d.ts +45 -4
- package/dist/index.js +165 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -23,6 +23,49 @@ const facts = await extractGraphFacts({ model, schema, chunks });
|
|
|
23
23
|
Database provisioning, persistence, and query execution belong to graph adapter packages such as
|
|
24
24
|
`@anvia/neo4j` and `@anvia/memgraph`.
|
|
25
25
|
|
|
26
|
+
## Ingestion
|
|
27
|
+
|
|
28
|
+
Managed graphs accept the same raw text document shape as vector ingestion:
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { ingestGraphText } from "@anvia/graph";
|
|
32
|
+
|
|
33
|
+
const ingestion = await ingestGraphText({
|
|
34
|
+
graph,
|
|
35
|
+
document: {
|
|
36
|
+
id: "incident-42",
|
|
37
|
+
text,
|
|
38
|
+
metadata: { tenant: "acme" },
|
|
39
|
+
},
|
|
40
|
+
extractionModel,
|
|
41
|
+
embeddingModel,
|
|
42
|
+
chunking: {
|
|
43
|
+
strategy: "recursive",
|
|
44
|
+
maxSize: 1_000,
|
|
45
|
+
overlap: 100,
|
|
46
|
+
separators: ["\n\n", "\n", " "],
|
|
47
|
+
},
|
|
48
|
+
conflict: "error",
|
|
49
|
+
orphanEntities: "delete",
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Use `ingestGraphDocuments()` for a batch. Both functions extract facts, embed chunks and entities,
|
|
54
|
+
and atomically replace each source document in the managed graph. Existing graph registrations are
|
|
55
|
+
read-only and are rejected as ingestion targets by TypeScript.
|
|
56
|
+
|
|
57
|
+
The result also exposes `vectorDocuments`, grouped by source document ID, so a vector store can
|
|
58
|
+
reuse the chunk embeddings without another model call:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
await vectorStore.upsert({ documents: ingestion.vectorDocuments });
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The graph and vector writes are separate transactions. Applications that require cross-store
|
|
65
|
+
reconciliation should persist their own ingestion status and retry the incomplete write. Advanced
|
|
66
|
+
callers can use `prepareGraphDocuments()` to run chunking, extraction, and embedding without writing,
|
|
67
|
+
then pass its graph fields to `graph.replaceDocuments()` and its `vectorDocuments` to a vector store.
|
|
68
|
+
|
|
26
69
|
## Search tool
|
|
27
70
|
|
|
28
71
|
Create the same Agent tool for any graph adapter implementing `GraphContextRetriever`:
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { RetrySetting, CompletionModel, Usage } from '@anvia/core';
|
|
2
|
-
import { EmbeddingModel } from '@anvia/core/embeddings';
|
|
2
|
+
import { EmbeddingModel, EmbeddedDocument } from '@anvia/core/embeddings';
|
|
3
3
|
import { Tool } from '@anvia/core/tool';
|
|
4
4
|
import { z } from 'zod';
|
|
5
5
|
|
|
@@ -238,6 +238,22 @@ type GraphWriteResult = Readonly<{
|
|
|
238
238
|
relationships: GraphChangeCounts;
|
|
239
239
|
mentions: GraphChangeCounts;
|
|
240
240
|
}>;
|
|
241
|
+
type GraphWriteConflict = "error" | "overwrite" | "keep-existing";
|
|
242
|
+
type GraphOrphanEntityPolicy = "delete" | "keep";
|
|
243
|
+
type ReplaceGraphDocumentsOptions<Schema extends GraphSchemaLike> = Readonly<{
|
|
244
|
+
documents: readonly GraphDocument[];
|
|
245
|
+
chunks: readonly EmbeddedDocument<GraphChunk>[];
|
|
246
|
+
entities: readonly EmbeddedDocument<GraphEntity<Schema>>[];
|
|
247
|
+
relationships: readonly GraphRelationship<Schema>[];
|
|
248
|
+
mentions: readonly GraphMention[];
|
|
249
|
+
conflict: GraphWriteConflict;
|
|
250
|
+
orphanEntities: GraphOrphanEntityPolicy;
|
|
251
|
+
abortSignal?: AbortSignal | undefined;
|
|
252
|
+
}>;
|
|
253
|
+
interface GraphDocumentWriter<Schema extends GraphSchemaLike = GraphSchemaLike> {
|
|
254
|
+
readonly schema: Schema;
|
|
255
|
+
replaceDocuments(options: ReplaceGraphDocumentsOptions<Schema>): Promise<GraphWriteResult>;
|
|
256
|
+
}
|
|
241
257
|
|
|
242
258
|
type ResolvedGraphExploreBase = Readonly<{
|
|
243
259
|
nodeTypes: readonly string[];
|
|
@@ -258,4 +274,4 @@ type ResolvedGraphExploreExpandOptions = ResolvedGraphExploreBase & Readonly<{
|
|
|
258
274
|
type ResolvedGraphExploreOptions = ResolvedGraphExploreOverviewOptions | ResolvedGraphExploreExpandOptions;
|
|
259
275
|
declare function resolveGraphExploreOptions<Schema extends GraphSchemaLike>(schema: Schema, options: GraphExploreOptions<Schema>): ResolvedGraphExploreOptions;
|
|
260
276
|
|
|
261
|
-
export { type
|
|
277
|
+
export { type GraphExploreExpandOptions as A, type GraphExploreNode as B, type CreateGraphSearchToolOptions as C, type GraphExploreOptions as D, type ExtractGraphFactsOptions as E, type GraphExploreOverviewOptions as F, type GraphSchemaLike as G, type GraphExploreRelationship as H, type GraphExploreResult as I, type GraphExplorer as J, type GraphFacts as K, type GraphHybridSearchOptions as L, type GraphNodeDefinition as M, type GraphNodeIdentity as N, type GraphPropertyPrimitive as O, type GraphRelationshipDefinition as P, type GraphRetrieveOptions as Q, type GraphSearchOptions as R, type GraphTraversalOptions as S, type GraphVectorSearchOptions as T, type ReplaceGraphDocumentsOptions as U, type ResolvedGraphExploreExpandOptions as V, type ResolvedGraphExploreOptions as W, type ResolvedGraphExploreOverviewOptions as X, resolveGraphExploreOptions as Y, type ExtractGraphFactsResult as a, type GraphEntity as b, type GraphDocumentWriter as c, type GraphWriteConflict as d, type GraphOrphanEntityPolicy as e, type GraphDocument as f, type GraphChunk as g, type GraphRelationship as h, type GraphMention as i, type GraphWriteResult as j, type GraphSchemaOptions as k, type GraphSchema as l, type GraphProperties as m, type GraphPropertyValue as n, type GraphContextRetriever as o, type GraphSearchTool as p, type GraphChangeCounts as q, type GraphContext as r, type GraphContextNode as s, type GraphContextRelationship as t, type GraphContextSeed as u, type GraphEvidence as v, type GraphEvidenceCapability as w, type GraphEvidenceFor as x, type GraphEvidenceOptions as y, type GraphExploreDirection as z };
|
package/dist/explore.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { V as ResolvedGraphExploreExpandOptions, W as ResolvedGraphExploreOptions, X as ResolvedGraphExploreOverviewOptions, Y as resolveGraphExploreOptions } from './explore-9jm2c1mG.js';
|
|
2
2
|
import '@anvia/core';
|
|
3
3
|
import '@anvia/core/embeddings';
|
|
4
4
|
import '@anvia/core/tool';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import * as _anvia_core from '@anvia/core';
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import { CompletionModel, RetrySetting, Usage } from '@anvia/core';
|
|
3
|
+
import { G as GraphSchemaLike, E as ExtractGraphFactsOptions, a as ExtractGraphFactsResult, b as GraphEntity, c as GraphDocumentWriter, d as GraphWriteConflict, e as GraphOrphanEntityPolicy, f as GraphDocument, g as GraphChunk, h as GraphRelationship, i as GraphMention, j as GraphWriteResult, k as GraphSchemaOptions, l as GraphSchema, m as GraphProperties, n as GraphPropertyValue, o as GraphContextRetriever, C as CreateGraphSearchToolOptions, p as GraphSearchTool } from './explore-9jm2c1mG.js';
|
|
4
|
+
export { q as GraphChangeCounts, r as GraphContext, s as GraphContextNode, t as GraphContextRelationship, u as GraphContextSeed, v as GraphEvidence, w as GraphEvidenceCapability, x as GraphEvidenceFor, y as GraphEvidenceOptions, z as GraphExploreDirection, A as GraphExploreExpandOptions, B as GraphExploreNode, D as GraphExploreOptions, F as GraphExploreOverviewOptions, H as GraphExploreRelationship, I as GraphExploreResult, J as GraphExplorer, K as GraphFacts, L as GraphHybridSearchOptions, M as GraphNodeDefinition, N as GraphNodeIdentity, O as GraphPropertyPrimitive, P as GraphRelationshipDefinition, Q as GraphRetrieveOptions, R as GraphSearchOptions, S as GraphTraversalOptions, T as GraphVectorSearchOptions, U as ReplaceGraphDocumentsOptions, V as ResolvedGraphExploreExpandOptions, W as ResolvedGraphExploreOptions, X as ResolvedGraphExploreOverviewOptions, Y as resolveGraphExploreOptions } from './explore-9jm2c1mG.js';
|
|
5
|
+
import { TextDocument, TextDocumentMetadata, TextDocumentChunkingOptions } from '@anvia/core/documents';
|
|
6
|
+
import { EmbeddingModel, EmbeddedDocument } from '@anvia/core/embeddings';
|
|
5
7
|
import '@anvia/core/tool';
|
|
6
8
|
import 'zod';
|
|
7
9
|
|
|
@@ -12,6 +14,45 @@ declare class GraphFactConflictError extends Error {
|
|
|
12
14
|
constructor(factKey: string, sourceChunkIds: readonly string[]);
|
|
13
15
|
}
|
|
14
16
|
|
|
17
|
+
type GraphPreparationOptions<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel> = Readonly<{
|
|
18
|
+
graph: Readonly<{
|
|
19
|
+
schema: Schema;
|
|
20
|
+
}>;
|
|
21
|
+
documents: readonly TextDocument<TextDocumentMetadata>[];
|
|
22
|
+
extractionModel: ExtractionModel;
|
|
23
|
+
embeddingModel: EmbeddingModel;
|
|
24
|
+
chunking?: TextDocumentChunkingOptions | undefined;
|
|
25
|
+
entityText?: ((entity: GraphEntity<Schema>) => string) | undefined;
|
|
26
|
+
instructions?: string | undefined;
|
|
27
|
+
retries?: RetrySetting | undefined;
|
|
28
|
+
concurrency?: number | undefined;
|
|
29
|
+
abortSignal?: AbortSignal | undefined;
|
|
30
|
+
}>;
|
|
31
|
+
type PrepareGraphDocumentsOptions<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel = CompletionModel> = GraphPreparationOptions<Schema, ExtractionModel>;
|
|
32
|
+
type IngestGraphDocumentsOptions<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel = CompletionModel> = Omit<GraphPreparationOptions<Schema, ExtractionModel>, "graph"> & Readonly<{
|
|
33
|
+
graph: GraphDocumentWriter<Schema>;
|
|
34
|
+
conflict: GraphWriteConflict;
|
|
35
|
+
orphanEntities: GraphOrphanEntityPolicy;
|
|
36
|
+
}>;
|
|
37
|
+
type IngestGraphTextOptions<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel = CompletionModel> = Omit<IngestGraphDocumentsOptions<Schema, ExtractionModel>, "documents"> & Readonly<{
|
|
38
|
+
document: TextDocument<TextDocumentMetadata>;
|
|
39
|
+
}>;
|
|
40
|
+
type PreparedGraphDocuments<Schema extends GraphSchemaLike> = Readonly<{
|
|
41
|
+
documents: readonly GraphDocument[];
|
|
42
|
+
chunks: readonly EmbeddedDocument<GraphChunk<TextDocumentMetadata>, TextDocumentMetadata>[];
|
|
43
|
+
vectorDocuments: readonly EmbeddedDocument<TextDocument<TextDocumentMetadata>, TextDocumentMetadata>[];
|
|
44
|
+
entities: readonly EmbeddedDocument<GraphEntity<Schema>>[];
|
|
45
|
+
relationships: readonly GraphRelationship<Schema>[];
|
|
46
|
+
mentions: readonly GraphMention[];
|
|
47
|
+
usage: Usage;
|
|
48
|
+
}>;
|
|
49
|
+
type IngestGraphDocumentsResult<Schema extends GraphSchemaLike> = PreparedGraphDocuments<Schema> & Readonly<{
|
|
50
|
+
write: GraphWriteResult;
|
|
51
|
+
}>;
|
|
52
|
+
declare function ingestGraphText<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel>(options: IngestGraphTextOptions<Schema, ExtractionModel>): Promise<IngestGraphDocumentsResult<Schema>>;
|
|
53
|
+
declare function ingestGraphDocuments<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel>(options: IngestGraphDocumentsOptions<Schema, ExtractionModel>): Promise<IngestGraphDocumentsResult<Schema>>;
|
|
54
|
+
declare function prepareGraphDocuments<Schema extends GraphSchemaLike, ExtractionModel extends CompletionModel>(options: PrepareGraphDocumentsOptions<Schema, ExtractionModel>): Promise<PreparedGraphDocuments<Schema>>;
|
|
55
|
+
|
|
15
56
|
declare const graphReservedPropertyPrefix = "__anvia_";
|
|
16
57
|
declare function defineGraphSchema<const Options extends GraphSchemaOptions>(options: Options): GraphSchema<Options>;
|
|
17
58
|
declare function validateGraphSchemaOptions(options: GraphSchemaOptions): void;
|
|
@@ -25,4 +66,4 @@ declare function assertGraphPropertyName(value: string): void;
|
|
|
25
66
|
|
|
26
67
|
declare function createGraphSearchTool<Schema extends GraphSchemaLike, Retriever extends GraphContextRetriever<Schema>>(options: CreateGraphSearchToolOptions<Schema, Retriever>): GraphSearchTool;
|
|
27
68
|
|
|
28
|
-
export { CreateGraphSearchToolOptions, ExtractGraphFactsOptions, ExtractGraphFactsResult, GraphContextRetriever, GraphFactConflictError, GraphProperties, GraphPropertyValue, GraphSchema, GraphSchemaLike, GraphSchemaOptions, GraphSearchTool, assertGraphName, assertGraphPropertyName, createGraphSearchTool, defineGraphSchema, extractGraphFacts, freezeGraphSchema, graphReservedPropertyPrefix, parseGraphProperties, parseGraphPropertyValue, validateGraphSchemaOptions };
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -421,6 +421,168 @@ async function mapConcurrent(values, concurrency, run) {
|
|
|
421
421
|
return output;
|
|
422
422
|
}
|
|
423
423
|
|
|
424
|
+
// src/ingest.ts
|
|
425
|
+
import {
|
|
426
|
+
chunkTextDocuments
|
|
427
|
+
} from "@anvia/core/documents";
|
|
428
|
+
import { embedDocuments } from "@anvia/core/embeddings";
|
|
429
|
+
async function ingestGraphText(options) {
|
|
430
|
+
return ingestGraphDocuments({
|
|
431
|
+
graph: options.graph,
|
|
432
|
+
documents: [options.document],
|
|
433
|
+
extractionModel: options.extractionModel,
|
|
434
|
+
embeddingModel: options.embeddingModel,
|
|
435
|
+
chunking: options.chunking,
|
|
436
|
+
entityText: options.entityText,
|
|
437
|
+
instructions: options.instructions,
|
|
438
|
+
retries: options.retries,
|
|
439
|
+
concurrency: options.concurrency,
|
|
440
|
+
abortSignal: options.abortSignal,
|
|
441
|
+
conflict: options.conflict,
|
|
442
|
+
orphanEntities: options.orphanEntities
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
async function ingestGraphDocuments(options) {
|
|
446
|
+
const prepared = await prepareGraphDocuments(options);
|
|
447
|
+
const write = await options.graph.replaceDocuments({
|
|
448
|
+
documents: prepared.documents,
|
|
449
|
+
chunks: prepared.chunks,
|
|
450
|
+
entities: prepared.entities,
|
|
451
|
+
relationships: prepared.relationships,
|
|
452
|
+
mentions: prepared.mentions,
|
|
453
|
+
conflict: options.conflict,
|
|
454
|
+
orphanEntities: options.orphanEntities,
|
|
455
|
+
abortSignal: options.abortSignal
|
|
456
|
+
});
|
|
457
|
+
return { ...prepared, write };
|
|
458
|
+
}
|
|
459
|
+
async function prepareGraphDocuments(options) {
|
|
460
|
+
validatePortableMetadata(options.documents);
|
|
461
|
+
const chunks = chunkTextDocuments({
|
|
462
|
+
documents: options.documents,
|
|
463
|
+
chunking: options.chunking
|
|
464
|
+
});
|
|
465
|
+
const graphChunks = chunks.map((chunk) => graphChunk(chunk));
|
|
466
|
+
const [facts, embeddedChunks] = await Promise.all([
|
|
467
|
+
extractGraphFacts({
|
|
468
|
+
model: options.extractionModel,
|
|
469
|
+
schema: options.graph.schema,
|
|
470
|
+
chunks: graphChunks,
|
|
471
|
+
instructions: options.instructions,
|
|
472
|
+
retries: options.retries,
|
|
473
|
+
concurrency: options.concurrency,
|
|
474
|
+
abortSignal: options.abortSignal
|
|
475
|
+
}),
|
|
476
|
+
embedDocuments({
|
|
477
|
+
model: options.embeddingModel,
|
|
478
|
+
documents: graphChunks,
|
|
479
|
+
id: (chunk) => chunk.id,
|
|
480
|
+
content: (chunk) => chunk.text,
|
|
481
|
+
metadata: (chunk) => chunk.metadata,
|
|
482
|
+
retries: options.retries,
|
|
483
|
+
concurrency: options.concurrency,
|
|
484
|
+
abortSignal: options.abortSignal
|
|
485
|
+
})
|
|
486
|
+
]);
|
|
487
|
+
const embeddedEntities = await embedDocuments({
|
|
488
|
+
model: options.embeddingModel,
|
|
489
|
+
documents: [...facts.output.entities],
|
|
490
|
+
id: (entity) => entity.key,
|
|
491
|
+
content: options.entityText ?? defaultGraphEntityText,
|
|
492
|
+
retries: options.retries,
|
|
493
|
+
concurrency: options.concurrency,
|
|
494
|
+
abortSignal: options.abortSignal
|
|
495
|
+
});
|
|
496
|
+
const vectorDocuments = groupVectorDocuments(options.documents, embeddedChunks.documents);
|
|
497
|
+
return {
|
|
498
|
+
documents: options.documents.map((document) => graphDocument(document)),
|
|
499
|
+
chunks: embeddedChunks.documents,
|
|
500
|
+
vectorDocuments,
|
|
501
|
+
entities: embeddedEntities.documents,
|
|
502
|
+
relationships: facts.output.relationships,
|
|
503
|
+
mentions: facts.output.mentions,
|
|
504
|
+
usage: facts.usage
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
function validatePortableMetadata(documents) {
|
|
508
|
+
for (const document of documents) {
|
|
509
|
+
if (document.metadata === void 0) {
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
const metadata = parseGraphProperties(
|
|
513
|
+
document.metadata,
|
|
514
|
+
`Text document ${document.id} metadata`
|
|
515
|
+
);
|
|
516
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
517
|
+
if (Array.isArray(value)) {
|
|
518
|
+
throw new TypeError(
|
|
519
|
+
`Text document ${document.id} metadata.${key} must be a portable primitive value`
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
function groupVectorDocuments(documents, chunks) {
|
|
526
|
+
const chunksByDocument = /* @__PURE__ */ new Map();
|
|
527
|
+
for (const chunk of chunks) {
|
|
528
|
+
const documentChunks = chunksByDocument.get(chunk.document.documentId);
|
|
529
|
+
if (documentChunks === void 0) {
|
|
530
|
+
chunksByDocument.set(chunk.document.documentId, [chunk]);
|
|
531
|
+
} else {
|
|
532
|
+
documentChunks.push(chunk);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return documents.map((document) => {
|
|
536
|
+
const documentChunks = chunksByDocument.get(document.id);
|
|
537
|
+
if (documentChunks === void 0) {
|
|
538
|
+
throw new TypeError(`Text document ${document.id} has no embedded graph chunks`);
|
|
539
|
+
}
|
|
540
|
+
const embeddedDocument = {
|
|
541
|
+
id: document.id,
|
|
542
|
+
document,
|
|
543
|
+
embeddings: documentChunks.flatMap((chunk) => chunk.embeddings)
|
|
544
|
+
};
|
|
545
|
+
if (document.metadata !== void 0) {
|
|
546
|
+
embeddedDocument.metadata = document.metadata;
|
|
547
|
+
}
|
|
548
|
+
return embeddedDocument;
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
function graphDocument(document) {
|
|
552
|
+
if (document.metadata === void 0) {
|
|
553
|
+
return { id: document.id };
|
|
554
|
+
}
|
|
555
|
+
return { id: document.id, properties: document.metadata };
|
|
556
|
+
}
|
|
557
|
+
function graphChunk(chunk) {
|
|
558
|
+
if (chunk.metadata === void 0) {
|
|
559
|
+
return {
|
|
560
|
+
id: chunk.id,
|
|
561
|
+
documentId: chunk.documentId,
|
|
562
|
+
index: chunk.index,
|
|
563
|
+
text: chunk.text
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
return {
|
|
567
|
+
id: chunk.id,
|
|
568
|
+
documentId: chunk.documentId,
|
|
569
|
+
index: chunk.index,
|
|
570
|
+
text: chunk.text,
|
|
571
|
+
metadata: chunk.metadata
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
function defaultGraphEntityText(entity) {
|
|
575
|
+
const properties2 = Object.entries(entity.properties).sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}: ${formatGraphProperty(value)}`).join("\n");
|
|
576
|
+
return properties2.length === 0 ? entity.type : `${entity.type}
|
|
577
|
+
${properties2}`;
|
|
578
|
+
}
|
|
579
|
+
function formatGraphProperty(value) {
|
|
580
|
+
if (Array.isArray(value)) {
|
|
581
|
+
return value.join(", ");
|
|
582
|
+
}
|
|
583
|
+
return String(value);
|
|
584
|
+
}
|
|
585
|
+
|
|
424
586
|
// src/tool.ts
|
|
425
587
|
import { createTool } from "@anvia/core/tool";
|
|
426
588
|
import { z as z3 } from "zod";
|
|
@@ -499,8 +661,11 @@ export {
|
|
|
499
661
|
extractGraphFacts,
|
|
500
662
|
freezeGraphSchema,
|
|
501
663
|
graphReservedPropertyPrefix,
|
|
664
|
+
ingestGraphDocuments,
|
|
665
|
+
ingestGraphText,
|
|
502
666
|
parseGraphProperties,
|
|
503
667
|
parseGraphPropertyValue,
|
|
668
|
+
prepareGraphDocuments,
|
|
504
669
|
resolveGraphExploreOptions,
|
|
505
670
|
validateGraphSchemaOptions
|
|
506
671
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/extract.ts","../src/schema.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 { 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,QACE,WAAW,SAAS,WAAW,KAC/B,IAAI,IAAI,WAAW,QAAQ,EAAE,SAAS,WAAW,SAAS,QAC1D;AACA,YAAM,IAAI,UAAU,QAAQ,IAAI,2CAA2C;AAAA,IAC7E;AACA,eAAW,YAAY,WAAW,UAAU;AAC1C,8BAAwB,QAAQ;AAChC,UAAI,EAAE,YAAY,WAAW,WAAW,QAAQ;AAC9C,cAAM,IAAI,UAAU,qBAAqB,QAAQ,4BAA4B,IAAI,GAAG;AAAA,MACtF;AAAA,IACF;AACA,eAAW,YAAY,OAAO,KAAK,WAAW,WAAW,KAAK,GAAG;AAC/D,8BAAwB,QAAQ;AAAA,IAClC;AAAA,EACF;AACA,aAAW,CAAC,MAAM,UAAU,KAAK,OAAO,QAAQ,QAAQ,aAAa,GAAG;AACtE,oBAAgB,MAAM,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;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","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 } 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,QACE,WAAW,SAAS,WAAW,KAC/B,IAAI,IAAI,WAAW,QAAQ,EAAE,SAAS,WAAW,SAAS,QAC1D;AACA,YAAM,IAAI,UAAU,QAAQ,IAAI,2CAA2C;AAAA,IAC7E;AACA,eAAW,YAAY,WAAW,UAAU;AAC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ACfA,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.4",
|
|
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.3"
|
|
41
41
|
},
|
|
42
42
|
"peerDependencies": {
|
|
43
|
-
"@anvia/core": "1.0.
|
|
43
|
+
"@anvia/core": "1.0.3"
|
|
44
44
|
},
|
|
45
45
|
"scripts": {
|
|
46
46
|
"build": "tsup src/index.ts src/explore.ts --format esm --dts --sourcemap --clean",
|