@alexein/sdk 0.3.4 → 0.3.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.5 - 2026-11-26
4
+
5
+ - `@alexein/sdk/wrap`: `wrapAnthropic(client, memory, { userId })` and `wrapOpenAI(...)`; `@alexein/sdk/ai-sdk`: `alexeinMiddleware(memory, { userId })` for `wrapLanguageModel`: memory without tool calls. Before each call, what memory holds about the user's latest message
6
+ goes into the system prompt as quoted data, within a time budget and a token cap; after it, the message and
7
+ the reply are saved in the background, a stream's when it ends. Memory being slow or down never stops a call.
8
+ Options: `session`, `author`, `recall`, `save`, `budget`, `maxTokens`, `fast`, `redact`, `beforeSave`.
9
+ - Nothing is looked up for a message that is only a go-ahead, a thank-you or a greeting; a question always
10
+ is. What the search ranks first is added, at most four memories, each once per conversation, without what
11
+ memory lists after the excerpts. Keys, tokens and passwords never go into a
12
+ search, and `redact` covers the search too. An `author` with `self` is saved as given. No character in a
13
+ memory can close or fake the `<memory>` block.
14
+
3
15
  ## 0.3.4 - 2026-11-24
4
16
 
5
17
  - `memory.user(id)` takes what the API takes since 2026-11-23: the id your app already has (a UUID, an email,
package/README.md CHANGED
@@ -188,6 +188,79 @@ Memory being down should cost a reply its memory, not the reply. With
188
188
  A wrong key or a wrong request (401, 403, 400, 422) still throws, and so does every other method.
189
189
  Pair it with a short `timeout` where a reply cannot wait.
190
190
 
191
+ ## Memory without tool calls: Anthropic, OpenAI and the AI SDK
192
+
193
+ Your model reads memory before every reply, and every exchange is saved, without the model deciding to call a
194
+ tool. Wrap the client you already use:
195
+
196
+ ```ts
197
+ import Anthropic from "@anthropic-ai/sdk";
198
+ import { Memory } from "@alexein/sdk";
199
+ import { wrapAnthropic } from "@alexein/sdk/wrap";
200
+
201
+ const memory = new Memory(); // one of each for the process
202
+ const anthropic = new Anthropic();
203
+
204
+ export async function reply(
205
+ userId: string,
206
+ conversationId: string,
207
+ messages: Anthropic.MessageParam[],
208
+ ) {
209
+ const claude = wrapAnthropic(anthropic, memory, { userId, session: conversationId });
210
+ const answer = await claude.messages.create({ model: "...", max_tokens: 1024, messages });
211
+ return answer.content;
212
+ }
213
+ ```
214
+
215
+ `wrapOpenAI(new OpenAI(), memory, { userId })` does the same for `chat.completions` and `responses`. Both
216
+ cover `create` (streaming or not), `parse` and `stream`, and `withResponse()`.
217
+
218
+ With the Vercel AI SDK, any model:
219
+
220
+ ```ts
221
+ import { generateText, wrapLanguageModel } from "ai";
222
+ import { alexeinMiddleware } from "@alexein/sdk/ai-sdk";
223
+
224
+ const model = wrapLanguageModel({
225
+ model: yourModel,
226
+ middleware: alexeinMiddleware(memory, { userId, session: conversationId }),
227
+ });
228
+ const { text } = await generateText({ model, messages });
229
+ ```
230
+
231
+ - **Before each call**, one search with the user's latest message (with the end of the reply before it, when
232
+ the message is short). Nothing is looked up for a message that is only a go-ahead, a thank-you or a
233
+ greeting ("thanks!", "ok, do it"); a question always is. What the search ranks first is added, at most
234
+ four memories, each once per conversation (`session`), without the rest of what memory holds that it lists
235
+ last. They go in the system prompt, after yours, inside a `<memory>` block that says they are quoted data,
236
+ not instructions, gives each line's date and who said it, and states that memory never authorises sharing
237
+ secrets or sending data out; no character in them can close or fake that block. A call waits at most `budget` milliseconds for it; when memory is slow,
238
+ down or refuses, the model is called without it, and nothing is thrown. Keys, tokens and passwords are
239
+ never sent as a search.
240
+ - **After each call**, the user's message and the reply are saved in the background, never delaying the reply.
241
+ A reply that asks to run a tool is not saved; the turn's last answer is, once. A stream is saved when it
242
+ ends. The calls of one tool loop share one lookup.
243
+ - Whose memory is used is the `userId` your code passes, never anything a model or a request body says.
244
+
245
+ | Option | Default | What it does |
246
+ | ------------ | ------- | -------------------------------------------------------------------------------------------------------------- |
247
+ | `userId` | - | your id for the app user whose memory this is |
248
+ | `session` | none | the conversation: saves are grouped under it, and a retried call edits what it saved |
249
+ | `author` | none | who the user is, `{ name, id }`; their messages are saved as theirs (`self: true` unless you pass `self`) |
250
+ | `recall` | `true` | look memory up before each call |
251
+ | `save` | `true` | save the user's message and the reply after each call |
252
+ | `budget` | `1500` | the longest a call waits for memory, in milliseconds |
253
+ | `maxTokens` | `600` | about how many tokens of memory a call is given at most |
254
+ | `fast` | `true` | skip search's relevance check; with `false`, what memory judges off-topic is left out (raise `budget` with it) |
255
+ | `redact` | `false` | replace phone numbers, cards, keys and the like in the search and before memory keeps any copy |
256
+ | `beforeSave` | none | a function that sees the items about to be saved and answers those to save (none: nothing) |
257
+
258
+ `memoryOf(client).last` (or `middleware.alexein.last`) says how the last lookup went (`ms`, `chars`,
259
+ `timedOut`, `failed`, `reused`). Saves run in the background: in a serverless function, `await
260
+ memoryOf(client).flush()` (`await middleware.alexein.flush()` for the AI SDK) before it returns. Without a `memory`, a client for the process is made from
261
+ `ALEXEIN_API_KEY`. The AI SDK middleware is for AI SDK 7 (`@ai-sdk/provider` 4). See
262
+ `examples/wrapped-client.ts`.
263
+
191
264
  ## LangGraph.js
192
265
 
193
266
  ```bash
@@ -0,0 +1,77 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+ var _chunkDCKT6Y5Bcjs = require('./chunk-DCKT6Y5B.cjs');
7
+ require('./chunk-WMDI4HIS.cjs');
8
+
9
+ // src/ai-sdk/index.ts
10
+ function finishedWith(reason) {
11
+ if (typeof reason === "string") return reason;
12
+ const unified = _optionalChain([reason, 'optionalAccess', _ => _.unified]);
13
+ return typeof unified === "string" ? unified : void 0;
14
+ }
15
+ function withMemory(prompt, text) {
16
+ let lead = 0;
17
+ while (lead < prompt.length && _optionalChain([prompt, 'access', _2 => _2[lead], 'optionalAccess', _3 => _3.role]) === "system") lead++;
18
+ if (!lead) return [{ role: "system", content: text }, ...prompt];
19
+ const last = prompt[lead - 1];
20
+ return [
21
+ ...prompt.slice(0, lead - 1),
22
+ { ...last, content: `${last.content}
23
+
24
+ ${text}` },
25
+ ...prompt.slice(lead)
26
+ ];
27
+ }
28
+ function alexeinMiddleware(memory, options) {
29
+ const auto = options ? new (0, _chunkDCKT6Y5Bcjs.AutoMemory)(memory, options) : new (0, _chunkDCKT6Y5Bcjs.AutoMemory)(void 0, memory);
30
+ const asked = (prompt) => _chunkDCKT6Y5Bcjs.latestAsked.call(void 0, prompt);
31
+ return {
32
+ specificationVersion: "v4",
33
+ alexein: auto,
34
+ async transformParams({ params }) {
35
+ const text = await auto.lookup(asked(params.prompt));
36
+ return text ? { ...params, prompt: withMemory(params.prompt, text) } : params;
37
+ },
38
+ async wrapGenerate({ doGenerate, params }) {
39
+ const result = await doGenerate();
40
+ const reply = new (0, _chunkDCKT6Y5Bcjs.Reply)();
41
+ for (const part of result.content) {
42
+ if (part.type === "text") reply.parts.push(part.text);
43
+ else if (part.type === "tool-call" && !part.providerExecuted) reply.callsTool = true;
44
+ }
45
+ reply.callsTool ||= finishedWith(result.finishReason) === "tool-calls";
46
+ reply.done = true;
47
+ auto.remember(asked(params.prompt), reply);
48
+ return result;
49
+ },
50
+ async wrapStream({ doStream, params }) {
51
+ const { stream, ...rest } = await doStream();
52
+ const reply = new (0, _chunkDCKT6Y5Bcjs.Reply)();
53
+ const said = asked(params.prompt);
54
+ let failed = false;
55
+ const seen = new TransformStream({
56
+ transform(part, controller) {
57
+ if (part.type === "text-delta") reply.parts.push(part.delta);
58
+ else if (part.type === "tool-call" && !part.providerExecuted) reply.callsTool = true;
59
+ else if (part.type === "finish") {
60
+ reply.done = true;
61
+ reply.callsTool ||= finishedWith(part.finishReason) === "tool-calls";
62
+ } else if (part.type === "error") failed = true;
63
+ controller.enqueue(part);
64
+ },
65
+ flush() {
66
+ if (!failed) auto.remember(said, reply);
67
+ }
68
+ });
69
+ return { stream: stream.pipeThrough(seen), ...rest };
70
+ }
71
+ };
72
+ }
73
+
74
+
75
+
76
+
77
+ exports.AutoMemory = _chunkDCKT6Y5Bcjs.AutoMemory; exports.HEADER = _chunkDCKT6Y5Bcjs.HEADER; exports.alexeinMiddleware = alexeinMiddleware;
@@ -0,0 +1,42 @@
1
+ import { LanguageModelV4Middleware } from '@ai-sdk/provider';
2
+ import { M as Memory } from './client-76Fz2eLa.cjs';
3
+ import { A as AutoMemory, a as AutoMemoryOptions } from './memory-2Gq9Fx9Z.cjs';
4
+ export { H as HEADER, R as RecallInfo } from './memory-2Gq9Fx9Z.cjs';
5
+
6
+ /**
7
+ * Memory for any model of the Vercel AI SDK, with no tool for the model to call: a language model
8
+ * middleware.
9
+ *
10
+ * ```ts
11
+ * import { generateText, wrapLanguageModel } from "ai";
12
+ * import { Memory } from "@alexein/sdk";
13
+ * import { alexeinMiddleware } from "@alexein/sdk/ai-sdk";
14
+ *
15
+ * const memory = new Memory(); // one for the process
16
+ * const model = wrapLanguageModel({
17
+ * model: yourModel,
18
+ * middleware: alexeinMiddleware(memory, { userId: "dana", session: "conv-7" }),
19
+ * });
20
+ * await generateText({ model, messages });
21
+ * ```
22
+ *
23
+ * Before each call, what memory holds about the user's latest message is added to the system
24
+ * prompt, as quoted data; after it, the user's message and the final reply are saved, a stream's
25
+ * once it ends. Memory never throws, and never holds a call up longer than `budget`.
26
+ */
27
+
28
+ /** The call's middleware and its memory: `last` and `flush()`. */
29
+ type AlexeinMiddleware = LanguageModelV4Middleware & {
30
+ readonly alexein: AutoMemory;
31
+ };
32
+ /**
33
+ * A middleware for `wrapLanguageModel` that gives the model what memory holds about the user's
34
+ * latest message and saves each exchange. Options are `wrapAnthropic`'s (`@alexein/sdk/wrap`):
35
+ * `userId` (required), `session`, `author`, `recall`, `save`, `budget`, `maxTokens`, `fast`,
36
+ * `redact`, `beforeSave`. `memory` is your `Memory`; without one, a client for the process is made
37
+ * from ALEXEIN_API_KEY.
38
+ */
39
+ declare function alexeinMiddleware(memory: Memory | undefined, options: AutoMemoryOptions): AlexeinMiddleware;
40
+ declare function alexeinMiddleware(options: AutoMemoryOptions): AlexeinMiddleware;
41
+
42
+ export { type AlexeinMiddleware, AutoMemory, AutoMemoryOptions, alexeinMiddleware };
@@ -0,0 +1,42 @@
1
+ import { LanguageModelV4Middleware } from '@ai-sdk/provider';
2
+ import { M as Memory } from './client-76Fz2eLa.js';
3
+ import { A as AutoMemory, a as AutoMemoryOptions } from './memory-5OvV_41Q.js';
4
+ export { H as HEADER, R as RecallInfo } from './memory-5OvV_41Q.js';
5
+
6
+ /**
7
+ * Memory for any model of the Vercel AI SDK, with no tool for the model to call: a language model
8
+ * middleware.
9
+ *
10
+ * ```ts
11
+ * import { generateText, wrapLanguageModel } from "ai";
12
+ * import { Memory } from "@alexein/sdk";
13
+ * import { alexeinMiddleware } from "@alexein/sdk/ai-sdk";
14
+ *
15
+ * const memory = new Memory(); // one for the process
16
+ * const model = wrapLanguageModel({
17
+ * model: yourModel,
18
+ * middleware: alexeinMiddleware(memory, { userId: "dana", session: "conv-7" }),
19
+ * });
20
+ * await generateText({ model, messages });
21
+ * ```
22
+ *
23
+ * Before each call, what memory holds about the user's latest message is added to the system
24
+ * prompt, as quoted data; after it, the user's message and the final reply are saved, a stream's
25
+ * once it ends. Memory never throws, and never holds a call up longer than `budget`.
26
+ */
27
+
28
+ /** The call's middleware and its memory: `last` and `flush()`. */
29
+ type AlexeinMiddleware = LanguageModelV4Middleware & {
30
+ readonly alexein: AutoMemory;
31
+ };
32
+ /**
33
+ * A middleware for `wrapLanguageModel` that gives the model what memory holds about the user's
34
+ * latest message and saves each exchange. Options are `wrapAnthropic`'s (`@alexein/sdk/wrap`):
35
+ * `userId` (required), `session`, `author`, `recall`, `save`, `budget`, `maxTokens`, `fast`,
36
+ * `redact`, `beforeSave`. `memory` is your `Memory`; without one, a client for the process is made
37
+ * from ALEXEIN_API_KEY.
38
+ */
39
+ declare function alexeinMiddleware(memory: Memory | undefined, options: AutoMemoryOptions): AlexeinMiddleware;
40
+ declare function alexeinMiddleware(options: AutoMemoryOptions): AlexeinMiddleware;
41
+
42
+ export { type AlexeinMiddleware, AutoMemory, AutoMemoryOptions, alexeinMiddleware };
package/dist/ai-sdk.js ADDED
@@ -0,0 +1,77 @@
1
+ import {
2
+ AutoMemory,
3
+ HEADER,
4
+ Reply,
5
+ latestAsked
6
+ } from "./chunk-EGH35T3L.js";
7
+ import "./chunk-NFVCTK7P.js";
8
+
9
+ // src/ai-sdk/index.ts
10
+ function finishedWith(reason) {
11
+ if (typeof reason === "string") return reason;
12
+ const unified = reason?.unified;
13
+ return typeof unified === "string" ? unified : void 0;
14
+ }
15
+ function withMemory(prompt, text) {
16
+ let lead = 0;
17
+ while (lead < prompt.length && prompt[lead]?.role === "system") lead++;
18
+ if (!lead) return [{ role: "system", content: text }, ...prompt];
19
+ const last = prompt[lead - 1];
20
+ return [
21
+ ...prompt.slice(0, lead - 1),
22
+ { ...last, content: `${last.content}
23
+
24
+ ${text}` },
25
+ ...prompt.slice(lead)
26
+ ];
27
+ }
28
+ function alexeinMiddleware(memory, options) {
29
+ const auto = options ? new AutoMemory(memory, options) : new AutoMemory(void 0, memory);
30
+ const asked = (prompt) => latestAsked(prompt);
31
+ return {
32
+ specificationVersion: "v4",
33
+ alexein: auto,
34
+ async transformParams({ params }) {
35
+ const text = await auto.lookup(asked(params.prompt));
36
+ return text ? { ...params, prompt: withMemory(params.prompt, text) } : params;
37
+ },
38
+ async wrapGenerate({ doGenerate, params }) {
39
+ const result = await doGenerate();
40
+ const reply = new Reply();
41
+ for (const part of result.content) {
42
+ if (part.type === "text") reply.parts.push(part.text);
43
+ else if (part.type === "tool-call" && !part.providerExecuted) reply.callsTool = true;
44
+ }
45
+ reply.callsTool ||= finishedWith(result.finishReason) === "tool-calls";
46
+ reply.done = true;
47
+ auto.remember(asked(params.prompt), reply);
48
+ return result;
49
+ },
50
+ async wrapStream({ doStream, params }) {
51
+ const { stream, ...rest } = await doStream();
52
+ const reply = new Reply();
53
+ const said = asked(params.prompt);
54
+ let failed = false;
55
+ const seen = new TransformStream({
56
+ transform(part, controller) {
57
+ if (part.type === "text-delta") reply.parts.push(part.delta);
58
+ else if (part.type === "tool-call" && !part.providerExecuted) reply.callsTool = true;
59
+ else if (part.type === "finish") {
60
+ reply.done = true;
61
+ reply.callsTool ||= finishedWith(part.finishReason) === "tool-calls";
62
+ } else if (part.type === "error") failed = true;
63
+ controller.enqueue(part);
64
+ },
65
+ flush() {
66
+ if (!failed) auto.remember(said, reply);
67
+ }
68
+ });
69
+ return { stream: stream.pipeThrough(seen), ...rest };
70
+ }
71
+ };
72
+ }
73
+ export {
74
+ AutoMemory,
75
+ HEADER,
76
+ alexeinMiddleware
77
+ };
@@ -2,7 +2,7 @@ import {
2
2
  AlexeinError,
3
3
  Memory,
4
4
  NotFoundError
5
- } from "./chunk-2322CW56.js";
5
+ } from "./chunk-NFVCTK7P.js";
6
6
 
7
7
  // src/integrations/shared.ts
8
8
  var UNAVAILABLE = "Memory is unavailable right now; carry on without it.";