@midsummer-ai/sdk 0.1.0-staging.3728 → 0.1.0-staging.3731
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/ai/contract.mjs +1 -1
- package/ai/index.d.mts +3 -2
- package/ai/index.mjs +1 -262
- package/ai/stand-in.mjs +1 -62
- package/ai-2Llbc56l.mjs +328 -0
- package/apps.d.mts +0 -15
- package/apps.mjs +19 -2
- package/auth/contract.d.mts +2 -2
- package/auth/contract.mjs +1 -1
- package/auth/index.d.mts +2 -2
- package/auth/index.mjs +1 -1
- package/auth/mail.mjs +2 -2
- package/auth/password.mjs +1 -1
- package/auth/react.d.mts +7 -2
- package/auth/react.mjs +44 -8
- package/auth/stand-in.d.mts +1 -1
- package/{auth-BA5Xdi-4.mjs → auth-BaGXVRYd.mjs} +38 -8
- package/billing/index.mjs +1 -1
- package/client-_Al5bpqX.mjs +877 -0
- package/{client-D3BZs3LA.d.mts → client-oAVg6vn_.d.mts} +64 -20
- package/client.mjs +1 -1
- package/contract.mjs +1 -1
- package/database/client.d.mts +2 -2
- package/database/client.mjs +2 -711
- package/database/react.d.mts +1 -1
- package/database/stand-in.mjs +1 -1
- package/email/client.mjs +1 -1
- package/email/contract.mjs +1 -1
- package/email/inbox.mjs +1 -1
- package/email/index.mjs +1 -1
- package/email/smtp.mjs +1 -1
- package/email/stand-in.mjs +1 -1
- package/{email-ynNo0HqT.mjs → email-DmWG_Ug-.mjs} +16 -2
- package/{engine-DDPJ2CET.mjs → engine-BmiPioJ2.mjs} +13 -2
- package/{here-1plIxb0D.mjs → here-BKjizr_N.mjs} +9 -1
- package/{index-C2Jo3JqT.d.mts → index-C8Ti5raa.d.mts} +2 -2
- package/index.mjs +1 -1
- package/package.json +1 -1
- package/{qr-CBh0LP2_.mjs → qr-Br1sOBmT.mjs} +1 -0
- package/queues/index.mjs +1 -1
- package/s3.mjs +1 -1
- package/socket.mjs +1 -1
- package/{src-BKKy9km-.mjs → src-DgX-tCDn.mjs} +2 -2
- package/storage/files.d.mts +1 -1
- package/storage/files.mjs +2 -2
- package/{store-CLGBhEpO.d.mts → store-Bx4dOx66.d.mts} +1 -1
- package/vector/index.mjs +1 -1
package/ai/contract.mjs
CHANGED
package/ai/index.d.mts
CHANGED
|
@@ -15,8 +15,9 @@
|
|
|
15
15
|
* (`responseFormat`), send images in a user message, set a reasoning effort, and name `fallback`
|
|
16
16
|
* Models asked in turn when one can't answer; `model` in what it spent is the one that replied.
|
|
17
17
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
18
|
+
* Under `midsummer dev` it returns the Stand-in's reply, an echo of the question, unless given an engine. Given an engine,
|
|
19
|
+
* calls go there instead: the Stand-in (`@midsummer-ai/sdk/ai/stand-in`) in tests, or, from code outside Midsummer,
|
|
20
|
+
* the platform with an AI key (`ai(aiClient(origin, { key }))`). Every engine is held to the cases in `@midsummer-ai/sdk/ai/contract`.
|
|
20
21
|
* A Model is named as `midsummer ai model list` lists it; leaving it out picks the default.
|
|
21
22
|
*
|
|
22
23
|
* Every failure is an `AiError`; its `code` tells you which kind: `invalid` (no such Model, nothing
|
package/ai/index.mjs
CHANGED
|
@@ -1,263 +1,2 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
//#region src/ai/index.ts
|
|
3
|
-
/**
|
|
4
|
-
* AI: Model calls from a Project's code, streamed or whole, each with the tokens and credits it spent.
|
|
5
|
-
* In a deployment, in any framework, `ai()` calls the team's AI Gateway with no key:
|
|
6
|
-
*
|
|
7
|
-
* import { ai } from "@midsummer-ai/sdk/ai"
|
|
8
|
-
*
|
|
9
|
-
* const models = ai()
|
|
10
|
-
* const answer = await models.complete({ prompt: "Name three rivers" })
|
|
11
|
-
* const stream = models.stream({ model: "claude-sonnet-5-5", messages: [{ role: "user", content: "Hi" }] })
|
|
12
|
-
* for await (const text of stream) write(text)
|
|
13
|
-
* const { credits } = await stream.done
|
|
14
|
-
*
|
|
15
|
-
* A call can pass tools (its calls come back as `toolCalls`), ask for JSON to a schema
|
|
16
|
-
* (`responseFormat`), send images in a user message, set a reasoning effort, and name `fallback`
|
|
17
|
-
* Models asked in turn when one can't answer; `model` in what it spent is the one that replied.
|
|
18
|
-
*
|
|
19
|
-
* Given an engine, calls go there instead: the Stand-in (`@midsummer-ai/sdk/ai/stand-in`) in tests, or,
|
|
20
|
-
* from code outside Midsummer, the platform with an AI key (`ai(aiClient(origin, { key }))`). Every engine is held to the cases in `@midsummer-ai/sdk/ai/contract`.
|
|
21
|
-
* A Model is named as `midsummer ai model list` lists it; leaving it out picks the default.
|
|
22
|
-
*
|
|
23
|
-
* Every failure is an `AiError`; its `code` tells you which kind: `invalid` (no such Model, nothing
|
|
24
|
-
* asked), `forbidden` (the key is not valid), `quota` (the Team's usage is holding back its calls),
|
|
25
|
-
* `conflict` (a retry by `idempotencyKey` of a call still under way) or `unavailable` (try again).
|
|
26
|
-
*/
|
|
27
|
-
var AiError = class extends Error {
|
|
28
|
-
code;
|
|
29
|
-
constructor(code, why) {
|
|
30
|
-
super(why);
|
|
31
|
-
this.code = code;
|
|
32
|
-
this.name = "AiError";
|
|
33
|
-
}
|
|
34
|
-
};
|
|
35
|
-
/** Tool call pieces, added up into whole calls in order. */
|
|
36
|
-
function toolCalls() {
|
|
37
|
-
const calls = /* @__PURE__ */ new Map();
|
|
38
|
-
return {
|
|
39
|
-
add({ index, id, name, arguments: more }) {
|
|
40
|
-
const made = calls.get(index) ?? {
|
|
41
|
-
id: "",
|
|
42
|
-
name: "",
|
|
43
|
-
arguments: ""
|
|
44
|
-
};
|
|
45
|
-
calls.set(index, {
|
|
46
|
-
id: id ?? made.id,
|
|
47
|
-
name: name ?? made.name,
|
|
48
|
-
arguments: made.arguments + more
|
|
49
|
-
});
|
|
50
|
-
},
|
|
51
|
-
whole: () => calls.size ? { toolCalls: [...calls.entries()].sort(([a], [b]) => a - b).map(([, made]) => made) } : {}
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
/**
|
|
55
|
-
* Checks a question's shape before it leaves the caller. Its parameters' ranges are the AI Gateway's to check, against
|
|
56
|
-
* the Models asked, so its errors are the only ones that name them.
|
|
57
|
-
*/
|
|
58
|
-
function checked(input) {
|
|
59
|
-
if (Boolean(input.prompt) === Boolean(input.messages)) throw new AiError("invalid", "Give a prompt or messages.");
|
|
60
|
-
if (input.messages && !input.messages.length) throw new AiError("invalid", "Give at least one message.");
|
|
61
|
-
if ((input.fallback?.length ?? 0) > 3) throw new AiError("invalid", "Name at most 3 fallback models.");
|
|
62
|
-
return input;
|
|
63
|
-
}
|
|
64
|
-
function ai(given) {
|
|
65
|
-
const engine = given ?? late(() => {
|
|
66
|
-
const handle = here()?.ai;
|
|
67
|
-
if (handle) return boundAi(handle);
|
|
68
|
-
throw new AiError("forbidden", "This code runs outside a deployment, so it calls models with an AI key: ai(aiClient(origin, { key })).");
|
|
69
|
-
});
|
|
70
|
-
return {
|
|
71
|
-
async complete(input) {
|
|
72
|
-
let text = "";
|
|
73
|
-
const calls = toolCalls();
|
|
74
|
-
for await (const event of engine.ask(checked(input))) if ("text" in event) text += event.text;
|
|
75
|
-
else if ("toolCall" in event) calls.add(event.toolCall);
|
|
76
|
-
else return {
|
|
77
|
-
...event.done,
|
|
78
|
-
text,
|
|
79
|
-
...calls.whole()
|
|
80
|
-
};
|
|
81
|
-
throw new AiError("unavailable", "The answer ended early. Try again.");
|
|
82
|
-
},
|
|
83
|
-
stream(input) {
|
|
84
|
-
let settle, fail;
|
|
85
|
-
const done = new Promise((resolve, reject) => {
|
|
86
|
-
settle = resolve;
|
|
87
|
-
fail = reject;
|
|
88
|
-
});
|
|
89
|
-
done.catch(() => void 0);
|
|
90
|
-
let asked;
|
|
91
|
-
try {
|
|
92
|
-
asked = checked(input);
|
|
93
|
-
} catch (error) {
|
|
94
|
-
fail(error);
|
|
95
|
-
return {
|
|
96
|
-
done,
|
|
97
|
-
[Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) })
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
async function* texts() {
|
|
101
|
-
try {
|
|
102
|
-
const calls = toolCalls();
|
|
103
|
-
for await (const event of engine.ask(asked)) if ("text" in event) yield event.text;
|
|
104
|
-
else if ("toolCall" in event) calls.add(event.toolCall);
|
|
105
|
-
else return settle({
|
|
106
|
-
...event.done,
|
|
107
|
-
...calls.whole()
|
|
108
|
-
});
|
|
109
|
-
throw new AiError("unavailable", "The answer ended early. Try again.");
|
|
110
|
-
} catch (error) {
|
|
111
|
-
fail(error);
|
|
112
|
-
throw error;
|
|
113
|
-
} finally {
|
|
114
|
-
fail(new AiError("unavailable", "The answer was not read to its end."));
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
return {
|
|
118
|
-
done,
|
|
119
|
-
[Symbol.asyncIterator]: texts
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
};
|
|
123
|
-
}
|
|
124
|
-
/** One line of the wire, checked whole: a piece of text, what the call spent, or why it stopped. Anything else is a broken answer. */
|
|
125
|
-
function parsed(line) {
|
|
126
|
-
const broken = () => new AiError("unavailable", "The answer could not be read. Try again.");
|
|
127
|
-
let event;
|
|
128
|
-
try {
|
|
129
|
-
event = JSON.parse(line);
|
|
130
|
-
} catch {
|
|
131
|
-
throw broken();
|
|
132
|
-
}
|
|
133
|
-
const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
134
|
-
const count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
135
|
-
if (!object(event)) throw broken();
|
|
136
|
-
if (typeof event.text === "string") return { text: event.text };
|
|
137
|
-
const call = event.toolCall;
|
|
138
|
-
if (object(call)) {
|
|
139
|
-
if (!count(call.index) || typeof call.arguments !== "string" || call.id !== void 0 && typeof call.id !== "string" || call.name !== void 0 && typeof call.name !== "string") throw broken();
|
|
140
|
-
return { toolCall: {
|
|
141
|
-
index: call.index,
|
|
142
|
-
...typeof call.id === "string" ? { id: call.id } : {},
|
|
143
|
-
...typeof call.name === "string" ? { name: call.name } : {},
|
|
144
|
-
arguments: call.arguments
|
|
145
|
-
} };
|
|
146
|
-
}
|
|
147
|
-
const done = event.done;
|
|
148
|
-
if (object(done)) {
|
|
149
|
-
if (typeof done.model !== "string" || !count(done.inputTokens) || !count(done.outputTokens) || typeof done.credits !== "number" || !(done.credits >= 0) || typeof done.catalogue !== "string" || done.cachedTokens !== void 0 && !count(done.cachedTokens)) throw broken();
|
|
150
|
-
return { done: {
|
|
151
|
-
model: done.model,
|
|
152
|
-
inputTokens: done.inputTokens,
|
|
153
|
-
...done.cachedTokens ? { cachedTokens: done.cachedTokens } : {},
|
|
154
|
-
outputTokens: done.outputTokens,
|
|
155
|
-
credits: done.credits,
|
|
156
|
-
catalogue: done.catalogue
|
|
157
|
-
} };
|
|
158
|
-
}
|
|
159
|
-
const error = event.error;
|
|
160
|
-
if (object(error) && (error.code === void 0 || typeof error.code === "string") && (error.message === void 0 || typeof error.message === "string")) return { error: {
|
|
161
|
-
...typeof error.code === "string" ? { code: error.code } : {},
|
|
162
|
-
...typeof error.message === "string" ? { message: error.message } : {}
|
|
163
|
-
} };
|
|
164
|
-
throw broken();
|
|
165
|
-
}
|
|
166
|
-
const CODES = {
|
|
167
|
-
400: "invalid",
|
|
168
|
-
401: "forbidden",
|
|
169
|
-
403: "forbidden",
|
|
170
|
-
409: "conflict",
|
|
171
|
-
429: "quota"
|
|
172
|
-
};
|
|
173
|
-
const CODE_NAMES = [
|
|
174
|
-
"invalid",
|
|
175
|
-
"forbidden",
|
|
176
|
-
"quota",
|
|
177
|
-
"conflict",
|
|
178
|
-
"unavailable"
|
|
179
|
-
];
|
|
180
|
-
/**
|
|
181
|
-
* The platform's AI Gateway at `origin` (the API's), for the AI key `key`: each call is one POST to
|
|
182
|
-
* `<origin>/v1/ai/ask`, which replies with newline-delimited JSON events as the Model writes.
|
|
183
|
-
*/
|
|
184
|
-
function aiClient(origin, options) {
|
|
185
|
-
const url = `${origin.replace(/\/+$/, "")}/v1/ai/ask`;
|
|
186
|
-
const send = options.fetch ?? ((input, init) => fetch(input, init));
|
|
187
|
-
return { async *ask(input) {
|
|
188
|
-
const leave = new AbortController();
|
|
189
|
-
let response;
|
|
190
|
-
try {
|
|
191
|
-
response = await send(url, {
|
|
192
|
-
method: "POST",
|
|
193
|
-
signal: leave.signal,
|
|
194
|
-
headers: { "Content-Type": "application/json" },
|
|
195
|
-
body: JSON.stringify({
|
|
196
|
-
...input,
|
|
197
|
-
key: options.key,
|
|
198
|
-
stream: true
|
|
199
|
-
})
|
|
200
|
-
});
|
|
201
|
-
} catch {
|
|
202
|
-
throw new AiError("unavailable", "The AI Gateway could not be reached. Try again.");
|
|
203
|
-
}
|
|
204
|
-
if (!response.ok || !response.body) {
|
|
205
|
-
const why = await response.json().then((body) => typeof body.error === "string" ? body.error : void 0, () => void 0);
|
|
206
|
-
throw new AiError(CODES[response.status] ?? "unavailable", why ?? `The AI Gateway returned ${response.status}.`);
|
|
207
|
-
}
|
|
208
|
-
try {
|
|
209
|
-
yield* eventsOf(response.body);
|
|
210
|
-
} finally {
|
|
211
|
-
leave.abort();
|
|
212
|
-
}
|
|
213
|
-
} };
|
|
214
|
-
}
|
|
215
|
-
/** The events of one call's newline-delimited JSON, as the AI Gateway streams them; cancelled when the reader leaves. */
|
|
216
|
-
async function* eventsOf(body) {
|
|
217
|
-
const decoder = new TextDecoder();
|
|
218
|
-
let pending = "";
|
|
219
|
-
const reader = body.getReader();
|
|
220
|
-
try {
|
|
221
|
-
while (true) {
|
|
222
|
-
let read;
|
|
223
|
-
try {
|
|
224
|
-
read = await reader.read();
|
|
225
|
-
} catch {
|
|
226
|
-
throw new AiError("unavailable", "The answer was cut off. Try again.");
|
|
227
|
-
}
|
|
228
|
-
pending += read.done ? decoder.decode() : decoder.decode(read.value, { stream: true });
|
|
229
|
-
let end;
|
|
230
|
-
while ((end = pending.indexOf("\n")) >= 0) {
|
|
231
|
-
const line = pending.slice(0, end).trim();
|
|
232
|
-
pending = pending.slice(end + 1);
|
|
233
|
-
if (!line) continue;
|
|
234
|
-
const event = parsed(line);
|
|
235
|
-
if ("error" in event) throw new AiError(event.error.code && CODE_NAMES.includes(event.error.code) ? event.error.code : "unavailable", event.error.message ?? "The model could not answer. Try again.");
|
|
236
|
-
yield event;
|
|
237
|
-
if ("done" in event) return;
|
|
238
|
-
}
|
|
239
|
-
if (read.done) throw new AiError("unavailable", "The answer ended early. Try again.");
|
|
240
|
-
}
|
|
241
|
-
} finally {
|
|
242
|
-
await reader.cancel().catch(() => void 0);
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
/**
|
|
246
|
-
* What Midsummer hands a Deployment as `context.ai`: the Team's AI Gateway, with no key. Each call
|
|
247
|
-
* streams the events `aiClient` reads.
|
|
248
|
-
*
|
|
249
|
-
* const answer = await ai(boundAi(context.ai)).complete({ prompt: "Hello" })
|
|
250
|
-
*/
|
|
251
|
-
function boundAi(handle) {
|
|
252
|
-
return { async *ask(input) {
|
|
253
|
-
let body;
|
|
254
|
-
try {
|
|
255
|
-
body = await handle.ask(input);
|
|
256
|
-
} catch (error) {
|
|
257
|
-
throw new AiError("unavailable", error instanceof Error ? error.message : "The AI Gateway could not be reached. Try again.");
|
|
258
|
-
}
|
|
259
|
-
yield* eventsOf(body);
|
|
260
|
-
} };
|
|
261
|
-
}
|
|
262
|
-
//#endregion
|
|
1
|
+
import { i as boundAi, n as ai, r as aiClient, t as AiError } from "../ai-2Llbc56l.mjs";
|
|
263
2
|
export { AiError, ai, aiClient, boundAi };
|
package/ai/stand-in.mjs
CHANGED
|
@@ -1,63 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
//#region src/ai/stand-in.ts
|
|
3
|
-
/**
|
|
4
|
-
* AI's Stand-in: Model calls replied to on this computer, for `midsummer dev` and tests, with no
|
|
5
|
-
* Model behind them. It passes the contract (`@midsummer-ai/sdk/ai/contract`); its replies are only
|
|
6
|
-
* an echo of the question, so code can be run end to end without spending credits.
|
|
7
|
-
*
|
|
8
|
-
* const models = ai(aiStandIn())
|
|
9
|
-
* await models.complete({ prompt: "Hi" }) // { text: "You asked: Hi", model: "stand-in", credits: 0, … }
|
|
10
|
-
*
|
|
11
|
-
* It offers the Models it is given (`stand-in` unless told), the first the default. Tokens are
|
|
12
|
-
* counted at about four characters a token, and cost nothing. Made to call a tool (`toolChoice`
|
|
13
|
-
* `required` or a name), it calls it with no arguments; a fallback is never needed.
|
|
14
|
-
*/
|
|
15
|
-
/** A message's text, without its images. */
|
|
16
|
-
const textOf = (content) => typeof content === "string" ? content : content.map((part) => part.type === "text" ? part.text : "").join("");
|
|
17
|
-
function aiStandIn(options = {}) {
|
|
18
|
-
const models = options.models?.length ? options.models : ["stand-in"];
|
|
19
|
-
const tokens = (text) => Math.ceil(text.length / 4);
|
|
20
|
-
return { async *ask(input) {
|
|
21
|
-
const model = input.model ?? models[0];
|
|
22
|
-
if (!models.includes(model)) throw new AiError("invalid", `There is no model ${model}.`);
|
|
23
|
-
const messages = [...input.system ? [{
|
|
24
|
-
role: "system",
|
|
25
|
-
content: input.system
|
|
26
|
-
}] : [], ...input.messages ?? [{
|
|
27
|
-
role: "user",
|
|
28
|
-
content: input.prompt ?? ""
|
|
29
|
-
}]];
|
|
30
|
-
const last = messages.filter((message) => message.role !== "system").at(-1);
|
|
31
|
-
if (!(last?.role === "tool" || last?.role === "user" && textOf(last.content).trim())) throw new AiError("invalid", "End with a user message that asks something, or with the results of the tools the model called.");
|
|
32
|
-
const inputTokens = tokens(messages.map((message) => textOf(message.content)).join(""));
|
|
33
|
-
const tool = typeof input.toolChoice === "object" ? input.toolChoice.name : input.toolChoice === "required" ? input.tools?.[0]?.name : void 0;
|
|
34
|
-
if (tool && last.role === "user") {
|
|
35
|
-
if (!input.tools?.some((given) => given.name === tool)) throw new AiError("invalid", `toolChoice names ${tool}, which isn't one of the tools given.`);
|
|
36
|
-
yield { toolCall: {
|
|
37
|
-
index: 0,
|
|
38
|
-
id: "call_stand_in_1",
|
|
39
|
-
name: tool,
|
|
40
|
-
arguments: "{}"
|
|
41
|
-
} };
|
|
42
|
-
yield { done: {
|
|
43
|
-
model,
|
|
44
|
-
inputTokens,
|
|
45
|
-
outputTokens: 1,
|
|
46
|
-
credits: 0,
|
|
47
|
-
catalogue: "stand-in"
|
|
48
|
-
} };
|
|
49
|
-
return;
|
|
50
|
-
}
|
|
51
|
-
const answer = `You asked: ${textOf(last.content)}`.slice(0, (input.maxTokens ?? 1024) * 4);
|
|
52
|
-
for (const piece of answer.match(/\S+\s*/g) ?? []) yield { text: piece };
|
|
53
|
-
yield { done: {
|
|
54
|
-
model,
|
|
55
|
-
inputTokens,
|
|
56
|
-
outputTokens: tokens(answer),
|
|
57
|
-
credits: 0,
|
|
58
|
-
catalogue: "stand-in"
|
|
59
|
-
} };
|
|
60
|
-
} };
|
|
61
|
-
}
|
|
62
|
-
//#endregion
|
|
1
|
+
import { a as aiStandIn } from "../ai-2Llbc56l.mjs";
|
|
63
2
|
export { aiStandIn };
|
package/ai-2Llbc56l.mjs
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { i as processEnv, n as late, t as here } from "./here-BKjizr_N.mjs";
|
|
2
|
+
//#region src/ai/stand-in.ts
|
|
3
|
+
/**
|
|
4
|
+
* AI's Stand-in: Model calls replied to on this computer, for `midsummer dev` and tests, with no
|
|
5
|
+
* Model behind them. It passes the contract (`@midsummer-ai/sdk/ai/contract`); its replies are only
|
|
6
|
+
* an echo of the question, so code can be run end to end without spending credits.
|
|
7
|
+
*
|
|
8
|
+
* const models = ai(aiStandIn())
|
|
9
|
+
* await models.complete({ prompt: "Hi" }) // { text: "You asked: Hi", model: "stand-in", credits: 0, … }
|
|
10
|
+
*
|
|
11
|
+
* It offers the Models it is given (`stand-in` unless told), the first the default. Tokens are
|
|
12
|
+
* counted at about four characters a token, and cost nothing. Made to call a tool (`toolChoice`
|
|
13
|
+
* `required` or a name), it calls it with no arguments; a fallback is never needed.
|
|
14
|
+
*/
|
|
15
|
+
/** A message's text, without its images. */
|
|
16
|
+
const textOf = (content) => typeof content === "string" ? content : content.map((part) => part.type === "text" ? part.text : "").join("");
|
|
17
|
+
function aiStandIn(options = {}) {
|
|
18
|
+
const models = options.models?.length ? options.models : ["stand-in"];
|
|
19
|
+
const tokens = (text) => Math.ceil(text.length / 4);
|
|
20
|
+
return { async *ask(input) {
|
|
21
|
+
const model = input.model ?? models[0];
|
|
22
|
+
if (!models.includes(model)) throw new AiError("invalid", `There is no model ${model}.`);
|
|
23
|
+
const messages = [...input.system ? [{
|
|
24
|
+
role: "system",
|
|
25
|
+
content: input.system
|
|
26
|
+
}] : [], ...input.messages ?? [{
|
|
27
|
+
role: "user",
|
|
28
|
+
content: input.prompt ?? ""
|
|
29
|
+
}]];
|
|
30
|
+
const last = messages.filter((message) => message.role !== "system").at(-1);
|
|
31
|
+
if (!(last?.role === "tool" || last?.role === "user" && textOf(last.content).trim())) throw new AiError("invalid", "End with a user message that asks something, or with the results of the tools the model called.");
|
|
32
|
+
const inputTokens = tokens(messages.map((message) => textOf(message.content)).join(""));
|
|
33
|
+
const tool = typeof input.toolChoice === "object" ? input.toolChoice.name : input.toolChoice === "required" ? input.tools?.[0]?.name : void 0;
|
|
34
|
+
if (tool && last.role === "user") {
|
|
35
|
+
if (!input.tools?.some((given) => given.name === tool)) throw new AiError("invalid", `toolChoice names ${tool}, which isn't one of the tools given.`);
|
|
36
|
+
yield { toolCall: {
|
|
37
|
+
index: 0,
|
|
38
|
+
id: "call_stand_in_1",
|
|
39
|
+
name: tool,
|
|
40
|
+
arguments: "{}"
|
|
41
|
+
} };
|
|
42
|
+
yield { done: {
|
|
43
|
+
model,
|
|
44
|
+
inputTokens,
|
|
45
|
+
outputTokens: 1,
|
|
46
|
+
credits: 0,
|
|
47
|
+
catalogue: "stand-in"
|
|
48
|
+
} };
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const answer = `You asked: ${textOf(last.content)}`.slice(0, (input.maxTokens ?? 1024) * 4);
|
|
52
|
+
for (const piece of answer.match(/\S+\s*/g) ?? []) yield { text: piece };
|
|
53
|
+
yield { done: {
|
|
54
|
+
model,
|
|
55
|
+
inputTokens,
|
|
56
|
+
outputTokens: tokens(answer),
|
|
57
|
+
credits: 0,
|
|
58
|
+
catalogue: "stand-in"
|
|
59
|
+
} };
|
|
60
|
+
} };
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
//#region src/ai/index.ts
|
|
64
|
+
/**
|
|
65
|
+
* AI: Model calls from a Project's code, streamed or whole, each with the tokens and credits it spent.
|
|
66
|
+
* In a deployment, in any framework, `ai()` calls the team's AI Gateway with no key:
|
|
67
|
+
*
|
|
68
|
+
* import { ai } from "@midsummer-ai/sdk/ai"
|
|
69
|
+
*
|
|
70
|
+
* const models = ai()
|
|
71
|
+
* const answer = await models.complete({ prompt: "Name three rivers" })
|
|
72
|
+
* const stream = models.stream({ model: "claude-sonnet-5-5", messages: [{ role: "user", content: "Hi" }] })
|
|
73
|
+
* for await (const text of stream) write(text)
|
|
74
|
+
* const { credits } = await stream.done
|
|
75
|
+
*
|
|
76
|
+
* A call can pass tools (its calls come back as `toolCalls`), ask for JSON to a schema
|
|
77
|
+
* (`responseFormat`), send images in a user message, set a reasoning effort, and name `fallback`
|
|
78
|
+
* Models asked in turn when one can't answer; `model` in what it spent is the one that replied.
|
|
79
|
+
*
|
|
80
|
+
* Under `midsummer dev` it returns the Stand-in's reply, an echo of the question, unless given an engine. Given an engine,
|
|
81
|
+
* calls go there instead: the Stand-in (`@midsummer-ai/sdk/ai/stand-in`) in tests, or, from code outside Midsummer,
|
|
82
|
+
* the platform with an AI key (`ai(aiClient(origin, { key }))`). Every engine is held to the cases in `@midsummer-ai/sdk/ai/contract`.
|
|
83
|
+
* A Model is named as `midsummer ai model list` lists it; leaving it out picks the default.
|
|
84
|
+
*
|
|
85
|
+
* Every failure is an `AiError`; its `code` tells you which kind: `invalid` (no such Model, nothing
|
|
86
|
+
* asked), `forbidden` (the key is not valid), `quota` (the Team's usage is holding back its calls),
|
|
87
|
+
* `conflict` (a retry by `idempotencyKey` of a call still under way) or `unavailable` (try again).
|
|
88
|
+
*/
|
|
89
|
+
/** The Stand-in as `midsummer dev` answers with it: an echo of the question, for any Model named, costing nothing. */
|
|
90
|
+
const devAi = { ask: (input) => aiStandIn({ models: [input.model ?? "stand-in"] }).ask(input) };
|
|
91
|
+
var AiError = class extends Error {
|
|
92
|
+
code;
|
|
93
|
+
constructor(code, why) {
|
|
94
|
+
super(why);
|
|
95
|
+
this.code = code;
|
|
96
|
+
this.name = "AiError";
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
/** Tool call pieces, added up into whole calls in order. */
|
|
100
|
+
function toolCalls() {
|
|
101
|
+
const calls = /* @__PURE__ */ new Map();
|
|
102
|
+
return {
|
|
103
|
+
add({ index, id, name, arguments: more }) {
|
|
104
|
+
const made = calls.get(index) ?? {
|
|
105
|
+
id: "",
|
|
106
|
+
name: "",
|
|
107
|
+
arguments: ""
|
|
108
|
+
};
|
|
109
|
+
calls.set(index, {
|
|
110
|
+
id: id ?? made.id,
|
|
111
|
+
name: name ?? made.name,
|
|
112
|
+
arguments: made.arguments + more
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
whole: () => calls.size ? { toolCalls: [...calls.entries()].sort(([a], [b]) => a - b).map(([, made]) => made) } : {}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Checks a question's shape before it leaves the caller. Its parameters' ranges are the AI Gateway's to check, against
|
|
120
|
+
* the Models asked, so its errors are the only ones that name them.
|
|
121
|
+
*/
|
|
122
|
+
function checked(input) {
|
|
123
|
+
if (Boolean(input.prompt) === Boolean(input.messages)) throw new AiError("invalid", "Give a prompt or messages.");
|
|
124
|
+
if (input.messages && !input.messages.length) throw new AiError("invalid", "Give at least one message.");
|
|
125
|
+
if ((input.fallback?.length ?? 0) > 3) throw new AiError("invalid", "Name at most 3 fallback models.");
|
|
126
|
+
return input;
|
|
127
|
+
}
|
|
128
|
+
function ai(given) {
|
|
129
|
+
const engine = given ?? late(() => {
|
|
130
|
+
const handle = here()?.ai;
|
|
131
|
+
if (handle) return boundAi(handle);
|
|
132
|
+
if (processEnv().MIDSUMMER_DEV === "1") return devAi;
|
|
133
|
+
throw new AiError("forbidden", "This code runs outside a deployment, so it calls models with an AI key: ai(aiClient(origin, { key })).");
|
|
134
|
+
});
|
|
135
|
+
return {
|
|
136
|
+
async complete(input) {
|
|
137
|
+
let text = "";
|
|
138
|
+
const calls = toolCalls();
|
|
139
|
+
for await (const event of engine.ask(checked(input))) if ("text" in event) text += event.text;
|
|
140
|
+
else if ("toolCall" in event) calls.add(event.toolCall);
|
|
141
|
+
else return {
|
|
142
|
+
...event.done,
|
|
143
|
+
text,
|
|
144
|
+
...calls.whole()
|
|
145
|
+
};
|
|
146
|
+
throw new AiError("unavailable", "The answer ended early. Try again.");
|
|
147
|
+
},
|
|
148
|
+
stream(input) {
|
|
149
|
+
let settle, fail;
|
|
150
|
+
const done = new Promise((resolve, reject) => {
|
|
151
|
+
settle = resolve;
|
|
152
|
+
fail = reject;
|
|
153
|
+
});
|
|
154
|
+
done.catch(() => void 0);
|
|
155
|
+
let asked;
|
|
156
|
+
try {
|
|
157
|
+
asked = checked(input);
|
|
158
|
+
} catch (error) {
|
|
159
|
+
fail(error);
|
|
160
|
+
return {
|
|
161
|
+
done,
|
|
162
|
+
[Symbol.asyncIterator]: () => ({ next: () => Promise.reject(error) })
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
async function* texts() {
|
|
166
|
+
try {
|
|
167
|
+
const calls = toolCalls();
|
|
168
|
+
for await (const event of engine.ask(asked)) if ("text" in event) yield event.text;
|
|
169
|
+
else if ("toolCall" in event) calls.add(event.toolCall);
|
|
170
|
+
else return settle({
|
|
171
|
+
...event.done,
|
|
172
|
+
...calls.whole()
|
|
173
|
+
});
|
|
174
|
+
throw new AiError("unavailable", "The answer ended early. Try again.");
|
|
175
|
+
} catch (error) {
|
|
176
|
+
fail(error);
|
|
177
|
+
throw error;
|
|
178
|
+
} finally {
|
|
179
|
+
fail(new AiError("unavailable", "The answer was not read to its end."));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
done,
|
|
184
|
+
[Symbol.asyncIterator]: texts
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/** One line of the wire, checked whole: a piece of text, what the call spent, or why it stopped. Anything else is a broken answer. */
|
|
190
|
+
function parsed(line) {
|
|
191
|
+
const broken = () => new AiError("unavailable", "The answer could not be read. Try again.");
|
|
192
|
+
let event;
|
|
193
|
+
try {
|
|
194
|
+
event = JSON.parse(line);
|
|
195
|
+
} catch {
|
|
196
|
+
throw broken();
|
|
197
|
+
}
|
|
198
|
+
const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
199
|
+
const count = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
200
|
+
if (!object(event)) throw broken();
|
|
201
|
+
if (typeof event.text === "string") return { text: event.text };
|
|
202
|
+
const call = event.toolCall;
|
|
203
|
+
if (object(call)) {
|
|
204
|
+
if (!count(call.index) || typeof call.arguments !== "string" || call.id !== void 0 && typeof call.id !== "string" || call.name !== void 0 && typeof call.name !== "string") throw broken();
|
|
205
|
+
return { toolCall: {
|
|
206
|
+
index: call.index,
|
|
207
|
+
...typeof call.id === "string" ? { id: call.id } : {},
|
|
208
|
+
...typeof call.name === "string" ? { name: call.name } : {},
|
|
209
|
+
arguments: call.arguments
|
|
210
|
+
} };
|
|
211
|
+
}
|
|
212
|
+
const done = event.done;
|
|
213
|
+
if (object(done)) {
|
|
214
|
+
if (typeof done.model !== "string" || !count(done.inputTokens) || !count(done.outputTokens) || typeof done.credits !== "number" || !(done.credits >= 0) || typeof done.catalogue !== "string" || done.cachedTokens !== void 0 && !count(done.cachedTokens)) throw broken();
|
|
215
|
+
return { done: {
|
|
216
|
+
model: done.model,
|
|
217
|
+
inputTokens: done.inputTokens,
|
|
218
|
+
...done.cachedTokens ? { cachedTokens: done.cachedTokens } : {},
|
|
219
|
+
outputTokens: done.outputTokens,
|
|
220
|
+
credits: done.credits,
|
|
221
|
+
catalogue: done.catalogue
|
|
222
|
+
} };
|
|
223
|
+
}
|
|
224
|
+
const error = event.error;
|
|
225
|
+
if (object(error) && (error.code === void 0 || typeof error.code === "string") && (error.message === void 0 || typeof error.message === "string")) return { error: {
|
|
226
|
+
...typeof error.code === "string" ? { code: error.code } : {},
|
|
227
|
+
...typeof error.message === "string" ? { message: error.message } : {}
|
|
228
|
+
} };
|
|
229
|
+
throw broken();
|
|
230
|
+
}
|
|
231
|
+
const CODES = {
|
|
232
|
+
400: "invalid",
|
|
233
|
+
401: "forbidden",
|
|
234
|
+
403: "forbidden",
|
|
235
|
+
409: "conflict",
|
|
236
|
+
429: "quota"
|
|
237
|
+
};
|
|
238
|
+
const CODE_NAMES = [
|
|
239
|
+
"invalid",
|
|
240
|
+
"forbidden",
|
|
241
|
+
"quota",
|
|
242
|
+
"conflict",
|
|
243
|
+
"unavailable"
|
|
244
|
+
];
|
|
245
|
+
/**
|
|
246
|
+
* The platform's AI Gateway at `origin` (the API's), for the AI key `key`: each call is one POST to
|
|
247
|
+
* `<origin>/v1/ai/ask`, which replies with newline-delimited JSON events as the Model writes.
|
|
248
|
+
*/
|
|
249
|
+
function aiClient(origin, options) {
|
|
250
|
+
const url = `${origin.replace(/\/+$/, "")}/v1/ai/ask`;
|
|
251
|
+
const send = options.fetch ?? ((input, init) => fetch(input, init));
|
|
252
|
+
return { async *ask(input) {
|
|
253
|
+
const leave = new AbortController();
|
|
254
|
+
let response;
|
|
255
|
+
try {
|
|
256
|
+
response = await send(url, {
|
|
257
|
+
method: "POST",
|
|
258
|
+
signal: leave.signal,
|
|
259
|
+
headers: { "Content-Type": "application/json" },
|
|
260
|
+
body: JSON.stringify({
|
|
261
|
+
...input,
|
|
262
|
+
key: options.key,
|
|
263
|
+
stream: true
|
|
264
|
+
})
|
|
265
|
+
});
|
|
266
|
+
} catch {
|
|
267
|
+
throw new AiError("unavailable", "The AI Gateway could not be reached. Try again.");
|
|
268
|
+
}
|
|
269
|
+
if (!response.ok || !response.body) {
|
|
270
|
+
const why = await response.json().then((body) => typeof body.error === "string" ? body.error : void 0, () => void 0);
|
|
271
|
+
throw new AiError(CODES[response.status] ?? "unavailable", why ?? `The AI Gateway returned ${response.status}.`);
|
|
272
|
+
}
|
|
273
|
+
try {
|
|
274
|
+
yield* eventsOf(response.body);
|
|
275
|
+
} finally {
|
|
276
|
+
leave.abort();
|
|
277
|
+
}
|
|
278
|
+
} };
|
|
279
|
+
}
|
|
280
|
+
/** The events of one call's newline-delimited JSON, as the AI Gateway streams them; cancelled when the reader leaves. */
|
|
281
|
+
async function* eventsOf(body) {
|
|
282
|
+
const decoder = new TextDecoder();
|
|
283
|
+
let pending = "";
|
|
284
|
+
const reader = body.getReader();
|
|
285
|
+
try {
|
|
286
|
+
while (true) {
|
|
287
|
+
let read;
|
|
288
|
+
try {
|
|
289
|
+
read = await reader.read();
|
|
290
|
+
} catch {
|
|
291
|
+
throw new AiError("unavailable", "The answer was cut off. Try again.");
|
|
292
|
+
}
|
|
293
|
+
pending += read.done ? decoder.decode() : decoder.decode(read.value, { stream: true });
|
|
294
|
+
let end;
|
|
295
|
+
while ((end = pending.indexOf("\n")) >= 0) {
|
|
296
|
+
const line = pending.slice(0, end).trim();
|
|
297
|
+
pending = pending.slice(end + 1);
|
|
298
|
+
if (!line) continue;
|
|
299
|
+
const event = parsed(line);
|
|
300
|
+
if ("error" in event) throw new AiError(event.error.code && CODE_NAMES.includes(event.error.code) ? event.error.code : "unavailable", event.error.message ?? "The model could not answer. Try again.");
|
|
301
|
+
yield event;
|
|
302
|
+
if ("done" in event) return;
|
|
303
|
+
}
|
|
304
|
+
if (read.done) throw new AiError("unavailable", "The answer ended early. Try again.");
|
|
305
|
+
}
|
|
306
|
+
} finally {
|
|
307
|
+
await reader.cancel().catch(() => void 0);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* What Midsummer hands a Deployment as `context.ai`: the Team's AI Gateway, with no key. Each call
|
|
312
|
+
* streams the events `aiClient` reads.
|
|
313
|
+
*
|
|
314
|
+
* const answer = await ai(boundAi(context.ai)).complete({ prompt: "Hello" })
|
|
315
|
+
*/
|
|
316
|
+
function boundAi(handle) {
|
|
317
|
+
return { async *ask(input) {
|
|
318
|
+
let body;
|
|
319
|
+
try {
|
|
320
|
+
body = await handle.ask(input);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
throw new AiError("unavailable", error instanceof Error ? error.message : "The AI Gateway could not be reached. Try again.");
|
|
323
|
+
}
|
|
324
|
+
yield* eventsOf(body);
|
|
325
|
+
} };
|
|
326
|
+
}
|
|
327
|
+
//#endregion
|
|
328
|
+
export { aiStandIn as a, boundAi as i, ai as n, aiClient as r, AiError as t };
|