@alexein/sdk 0.3.3 → 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 +18 -0
- package/README.md +88 -5
- package/dist/ai-sdk.cjs +77 -0
- package/dist/ai-sdk.d.cts +42 -0
- package/dist/ai-sdk.d.ts +42 -0
- package/dist/ai-sdk.js +77 -0
- package/dist/{chunk-HDNKPJS2.js → chunk-C3LLPVOJ.js} +1 -1
- package/dist/chunk-DCKT6Y5B.cjs +378 -0
- package/dist/chunk-EGH35T3L.js +378 -0
- package/dist/{chunk-5YIOYX3J.js → chunk-NFVCTK7P.js} +7 -5
- package/dist/{chunk-LWBADF3F.cjs → chunk-NKBLBBGO.cjs} +4 -4
- package/dist/{chunk-34W2JJVD.cjs → chunk-WMDI4HIS.cjs} +8 -6
- package/dist/{client-Bz10lVYG.d.cts → client-76Fz2eLa.d.cts} +9 -4
- package/dist/{client-Bz10lVYG.d.ts → client-76Fz2eLa.d.ts} +9 -4
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/langgraph.cjs +15 -15
- package/dist/langgraph.d.cts +1 -1
- package/dist/langgraph.d.ts +1 -1
- package/dist/langgraph.js +2 -2
- package/dist/memory-2Gq9Fx9Z.d.cts +101 -0
- package/dist/memory-5OvV_41Q.d.ts +101 -0
- package/dist/openai-agents.cjs +18 -18
- package/dist/openai-agents.d.cts +1 -1
- package/dist/openai-agents.d.ts +1 -1
- package/dist/openai-agents.js +2 -2
- package/dist/wrap.cjs +318 -0
- package/dist/wrap.d.cts +59 -0
- package/dist/wrap.d.ts +59 -0
- package/dist/wrap.js +318 -0
- package/package.json +39 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
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
|
+
|
|
15
|
+
## 0.3.4 - 2026-11-24
|
|
16
|
+
|
|
17
|
+
- `memory.user(id)` takes what the API takes since 2026-11-23: the id your app already has (a UUID, an email,
|
|
18
|
+
`auth0|...`), up to 128 characters with no control character, no space at either end, ASCII only. Before:
|
|
19
|
+
1 to 35 letters, digits, `.`, `_` and `-`.
|
|
20
|
+
|
|
3
21
|
## 0.3.3 - 2026-11-20
|
|
4
22
|
|
|
5
23
|
The same version as `alexein` on PyPI, which has the same changes.
|
package/README.md
CHANGED
|
@@ -21,7 +21,13 @@ import { Memory } from "@alexein/sdk";
|
|
|
21
21
|
const memory = new Memory(); // reads ALEXEIN_API_KEY
|
|
22
22
|
const dana = memory.user("dana"); // your own id for one of your app users
|
|
23
23
|
|
|
24
|
-
await dana.add("I moved to Lisbon for the job at Acme.", {
|
|
24
|
+
await dana.add("I moved to Lisbon for the job at Acme.", {
|
|
25
|
+
id: "move", // sent again, it edits this item, never copies it
|
|
26
|
+
role: "user",
|
|
27
|
+
author: { name: "Dana", self: true }, // Dana's own words, and her name
|
|
28
|
+
session: "onboarding",
|
|
29
|
+
wait: true, // searchable once it returns
|
|
30
|
+
});
|
|
25
31
|
await dana.add(
|
|
26
32
|
{ id: "diet", kind: "note", text: "Vegetarian, allergic to peanuts." },
|
|
27
33
|
{ wait: true },
|
|
@@ -32,9 +38,10 @@ console.log(result.context()); // ready to paste into a prompt
|
|
|
32
38
|
```
|
|
33
39
|
|
|
34
40
|
Make a key in the console, under **API keys**. A key belongs to one project; each app user you name
|
|
35
|
-
with `memory.user(...)` has a memory of their own inside it. An app user id is
|
|
36
|
-
|
|
37
|
-
for any other, before a
|
|
41
|
+
with `memory.user(...)` has a memory of their own inside it. An app user id is the id your app
|
|
42
|
+
already has for them (a UUID, an email, `auth0|...`): up to 128 characters, no control characters,
|
|
43
|
+
no space at either end, ASCII only; `memory.user()` throws a `RangeError` for any other, before a
|
|
44
|
+
request is made.
|
|
38
45
|
|
|
39
46
|
## Settings
|
|
40
47
|
|
|
@@ -77,7 +84,10 @@ await dana.add("Vegetarian, allergic to peanuts.", { id: "diet", kind: "note" })
|
|
|
77
84
|
The item fields are `text` (required), `kind`, `id`, `session`, `role`, `author`, `title`, `about`,
|
|
78
85
|
`at`, `expires` and `metadata`. The same `id` again is an edit; as an option, `id` names the one item
|
|
79
86
|
added, and with several items it is a `RangeError`. `wait: true` answers once the items
|
|
80
|
-
are searchable
|
|
87
|
+
are searchable, so search straight after an add with `wait: true`. On what the app user says
|
|
88
|
+
themselves, pass `author: { name, self: true }`: memory then knows the words are theirs and what they
|
|
89
|
+
are called, so a question that names them ("Where does Dana live?") finds them. Without an author, a
|
|
90
|
+
message is kept as said by its `role`, not by anyone memory knows. `redact: true` replaces phone numbers, cards, keys and the like before memory keeps
|
|
81
91
|
them. More than 500 items go as several requests, each with an `Idempotency-Key` its retries send
|
|
82
92
|
again, so a retry never saves an item twice.
|
|
83
93
|
|
|
@@ -178,6 +188,79 @@ Memory being down should cost a reply its memory, not the reply. With
|
|
|
178
188
|
A wrong key or a wrong request (401, 403, 400, 422) still throws, and so does every other method.
|
|
179
189
|
Pair it with a short `timeout` where a reply cannot wait.
|
|
180
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
|
+
|
|
181
264
|
## LangGraph.js
|
|
182
265
|
|
|
183
266
|
```bash
|
package/dist/ai-sdk.cjs
ADDED
|
@@ -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 };
|
package/dist/ai-sdk.d.ts
ADDED
|
@@ -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
|
+
};
|