@statelyai/agent 2.0.0-alpha.21 → 2.0.0-alpha.23
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/ai-sdk.cjs +53 -25
- package/dist/ai-sdk.d.cts +20 -12
- package/dist/ai-sdk.d.mts +20 -12
- package/dist/ai-sdk.mjs +53 -25
- package/dist/{decision-JWx6n3xR.mjs → decision-BBZ2jMO1.mjs} +542 -84
- package/dist/{decision-BnTCsuJv.cjs → decision-Cv6SfNWl.cjs} +629 -99
- package/dist/index.cjs +2225 -1032
- package/dist/index.d.cts +415 -276
- package/dist/index.d.mts +415 -276
- package/dist/index.mjs +2163 -983
- package/dist/machines.cjs +30 -2
- package/dist/machines.d.cts +151 -54
- package/dist/machines.d.mts +151 -54
- package/dist/machines.mjs +30 -2
- package/dist/openai.cjs +447 -0
- package/dist/openai.d.cts +177 -0
- package/dist/openai.d.mts +177 -0
- package/dist/openai.mjs +437 -0
- package/dist/otel.cjs +3 -6
- package/dist/otel.d.cts +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/otel.mjs +3 -6
- package/dist/run-agent-Ck7Sa3Tb.d.mts +968 -0
- package/dist/run-agent-DWqA8KiI.d.cts +968 -0
- package/dist/setup-agent-CeO2fARv.mjs +639 -0
- package/dist/setup-agent-Dl2VELLi.cjs +663 -0
- package/dist/{text-logic-Mmbgb2jy.d.cts → text-logic-C7bSnH_B.d.cts} +238 -44
- package/dist/{text-logic-BR5twXCv.d.mts → text-logic-DJBK3LbG.d.mts} +238 -44
- package/dist/{types-DSdj2tGs.d.cts → types-CjHk5OdH.d.cts} +4 -19
- package/dist/{types-CvWRGFxP.d.mts → types-DWA6X9R-.d.mts} +4 -19
- package/package.json +17 -21
- package/readme.md +32 -17
- package/dist/errors-BQRk9eiZ.d.cts +0 -19
- package/dist/errors-C9rxnWbX.d.mts +0 -19
- package/dist/errors-CeSXQx0v.mjs +0 -23
- package/dist/errors-DUBBzRLP.cjs +0 -28
- package/dist/event-log-store-Bz7HDBkE.d.cts +0 -145
- package/dist/event-log-store-DmIDosD6.mjs +0 -427
- package/dist/event-log-store-a_TKy1gk.cjs +0 -468
- package/dist/event-log-store-hrA1vqtN.d.mts +0 -145
- package/dist/run-agent-DBNI8ETM.d.mts +0 -1098
- package/dist/run-agent-Do094mGu.d.cts +0 -1098
- package/dist/setup-agent-91FSuZbB.cjs +0 -1641
- package/dist/setup-agent-DqqdcdNh.mjs +0 -1521
- package/dist/sqlite.cjs +0 -129
- package/dist/sqlite.d.cts +0 -57
- package/dist/sqlite.d.mts +0 -57
- package/dist/sqlite.mjs +0 -127
package/dist/openai.cjs
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_decision = require("./decision-Cv6SfNWl.cjs");
|
|
3
|
+
//#region src/openai/index.ts
|
|
4
|
+
/** Thrown for a message part Chat Completions cannot carry — dropping it would
|
|
5
|
+
* silently change what the model sees. */
|
|
6
|
+
function unsupportedPart(role, type) {
|
|
7
|
+
throw new Error(`createOpenAiExecutors: a ${role} message part of type '${type}' has no Chat Completions equivalent. Send text, image, tool-call, or tool-result parts, or convert it before the request.`);
|
|
8
|
+
}
|
|
9
|
+
/** A `DataContent`/`URL` image as the URL string OpenAI's `image_url` part wants:
|
|
10
|
+
* an http(s) or `data:` string and a `URL` pass through, a bare base64 string and
|
|
11
|
+
* raw bytes are wrapped in a data URL. */
|
|
12
|
+
function toImageUrl(image, mediaType) {
|
|
13
|
+
if (image instanceof URL) return image.href;
|
|
14
|
+
const type = mediaType ?? "image/jpeg";
|
|
15
|
+
if (typeof image === "string") return /^(https?:|data:)/.test(image) ? image : `data:${type};base64,${image}`;
|
|
16
|
+
const bytes = image instanceof Uint8Array ? image : new Uint8Array(image);
|
|
17
|
+
const encode = globalThis.btoa;
|
|
18
|
+
if (!encode) throw new Error("createOpenAiExecutors: binary image parts need a global `btoa` to base64-encode. Pass the image as a URL or a base64 string instead.");
|
|
19
|
+
let binary = "";
|
|
20
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
21
|
+
return `data:${type};base64,${encode(binary)}`;
|
|
22
|
+
}
|
|
23
|
+
/** One OpenAI tool message per `ToolResultPart` — the tool role is one message per result. */
|
|
24
|
+
function toToolMessage(part) {
|
|
25
|
+
return {
|
|
26
|
+
role: "tool",
|
|
27
|
+
content: part.output.type === "text" || part.output.type === "error-text" ? part.output.value : JSON.stringify(part.output.value),
|
|
28
|
+
tool_call_id: part.toolCallId
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** Maps `AgentTextRequest.messages`/`system`/`prompt` to OpenAI chat messages. */
|
|
32
|
+
function toOpenAiMessages(request) {
|
|
33
|
+
if (request.messages) return request.messages.flatMap((message) => {
|
|
34
|
+
switch (message.role) {
|
|
35
|
+
case "system": return [{
|
|
36
|
+
role: "system",
|
|
37
|
+
content: message.content
|
|
38
|
+
}];
|
|
39
|
+
case "user":
|
|
40
|
+
if (typeof message.content === "string") return [{
|
|
41
|
+
role: "user",
|
|
42
|
+
content: message.content
|
|
43
|
+
}];
|
|
44
|
+
return [{
|
|
45
|
+
role: "user",
|
|
46
|
+
content: message.content.map((part) => {
|
|
47
|
+
switch (part.type) {
|
|
48
|
+
case "text": return {
|
|
49
|
+
type: "text",
|
|
50
|
+
text: part.text
|
|
51
|
+
};
|
|
52
|
+
case "image": return {
|
|
53
|
+
type: "image_url",
|
|
54
|
+
image_url: { url: toImageUrl(part.image, part.mediaType) }
|
|
55
|
+
};
|
|
56
|
+
default: return unsupportedPart("user", part.type);
|
|
57
|
+
}
|
|
58
|
+
})
|
|
59
|
+
}];
|
|
60
|
+
case "assistant": {
|
|
61
|
+
if (typeof message.content === "string") return [{
|
|
62
|
+
role: "assistant",
|
|
63
|
+
content: message.content
|
|
64
|
+
}];
|
|
65
|
+
let text = "";
|
|
66
|
+
const toolCalls = [];
|
|
67
|
+
const trailing = [];
|
|
68
|
+
for (const part of message.content) switch (part.type) {
|
|
69
|
+
case "text":
|
|
70
|
+
text += part.text;
|
|
71
|
+
break;
|
|
72
|
+
case "tool-call":
|
|
73
|
+
toolCalls.push({
|
|
74
|
+
id: part.toolCallId,
|
|
75
|
+
type: "function",
|
|
76
|
+
function: {
|
|
77
|
+
name: part.toolName,
|
|
78
|
+
arguments: JSON.stringify(part.input ?? {})
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
break;
|
|
82
|
+
case "tool-result":
|
|
83
|
+
trailing.push(toToolMessage(part));
|
|
84
|
+
break;
|
|
85
|
+
default: unsupportedPart("assistant", part.type);
|
|
86
|
+
}
|
|
87
|
+
return [{
|
|
88
|
+
role: "assistant",
|
|
89
|
+
content: text,
|
|
90
|
+
...toolCalls.length > 0 ? { tool_calls: toolCalls } : {}
|
|
91
|
+
}, ...trailing];
|
|
92
|
+
}
|
|
93
|
+
case "tool": return message.content.map(toToolMessage);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
const messages = [];
|
|
97
|
+
if (request.system) messages.push({
|
|
98
|
+
role: "system",
|
|
99
|
+
content: request.system
|
|
100
|
+
});
|
|
101
|
+
messages.push({
|
|
102
|
+
role: "user",
|
|
103
|
+
content: request.prompt ?? ""
|
|
104
|
+
});
|
|
105
|
+
return messages;
|
|
106
|
+
}
|
|
107
|
+
/** Drops keys whose value is `undefined`, so a spread cannot erase what it lands on. */
|
|
108
|
+
function defined(settings) {
|
|
109
|
+
return Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== void 0));
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Maps the generation settings a text and a decision request share onto OpenAI
|
|
113
|
+
* Chat Completions parameters, with unset keys omitted.
|
|
114
|
+
*
|
|
115
|
+
* Omitting matters: these are the top layer of a stack — the host's
|
|
116
|
+
* {@link CreateOpenAiExecutorsOptions.settings}, then the request's — and an
|
|
117
|
+
* `undefined` spread over the layer below would erase it.
|
|
118
|
+
*
|
|
119
|
+
* `max_tokens` is deprecated by OpenAI in favor of `max_completion_tokens`, so
|
|
120
|
+
* that's what `maxOutputTokens` targets. Chat Completions has no `top_k`
|
|
121
|
+
* parameter, so `topK` is dropped.
|
|
122
|
+
*/
|
|
123
|
+
function toOpenAiCallSettings(request) {
|
|
124
|
+
return defined({
|
|
125
|
+
temperature: request.temperature,
|
|
126
|
+
max_completion_tokens: request.maxOutputTokens,
|
|
127
|
+
top_p: request.topP,
|
|
128
|
+
seed: request.seed,
|
|
129
|
+
stop: request.stopSequences
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/** A tool `description` may be a string or, for an AI SDK v7 tool, a function
|
|
133
|
+
* of the call's context. A raw JSON payload can only carry the static form. */
|
|
134
|
+
function staticDescription(descriptor) {
|
|
135
|
+
if (typeof descriptor === "function") return;
|
|
136
|
+
return typeof descriptor.description === "string" ? descriptor.description : void 0;
|
|
137
|
+
}
|
|
138
|
+
/** One OpenAI function tool per `AgentTools` entry. */
|
|
139
|
+
function toOpenAiTools(tools) {
|
|
140
|
+
return Object.entries(tools).flatMap(([name, descriptor]) => {
|
|
141
|
+
if (!descriptor) return [];
|
|
142
|
+
const inputSchema = typeof descriptor === "function" ? void 0 : descriptor.inputSchema;
|
|
143
|
+
return [{
|
|
144
|
+
type: "function",
|
|
145
|
+
function: {
|
|
146
|
+
name,
|
|
147
|
+
description: staticDescription(descriptor),
|
|
148
|
+
parameters: (require_decision.isStandardSchema(inputSchema) ? require_decision.getJsonSchemaSync(inputSchema) : void 0) ?? {}
|
|
149
|
+
}
|
|
150
|
+
}];
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Maps an {@link AgentToolChoice} onto OpenAI's `tool_choice` —
|
|
155
|
+
* `{ type: 'tool', name }` becomes `{ type: 'function', function: { name } }`;
|
|
156
|
+
* `'auto'`/`'none'`/`'required'` are OpenAI's own vocabulary and pass through.
|
|
157
|
+
* `undefined` stays `undefined`, so the key is omitted.
|
|
158
|
+
*/
|
|
159
|
+
function toOpenAiToolChoice(toolChoice) {
|
|
160
|
+
if (toolChoice === void 0) return;
|
|
161
|
+
return typeof toolChoice === "object" ? {
|
|
162
|
+
type: "function",
|
|
163
|
+
function: { name: toolChoice.name }
|
|
164
|
+
} : toolChoice;
|
|
165
|
+
}
|
|
166
|
+
/** One OpenAI function tool per candidate decision event — the "tool-per-event
|
|
167
|
+
* + tool_choice: 'required'" recipe, mirroring `toAiSdkEventTools`. */
|
|
168
|
+
function toOpenAiEventTools(events) {
|
|
169
|
+
return events.map((event) => ({
|
|
170
|
+
type: "function",
|
|
171
|
+
function: {
|
|
172
|
+
name: event.toolName,
|
|
173
|
+
description: `Choose the '${event.type}' move.`,
|
|
174
|
+
parameters: require_decision.getJsonSchemaSync(event.inputSchema) ?? {}
|
|
175
|
+
}
|
|
176
|
+
}));
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Messages for a decision request, with prior failed `attempts` rendered as an
|
|
180
|
+
* appended user message so retries converge. Mirrors the AI SDK adapter's
|
|
181
|
+
* `toDecisionMessages`.
|
|
182
|
+
*/
|
|
183
|
+
function toDecisionMessages(request) {
|
|
184
|
+
const messages = toOpenAiMessages(request);
|
|
185
|
+
for (const attempt of require_decision.renderDecisionAttempts(request)) messages.push({
|
|
186
|
+
role: "user",
|
|
187
|
+
content: attempt.content
|
|
188
|
+
});
|
|
189
|
+
return messages;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Folds OpenAI's usage payload onto the flat {@link AgentCallUsage} field names
|
|
193
|
+
* core aggregates. OpenAI nests the reasoning count under
|
|
194
|
+
* `completion_tokens_details` and the cache-read count under
|
|
195
|
+
* `prompt_tokens_details`; a field the response omitted stays omitted, so it
|
|
196
|
+
* never contributes a `0` to a run's partial sums.
|
|
197
|
+
*/
|
|
198
|
+
function toAgentCallUsage(usage) {
|
|
199
|
+
if (!usage) return;
|
|
200
|
+
const reasoningTokens = usage.completion_tokens_details?.reasoning_tokens;
|
|
201
|
+
const cachedInputTokens = usage.prompt_tokens_details?.cached_tokens;
|
|
202
|
+
return {
|
|
203
|
+
...usage.prompt_tokens !== void 0 ? { inputTokens: usage.prompt_tokens } : {},
|
|
204
|
+
...usage.completion_tokens !== void 0 ? { outputTokens: usage.completion_tokens } : {},
|
|
205
|
+
...usage.total_tokens !== void 0 ? { totalTokens: usage.total_tokens } : {},
|
|
206
|
+
...reasoningTokens !== void 0 ? { reasoningTokens } : {},
|
|
207
|
+
...cachedInputTokens !== void 0 ? { cachedInputTokens } : {}
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Maps an OpenAI `finish_reason` onto the portable {@link AgentFinishReason}.
|
|
212
|
+
* `'function_call'` (the deprecated legacy path) joins `'tool_calls'` under
|
|
213
|
+
* `'tool-calls'`; anything unrecognized, including a missing reason, lands on
|
|
214
|
+
* `'other'`. OpenAI's own string stays on the result's `raw`.
|
|
215
|
+
*/
|
|
216
|
+
function toAgentFinishReason(finishReason) {
|
|
217
|
+
switch (finishReason) {
|
|
218
|
+
case "stop": return "stop";
|
|
219
|
+
case "length": return "length";
|
|
220
|
+
case "tool_calls":
|
|
221
|
+
case "function_call": return "tool-calls";
|
|
222
|
+
case "content_filter": return "content-filter";
|
|
223
|
+
default: return "other";
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/** Resolves the host's `settings` option for one request. */
|
|
227
|
+
function callSettings(options, request) {
|
|
228
|
+
const settings = options.settings;
|
|
229
|
+
if (typeof settings === "function") return settings(request) ?? {};
|
|
230
|
+
const entry = settings?.[request.model];
|
|
231
|
+
if (entry === void 0) return {};
|
|
232
|
+
if (typeof entry !== "object" || entry === null) throw new Error(`createOpenAiExecutors: \`settings\` is keyed by model ref, so every value must be an object of OpenAI parameters, but '${request.model}' is a ${typeof entry}. Pass a function if you want one set of settings for every call.`);
|
|
233
|
+
return entry;
|
|
234
|
+
}
|
|
235
|
+
function truncated(request, info, partialOutput, cause) {
|
|
236
|
+
return new require_decision.AgentTruncatedError(`createOpenAiExecutors: request '${request.name ?? "(unnamed)"}' hit the output token limit — its structured output never completed. Raise \`maxOutputTokens\`, shorten the input, or ask for a smaller output schema.`, {
|
|
237
|
+
requestName: request.name ?? "(unnamed)",
|
|
238
|
+
...info?.requestId !== void 0 ? { requestId: info.requestId } : {},
|
|
239
|
+
...partialOutput !== void 0 ? { partialOutput } : {},
|
|
240
|
+
...cause !== void 0 ? { cause } : {}
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
function usageField(usage) {
|
|
244
|
+
return usage ? { usage } : {};
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Adds two calls' usage together, field by field. A tool loop makes several
|
|
248
|
+
* OpenAI calls per request, and core folds ONE `usage` per executor result into
|
|
249
|
+
* the run's totals, so the steps' usages have to be summed here or the run
|
|
250
|
+
* undercounts. A field neither call reported stays absent.
|
|
251
|
+
*/
|
|
252
|
+
function addAgentCallUsage(total, next) {
|
|
253
|
+
if (!total || !next) return total ?? next;
|
|
254
|
+
const sum = {};
|
|
255
|
+
for (const field of require_decision.AGENT_USAGE_TOKEN_FIELDS) if (total[field] !== void 0 || next[field] !== void 0) sum[field] = (total[field] ?? 0) + (next[field] ?? 0);
|
|
256
|
+
return sum;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* The function that runs one of the request's tools host-side, or `undefined`
|
|
260
|
+
* when the tool has no `execute` (a client-side tool: the model's call is
|
|
261
|
+
* handed back to the caller instead of being answered here).
|
|
262
|
+
*/
|
|
263
|
+
function toolExecutor(tools, name) {
|
|
264
|
+
const descriptor = tools[name];
|
|
265
|
+
if (!descriptor) return;
|
|
266
|
+
if (typeof descriptor === "function") return (input) => descriptor(input);
|
|
267
|
+
const execute = descriptor.execute;
|
|
268
|
+
return typeof execute === "function" ? (input) => execute(input) : void 0;
|
|
269
|
+
}
|
|
270
|
+
function toToolContent(output) {
|
|
271
|
+
return typeof output === "string" ? output : JSON.stringify(output ?? null);
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Builds the `{ generateText, streamText, decide }` executor set for the raw
|
|
275
|
+
* `openai` package's Chat Completions API. Compare `createAiSdkExecutors` —
|
|
276
|
+
* same shape, different SDK underneath.
|
|
277
|
+
*
|
|
278
|
+
* Structured output uses `response_format: { type: 'json_schema' }` around the
|
|
279
|
+
* uniform `{ result, reasoning? }` envelope, and decisions force a tool call
|
|
280
|
+
* with `tool_choice: 'required'`, one function tool per candidate event.
|
|
281
|
+
*
|
|
282
|
+
* @example
|
|
283
|
+
* ```ts
|
|
284
|
+
* const executors = createOpenAiExecutors({
|
|
285
|
+
* client: new OpenAI(),
|
|
286
|
+
* resolveModel: () => 'gpt-5.4-mini',
|
|
287
|
+
* });
|
|
288
|
+
* const result = await runAgent(machine, { input, executors });
|
|
289
|
+
* ```
|
|
290
|
+
*/
|
|
291
|
+
function createOpenAiExecutors(options) {
|
|
292
|
+
const { client, resolveModel = (modelRef) => modelRef } = options;
|
|
293
|
+
const textParams = (request, messages, extra = {}) => {
|
|
294
|
+
const tools = toOpenAiTools(request.tools);
|
|
295
|
+
return {
|
|
296
|
+
model: resolveModel(request.model),
|
|
297
|
+
messages,
|
|
298
|
+
...callSettings(options, request),
|
|
299
|
+
...toOpenAiCallSettings(request),
|
|
300
|
+
...tools.length > 0 ? { tools } : {},
|
|
301
|
+
...extra
|
|
302
|
+
};
|
|
303
|
+
};
|
|
304
|
+
const envelopeSchema = async (request) => {
|
|
305
|
+
if (require_decision.getAgentOutputMode(request.outputSchema) !== "structured") return;
|
|
306
|
+
return require_decision.getJsonSchema(require_decision.buildEnvelopeSchema(request.outputSchema, { reasoning: request.includeReasoning }));
|
|
307
|
+
};
|
|
308
|
+
const generateText = async (request, info) => {
|
|
309
|
+
const jsonSchema = await envelopeSchema(request);
|
|
310
|
+
const responseFormat = jsonSchema ? { response_format: {
|
|
311
|
+
type: "json_schema",
|
|
312
|
+
json_schema: {
|
|
313
|
+
name: "output",
|
|
314
|
+
schema: jsonSchema,
|
|
315
|
+
strict: false
|
|
316
|
+
}
|
|
317
|
+
} } : {};
|
|
318
|
+
const maxSteps = typeof request.maxSteps === "number" && Number.isFinite(request.maxSteps) ? Math.max(1, Math.floor(request.maxSteps)) : 1;
|
|
319
|
+
const messages = toOpenAiMessages(request);
|
|
320
|
+
const toolChoice = toOpenAiToolChoice(request.toolChoice);
|
|
321
|
+
let response;
|
|
322
|
+
let usage;
|
|
323
|
+
let step = 0;
|
|
324
|
+
for (;;) {
|
|
325
|
+
step++;
|
|
326
|
+
response = await client.chat.completions.create(textParams(request, messages, {
|
|
327
|
+
...responseFormat,
|
|
328
|
+
...step === 1 && toolChoice !== void 0 ? { tool_choice: toolChoice } : {}
|
|
329
|
+
}), { signal: info?.signal });
|
|
330
|
+
usage = addAgentCallUsage(usage, toAgentCallUsage(response.usage));
|
|
331
|
+
const message = response.choices[0]?.message;
|
|
332
|
+
const toolCalls = message?.tool_calls ?? [];
|
|
333
|
+
if (toolCalls.length === 0 || step >= maxSteps) break;
|
|
334
|
+
const executors = toolCalls.map((call) => call.type === "function" ? toolExecutor(request.tools, call.function.name) : void 0);
|
|
335
|
+
if (executors.some((execute) => !execute)) break;
|
|
336
|
+
messages.push(message);
|
|
337
|
+
for (const [index, call] of toolCalls.entries()) {
|
|
338
|
+
const input = call.type === "function" && call.function.arguments ? JSON.parse(call.function.arguments) : {};
|
|
339
|
+
let content;
|
|
340
|
+
try {
|
|
341
|
+
content = toToolContent(await executors[index](input));
|
|
342
|
+
} catch (error) {
|
|
343
|
+
content = `Error: ${error instanceof Error ? error.message : String(error)}`;
|
|
344
|
+
}
|
|
345
|
+
messages.push({
|
|
346
|
+
role: "tool",
|
|
347
|
+
tool_call_id: call.id,
|
|
348
|
+
content
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
const unwrap = (content) => require_decision.parseStructuredEnvelope(request, content ? JSON.parse(content) : void 0);
|
|
353
|
+
const choice = response.choices[0];
|
|
354
|
+
const finishReason = toAgentFinishReason(choice?.finish_reason);
|
|
355
|
+
const content = choice?.message.content;
|
|
356
|
+
if (jsonSchema) {
|
|
357
|
+
if (finishReason === "length") throw truncated(request, info, content ?? void 0);
|
|
358
|
+
const parsed = unwrap(content);
|
|
359
|
+
return {
|
|
360
|
+
output: parsed.result,
|
|
361
|
+
...typeof parsed.reasoning === "string" ? { reasoning: parsed.reasoning } : {},
|
|
362
|
+
...usageField(usage),
|
|
363
|
+
finishReason,
|
|
364
|
+
raw: response
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
return {
|
|
368
|
+
output: content ?? "",
|
|
369
|
+
...usageField(usage),
|
|
370
|
+
finishReason,
|
|
371
|
+
raw: response
|
|
372
|
+
};
|
|
373
|
+
};
|
|
374
|
+
const streamText = async (request, info) => {
|
|
375
|
+
if (require_decision.getAgentOutputMode(request.outputSchema) === "structured") throw new Error("createOpenAiExecutors: streamText is text-only — a request declaring a structured output schema must be routed to generateText.");
|
|
376
|
+
if (Object.keys(request.tools ?? {}).length > 0) throw new Error("createOpenAiExecutors: streamText is text-only — a request declaring tools must be routed to generateText.");
|
|
377
|
+
const stream = await client.chat.completions.create({
|
|
378
|
+
model: resolveModel(request.model),
|
|
379
|
+
messages: toOpenAiMessages(request),
|
|
380
|
+
...callSettings(options, request),
|
|
381
|
+
...toOpenAiCallSettings(request),
|
|
382
|
+
stream: true,
|
|
383
|
+
stream_options: { include_usage: true }
|
|
384
|
+
}, { signal: info?.signal });
|
|
385
|
+
let text = "";
|
|
386
|
+
let finishReason = "other";
|
|
387
|
+
let usage;
|
|
388
|
+
let last;
|
|
389
|
+
for await (const chunk of stream) {
|
|
390
|
+
last = chunk;
|
|
391
|
+
const choice = chunk.choices[0];
|
|
392
|
+
const delta = choice?.delta.content;
|
|
393
|
+
if (delta) {
|
|
394
|
+
text += delta;
|
|
395
|
+
info?.onChunk?.(delta);
|
|
396
|
+
}
|
|
397
|
+
if (choice?.finish_reason) finishReason = toAgentFinishReason(choice.finish_reason);
|
|
398
|
+
if (chunk.usage) usage = chunk.usage;
|
|
399
|
+
}
|
|
400
|
+
return {
|
|
401
|
+
output: text,
|
|
402
|
+
...usageField(toAgentCallUsage(usage)),
|
|
403
|
+
finishReason,
|
|
404
|
+
raw: last
|
|
405
|
+
};
|
|
406
|
+
};
|
|
407
|
+
const decide = async (request, info) => {
|
|
408
|
+
const response = await client.chat.completions.create({
|
|
409
|
+
model: resolveModel(request.model),
|
|
410
|
+
messages: toDecisionMessages(request),
|
|
411
|
+
...callSettings(options, request),
|
|
412
|
+
...toOpenAiCallSettings(request),
|
|
413
|
+
tools: toOpenAiEventTools(request.events),
|
|
414
|
+
tool_choice: "required"
|
|
415
|
+
}, { signal: info?.signal });
|
|
416
|
+
const toolCall = response.choices[0]?.message.tool_calls?.[0];
|
|
417
|
+
if (!toolCall || toolCall.type !== "function") throw new Error("createOpenAiExecutors: decide — model did not call an event tool.");
|
|
418
|
+
const chosenEvent = request.events.find((event) => event.toolName === toolCall.function.name);
|
|
419
|
+
if (!chosenEvent) throw new Error(`createOpenAiExecutors: decide — model called unknown tool '${toolCall.function.name}'.`);
|
|
420
|
+
const args = toolCall.function.arguments ? JSON.parse(toolCall.function.arguments) : {};
|
|
421
|
+
return {
|
|
422
|
+
event: {
|
|
423
|
+
...args && typeof args === "object" ? args : {},
|
|
424
|
+
type: chosenEvent.type
|
|
425
|
+
},
|
|
426
|
+
...usageField(toAgentCallUsage(response.usage)),
|
|
427
|
+
finishReason: toAgentFinishReason(response.choices[0]?.finish_reason),
|
|
428
|
+
raw: response
|
|
429
|
+
};
|
|
430
|
+
};
|
|
431
|
+
return {
|
|
432
|
+
generateText,
|
|
433
|
+
streamText,
|
|
434
|
+
decide
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
//#endregion
|
|
438
|
+
exports.addAgentCallUsage = addAgentCallUsage;
|
|
439
|
+
exports.createOpenAiExecutors = createOpenAiExecutors;
|
|
440
|
+
exports.toAgentCallUsage = toAgentCallUsage;
|
|
441
|
+
exports.toAgentFinishReason = toAgentFinishReason;
|
|
442
|
+
exports.toDecisionMessages = toDecisionMessages;
|
|
443
|
+
exports.toOpenAiCallSettings = toOpenAiCallSettings;
|
|
444
|
+
exports.toOpenAiEventTools = toOpenAiEventTools;
|
|
445
|
+
exports.toOpenAiMessages = toOpenAiMessages;
|
|
446
|
+
exports.toOpenAiToolChoice = toOpenAiToolChoice;
|
|
447
|
+
exports.toOpenAiTools = toOpenAiTools;
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { i as AgentToolChoice, n as AgentMessage, s as AgentTools, u as ChosenEvent } from "./types-CjHk5OdH.cjs";
|
|
2
|
+
import { F as AgentDecisionRequest, K as AgentEventDescriptor, c as AgentRequestExecutorInfo, f as AgentTextRequest, r as AgentFinishReason, t as AgentCallUsage } from "./text-logic-C7bSnH_B.cjs";
|
|
3
|
+
import OpenAI from "openai";
|
|
4
|
+
import { ChatCompletion, ChatCompletionCreateParamsNonStreaming, ChatCompletionMessageParam, ChatCompletionTool } from "openai/resources/chat/completions/completions.js";
|
|
5
|
+
|
|
6
|
+
//#region src/openai/index.d.ts
|
|
7
|
+
/** Maps `AgentTextRequest.messages`/`system`/`prompt` to OpenAI chat messages. */
|
|
8
|
+
declare function toOpenAiMessages(request: Pick<AgentTextRequest, "system" | "prompt"> & {
|
|
9
|
+
messages?: AgentMessage[];
|
|
10
|
+
}): ChatCompletionMessageParam[];
|
|
11
|
+
/**
|
|
12
|
+
* Maps the generation settings a text and a decision request share onto OpenAI
|
|
13
|
+
* Chat Completions parameters, with unset keys omitted.
|
|
14
|
+
*
|
|
15
|
+
* Omitting matters: these are the top layer of a stack — the host's
|
|
16
|
+
* {@link CreateOpenAiExecutorsOptions.settings}, then the request's — and an
|
|
17
|
+
* `undefined` spread over the layer below would erase it.
|
|
18
|
+
*
|
|
19
|
+
* `max_tokens` is deprecated by OpenAI in favor of `max_completion_tokens`, so
|
|
20
|
+
* that's what `maxOutputTokens` targets. Chat Completions has no `top_k`
|
|
21
|
+
* parameter, so `topK` is dropped.
|
|
22
|
+
*/
|
|
23
|
+
declare function toOpenAiCallSettings(request: Pick<AgentTextRequest, "temperature" | "maxOutputTokens" | "topP" | "seed" | "stopSequences">): Partial<{
|
|
24
|
+
temperature: number | undefined;
|
|
25
|
+
max_completion_tokens: number | undefined;
|
|
26
|
+
top_p: number | undefined;
|
|
27
|
+
seed: number | undefined;
|
|
28
|
+
stop: string[] | undefined;
|
|
29
|
+
}>;
|
|
30
|
+
/** One OpenAI function tool per `AgentTools` entry. */
|
|
31
|
+
declare function toOpenAiTools(tools: AgentTools): ChatCompletionTool[];
|
|
32
|
+
/**
|
|
33
|
+
* Maps an {@link AgentToolChoice} onto OpenAI's `tool_choice` —
|
|
34
|
+
* `{ type: 'tool', name }` becomes `{ type: 'function', function: { name } }`;
|
|
35
|
+
* `'auto'`/`'none'`/`'required'` are OpenAI's own vocabulary and pass through.
|
|
36
|
+
* `undefined` stays `undefined`, so the key is omitted.
|
|
37
|
+
*/
|
|
38
|
+
declare function toOpenAiToolChoice(toolChoice: AgentToolChoice | undefined): "auto" | "none" | "required" | {
|
|
39
|
+
type: "function";
|
|
40
|
+
function: {
|
|
41
|
+
name: string;
|
|
42
|
+
};
|
|
43
|
+
} | undefined;
|
|
44
|
+
/** One OpenAI function tool per candidate decision event — the "tool-per-event
|
|
45
|
+
* + tool_choice: 'required'" recipe, mirroring `toAiSdkEventTools`. */
|
|
46
|
+
declare function toOpenAiEventTools(events: AgentEventDescriptor[]): ChatCompletionTool[];
|
|
47
|
+
/**
|
|
48
|
+
* Messages for a decision request, with prior failed `attempts` rendered as an
|
|
49
|
+
* appended user message so retries converge. Mirrors the AI SDK adapter's
|
|
50
|
+
* `toDecisionMessages`.
|
|
51
|
+
*/
|
|
52
|
+
declare function toDecisionMessages(request: Pick<AgentDecisionRequest, "messages" | "prompt" | "events" | "attempts">): ChatCompletionMessageParam[];
|
|
53
|
+
type OpenAiUsage = NonNullable<ChatCompletion["usage"]>;
|
|
54
|
+
/**
|
|
55
|
+
* Folds OpenAI's usage payload onto the flat {@link AgentCallUsage} field names
|
|
56
|
+
* core aggregates. OpenAI nests the reasoning count under
|
|
57
|
+
* `completion_tokens_details` and the cache-read count under
|
|
58
|
+
* `prompt_tokens_details`; a field the response omitted stays omitted, so it
|
|
59
|
+
* never contributes a `0` to a run's partial sums.
|
|
60
|
+
*/
|
|
61
|
+
declare function toAgentCallUsage(usage: OpenAiUsage | undefined): AgentCallUsage | undefined;
|
|
62
|
+
/**
|
|
63
|
+
* Maps an OpenAI `finish_reason` onto the portable {@link AgentFinishReason}.
|
|
64
|
+
* `'function_call'` (the deprecated legacy path) joins `'tool_calls'` under
|
|
65
|
+
* `'tool-calls'`; anything unrecognized, including a missing reason, lands on
|
|
66
|
+
* `'other'`. OpenAI's own string stays on the result's `raw`.
|
|
67
|
+
*/
|
|
68
|
+
declare function toAgentFinishReason(finishReason: ChatCompletion.Choice["finish_reason"] | null | undefined): AgentFinishReason;
|
|
69
|
+
/**
|
|
70
|
+
* Per-call OpenAI Chat Completions parameters a host can apply on top of what
|
|
71
|
+
* the machine asked for — `reasoning_effort`, `service_tier`,
|
|
72
|
+
* `max_completion_tokens`, and anything else the API accepts. Typed straight
|
|
73
|
+
* off the installed `openai` package, so it tracks that version instead of
|
|
74
|
+
* restating its vocabulary.
|
|
75
|
+
*
|
|
76
|
+
* The request's own fields are excluded: `model`, `messages`, `tools`,
|
|
77
|
+
* `tool_choice`, `response_format`, `n`, and the streaming switches belong to
|
|
78
|
+
* the machine and the adapter, and a host override would silently contradict
|
|
79
|
+
* them.
|
|
80
|
+
*/
|
|
81
|
+
type OpenAiCallSettings = Omit<Partial<ChatCompletionCreateParamsNonStreaming>, "model" | "messages" | "tools" | "tool_choice" | "response_format" | "n" | "stream">;
|
|
82
|
+
/**
|
|
83
|
+
* Options for {@link createOpenAiExecutors}.
|
|
84
|
+
*
|
|
85
|
+
* `client` is the injected `OpenAI` instance — this adapter never constructs
|
|
86
|
+
* one, so the API key, base URL, and transport stay the host's business.
|
|
87
|
+
*
|
|
88
|
+
* `resolveModel` maps a machine's model *ref* (e.g. `'ticketTriage'`) to a real
|
|
89
|
+
* OpenAI model id. A machine's requests carry refs, not ids, so a raw-SDK host
|
|
90
|
+
* must resolve them (the AI SDK adapter does this via its `models` map).
|
|
91
|
+
* Defaults to identity, for machines that already use real ids.
|
|
92
|
+
*
|
|
93
|
+
* `settings` carries provider knobs that are the HOST's business rather than
|
|
94
|
+
* the machine's, such as reasoning effort. Pass a map keyed by model ref to
|
|
95
|
+
* give a ref a persona — `deep` thinks harder than `quick` — without the
|
|
96
|
+
* machine naming a provider knob, or a function to vary settings per request
|
|
97
|
+
* (`request.name` is the request's registered key; return `undefined` for the
|
|
98
|
+
* defaults). Settings are merged UNDER what the request declared, so a machine
|
|
99
|
+
* that set `maxOutputTokens` still wins.
|
|
100
|
+
*/
|
|
101
|
+
type CreateOpenAiExecutorsOptions = {
|
|
102
|
+
client: OpenAI;
|
|
103
|
+
resolveModel?: (modelRef: string) => string;
|
|
104
|
+
settings?: Record<string, OpenAiCallSettings> | ((request: AgentTextRequest | AgentDecisionRequest) => OpenAiCallSettings | undefined);
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* Raw result shape from {@link OpenAiExecutors.generateText} — the `{ output }`
|
|
108
|
+
* envelope (the validated structured object for structured-output requests, or
|
|
109
|
+
* the model's text otherwise) plus the call metadata. Core only reads `output`; everything else flows
|
|
110
|
+
* verbatim to `runAgent`'s `onResult(request, { raw })`.
|
|
111
|
+
*/
|
|
112
|
+
type OpenAiGenerateResult = {
|
|
113
|
+
output: unknown;
|
|
114
|
+
/** The model's reasoning, present only when the request opted in via
|
|
115
|
+
* `includeReasoning` and the model produced it. Never enters machine
|
|
116
|
+
* context/output. */
|
|
117
|
+
reasoning?: string;
|
|
118
|
+
/** The call's token usage, on the flat field names `runAgent` folds into the
|
|
119
|
+
* run result's aggregated `AgentUsage`. Absent when OpenAI reported none. */
|
|
120
|
+
usage?: AgentCallUsage; /** Why the call stopped, normalized to the portable {@link AgentFinishReason}. OpenAI's own value stays on `raw`. */
|
|
121
|
+
finishReason: AgentFinishReason; /** The untouched OpenAI response. */
|
|
122
|
+
raw: unknown;
|
|
123
|
+
};
|
|
124
|
+
/** Raw result shape from {@link OpenAiExecutors.streamText} — the accumulated text once the stream finishes (chunks are delivered separately via `onChunk`), plus the stream's final usage/finish metadata. */
|
|
125
|
+
type OpenAiStreamResult = {
|
|
126
|
+
output: string; /** Present when the stream carried a usage chunk (the adapter asks for one via `stream_options`). */
|
|
127
|
+
usage?: AgentCallUsage;
|
|
128
|
+
finishReason: AgentFinishReason; /** The last chunk seen, which carries the stream's finish metadata. */
|
|
129
|
+
raw: unknown;
|
|
130
|
+
};
|
|
131
|
+
/** Raw result shape from {@link OpenAiExecutors.decide} — the chosen event plus the call metadata, delivered per decision attempt to `onResult`. */
|
|
132
|
+
type OpenAiDecideResult = {
|
|
133
|
+
event: ChosenEvent;
|
|
134
|
+
usage?: AgentCallUsage;
|
|
135
|
+
finishReason: AgentFinishReason;
|
|
136
|
+
raw: unknown;
|
|
137
|
+
};
|
|
138
|
+
/** `createOpenAiExecutors` always populates all three slots (unlike the general
|
|
139
|
+
* `AgentRequestExecutors`, where `streamText`/`decide` are optional), and its
|
|
140
|
+
* results are concretely typed. */
|
|
141
|
+
interface OpenAiExecutors {
|
|
142
|
+
generateText: (request: AgentTextRequest & {
|
|
143
|
+
tools: AgentTools;
|
|
144
|
+
}, info?: AgentRequestExecutorInfo) => Promise<OpenAiGenerateResult>;
|
|
145
|
+
streamText: (request: AgentTextRequest & {
|
|
146
|
+
tools: AgentTools;
|
|
147
|
+
}, info?: AgentRequestExecutorInfo) => Promise<OpenAiStreamResult>;
|
|
148
|
+
decide: (request: AgentDecisionRequest, info?: AgentRequestExecutorInfo) => Promise<OpenAiDecideResult>;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Adds two calls' usage together, field by field. A tool loop makes several
|
|
152
|
+
* OpenAI calls per request, and core folds ONE `usage` per executor result into
|
|
153
|
+
* the run's totals, so the steps' usages have to be summed here or the run
|
|
154
|
+
* undercounts. A field neither call reported stays absent.
|
|
155
|
+
*/
|
|
156
|
+
declare function addAgentCallUsage(total: AgentCallUsage | undefined, next: AgentCallUsage | undefined): AgentCallUsage | undefined;
|
|
157
|
+
/**
|
|
158
|
+
* Builds the `{ generateText, streamText, decide }` executor set for the raw
|
|
159
|
+
* `openai` package's Chat Completions API. Compare `createAiSdkExecutors` —
|
|
160
|
+
* same shape, different SDK underneath.
|
|
161
|
+
*
|
|
162
|
+
* Structured output uses `response_format: { type: 'json_schema' }` around the
|
|
163
|
+
* uniform `{ result, reasoning? }` envelope, and decisions force a tool call
|
|
164
|
+
* with `tool_choice: 'required'`, one function tool per candidate event.
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```ts
|
|
168
|
+
* const executors = createOpenAiExecutors({
|
|
169
|
+
* client: new OpenAI(),
|
|
170
|
+
* resolveModel: () => 'gpt-5.4-mini',
|
|
171
|
+
* });
|
|
172
|
+
* const result = await runAgent(machine, { input, executors });
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
declare function createOpenAiExecutors(options: CreateOpenAiExecutorsOptions): OpenAiExecutors;
|
|
176
|
+
//#endregion
|
|
177
|
+
export { CreateOpenAiExecutorsOptions, OpenAiCallSettings, OpenAiDecideResult, OpenAiExecutors, OpenAiGenerateResult, OpenAiStreamResult, addAgentCallUsage, createOpenAiExecutors, toAgentCallUsage, toAgentFinishReason, toDecisionMessages, toOpenAiCallSettings, toOpenAiEventTools, toOpenAiMessages, toOpenAiToolChoice, toOpenAiTools };
|