korely-memory 0.1.7 → 0.1.9
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 +79 -0
- package/dist/ai-sdk.cjs +361 -0
- package/dist/ai-sdk.d.cts +156 -0
- package/dist/ai-sdk.d.ts +156 -0
- package/dist/ai-sdk.js +334 -0
- package/dist/index.cjs +21 -9
- package/dist/index.d.cts +22 -2
- package/dist/index.d.ts +22 -2
- package/dist/index.js +18 -6
- package/package.json +25 -2
package/README.md
CHANGED
|
@@ -33,6 +33,61 @@ console.log(ctx.context); // drop straight into your system prompt
|
|
|
33
33
|
That's the whole loop: `add` to remember, `getContext` (or `search`) to recall.
|
|
34
34
|
Behind `add`, Korely extracts typed, bi-temporal facts; you just hand it text.
|
|
35
35
|
|
|
36
|
+
## Vercel AI SDK
|
|
37
|
+
|
|
38
|
+
`korely-memory/ai-sdk` gives any [AI SDK](https://ai-sdk.dev) model (AI SDK 5,
|
|
39
|
+
6 or 7) a memory of each of your users. Install `ai` next to this package; the
|
|
40
|
+
core client never loads it.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
// app/api/chat/route.ts
|
|
44
|
+
import {
|
|
45
|
+
convertToModelMessages,
|
|
46
|
+
createUIMessageStreamResponse,
|
|
47
|
+
streamText,
|
|
48
|
+
toUIMessageStream,
|
|
49
|
+
type UIMessage,
|
|
50
|
+
} from "ai";
|
|
51
|
+
import { waitUntil } from "@vercel/functions";
|
|
52
|
+
import { withKorelyMemory } from "korely-memory/ai-sdk";
|
|
53
|
+
|
|
54
|
+
export async function POST(req: Request) {
|
|
55
|
+
const { messages }: { messages: UIMessage[] } = await req.json();
|
|
56
|
+
const userId = await currentUserId(req); // from your auth, never from the request body
|
|
57
|
+
|
|
58
|
+
const result = streamText({
|
|
59
|
+
model: withKorelyMemory("anthropic/claude-sonnet-5.5", { userId, waitUntil }),
|
|
60
|
+
instructions: "You are the support assistant of Acme.",
|
|
61
|
+
messages: await convertToModelMessages(messages),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }) });
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Before each call, the wrapper reads `getContext` for the latest user message
|
|
69
|
+
and adds what Korely knows as system messages after your own: first the part
|
|
70
|
+
that is the same on every call, so the provider's prompt cache keeps it, then
|
|
71
|
+
`Current date: YYYY-MM-DD` and the facts and memories this question brought.
|
|
72
|
+
After a reply that ends the turn, it stores the user message and the reply as
|
|
73
|
+
one memory, without waiting for the write (`waitUntil` keeps a serverless
|
|
74
|
+
function alive until it lands). If Korely cannot be reached, or takes longer
|
|
75
|
+
than `contextTimeoutMs` (5 s) to answer, the call goes on without memory,
|
|
76
|
+
`onError` is told, and an answer that arrives later is dropped.
|
|
77
|
+
|
|
78
|
+
Options: `userId` (required), `agentId`, `runId`, `client` (a configured
|
|
79
|
+
`Korely`, default `new Korely()`), `tokenBudget` (800), `contextTimeoutMs`
|
|
80
|
+
(5000; 0 waits for the client's own 30 s), `includeDate` (true), `timeZone`
|
|
81
|
+
("UTC"), `remember` (true), `waitUntil`, `onError`.
|
|
82
|
+
|
|
83
|
+
To let the model decide when to look something up or save it, give it the
|
|
84
|
+
tools instead: `tools: korelyTools({ userId })` adds `searchMemory` and
|
|
85
|
+
`addMemory`, and takes the same options except `remember` and `waitUntil`.
|
|
86
|
+
`searchMemory` also waits at most `contextTimeoutMs`, then tells the model the
|
|
87
|
+
memory is unavailable right now (`onError` hears of it, phase `"search"`).
|
|
88
|
+
Either way the user comes from your code: the model has no field to name
|
|
89
|
+
another one.
|
|
90
|
+
|
|
36
91
|
## Methods
|
|
37
92
|
|
|
38
93
|
Every method maps to one REST endpoint.
|
|
@@ -117,6 +172,30 @@ new Korely({
|
|
|
117
172
|
});
|
|
118
173
|
```
|
|
119
174
|
|
|
175
|
+
### Your own server (korely-agent)
|
|
176
|
+
|
|
177
|
+
Point the client at your install with `baseUrl`, or with the `KORELY_BASE_URL`
|
|
178
|
+
env var, and use the key your install issued (`kor_self_...`):
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
const korely = new Korely({
|
|
182
|
+
apiKey: "kor_self_...", // or KORELY_API_KEY
|
|
183
|
+
baseUrl: "https://memory.example.com", // or KORELY_BASE_URL
|
|
184
|
+
});
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
The option is `baseUrl`, in camelCase. `base_url` is the Python spelling and
|
|
188
|
+
this SDK refuses it, rather than ignore it and send your memories to the hosted
|
|
189
|
+
service. A `kor_self_` key is never sent to the hosted service, and a
|
|
190
|
+
`kor_live_` key is never sent anywhere else.
|
|
191
|
+
|
|
192
|
+
For a server whose certificate a private CA signed (Caddy's local CA on a
|
|
193
|
+
laptop install), Node reads the CA from `NODE_EXTRA_CA_CERTS`:
|
|
194
|
+
|
|
195
|
+
```sh
|
|
196
|
+
NODE_EXTRA_CA_CERTS=/path/to/root.crt node agent.js
|
|
197
|
+
```
|
|
198
|
+
|
|
120
199
|
Requires Node 18+ (native `fetch`), or any runtime with a global `fetch`. On
|
|
121
200
|
older runtimes, pass one via `{ fetch }`.
|
|
122
201
|
|
package/dist/ai-sdk.cjs
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/ai-sdk.ts
|
|
21
|
+
var ai_sdk_exports = {};
|
|
22
|
+
__export(ai_sdk_exports, {
|
|
23
|
+
korelyMemoryMiddleware: () => korelyMemoryMiddleware,
|
|
24
|
+
korelyTools: () => korelyTools,
|
|
25
|
+
withKorelyMemory: () => withKorelyMemory
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(ai_sdk_exports);
|
|
28
|
+
var import_ai = require("ai");
|
|
29
|
+
var import_korely_memory = require("korely-memory");
|
|
30
|
+
var QUERY_MAX = 2e3;
|
|
31
|
+
var CONTENT_MAX = 16e3;
|
|
32
|
+
var USER_MAX = 6e3;
|
|
33
|
+
var TURN_OVERHEAD = 18;
|
|
34
|
+
var DEFAULT_TOKEN_BUDGET = 800;
|
|
35
|
+
var CONTEXT_REUSE_MS = 5 * 6e4;
|
|
36
|
+
var FAILURE_REUSE_MS = 3e4;
|
|
37
|
+
var DEFAULT_CONTEXT_TIMEOUT_MS = 5e3;
|
|
38
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
39
|
+
function scopeOf(options, caller) {
|
|
40
|
+
const o = options ?? {};
|
|
41
|
+
if (typeof o.userId !== "string" || !o.userId.trim()) {
|
|
42
|
+
throw new import_korely_memory.KorelyError(
|
|
43
|
+
`${caller} needs a userId: the id of your end user, from your own auth. Without it a read would span every end user of the project.`
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
client: o.client ?? new import_korely_memory.Korely(),
|
|
48
|
+
userId: o.userId,
|
|
49
|
+
agentId: o.agentId,
|
|
50
|
+
runId: o.runId,
|
|
51
|
+
tokenBudget: o.tokenBudget ?? DEFAULT_TOKEN_BUDGET,
|
|
52
|
+
today: o.includeDate === false ? void 0 : dateLine(o.timeZone),
|
|
53
|
+
limit: contextLimit(o.contextTimeoutMs),
|
|
54
|
+
report: reporter(o.onError)
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function dateLine(timeZone) {
|
|
58
|
+
if (!timeZone) return () => `Current date: ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`;
|
|
59
|
+
let format;
|
|
60
|
+
try {
|
|
61
|
+
format = new Intl.DateTimeFormat("en-US", {
|
|
62
|
+
timeZone,
|
|
63
|
+
year: "numeric",
|
|
64
|
+
month: "2-digit",
|
|
65
|
+
day: "2-digit"
|
|
66
|
+
});
|
|
67
|
+
} catch {
|
|
68
|
+
throw new import_korely_memory.KorelyError(`timeZone ${JSON.stringify(timeZone)} is not an IANA time zone, e.g. "Europe/Rome".`);
|
|
69
|
+
}
|
|
70
|
+
return () => {
|
|
71
|
+
const part = {};
|
|
72
|
+
for (const { type, value } of format.formatToParts(/* @__PURE__ */ new Date())) part[type] = value;
|
|
73
|
+
return `Current date: ${part.year}-${part.month}-${part.day}`;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function clip(text, max) {
|
|
77
|
+
if (text.length <= max) return text;
|
|
78
|
+
const mark = " \u2026 ";
|
|
79
|
+
const headLength = Math.floor((max - mark.length) / 2);
|
|
80
|
+
let head = text.slice(0, headLength);
|
|
81
|
+
let tail = text.slice(text.length - (max - mark.length - headLength));
|
|
82
|
+
if (/[\uD800-\uDBFF]$/.test(head)) head = head.slice(0, -1);
|
|
83
|
+
if (/^[\uDC00-\uDFFF]/.test(tail)) tail = tail.slice(1);
|
|
84
|
+
return head + mark + tail;
|
|
85
|
+
}
|
|
86
|
+
function isText(part) {
|
|
87
|
+
return part.type === "text" && typeof part.text === "string";
|
|
88
|
+
}
|
|
89
|
+
function latestUserText(prompt) {
|
|
90
|
+
for (let i = prompt.length - 1; i >= 0; i--) {
|
|
91
|
+
const message = prompt[i];
|
|
92
|
+
if (message.role !== "user") continue;
|
|
93
|
+
const content = message.content;
|
|
94
|
+
if (typeof content === "string") return content.trim();
|
|
95
|
+
if (!Array.isArray(content)) return "";
|
|
96
|
+
return content.filter(isText).map((part) => part.text).join("\n").trim();
|
|
97
|
+
}
|
|
98
|
+
return "";
|
|
99
|
+
}
|
|
100
|
+
function userMessageCount(prompt) {
|
|
101
|
+
return prompt.filter((message) => message.role === "user").length;
|
|
102
|
+
}
|
|
103
|
+
function partsOf(ctx) {
|
|
104
|
+
const stable = typeof ctx?.stable === "string" ? ctx.stable : "";
|
|
105
|
+
const volatile = typeof ctx?.volatile === "string" ? ctx.volatile : "";
|
|
106
|
+
if (stable.trim() || volatile.trim()) return { stable, volatile };
|
|
107
|
+
return { stable: "", volatile: typeof ctx?.context === "string" ? ctx.context : "" };
|
|
108
|
+
}
|
|
109
|
+
function memoryMessages(parts, date) {
|
|
110
|
+
const messages = [];
|
|
111
|
+
if (parts?.stable.trim()) messages.push({ role: "system", content: parts.stable });
|
|
112
|
+
const turn = [date, parts?.volatile.trim() ? parts.volatile : void 0].filter(Boolean).join("\n\n");
|
|
113
|
+
if (turn) messages.push({ role: "system", content: turn });
|
|
114
|
+
return messages;
|
|
115
|
+
}
|
|
116
|
+
function withMemory(prompt, messages) {
|
|
117
|
+
let head = 0;
|
|
118
|
+
while (head < prompt.length && prompt[head].role === "system") head++;
|
|
119
|
+
return [...prompt.slice(0, head), ...messages, ...prompt.slice(head)];
|
|
120
|
+
}
|
|
121
|
+
function endsTurn(finishReason, content) {
|
|
122
|
+
const reason = typeof finishReason === "string" ? finishReason : finishReason?.unified;
|
|
123
|
+
if (reason === "tool-calls" || reason === "error") return false;
|
|
124
|
+
return !content.some(
|
|
125
|
+
(part) => part.type === "tool-call" && !part.providerExecuted
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
function contextLimit(value) {
|
|
129
|
+
const ms = value ?? DEFAULT_CONTEXT_TIMEOUT_MS;
|
|
130
|
+
if (typeof ms !== "number" || Number.isNaN(ms) || ms < 0) {
|
|
131
|
+
throw new import_korely_memory.KorelyError(
|
|
132
|
+
`contextTimeoutMs must be a number of milliseconds, 0 or more, got ${JSON.stringify(value)}. 0 or Infinity waits for the client's own timeout.`
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
return ms === 0 || ms >= MAX_TIMER_MS ? void 0 : ms;
|
|
136
|
+
}
|
|
137
|
+
var DEFAULT_WARNING = {
|
|
138
|
+
context: "korely-memory/ai-sdk: could not read the memory; this call went on without it.",
|
|
139
|
+
remember: "korely-memory/ai-sdk: could not store the turn.",
|
|
140
|
+
search: "korely-memory/ai-sdk: searchMemory could not read the memory."
|
|
141
|
+
};
|
|
142
|
+
function reporter(onError) {
|
|
143
|
+
return (error, phase) => {
|
|
144
|
+
try {
|
|
145
|
+
if (onError) onError(error, { phase });
|
|
146
|
+
else console.warn(DEFAULT_WARNING[phase], error);
|
|
147
|
+
} catch {
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function readWithin(read, limit) {
|
|
152
|
+
return new Promise((resolve) => {
|
|
153
|
+
let timer;
|
|
154
|
+
const finish = (outcome) => {
|
|
155
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
156
|
+
resolve(outcome);
|
|
157
|
+
};
|
|
158
|
+
if (limit !== void 0) {
|
|
159
|
+
timer = setTimeout(() => {
|
|
160
|
+
const error = new import_korely_memory.KorelyError(`GET /v1/context took longer than ${limit} ms (contextTimeoutMs).`);
|
|
161
|
+
finish({ ok: false, error, timedOut: true });
|
|
162
|
+
}, limit);
|
|
163
|
+
}
|
|
164
|
+
Promise.resolve().then(read).then(
|
|
165
|
+
(ctx) => finish({ ok: true, ctx }),
|
|
166
|
+
(error) => finish({ ok: false, error, timedOut: false })
|
|
167
|
+
);
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
function korelyMemoryMiddleware(options) {
|
|
171
|
+
const scope = scopeOf(options, "korelyMemoryMiddleware");
|
|
172
|
+
const remember = options.remember ?? true;
|
|
173
|
+
const report = scope.report;
|
|
174
|
+
const waitUntil = options.waitUntil;
|
|
175
|
+
let lastTurn;
|
|
176
|
+
function contextFor(query, turn) {
|
|
177
|
+
const key = `${turn}\0${query}`;
|
|
178
|
+
if (lastTurn && lastTurn.key === key && Date.now() < lastTurn.until) return lastTurn.parts;
|
|
179
|
+
const entry = { key, until: Date.now() + CONTEXT_REUSE_MS, parts: Promise.resolve(void 0) };
|
|
180
|
+
entry.parts = readWithin(
|
|
181
|
+
() => scope.client.getContext({
|
|
182
|
+
query: clip(query, QUERY_MAX),
|
|
183
|
+
user_id: scope.userId,
|
|
184
|
+
agent_id: scope.agentId,
|
|
185
|
+
token_budget: scope.tokenBudget
|
|
186
|
+
}),
|
|
187
|
+
scope.limit
|
|
188
|
+
).then((outcome) => {
|
|
189
|
+
if (outcome.ok) return partsOf(outcome.ctx);
|
|
190
|
+
entry.until = Date.now() + FAILURE_REUSE_MS;
|
|
191
|
+
report(outcome.error, "context");
|
|
192
|
+
return void 0;
|
|
193
|
+
}).catch(() => void 0);
|
|
194
|
+
lastTurn = entry;
|
|
195
|
+
return entry.parts;
|
|
196
|
+
}
|
|
197
|
+
function rememberTurn(prompt, reply) {
|
|
198
|
+
const user = latestUserText(prompt);
|
|
199
|
+
if (!user || !reply.trim()) return;
|
|
200
|
+
const userPart = clip(user, USER_MAX);
|
|
201
|
+
const replyPart = clip(reply, CONTENT_MAX - TURN_OVERHEAD - userPart.length);
|
|
202
|
+
const write = Promise.resolve().then(
|
|
203
|
+
() => scope.client.add(
|
|
204
|
+
[
|
|
205
|
+
{ role: "user", content: userPart },
|
|
206
|
+
{ role: "assistant", content: replyPart }
|
|
207
|
+
],
|
|
208
|
+
{ user_id: scope.userId, agent_id: scope.agentId, run_id: scope.runId }
|
|
209
|
+
)
|
|
210
|
+
).then(
|
|
211
|
+
() => void 0,
|
|
212
|
+
(error) => report(error, "remember")
|
|
213
|
+
);
|
|
214
|
+
if (!waitUntil) return;
|
|
215
|
+
try {
|
|
216
|
+
waitUntil(write);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
report(error, "remember");
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return {
|
|
222
|
+
specificationVersion: "v4",
|
|
223
|
+
transformParams: async ({ params }) => {
|
|
224
|
+
const query = latestUserText(params.prompt);
|
|
225
|
+
const parts = query ? await contextFor(query, userMessageCount(params.prompt)) : void 0;
|
|
226
|
+
const added = memoryMessages(parts, scope.today?.());
|
|
227
|
+
return added.length ? { ...params, prompt: withMemory(params.prompt, added) } : params;
|
|
228
|
+
},
|
|
229
|
+
wrapGenerate: async ({ doGenerate, params }) => {
|
|
230
|
+
const result = await doGenerate();
|
|
231
|
+
if (remember) {
|
|
232
|
+
try {
|
|
233
|
+
if (endsTurn(result.finishReason, result.content)) {
|
|
234
|
+
rememberTurn(params.prompt, result.content.filter(isText).map((part) => part.text).join(""));
|
|
235
|
+
}
|
|
236
|
+
} catch (error) {
|
|
237
|
+
report(error, "remember");
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return result;
|
|
241
|
+
},
|
|
242
|
+
wrapStream: async ({ doStream, params }) => {
|
|
243
|
+
const result = await doStream();
|
|
244
|
+
if (!remember) return result;
|
|
245
|
+
let reply = "";
|
|
246
|
+
let toolCall = false;
|
|
247
|
+
let failed = false;
|
|
248
|
+
let finished = false;
|
|
249
|
+
const watch = new TransformStream({
|
|
250
|
+
transform(part, controller) {
|
|
251
|
+
controller.enqueue(part);
|
|
252
|
+
if (finished) return;
|
|
253
|
+
try {
|
|
254
|
+
if (part.type === "text-delta") reply += part.delta;
|
|
255
|
+
else if (part.type === "tool-call") toolCall ||= !part.providerExecuted;
|
|
256
|
+
else if (part.type === "error") failed = true;
|
|
257
|
+
else if (part.type === "finish") {
|
|
258
|
+
finished = true;
|
|
259
|
+
if (!failed && !toolCall && endsTurn(part.finishReason, [])) rememberTurn(params.prompt, reply);
|
|
260
|
+
}
|
|
261
|
+
} catch (error) {
|
|
262
|
+
report(error, "remember");
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
return { ...result, stream: result.stream.pipeThrough(watch) };
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
function resolveModel(model) {
|
|
271
|
+
if (typeof model !== "string") return model;
|
|
272
|
+
const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? import_ai.gateway;
|
|
273
|
+
return provider.languageModel(model);
|
|
274
|
+
}
|
|
275
|
+
function withKorelyMemory(model, options) {
|
|
276
|
+
const middleware = korelyMemoryMiddleware(options);
|
|
277
|
+
return (0, import_ai.wrapLanguageModel)({ model: resolveModel(model), middleware });
|
|
278
|
+
}
|
|
279
|
+
var NOTHING_IN_MEMORY = "Nothing in memory bears on this.";
|
|
280
|
+
var MEMORY_UNAVAILABLE = "Memory is unavailable right now: earlier conversations cannot be checked. Answer from this conversation alone.";
|
|
281
|
+
function oneText(value, key, max) {
|
|
282
|
+
const raw = value && typeof value === "object" ? value[key] : void 0;
|
|
283
|
+
if (typeof raw !== "string" || !raw.trim()) {
|
|
284
|
+
return { success: false, error: new Error(`${key} must be a non-empty string.`) };
|
|
285
|
+
}
|
|
286
|
+
return { success: true, value: { [key]: clip(raw.trim(), max) } };
|
|
287
|
+
}
|
|
288
|
+
function korelyTools(options) {
|
|
289
|
+
const scope = scopeOf(options, "korelyTools");
|
|
290
|
+
const withDate = (text) => scope.today ? `${scope.today()}
|
|
291
|
+
|
|
292
|
+
${text}` : text;
|
|
293
|
+
return {
|
|
294
|
+
searchMemory: (0, import_ai.tool)({
|
|
295
|
+
description: "Look up what you know about the user from earlier conversations: facts about their life and work, preferences, decisions, plans, and what they said before. Use it when the answer may depend on something the user told you in the past.",
|
|
296
|
+
inputSchema: (0, import_ai.jsonSchema)(
|
|
297
|
+
{
|
|
298
|
+
type: "object",
|
|
299
|
+
properties: {
|
|
300
|
+
query: {
|
|
301
|
+
type: "string",
|
|
302
|
+
description: 'What to look up, as a short question or a few words, e.g. "preferred contact channel".'
|
|
303
|
+
}
|
|
304
|
+
},
|
|
305
|
+
required: ["query"],
|
|
306
|
+
additionalProperties: false
|
|
307
|
+
},
|
|
308
|
+
{ validate: (value) => oneText(value, "query", QUERY_MAX) }
|
|
309
|
+
),
|
|
310
|
+
execute: async ({ query }) => {
|
|
311
|
+
const outcome = await readWithin(
|
|
312
|
+
() => scope.client.getContext({
|
|
313
|
+
query,
|
|
314
|
+
user_id: scope.userId,
|
|
315
|
+
agent_id: scope.agentId,
|
|
316
|
+
token_budget: scope.tokenBudget
|
|
317
|
+
}),
|
|
318
|
+
scope.limit
|
|
319
|
+
);
|
|
320
|
+
if (!outcome.ok) {
|
|
321
|
+
scope.report(outcome.error, "search");
|
|
322
|
+
if (!outcome.timedOut) throw outcome.error;
|
|
323
|
+
return withDate(MEMORY_UNAVAILABLE);
|
|
324
|
+
}
|
|
325
|
+
const ctx = outcome.ctx;
|
|
326
|
+
return withDate(typeof ctx?.context === "string" && ctx.context.trim() ? ctx.context : NOTHING_IN_MEMORY);
|
|
327
|
+
}
|
|
328
|
+
}),
|
|
329
|
+
addMemory: (0, import_ai.tool)({
|
|
330
|
+
description: "Save something worth remembering about the user for future conversations: a fact about their life or work, a preference, a decision, a plan. One self-contained statement per call. Never save passwords, card numbers or other secrets.",
|
|
331
|
+
inputSchema: (0, import_ai.jsonSchema)(
|
|
332
|
+
{
|
|
333
|
+
type: "object",
|
|
334
|
+
properties: {
|
|
335
|
+
memory: {
|
|
336
|
+
type: "string",
|
|
337
|
+
description: 'The statement to remember, e.g. "Maria prefers email over Slack."'
|
|
338
|
+
}
|
|
339
|
+
},
|
|
340
|
+
required: ["memory"],
|
|
341
|
+
additionalProperties: false
|
|
342
|
+
},
|
|
343
|
+
{ validate: (value) => oneText(value, "memory", CONTENT_MAX) }
|
|
344
|
+
),
|
|
345
|
+
execute: async ({ memory }) => {
|
|
346
|
+
const saved = await scope.client.add(memory, {
|
|
347
|
+
user_id: scope.userId,
|
|
348
|
+
agent_id: scope.agentId,
|
|
349
|
+
run_id: scope.runId
|
|
350
|
+
});
|
|
351
|
+
return saved?.id ? { saved: true, id: saved.id } : { saved: true };
|
|
352
|
+
}
|
|
353
|
+
})
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
357
|
+
0 && (module.exports = {
|
|
358
|
+
korelyMemoryMiddleware,
|
|
359
|
+
korelyTools,
|
|
360
|
+
withKorelyMemory
|
|
361
|
+
});
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { Tool, LanguageModelMiddleware, LanguageModel, wrapLanguageModel } from 'ai';
|
|
2
|
+
import { Korely } from 'korely-memory';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* korely-memory/ai-sdk: Korely memory for the Vercel AI SDK.
|
|
6
|
+
*
|
|
7
|
+
* Two ways in, and they combine:
|
|
8
|
+
*
|
|
9
|
+
* import { withKorelyMemory, korelyTools } from "korely-memory/ai-sdk";
|
|
10
|
+
*
|
|
11
|
+
* // Every call reads the memory first and stores the turn after.
|
|
12
|
+
* const model = withKorelyMemory("anthropic/claude-sonnet-5.5", { userId: "customer-4812" });
|
|
13
|
+
*
|
|
14
|
+
* // Or the model decides when to look something up or save it.
|
|
15
|
+
* const tools = korelyTools({ userId: "customer-4812" });
|
|
16
|
+
*
|
|
17
|
+
* `ai` is an optional peer dependency: only this entry point imports it, so
|
|
18
|
+
* the core client stays without runtime dependencies. The client itself comes
|
|
19
|
+
* from "korely-memory", not from a copy bundled here, so `instanceof
|
|
20
|
+
* KorelyError` holds whichever entry point an error came through.
|
|
21
|
+
*
|
|
22
|
+
* Written against AI SDK 7 (language model specification v4). The parts of
|
|
23
|
+
* the specification read here, prompt messages, text and tool-call parts,
|
|
24
|
+
* stream deltas, are the same in AI SDK 5 and 6, and the one difference that
|
|
25
|
+
* matters (a finish reason that is a string in v5 and an object since v6) is
|
|
26
|
+
* handled, so the peer range covers all three.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Where a failure happened: reading the context before a call ("context"),
|
|
31
|
+
* storing the turn after it ("remember"), or the searchMemory tool ("search").
|
|
32
|
+
*/
|
|
33
|
+
type KorelyPhase = "context" | "remember" | "search";
|
|
34
|
+
interface KorelyToolsOptions {
|
|
35
|
+
/**
|
|
36
|
+
* The end user whose memory is read and written: your user's id, taken
|
|
37
|
+
* from your own auth. Required, and never taken from the model: without
|
|
38
|
+
* it a read would span every end user of the project.
|
|
39
|
+
*/
|
|
40
|
+
userId: string;
|
|
41
|
+
/** Agent namespace, when one project runs several agents. */
|
|
42
|
+
agentId?: string;
|
|
43
|
+
/**
|
|
44
|
+
* Session id stored on the memories this integration writes. Reads are not
|
|
45
|
+
* narrowed to it: a new session recalls what the user said in an old one.
|
|
46
|
+
*/
|
|
47
|
+
runId?: string;
|
|
48
|
+
/** The client to use. Default: `new Korely()`, configured from the environment (KORELY_API_KEY, KORELY_BASE_URL). */
|
|
49
|
+
client?: Korely;
|
|
50
|
+
/** Token budget of the context block (`token_budget`). Default 800, the API's default. */
|
|
51
|
+
tokenBudget?: number;
|
|
52
|
+
/** Add a "Current date: YYYY-MM-DD" line. Default true: the reader answers better when its prompt carries the date. */
|
|
53
|
+
includeDate?: boolean;
|
|
54
|
+
/** IANA time zone of that date, e.g. "Europe/Rome". Default UTC, the zone of the dates in the facts. */
|
|
55
|
+
timeZone?: string;
|
|
56
|
+
/**
|
|
57
|
+
* How long a read of the memory may take, in milliseconds: the context read
|
|
58
|
+
* before each call, and searchMemory. Default 5000. Past it the call goes on
|
|
59
|
+
* without the memory, or searchMemory tells the model the memory is
|
|
60
|
+
* unavailable right now; `onError` hears of it, and the answer that arrives
|
|
61
|
+
* later is dropped. 0 or Infinity waits for the client's own `timeoutMs`
|
|
62
|
+
* instead (30 s by default).
|
|
63
|
+
*/
|
|
64
|
+
contextTimeoutMs?: number;
|
|
65
|
+
/**
|
|
66
|
+
* Called when the memory cannot be read or a turn cannot be stored, with
|
|
67
|
+
* where it happened: "context" (the read before a call, which goes on
|
|
68
|
+
* without it), "remember" (the write after it), "search" (searchMemory: past
|
|
69
|
+
* `contextTimeoutMs` it tells the model the memory is unavailable, any other
|
|
70
|
+
* failure rejects and the AI SDK hands it to the model). Default: a console
|
|
71
|
+
* warning.
|
|
72
|
+
*/
|
|
73
|
+
onError?: (error: unknown, info: {
|
|
74
|
+
phase: KorelyPhase;
|
|
75
|
+
}) => void;
|
|
76
|
+
}
|
|
77
|
+
interface KorelyMemoryOptions extends KorelyToolsOptions {
|
|
78
|
+
/**
|
|
79
|
+
* Store each finished turn (the latest user message and the reply) as a
|
|
80
|
+
* memory, after the call and without waiting for it. Default true: a memory
|
|
81
|
+
* that nothing writes to has nothing to recall. Turn it off when the app
|
|
82
|
+
* writes memories itself, or has no consent to store the conversation.
|
|
83
|
+
*/
|
|
84
|
+
remember?: boolean;
|
|
85
|
+
/**
|
|
86
|
+
* Hands over the pending write so a serverless runtime keeps the function
|
|
87
|
+
* alive until it is done, e.g. `waitUntil` from "@vercel/functions" or
|
|
88
|
+
* `after` from "next/server". Without it the write is fire-and-forget.
|
|
89
|
+
*/
|
|
90
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
91
|
+
}
|
|
92
|
+
/** The two tools `korelyTools()` returns, ready to spread into `tools`. */
|
|
93
|
+
type KorelyTools = {
|
|
94
|
+
searchMemory: Tool<{
|
|
95
|
+
query: string;
|
|
96
|
+
}, string>;
|
|
97
|
+
addMemory: Tool<{
|
|
98
|
+
memory: string;
|
|
99
|
+
}, {
|
|
100
|
+
saved: true;
|
|
101
|
+
id?: string;
|
|
102
|
+
}>;
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* The middleware behind `withKorelyMemory`, for composing with other
|
|
106
|
+
* middleware in `wrapLanguageModel`. `defaultInstructionsMiddleware` adds its
|
|
107
|
+
* instructions only to a call without system messages, and this adds some, so
|
|
108
|
+
* put that one first in the array (it runs first).
|
|
109
|
+
*/
|
|
110
|
+
declare function korelyMemoryMiddleware(options: KorelyMemoryOptions): LanguageModelMiddleware;
|
|
111
|
+
/**
|
|
112
|
+
* Wraps a language model so that every call reads the user's memory first and
|
|
113
|
+
* stores the turn after.
|
|
114
|
+
*
|
|
115
|
+
* Before each call, `GET /v1/context` for the latest user message, added as
|
|
116
|
+
* system messages after the app's own: the stable part first, then the
|
|
117
|
+
* current date and the part this question brought. The call waits for that
|
|
118
|
+
* read for at most `contextTimeoutMs` (5 s by default), then goes on without
|
|
119
|
+
* it. After a call that ends the turn, the user message and the reply are
|
|
120
|
+
* stored as one memory (`remember`), and the call does not wait for that
|
|
121
|
+
* write. Neither step can fail the call: a failure or a timeout goes to
|
|
122
|
+
* `onError`, and the call goes on without the context or without the write.
|
|
123
|
+
*
|
|
124
|
+
* Create it per request, with the id of the user making it:
|
|
125
|
+
*
|
|
126
|
+
* const result = streamText({
|
|
127
|
+
* model: withKorelyMemory("anthropic/claude-sonnet-5.5", { userId, waitUntil }),
|
|
128
|
+
* messages,
|
|
129
|
+
* });
|
|
130
|
+
*
|
|
131
|
+
* A model already wrapped with `defaultInstructionsMiddleware` would lose
|
|
132
|
+
* its default instructions under this one: compose the two with
|
|
133
|
+
* `korelyMemoryMiddleware` instead.
|
|
134
|
+
*/
|
|
135
|
+
declare function withKorelyMemory(model: LanguageModel, options: KorelyMemoryOptions): ReturnType<typeof wrapLanguageModel>;
|
|
136
|
+
/**
|
|
137
|
+
* Two tools that let the model use the memory on its own initiative:
|
|
138
|
+
* `searchMemory` (what Korely knows that bears on a query: current facts
|
|
139
|
+
* first, then the memories, from `GET /v1/context`) and `addMemory` (store a
|
|
140
|
+
* statement, `POST /v1/memories`).
|
|
141
|
+
*
|
|
142
|
+
* The user, agent and run come from `options`, never from the model: the
|
|
143
|
+
* tools' inputs have no such field, so the model cannot choose whose memory
|
|
144
|
+
* it reads or writes. Create them per request, with the id of the user
|
|
145
|
+
* making it.
|
|
146
|
+
*
|
|
147
|
+
* searchMemory waits for the memory at most `contextTimeoutMs` (5 s by
|
|
148
|
+
* default), then tells the model the memory is unavailable right now, so a
|
|
149
|
+
* slow Korely cannot stall the agent; the answer that arrives later is
|
|
150
|
+
* dropped. Any other failure rejects, and the AI SDK hands the error to the
|
|
151
|
+
* model as the tool's result. Both reach `onError` (phase "search").
|
|
152
|
+
* addMemory rejects on failure, and the AI SDK hands the error to the model.
|
|
153
|
+
*/
|
|
154
|
+
declare function korelyTools(options: KorelyToolsOptions): KorelyTools;
|
|
155
|
+
|
|
156
|
+
export { type KorelyMemoryOptions, type KorelyPhase, type KorelyTools, type KorelyToolsOptions, korelyMemoryMiddleware, korelyTools, withKorelyMemory };
|