@typegraph-ai/adapter-redis 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 TypeGraph
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,164 @@
1
+ # @typegraph-ai/adapter-redis
2
+
3
+ Redis-backed cache utilities for self-hosted TypeGraph deployments.
4
+
5
+ This package currently provides an extraction coreference cache. It is not a
6
+ vector store, memory store, graph store, or queue adapter. Its job is narrower:
7
+ it lets TypeGraph remember recently resolved entities during extraction so
8
+ large document, event, and thread ingestion jobs keep entity names consistent
9
+ across chunks and batches.
10
+
11
+ Cloud users do not configure this adapter. TypeGraph Cloud manages extraction
12
+ cache infrastructure for hosted API-key clients.
13
+
14
+ ## What It Does
15
+
16
+ During graph extraction, TypeGraph may see the same real-world entity many times:
17
+
18
+ - `Acme`
19
+ - `Acme Inc.`
20
+ - `ACME Corporation`
21
+ - `the customer`
22
+
23
+ The extractor resolves those mentions into normalized entities. Without a shared
24
+ cache, each chunk or worker may have to rediscover the same mappings. With this
25
+ adapter, TypeGraph stores a compact list of recently extracted entities in Redis
26
+ and passes it back into later extraction calls.
27
+
28
+ That improves:
29
+
30
+ - entity consistency across chunks;
31
+ - event/document/thread extraction continuity;
32
+ - multi-worker self-hosted ingestion behavior;
33
+ - retry behavior after transient extraction failures.
34
+
35
+ It does not grant access, route graph writes, or change search results by itself.
36
+ Access and graph boundaries still come from TypeGraph tenant, graph, bucket, and
37
+ context configuration.
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ pnpm add @typegraph-ai/adapter-redis
43
+ ```
44
+
45
+ You also need a Redis client. This package intentionally does not depend on a
46
+ specific Redis library. It accepts any client with compatible `get` and `set`
47
+ methods.
48
+
49
+ ```ts
50
+ interface RedisCoreferenceClient {
51
+ get<T = unknown>(key: string): Promise<T | null>
52
+ set(key: string, value: unknown, options?: { ex?: number }): Promise<unknown>
53
+ }
54
+ ```
55
+
56
+ For Upstash, use `@typegraph-ai/adapter-redis-upstash`.
57
+
58
+ ## Usage
59
+
60
+ ```ts
61
+ import { typegraphInit } from '@typegraph-ai/sdk'
62
+ import { createRedisCoreferenceCache } from '@typegraph-ai/adapter-redis'
63
+
64
+ const extractionCoreferenceCache = createRedisCoreferenceCache({
65
+ redis,
66
+ namespace: 'tenant_public',
67
+ ttlSeconds: 4 * 60 * 60,
68
+ })
69
+
70
+ const typegraph = await typegraphInit({
71
+ vectorStore,
72
+ embedding,
73
+ searchEmbedding,
74
+ llm,
75
+ extractionCoreferenceCache,
76
+ })
77
+ ```
78
+
79
+ `tenantId` defaults to `public` when omitted. For multi-tenant self-hosted apps,
80
+ use a namespace that includes your tenant or deployment boundary:
81
+
82
+ ```ts
83
+ const extractionCoreferenceCache = createRedisCoreferenceCache({
84
+ redis,
85
+ namespace: `schema_${schemaName}:tenant_${tenantId}`,
86
+ })
87
+ ```
88
+
89
+ ## Options
90
+
91
+ ```ts
92
+ type RedisCoreferenceCacheOptions = {
93
+ redis: RedisCoreferenceClient
94
+ namespace?: string
95
+ ttlSeconds?: number
96
+ maxEntities?: number
97
+ maxAliases?: number
98
+ maxTypeCandidates?: number
99
+ onError?: (error: unknown) => void
100
+ }
101
+ ```
102
+
103
+ ### `redis`
104
+
105
+ Required Redis-compatible client.
106
+
107
+ The adapter stores JSON-compatible arrays of extracted entity records. The Redis
108
+ client may serialize values itself, or it may return strings. The adapter handles
109
+ both parsed arrays and JSON strings on reads.
110
+
111
+ ### `namespace`
112
+
113
+ Optional logical prefix for cache keys. Use this to isolate environments,
114
+ schemas, tenants, or test runs.
115
+
116
+ The final key also includes TypeGraph extraction context such as tenant, bucket,
117
+ group, user, agent, and thread when those fields are available.
118
+
119
+ ### `ttlSeconds`
120
+
121
+ How long cache entries live. Defaults to 4 hours.
122
+
123
+ This cache is intentionally temporary. It should help active ingestion jobs
124
+ maintain continuity, not become a permanent entity store.
125
+
126
+ ### `maxEntities`, `maxAliases`, `maxTypeCandidates`
127
+
128
+ Compaction limits applied before saving. Defaults are conservative so the cache
129
+ stays small:
130
+
131
+ - `maxEntities`: `120`
132
+ - `maxAliases`: `12`
133
+ - `maxTypeCandidates`: `4`
134
+
135
+ ### `onError`
136
+
137
+ Optional error hook. Cache failures are swallowed after calling this hook. This
138
+ is deliberate: Redis should improve extraction quality and throughput, but it
139
+ should not make document ingestion fail when the primary database and extractor
140
+ are healthy.
141
+
142
+ ## Key Shape
143
+
144
+ Keys are URL-encoded and prefixed:
145
+
146
+ ```text
147
+ typegraph:coreference:<namespace>:<tenantId>:<bucketId>:group:<groupId>:user:<userId>:agent:<agentId>:thread:<threadId>
148
+ ```
149
+
150
+ Only fields present in the extraction context are included.
151
+
152
+ ## Self-Hosted vs Cloud
153
+
154
+ Use this adapter when you run TypeGraph yourself and want Redis-backed extraction
155
+ continuity across workers.
156
+
157
+ Do not use it when calling TypeGraph Cloud with an API key. Cloud manages this
158
+ cache internally and may use different infrastructure.
159
+
160
+ ## Related Packages
161
+
162
+ - `@typegraph-ai/adapter-redis-upstash`: Upstash Redis wrapper around this package.
163
+ - `@typegraph-ai/adapter-pgvector`: Postgres/pgvector storage adapter for TypeGraph data.
164
+ - `@typegraph-ai/sdk`: TypeGraph SDK.
@@ -0,0 +1,18 @@
1
+ import type { ExtractionCoreferenceCache } from '@typegraph-ai/sdk';
2
+ export interface RedisCoreferenceClient {
3
+ get<T = unknown>(key: string): Promise<T | null>;
4
+ set(key: string, value: unknown, options?: {
5
+ ex?: number | undefined;
6
+ }): Promise<unknown>;
7
+ }
8
+ export interface RedisCoreferenceCacheOptions {
9
+ redis: RedisCoreferenceClient;
10
+ namespace?: string | undefined;
11
+ ttlSeconds?: number | undefined;
12
+ maxEntities?: number | undefined;
13
+ maxAliases?: number | undefined;
14
+ maxTypeCandidates?: number | undefined;
15
+ onError?: ((error: unknown) => void) | undefined;
16
+ }
17
+ export declare function createRedisCoreferenceCache(options: RedisCoreferenceCacheOptions): ExtractionCoreferenceCache;
18
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,0BAA0B,EAE3B,MAAM,mBAAmB,CAAA;AAE1B,MAAM,WAAW,sBAAsB;IACrC,GAAG,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAA;IAChD,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE;QAAE,EAAE,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;CAC1F;AAED,MAAM,WAAW,4BAA4B;IAC3C,KAAK,EAAE,sBAAsB,CAAA;IAC7B,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC9B,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC/B,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAChC,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IAC/B,iBAAiB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IACtC,OAAO,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG,SAAS,CAAA;CACjD;AAOD,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,4BAA4B,GAAG,0BAA0B,CA2B7G"}
package/dist/index.js ADDED
@@ -0,0 +1,83 @@
1
+ const DEFAULT_TTL_SECONDS = 60 * 60 * 4;
2
+ const DEFAULT_MAX_ENTITIES = 120;
3
+ const DEFAULT_MAX_ALIASES = 12;
4
+ const DEFAULT_MAX_TYPE_CANDIDATES = 4;
5
+ export function createRedisCoreferenceCache(options) {
6
+ const ttlSeconds = options.ttlSeconds ?? DEFAULT_TTL_SECONDS;
7
+ const maxEntities = options.maxEntities ?? DEFAULT_MAX_ENTITIES;
8
+ const maxAliases = options.maxAliases ?? DEFAULT_MAX_ALIASES;
9
+ const maxTypeCandidates = options.maxTypeCandidates ?? DEFAULT_MAX_TYPE_CANDIDATES;
10
+ return {
11
+ async load(key) {
12
+ try {
13
+ return normalizeEntities(await options.redis.get(cacheKey(options.namespace, key)));
14
+ }
15
+ catch (error) {
16
+ options.onError?.(error);
17
+ return [];
18
+ }
19
+ },
20
+ async save(key, entities) {
21
+ try {
22
+ await options.redis.set(cacheKey(options.namespace, key), compactEntities(entities, maxEntities, maxAliases, maxTypeCandidates), { ex: ttlSeconds });
23
+ }
24
+ catch (error) {
25
+ options.onError?.(error);
26
+ }
27
+ },
28
+ };
29
+ }
30
+ function cacheKey(namespace, key) {
31
+ const parts = [
32
+ 'typegraph',
33
+ 'coreference',
34
+ namespace ?? 'default',
35
+ key.tenantId ?? 'public',
36
+ key.bucketId,
37
+ key.groupId ? `group:${key.groupId}` : undefined,
38
+ key.userId ? `user:${key.userId}` : undefined,
39
+ key.agentId ? `agent:${key.agentId}` : undefined,
40
+ key.threadId ? `thread:${key.threadId}` : undefined,
41
+ ].filter((part) => Boolean(part));
42
+ return parts.map(encodeURIComponent).join(':');
43
+ }
44
+ function normalizeEntities(value) {
45
+ if (typeof value === 'string') {
46
+ try {
47
+ return normalizeEntities(JSON.parse(value));
48
+ }
49
+ catch {
50
+ return [];
51
+ }
52
+ }
53
+ if (!Array.isArray(value))
54
+ return [];
55
+ return value.filter(isExtractedEntity);
56
+ }
57
+ function isExtractedEntity(value) {
58
+ if (!value || typeof value !== 'object')
59
+ return false;
60
+ const entity = value;
61
+ return typeof entity.type === 'string' && typeof entity.name === 'string';
62
+ }
63
+ function compactEntities(entities, maxEntities, maxAliases, maxTypeCandidates) {
64
+ const byKey = new Map();
65
+ for (const entity of entities) {
66
+ const key = `${entity.type}:${entity.name.toLowerCase()}`;
67
+ if (byKey.has(key))
68
+ continue;
69
+ byKey.set(key, {
70
+ type: entity.type,
71
+ id: entity.id,
72
+ name: entity.name,
73
+ description: entity.description,
74
+ aliases: entity.aliases?.slice(0, maxAliases),
75
+ typeCandidates: entity.typeCandidates?.slice(0, maxTypeCandidates),
76
+ metadata: entity.metadata,
77
+ });
78
+ if (byKey.size >= maxEntities)
79
+ break;
80
+ }
81
+ return [...byKey.values()];
82
+ }
83
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAqBA,MAAM,mBAAmB,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;AACvC,MAAM,oBAAoB,GAAG,GAAG,CAAA;AAChC,MAAM,mBAAmB,GAAG,EAAE,CAAA;AAC9B,MAAM,2BAA2B,GAAG,CAAC,CAAA;AAErC,MAAM,UAAU,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AED,SAAS,eAAe,CACtB,QAA2B,EAC3B,WAAmB,EACnB,UAAkB,EAClB,iBAAyB;IAEzB,MAAM,KAAK,GAAG,IAAI,GAAG,EAA2B,CAAA;IAChD,KAAK,MAAM,MAAM,IAAI,QAAQ,EAAE,CAAC;QAC9B,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,CAAA;QACzD,IAAI,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC;YAAE,SAAQ;QAC5B,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE;YACb,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,EAAE,EAAE,MAAM,CAAC,EAAE;YACb,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,WAAW,EAAE,MAAM,CAAC,WAAW;YAC/B,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,EAAE,UAAU,CAAC;YAC7C,cAAc,EAAE,MAAM,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC,EAAE,iBAAiB,CAAC;YAClE,QAAQ,EAAE,MAAM,CAAC,QAAQ;SAC1B,CAAC,CAAA;QACF,IAAI,KAAK,CAAC,IAAI,IAAI,WAAW;YAAE,MAAK;IACtC,CAAC;IACD,OAAO,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,CAAA;AAC5B,CAAC"}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@typegraph-ai/adapter-redis",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "default": "./dist/index.js"
16
+ }
17
+ },
18
+ "dependencies": {
19
+ "@typegraph-ai/sdk": "0.5.1"
20
+ },
21
+ "peerDependencies": {
22
+ "@typegraph-ai/sdk": "0.5.1"
23
+ },
24
+ "publishConfig": {
25
+ "registry": "https://registry.npmjs.org"
26
+ },
27
+ "devDependencies": {
28
+ "typescript": "^5.4.0"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc",
32
+ "clean": "rm -rf dist"
33
+ }
34
+ }