@zhivex-ai/core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/catalog.d.ts +15 -0
- package/dist/catalog.d.ts.map +1 -0
- package/dist/catalog.js +18 -0
- package/dist/catalog.js.map +1 -0
- package/dist/embed.d.ts +4 -0
- package/dist/embed.d.ts.map +1 -0
- package/dist/embed.js +16 -0
- package/dist/embed.js.map +1 -0
- package/dist/errors.d.ts +23 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +26 -0
- package/dist/errors.js.map +1 -0
- package/dist/fetch.d.ts +5 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/fetch.js +25 -0
- package/dist/fetch.js.map +1 -0
- package/dist/generate-object.d.ts +5 -0
- package/dist/generate-object.d.ts.map +1 -0
- package/dist/generate-object.js +327 -0
- package/dist/generate-object.js.map +1 -0
- package/dist/generate-text.d.ts +5 -0
- package/dist/generate-text.d.ts.map +1 -0
- package/dist/generate-text.js +266 -0
- package/dist/generate-text.js.map +1 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/messages.d.ts +17 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +92 -0
- package/dist/messages.js.map +1 -0
- package/dist/middleware.d.ts +27 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +168 -0
- package/dist/middleware.js.map +1 -0
- package/dist/runtime.d.ts +9 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/runtime.js +62 -0
- package/dist/runtime.js.map +1 -0
- package/dist/stream.d.ts +17 -0
- package/dist/stream.d.ts.map +1 -0
- package/dist/stream.js +110 -0
- package/dist/stream.js.map +1 -0
- package/dist/types.d.ts +315 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/ui.d.ts +10 -0
- package/dist/ui.d.ts.map +1 -0
- package/dist/ui.js +65 -0
- package/dist/ui.js.map +1 -0
- package/package.json +32 -0
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { ParseError, UnsupportedFeatureError, ValidationError } from "./errors.js";
|
|
2
|
+
import { createTextMessage, getTextFromMessages, normalizeFinishReason, resultMessages, serializeJsonValue, toolCallPart, toolResultPart, validateMessageParts } from "./messages.js";
|
|
3
|
+
const validateInputSource = (options) => {
|
|
4
|
+
if (options.prompt !== undefined && options.messages !== undefined) {
|
|
5
|
+
throw new ValidationError('Pass either "prompt" or "messages", but not both.');
|
|
6
|
+
}
|
|
7
|
+
};
|
|
8
|
+
const buildMessages = (options) => {
|
|
9
|
+
validateInputSource(options);
|
|
10
|
+
const messages = [...(options.messages ?? [])];
|
|
11
|
+
if (options.system) {
|
|
12
|
+
messages.unshift(createTextMessage("system", options.system));
|
|
13
|
+
}
|
|
14
|
+
if (options.prompt) {
|
|
15
|
+
messages.push(createTextMessage("user", options.prompt));
|
|
16
|
+
}
|
|
17
|
+
return messages;
|
|
18
|
+
};
|
|
19
|
+
const toRequest = (options, messages) => ({
|
|
20
|
+
messages,
|
|
21
|
+
tools: options.tools,
|
|
22
|
+
temperature: options.temperature,
|
|
23
|
+
maxTokens: options.maxTokens,
|
|
24
|
+
providerOptions: options.providerOptions,
|
|
25
|
+
structuredOutput: options.structuredOutput,
|
|
26
|
+
abortSignal: options.abortSignal,
|
|
27
|
+
timeoutMs: options.timeoutMs,
|
|
28
|
+
maxRetries: options.maxRetries,
|
|
29
|
+
retryBackoffMs: options.retryBackoffMs
|
|
30
|
+
});
|
|
31
|
+
const executeTools = async (toolCalls, options) => {
|
|
32
|
+
const results = [];
|
|
33
|
+
for (const call of toolCalls) {
|
|
34
|
+
const tool = options.tools?.[call.name];
|
|
35
|
+
if (!tool) {
|
|
36
|
+
throw new ValidationError(`Tool "${call.name}" was requested by the model but is not registered.`);
|
|
37
|
+
}
|
|
38
|
+
const parsed = tool.schema.safeParse(call.input);
|
|
39
|
+
if (!parsed.success) {
|
|
40
|
+
throw new ValidationError(`Invalid input for tool "${call.name}": ${parsed.error.message}`);
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
const output = serializeJsonValue(await tool.execute(parsed.data));
|
|
44
|
+
results.push({
|
|
45
|
+
toolCallId: call.id,
|
|
46
|
+
toolName: call.name,
|
|
47
|
+
output,
|
|
48
|
+
isError: false
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
results.push({
|
|
53
|
+
toolCallId: call.id,
|
|
54
|
+
toolName: call.name,
|
|
55
|
+
error: { message: error instanceof Error ? error.message : "Tool execution failed." },
|
|
56
|
+
isError: true
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return results;
|
|
61
|
+
};
|
|
62
|
+
export const normalizeMessages = buildMessages;
|
|
63
|
+
const extractToolCalls = (messages) => messages.flatMap((message) => message.parts
|
|
64
|
+
.filter((part) => part.type === "tool-call")
|
|
65
|
+
.map((part) => part.toolCall));
|
|
66
|
+
export const generateText = async (options) => {
|
|
67
|
+
const maxSteps = Math.max(1, options.maxSteps ?? 1);
|
|
68
|
+
const allMessages = buildMessages(options);
|
|
69
|
+
const steps = [];
|
|
70
|
+
validateMessageParts(options.model, allMessages);
|
|
71
|
+
if (options.tools && !options.model.capabilities.tools) {
|
|
72
|
+
throw new UnsupportedFeatureError(`Model "${options.model.provider}/${options.model.modelId}" does not support tools.`);
|
|
73
|
+
}
|
|
74
|
+
const toolResults = [];
|
|
75
|
+
let finalResult;
|
|
76
|
+
for (let step = 0; step < maxSteps; step += 1) {
|
|
77
|
+
const request = toRequest(options, allMessages);
|
|
78
|
+
const response = await options.model.generate(request);
|
|
79
|
+
steps.push({ request, response });
|
|
80
|
+
finalResult = response;
|
|
81
|
+
const responseMessages = resultMessages(response);
|
|
82
|
+
if (responseMessages.length) {
|
|
83
|
+
allMessages.push(...responseMessages);
|
|
84
|
+
}
|
|
85
|
+
const toolCalls = extractToolCalls(responseMessages);
|
|
86
|
+
if (!toolCalls.length) {
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
const currentToolResults = await executeTools(toolCalls, options);
|
|
90
|
+
toolResults.push(...currentToolResults);
|
|
91
|
+
for (const result of currentToolResults) {
|
|
92
|
+
allMessages.push({
|
|
93
|
+
role: "tool",
|
|
94
|
+
parts: [toolResultPart(result)]
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (!finalResult) {
|
|
99
|
+
throw new ParseError("Model did not return a result.");
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
text: getTextFromMessages(allMessages),
|
|
103
|
+
finishReason: finalResult.finishReason,
|
|
104
|
+
providerFinishReason: finalResult.providerFinishReason,
|
|
105
|
+
usage: finalResult.usage,
|
|
106
|
+
steps,
|
|
107
|
+
messages: allMessages,
|
|
108
|
+
toolResults
|
|
109
|
+
};
|
|
110
|
+
};
|
|
111
|
+
export const streamText = (options) => {
|
|
112
|
+
const maxSteps = Math.max(1, options.maxSteps ?? 1);
|
|
113
|
+
const baseMessages = buildMessages(options);
|
|
114
|
+
validateMessageParts(options.model, baseMessages);
|
|
115
|
+
if (!options.model.stream) {
|
|
116
|
+
throw new ValidationError(`Model "${options.model.provider}/${options.model.modelId}" does not support streaming.`);
|
|
117
|
+
}
|
|
118
|
+
const streamModel = options.model.stream.bind(options.model);
|
|
119
|
+
if (options.tools && !options.model.capabilities.tools) {
|
|
120
|
+
throw new UnsupportedFeatureError(`Model "${options.model.provider}/${options.model.modelId}" does not support tools.`);
|
|
121
|
+
}
|
|
122
|
+
const subscribers = new Set();
|
|
123
|
+
const history = [];
|
|
124
|
+
let done = false;
|
|
125
|
+
let finalResultPromise;
|
|
126
|
+
const publish = (value) => {
|
|
127
|
+
history.push(value);
|
|
128
|
+
for (const subscriber of subscribers) {
|
|
129
|
+
subscriber(value);
|
|
130
|
+
}
|
|
131
|
+
if (value.done) {
|
|
132
|
+
done = true;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
const createEventStream = async function* () {
|
|
136
|
+
let cursor = 0;
|
|
137
|
+
while (true) {
|
|
138
|
+
while (cursor < history.length) {
|
|
139
|
+
const item = history[cursor];
|
|
140
|
+
cursor += 1;
|
|
141
|
+
if (item.done) {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
yield item.value;
|
|
145
|
+
}
|
|
146
|
+
if (done) {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
await new Promise((resolve) => {
|
|
150
|
+
const subscriber = (value) => {
|
|
151
|
+
subscribers.delete(subscriber);
|
|
152
|
+
resolve(value);
|
|
153
|
+
};
|
|
154
|
+
subscribers.add(subscriber);
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
const runner = async () => {
|
|
159
|
+
const allMessages = [...baseMessages];
|
|
160
|
+
const steps = [];
|
|
161
|
+
const toolResults = [];
|
|
162
|
+
let finalResult;
|
|
163
|
+
for (let step = 0; step < maxSteps; step += 1) {
|
|
164
|
+
const request = toRequest(options, allMessages);
|
|
165
|
+
const stream = await streamModel(request);
|
|
166
|
+
const stepMessages = [];
|
|
167
|
+
let textBuffer = "";
|
|
168
|
+
let finishReason = normalizeFinishReason("stop");
|
|
169
|
+
let providerFinishReason;
|
|
170
|
+
let usage = undefined;
|
|
171
|
+
for await (const event of stream) {
|
|
172
|
+
publish({ done: false, value: event });
|
|
173
|
+
if (event.type === "text-delta") {
|
|
174
|
+
textBuffer += event.textDelta;
|
|
175
|
+
}
|
|
176
|
+
if (event.type === "tool-call") {
|
|
177
|
+
const existingAssistant = stepMessages.find((message) => message.role === "assistant");
|
|
178
|
+
if (existingAssistant) {
|
|
179
|
+
existingAssistant.parts.push(toolCallPart(event.toolCall));
|
|
180
|
+
}
|
|
181
|
+
else {
|
|
182
|
+
stepMessages.push({
|
|
183
|
+
role: "assistant",
|
|
184
|
+
parts: [toolCallPart(event.toolCall)]
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (event.type === "finish") {
|
|
189
|
+
finishReason = event.finishReason;
|
|
190
|
+
providerFinishReason = event.providerFinishReason;
|
|
191
|
+
usage = event.usage;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (textBuffer) {
|
|
195
|
+
const assistant = stepMessages.find((message) => message.role === "assistant");
|
|
196
|
+
if (assistant) {
|
|
197
|
+
assistant.parts.unshift({ type: "text", text: textBuffer });
|
|
198
|
+
}
|
|
199
|
+
else {
|
|
200
|
+
stepMessages.unshift(createTextMessage("assistant", textBuffer));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
finalResult = {
|
|
204
|
+
messages: stepMessages,
|
|
205
|
+
text: textBuffer,
|
|
206
|
+
finishReason,
|
|
207
|
+
providerFinishReason,
|
|
208
|
+
usage
|
|
209
|
+
};
|
|
210
|
+
steps.push({ request, response: finalResult });
|
|
211
|
+
allMessages.push(...stepMessages);
|
|
212
|
+
const toolCalls = extractToolCalls(stepMessages);
|
|
213
|
+
if (!toolCalls.length) {
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
const currentToolResults = await executeTools(toolCalls, options);
|
|
217
|
+
toolResults.push(...currentToolResults);
|
|
218
|
+
for (const toolResult of currentToolResults) {
|
|
219
|
+
publish({ done: false, value: { type: "tool-result", toolResult } });
|
|
220
|
+
allMessages.push({
|
|
221
|
+
role: "tool",
|
|
222
|
+
parts: [toolResultPart(toolResult)]
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (!finalResult) {
|
|
227
|
+
throw new ParseError("Model did not return a result.");
|
|
228
|
+
}
|
|
229
|
+
publish({
|
|
230
|
+
done: false,
|
|
231
|
+
value: {
|
|
232
|
+
type: "finish",
|
|
233
|
+
finishReason: finalResult.finishReason,
|
|
234
|
+
providerFinishReason: finalResult.providerFinishReason,
|
|
235
|
+
usage: finalResult.usage
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
publish({ done: true, value: undefined });
|
|
239
|
+
return {
|
|
240
|
+
text: getTextFromMessages(allMessages),
|
|
241
|
+
finishReason: finalResult.finishReason,
|
|
242
|
+
providerFinishReason: finalResult.providerFinishReason,
|
|
243
|
+
usage: finalResult.usage,
|
|
244
|
+
steps,
|
|
245
|
+
messages: allMessages,
|
|
246
|
+
toolResults
|
|
247
|
+
};
|
|
248
|
+
};
|
|
249
|
+
finalResultPromise = runner().catch((error) => {
|
|
250
|
+
publish({ done: false, value: { type: "error", error: error instanceof Error ? error : new Error(String(error)) } });
|
|
251
|
+
publish({ done: true, value: undefined });
|
|
252
|
+
throw error;
|
|
253
|
+
});
|
|
254
|
+
return {
|
|
255
|
+
eventStream: createEventStream(),
|
|
256
|
+
textStream: (async function* () {
|
|
257
|
+
for await (const event of createEventStream()) {
|
|
258
|
+
if (event.type === "text-delta") {
|
|
259
|
+
yield event.textDelta;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
})(),
|
|
263
|
+
collect: async () => finalResultPromise
|
|
264
|
+
};
|
|
265
|
+
};
|
|
266
|
+
//# sourceMappingURL=generate-text.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-text.js","sourceRoot":"","sources":["../src/generate-text.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnF,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,cAAc,EACd,kBAAkB,EAClB,YAAY,EACZ,cAAc,EACd,oBAAoB,EACrB,MAAM,eAAe,CAAC;AAavB,MAAM,mBAAmB,GAAG,CAAC,OAAyD,EAAE,EAAE;IACxF,IAAI,OAAO,CAAC,MAAM,KAAK,SAAS,IAAI,OAAO,CAAC,QAAQ,KAAK,SAAS,EAAE,CAAC;QACnE,MAAM,IAAI,eAAe,CAAC,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export * from "./fetch.js";
|
|
5
|
+
export { generateObject, streamObject } from "./generate-object.js";
|
|
6
|
+
export { generateText, normalizeMessages, streamText } from "./generate-text.js";
|
|
7
|
+
export { assistant, createTextMessage, getTextFromMessages, getTextFromParts, getToolCallsFromEvents, normalizeFinishReason, resultMessages, serializeJsonValue, system, textPart, tool, toolCallPart, toolResultPart, user, validateMessageParts } from "./messages.js";
|
|
8
|
+
export * from "./middleware.js";
|
|
9
|
+
export { createProviderAdapter, mergeAbortSignals, withRetry, withTimeoutSignal } from "./runtime.js";
|
|
10
|
+
export * from "./stream.js";
|
|
11
|
+
export * from "./types.js";
|
|
12
|
+
export * from "./ui.js";
|
|
13
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC9C,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACjF,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,mBAAmB,EACnB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,cAAc,EACd,kBAAkB,EAClB,MAAM,EACN,QAAQ,EACR,IAAI,EACJ,YAAY,EACZ,cAAc,EACd,IAAI,EACJ,oBAAoB,EACrB,MAAM,eAAe,CAAC;AACvB,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACtG,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,SAAS,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { embed, embedMany } from "./embed.js";
|
|
2
|
+
export * from "./catalog.js";
|
|
3
|
+
export * from "./errors.js";
|
|
4
|
+
export * from "./fetch.js";
|
|
5
|
+
export { generateObject, streamObject } from "./generate-object.js";
|
|
6
|
+
export { generateText, normalizeMessages, streamText } from "./generate-text.js";
|
|
7
|
+
export { assistant, createTextMessage, getTextFromMessages, getTextFromParts, getToolCallsFromEvents, normalizeFinishReason, resultMessages, serializeJsonValue, system, textPart, tool, toolCallPart, toolResultPart, user, validateMessageParts } from "./messages.js";
|
|
8
|
+
export * from "./middleware.js";
|
|
9
|
+
export { createProviderAdapter, mergeAbortSignals, withRetry, withTimeoutSignal } from "./runtime.js";
|
|
10
|
+
export * from "./stream.js";
|
|
11
|
+
export * from "./types.js";
|
|
12
|
+
export * from "./ui.js";
|
|
13
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC9C,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACjF,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,mBAAmB,EACnB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,cAAc,EACd,kBAAkB,EAClB,MAAM,EACN,QAAQ,EACR,IAAI,EACJ,YAAY,EACZ,cAAc,EACd,IAAI,EACJ,oBAAoB,EACrB,MAAM,eAAe,CAAC;AACvB,cAAc,iBAAiB,CAAC;AAChC,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACtG,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,SAAS,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ContentPart, FinishReason, GenerateResult, JsonValue, LanguageModel, ModelMessage, StreamEvent, ToolCall, ToolDefinition, ToolExecutionResult } from "./types.js";
|
|
2
|
+
export declare const textPart: (text: string) => ContentPart;
|
|
3
|
+
export declare const toolCallPart: (toolCall: ToolCall) => ContentPart;
|
|
4
|
+
export declare const toolResultPart: (toolResult: ToolExecutionResult) => ContentPart;
|
|
5
|
+
export declare const createTextMessage: (role: ModelMessage["role"], text: string) => ModelMessage;
|
|
6
|
+
export declare const system: (text: string) => ModelMessage;
|
|
7
|
+
export declare const user: (input: string | ContentPart[]) => ModelMessage;
|
|
8
|
+
export declare const assistant: (input: string | ContentPart[]) => ModelMessage;
|
|
9
|
+
export declare const getTextFromParts: (parts: ContentPart[]) => string;
|
|
10
|
+
export declare const getTextFromMessages: (messages: ModelMessage[]) => string;
|
|
11
|
+
export declare const serializeJsonValue: (value: unknown) => JsonValue;
|
|
12
|
+
export declare const tool: <TTool extends ToolDefinition>(definition: TTool) => TTool;
|
|
13
|
+
export declare const normalizeFinishReason: (reason: string | undefined | null) => FinishReason | undefined;
|
|
14
|
+
export declare const resultMessages: (result: GenerateResult) => ModelMessage[];
|
|
15
|
+
export declare const validateMessageParts: (model: LanguageModel, messages: ModelMessage[]) => void;
|
|
16
|
+
export declare const getToolCallsFromEvents: (events: StreamEvent[]) => ToolCall[];
|
|
17
|
+
//# sourceMappingURL=messages.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../src/messages.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,cAAc,EACd,SAAS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|
package/dist/messages.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { UnsupportedFeatureError } from "./errors.js";
|
|
2
|
+
export const textPart = (text) => ({ type: "text", text });
|
|
3
|
+
const normalizeMessageParts = (input) => (typeof input === "string" ? [textPart(input)] : input);
|
|
4
|
+
export const toolCallPart = (toolCall) => ({
|
|
5
|
+
type: "tool-call",
|
|
6
|
+
toolCall
|
|
7
|
+
});
|
|
8
|
+
export const toolResultPart = (toolResult) => ({
|
|
9
|
+
type: "tool-result",
|
|
10
|
+
toolResult
|
|
11
|
+
});
|
|
12
|
+
export const createTextMessage = (role, text) => ({
|
|
13
|
+
role,
|
|
14
|
+
parts: [textPart(text)]
|
|
15
|
+
});
|
|
16
|
+
export const system = (text) => ({
|
|
17
|
+
role: "system",
|
|
18
|
+
parts: [textPart(text)]
|
|
19
|
+
});
|
|
20
|
+
export const user = (input) => ({
|
|
21
|
+
role: "user",
|
|
22
|
+
parts: normalizeMessageParts(input)
|
|
23
|
+
});
|
|
24
|
+
export const assistant = (input) => ({
|
|
25
|
+
role: "assistant",
|
|
26
|
+
parts: normalizeMessageParts(input)
|
|
27
|
+
});
|
|
28
|
+
export const getTextFromParts = (parts) => parts
|
|
29
|
+
.filter((part) => part.type === "text")
|
|
30
|
+
.map((part) => part.text)
|
|
31
|
+
.join("");
|
|
32
|
+
export const getTextFromMessages = (messages) => messages
|
|
33
|
+
.filter((message) => message.role === "assistant")
|
|
34
|
+
.map((message) => getTextFromParts(message.parts))
|
|
35
|
+
.join("");
|
|
36
|
+
export const serializeJsonValue = (value) => JSON.parse(JSON.stringify(value));
|
|
37
|
+
export const tool = (definition) => definition;
|
|
38
|
+
export const normalizeFinishReason = (reason) => {
|
|
39
|
+
if (!reason) {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
switch (reason.toLowerCase()) {
|
|
43
|
+
case "stop":
|
|
44
|
+
case "end_turn":
|
|
45
|
+
return "stop";
|
|
46
|
+
case "length":
|
|
47
|
+
case "max_tokens":
|
|
48
|
+
return "length";
|
|
49
|
+
case "tool_calls":
|
|
50
|
+
case "tool_use":
|
|
51
|
+
return "tool-calls";
|
|
52
|
+
case "content_filter":
|
|
53
|
+
return "content-filter";
|
|
54
|
+
case "error":
|
|
55
|
+
return "error";
|
|
56
|
+
default:
|
|
57
|
+
return "unknown";
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
export const resultMessages = (result) => {
|
|
61
|
+
if (result.messages?.length) {
|
|
62
|
+
return result.messages;
|
|
63
|
+
}
|
|
64
|
+
if (result.message) {
|
|
65
|
+
return [result.message];
|
|
66
|
+
}
|
|
67
|
+
if (result.text) {
|
|
68
|
+
return [createTextMessage("assistant", result.text)];
|
|
69
|
+
}
|
|
70
|
+
return [];
|
|
71
|
+
};
|
|
72
|
+
export const validateMessageParts = (model, messages) => {
|
|
73
|
+
for (const message of messages) {
|
|
74
|
+
for (const part of message.parts) {
|
|
75
|
+
if (part.type === "image" && !model.capabilities.vision) {
|
|
76
|
+
throw new UnsupportedFeatureError(`Model "${model.provider}/${model.modelId}" does not support image inputs.`);
|
|
77
|
+
}
|
|
78
|
+
if (part.type === "file" && !model.capabilities.files) {
|
|
79
|
+
throw new UnsupportedFeatureError(`Model "${model.provider}/${model.modelId}" does not support file inputs.`);
|
|
80
|
+
}
|
|
81
|
+
if (part.type === "tool-call" || part.type === "tool-result") {
|
|
82
|
+
if (!model.capabilities.tools) {
|
|
83
|
+
throw new UnsupportedFeatureError(`Model "${model.provider}/${model.modelId}" does not support tool calling.`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
export const getToolCallsFromEvents = (events) => events
|
|
90
|
+
.filter((event) => event.type === "tool-call")
|
|
91
|
+
.map((event) => event.toolCall);
|
|
92
|
+
//# sourceMappingURL=messages.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"messages.js","sourceRoot":"","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IAAI,CAAC,IAAI,KAAK,WAAW,IAAI,IAAI,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;gBAC7D,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC;oBAC9B,MAAM,IAAI,uBAAuB,CAC/B,UAAU,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,OAAO,kCAAkC,CAC5E,CAAC;gBACJ,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,MAAqB,EAAc,EAAE,CAC1E,MAAM;KACH,MAAM,CAAC,CAAC,KAAK,EAAwD,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC;KACnG,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { CircuitBreakerState, GenerateResult, LanguageModel, LanguageModelMiddleware, LanguageModelTelemetryEvent, ModelGenerateInput, ProviderOptions } from "./types.js";
|
|
2
|
+
export interface GenerateCache {
|
|
3
|
+
get(key: string): Promise<GenerateResult | undefined> | GenerateResult | undefined;
|
|
4
|
+
set(key: string, value: GenerateResult): Promise<void> | void;
|
|
5
|
+
}
|
|
6
|
+
export declare const wrapLanguageModel: <TProviderOptions extends ProviderOptions>(model: LanguageModel<TProviderOptions>, middlewares: Array<LanguageModelMiddleware<TProviderOptions>>) => LanguageModel<TProviderOptions>;
|
|
7
|
+
export declare const createTelemetryMiddleware: <TProviderOptions extends ProviderOptions>(options: {
|
|
8
|
+
onEvent: (event: LanguageModelTelemetryEvent<TProviderOptions>) => void | Promise<void>;
|
|
9
|
+
}) => LanguageModelMiddleware<TProviderOptions>;
|
|
10
|
+
export declare const createCachedGenerateMiddleware: <TProviderOptions extends ProviderOptions>(options: {
|
|
11
|
+
cache: GenerateCache;
|
|
12
|
+
getKey?: (input: ModelGenerateInput<TProviderOptions>, model: LanguageModel<TProviderOptions>) => string;
|
|
13
|
+
}) => LanguageModelMiddleware<TProviderOptions>;
|
|
14
|
+
export declare const createInMemoryGenerateCache: () => GenerateCache;
|
|
15
|
+
export declare const createFileGenerateCache: (options: {
|
|
16
|
+
dir: string;
|
|
17
|
+
}) => GenerateCache;
|
|
18
|
+
export declare const createCircuitBreakerMiddleware: <TProviderOptions extends ProviderOptions>(options: {
|
|
19
|
+
failureThreshold?: number;
|
|
20
|
+
cooldownMs?: number;
|
|
21
|
+
isFailure?: (error: Error) => boolean;
|
|
22
|
+
onStateChange?: (state: CircuitBreakerState & {
|
|
23
|
+
model: LanguageModel<TProviderOptions>;
|
|
24
|
+
status: "open" | "half-open" | "closed";
|
|
25
|
+
}) => void | Promise<void>;
|
|
26
|
+
}) => LanguageModelMiddleware<TProviderOptions>;
|
|
27
|
+
//# sourceMappingURL=middleware.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,mBAAmB,EACnB,cAAc,EACd,aAAa,EACb,uBAAuB,EACvB,2BAA2B,EAC3B,kBAAkB,EAClB,eAAe,EAChB,MAAM,YAAY,CAAC;AAIpB,MAAM,WAAW,aAAa;IAC5B,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC,GAAG,cAAc,GAAG,SAAS,CAAC;IACnF,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CAC/D;AAED,eAAO,MAAM,iBAAiB,GAAI,gBAAgB,SAAS,eAAe,EACxE,OAAO,aAAa,CAAC,gBAAgB,CAAC,EACtC,aAAa,KAAK,CAAC,uBAAuB,CAAC,gBAAgB,CAAC,CAAC,KAC5D,aAAa,CAAC,gBAAgB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
const serializeInput = (input) => JSON.stringify(input);
|
|
4
|
+
export const wrapLanguageModel = (model, middlewares) => {
|
|
5
|
+
if (!middlewares.length) {
|
|
6
|
+
return model;
|
|
7
|
+
}
|
|
8
|
+
return {
|
|
9
|
+
...model,
|
|
10
|
+
async generate(input) {
|
|
11
|
+
let index = -1;
|
|
12
|
+
const run = async (position) => {
|
|
13
|
+
if (position <= index) {
|
|
14
|
+
throw new Error("Language model middleware called next() multiple times.");
|
|
15
|
+
}
|
|
16
|
+
index = position;
|
|
17
|
+
const middleware = middlewares[position];
|
|
18
|
+
if (!middleware?.wrapGenerate) {
|
|
19
|
+
return position >= middlewares.length ? model.generate(input) : run(position + 1);
|
|
20
|
+
}
|
|
21
|
+
return middleware.wrapGenerate({ model, input }, () => run(position + 1));
|
|
22
|
+
};
|
|
23
|
+
return run(0);
|
|
24
|
+
},
|
|
25
|
+
stream: model.stream?.bind(model)
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
export const createTelemetryMiddleware = (options) => ({
|
|
29
|
+
name: "telemetry",
|
|
30
|
+
async wrapGenerate(context, next) {
|
|
31
|
+
const startedAt = Date.now();
|
|
32
|
+
await options.onEvent({
|
|
33
|
+
type: "generate-start",
|
|
34
|
+
model: context.model,
|
|
35
|
+
input: context.input,
|
|
36
|
+
startedAt
|
|
37
|
+
});
|
|
38
|
+
try {
|
|
39
|
+
const output = await next();
|
|
40
|
+
const finishedAt = Date.now();
|
|
41
|
+
await options.onEvent({
|
|
42
|
+
type: "generate-finish",
|
|
43
|
+
model: context.model,
|
|
44
|
+
input: context.input,
|
|
45
|
+
output,
|
|
46
|
+
startedAt,
|
|
47
|
+
finishedAt,
|
|
48
|
+
latencyMs: finishedAt - startedAt
|
|
49
|
+
});
|
|
50
|
+
return output;
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
const finishedAt = Date.now();
|
|
54
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
55
|
+
await options.onEvent({
|
|
56
|
+
type: "generate-error",
|
|
57
|
+
model: context.model,
|
|
58
|
+
input: context.input,
|
|
59
|
+
error: err,
|
|
60
|
+
startedAt,
|
|
61
|
+
finishedAt,
|
|
62
|
+
latencyMs: finishedAt - startedAt
|
|
63
|
+
});
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
export const createCachedGenerateMiddleware = (options) => ({
|
|
69
|
+
name: "cache",
|
|
70
|
+
async wrapGenerate(context, next) {
|
|
71
|
+
const key = options.getKey?.(context.input, context.model) ??
|
|
72
|
+
serializeInput({
|
|
73
|
+
provider: context.model.provider,
|
|
74
|
+
modelId: context.model.modelId,
|
|
75
|
+
input: context.input
|
|
76
|
+
});
|
|
77
|
+
const cached = await options.cache.get(key);
|
|
78
|
+
if (cached) {
|
|
79
|
+
return cached;
|
|
80
|
+
}
|
|
81
|
+
const output = await next();
|
|
82
|
+
await options.cache.set(key, output);
|
|
83
|
+
return output;
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
export const createInMemoryGenerateCache = () => {
|
|
87
|
+
const store = new Map();
|
|
88
|
+
return {
|
|
89
|
+
get(key) {
|
|
90
|
+
return store.get(key);
|
|
91
|
+
},
|
|
92
|
+
set(key, value) {
|
|
93
|
+
store.set(key, value);
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
export const createFileGenerateCache = (options) => {
|
|
98
|
+
const getPath = (key) => path.join(options.dir, `${Buffer.from(key).toString("base64url")}.json`);
|
|
99
|
+
return {
|
|
100
|
+
async get(key) {
|
|
101
|
+
try {
|
|
102
|
+
const file = await fs.readFile(getPath(key), "utf8");
|
|
103
|
+
return JSON.parse(file);
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
const err = error;
|
|
107
|
+
if (err?.code === "ENOENT") {
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
async set(key, value) {
|
|
114
|
+
await fs.mkdir(options.dir, { recursive: true });
|
|
115
|
+
await fs.writeFile(getPath(key), JSON.stringify(value), "utf8");
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
};
|
|
119
|
+
export const createCircuitBreakerMiddleware = (options) => {
|
|
120
|
+
const failureThreshold = Math.max(1, options.failureThreshold ?? 3);
|
|
121
|
+
const cooldownMs = Math.max(0, options.cooldownMs ?? 30_000);
|
|
122
|
+
const state = { failures: 0 };
|
|
123
|
+
return {
|
|
124
|
+
name: "circuit-breaker",
|
|
125
|
+
async wrapGenerate(context, next) {
|
|
126
|
+
const now = Date.now();
|
|
127
|
+
if (state.openedAt && now - state.openedAt < cooldownMs) {
|
|
128
|
+
throw new Error(`Circuit breaker open for model "${context.model.provider}/${context.model.modelId}".`);
|
|
129
|
+
}
|
|
130
|
+
if (state.openedAt && now - state.openedAt >= cooldownMs) {
|
|
131
|
+
await options.onStateChange?.({
|
|
132
|
+
...state,
|
|
133
|
+
model: context.model,
|
|
134
|
+
status: "half-open"
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
try {
|
|
138
|
+
const result = await next();
|
|
139
|
+
state.failures = 0;
|
|
140
|
+
state.openedAt = undefined;
|
|
141
|
+
await options.onStateChange?.({
|
|
142
|
+
...state,
|
|
143
|
+
model: context.model,
|
|
144
|
+
status: "closed"
|
|
145
|
+
});
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
150
|
+
const isFailure = options.isFailure?.(err) ?? true;
|
|
151
|
+
if (!isFailure) {
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
state.failures += 1;
|
|
155
|
+
if (state.failures >= failureThreshold) {
|
|
156
|
+
state.openedAt = Date.now();
|
|
157
|
+
await options.onStateChange?.({
|
|
158
|
+
...state,
|
|
159
|
+
model: context.model,
|
|
160
|
+
status: "open"
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
//# sourceMappingURL=middleware.js.map
|