@zenmux/rosetta-ai 1.0.31 → 1.0.33

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.
@@ -0,0 +1,346 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateResponsesInteractionsParameters = validateResponsesInteractionsParameters;
4
+ exports.convertResponsesInteractionRequest = convertResponsesInteractionRequest;
5
+ const types_1 = require("../interactions/types");
6
+ function validateResponsesInteractionsParameters(params) {
7
+ if (params.include != null && !Array.isArray(params.include))
8
+ fail("include must be an array");
9
+ if (params.tools != null && !Array.isArray(params.tools))
10
+ fail("tools must be an array");
11
+ if (params.reasoning != null) {
12
+ const reasoning = object(params.reasoning, "reasoning");
13
+ for (const [key, value] of Object.entries(reasoning))
14
+ if (value != null && !["effort", "summary"].includes(key))
15
+ fail(`Unsupported reasoning.${key} for Interactions V1`);
16
+ }
17
+ if (params.text?.format?.type === "json_schema" && params.text.format.strict === true)
18
+ fail("Interactions V1 cannot guarantee text.format.strict=true");
19
+ if (params.tools?.some(tool => tool?.type === "function" && tool.strict === true))
20
+ fail("Interactions V1 cannot guarantee function strict=true");
21
+ for (const key of [
22
+ "temperature",
23
+ "top_p",
24
+ "top_logprobs",
25
+ "max_tool_calls",
26
+ "prompt_cache_key",
27
+ "prompt_cache_retention",
28
+ "safety_identifier",
29
+ "user",
30
+ "prompt",
31
+ "conversation",
32
+ ]) {
33
+ if (object(params, "params")[key] != null)
34
+ fail(`${key} is not supported by the Interactions converter`);
35
+ }
36
+ if (params.background === true)
37
+ fail("background=true is not supported; use synchronous requests");
38
+ if (params.previous_response_id)
39
+ fail("previous_response_id is not supported; send complete input history");
40
+ if (params.parallel_tool_calls === false)
41
+ fail("Interactions V1 cannot enforce parallel_tool_calls=false");
42
+ if (params.truncation != null && params.truncation !== "disabled")
43
+ fail("truncation=auto has no equivalent in Interactions V1");
44
+ if (params.service_tier != null && params.service_tier !== "auto")
45
+ fail("service_tier has no equivalent in Interactions V1");
46
+ if (params.stream_options != null && Object.keys(params.stream_options).length)
47
+ fail("stream_options has no equivalent in Interactions V1");
48
+ if (params.text?.verbosity != null)
49
+ fail("text.verbosity has no equivalent in Interactions V1");
50
+ if (params.reasoning?.effort != null &&
51
+ !["minimal", "low", "medium", "high"].includes(params.reasoning.effort))
52
+ fail("Unsupported reasoning.effort for Interactions V1");
53
+ if (params.reasoning?.summary != null && params.reasoning.summary !== "auto")
54
+ fail("Only reasoning.summary=auto has an equivalent in Interactions V1");
55
+ if (params.include?.length)
56
+ fail("include has no supported equivalent in Interactions conversion");
57
+ const known = new Set([
58
+ "model",
59
+ "input",
60
+ "instructions",
61
+ "tools",
62
+ "tool_choice",
63
+ "parallel_tool_calls",
64
+ "text",
65
+ "reasoning",
66
+ "include",
67
+ "max_output_tokens",
68
+ "metadata",
69
+ "store",
70
+ "stream",
71
+ "background",
72
+ "previous_response_id",
73
+ "truncation",
74
+ "service_tier",
75
+ "stream_options",
76
+ "temperature",
77
+ "top_p",
78
+ "top_logprobs",
79
+ "max_tool_calls",
80
+ "prompt_cache_key",
81
+ "prompt_cache_retention",
82
+ "safety_identifier",
83
+ "user",
84
+ "prompt",
85
+ "conversation",
86
+ ]);
87
+ for (const [key, value] of Object.entries(params)) {
88
+ if (value != null && !known.has(key))
89
+ fail(`Unsupported Responses parameter: ${key}`);
90
+ }
91
+ for (const key of ["store", "stream", "background", "parallel_tool_calls"]) {
92
+ if (params[key] != null && typeof params[key] !== "boolean")
93
+ fail(`${key} must be a boolean`);
94
+ }
95
+ if (params.max_output_tokens != null &&
96
+ (!Number.isSafeInteger(params.max_output_tokens) || params.max_output_tokens <= 0))
97
+ fail("max_output_tokens must be a positive integer");
98
+ }
99
+ /** Input ranges let a gateway restore native history/media without reimplementing conversion. */
100
+ function convertResponsesInteractionRequest(params) {
101
+ validateResponsesInteractionsParameters(params);
102
+ if (typeof params.model !== "string" || !params.model)
103
+ fail("model is required");
104
+ const input = [];
105
+ const system = [];
106
+ if (params.instructions != null)
107
+ system.push(string(params.instructions, "instructions"));
108
+ const names = new Map();
109
+ const results = new Set();
110
+ if (typeof params.input === "string")
111
+ input.push({ type: "user_input", content: [{ type: "text", text: params.input }] });
112
+ else if (Array.isArray(params.input)) {
113
+ for (const raw of params.input) {
114
+ const item = object(raw, "input item");
115
+ if (item.interactions != null)
116
+ fail("Native input history is not supported by Responses conversion");
117
+ if (item.type === "function_call") {
118
+ const id = nonempty(item.call_id, "function_call.call_id");
119
+ const name = nonempty(item.name, "function_call.name");
120
+ if (names.has(id))
121
+ fail("Duplicate function_call.call_id");
122
+ names.set(id, name);
123
+ input.push({ type: "function_call", id, name, arguments: parseArguments(item.arguments) });
124
+ }
125
+ else if (item.type === "function_call_output") {
126
+ const id = nonempty(item.call_id, "function_call_output.call_id");
127
+ if (!names.has(id) || results.has(id))
128
+ fail("Function result must match one preceding call");
129
+ results.add(id);
130
+ const result = typeof item.output === "string" ? item.output : parts(item.output).map(convertContent);
131
+ input.push({ type: "function_result", call_id: id, name: names.get(id), result });
132
+ }
133
+ else if (item.type === "reasoning") {
134
+ if (item.encrypted_content != null)
135
+ fail("Reasoning encrypted_content has no equivalent in Interactions conversion");
136
+ const summary = parts(item.summary).map(part => {
137
+ if (part.type !== "summary_text")
138
+ return fail("Unsupported reasoning summary part");
139
+ return { type: "text", text: string(part.text, "summary.text") };
140
+ });
141
+ if (summary.length)
142
+ input.push({ type: "thought", summary });
143
+ }
144
+ else if (item.type == null || item.type === "message") {
145
+ const role = item.role;
146
+ const content = typeof item.content === "string"
147
+ ? [{ type: "text", text: item.content }]
148
+ : parts(item.content).map(convertContent);
149
+ if (role === "system" || role === "developer") {
150
+ if (content.some(part => part.type !== "text"))
151
+ fail("System/developer messages must contain text");
152
+ system.push(content.map(part => (part.type === "text" ? part.text : "")).join(""));
153
+ }
154
+ else if (role === "user" || role === "assistant") {
155
+ input.push({ type: role === "user" ? "user_input" : "model_output", content });
156
+ }
157
+ else
158
+ fail("Unsupported Responses message role");
159
+ }
160
+ else
161
+ fail(`Unsupported Responses input item: ${item.type}`);
162
+ }
163
+ }
164
+ else
165
+ fail("input must be a string or an array of items");
166
+ const config = {};
167
+ if (params.max_output_tokens != null)
168
+ config.max_output_tokens = params.max_output_tokens;
169
+ if (params.reasoning?.effort != null)
170
+ config.thinking_level = params.reasoning
171
+ .effort;
172
+ if (params.reasoning?.summary === "auto")
173
+ config.thinking_summaries = "auto";
174
+ const tools = [];
175
+ const toolNames = new Set();
176
+ for (const raw of params.tools ?? []) {
177
+ const tool = object(raw, "tool");
178
+ if (tool.type === "function") {
179
+ const name = nonempty(tool.name, "function.name");
180
+ if (toolNames.has(name))
181
+ fail("Duplicate function tool name");
182
+ toolNames.add(name);
183
+ if (tool.strict === true)
184
+ fail("Interactions V1 cannot guarantee function strict=true");
185
+ if (tool.namespace != null)
186
+ fail("Namespaced tools are not supported by Interactions V1");
187
+ tools.push({
188
+ type: "function",
189
+ name,
190
+ ...(tool.description != null && { description: string(tool.description, "description") }),
191
+ ...(tool.parameters != null && { parameters: object(tool.parameters, "parameters") }),
192
+ });
193
+ }
194
+ else
195
+ fail(`Unsupported Interactions tool: ${tool.type}`);
196
+ }
197
+ if (params.tool_choice != null) {
198
+ const choice = params.tool_choice;
199
+ if (typeof choice === "string") {
200
+ if (!["auto", "none", "required"].includes(choice))
201
+ fail("Unsupported tool_choice");
202
+ config.tool_choice = choice === "required" ? "any" : choice;
203
+ }
204
+ else {
205
+ const value = object(choice, "tool_choice");
206
+ const chosen = value.type === "function"
207
+ ? [value]
208
+ : value.type === "allowed_tools"
209
+ ? parts(value.tools)
210
+ : fail("Unsupported tool_choice type");
211
+ const mode = value.type === "function" ? "required" : value.mode;
212
+ if (mode !== "auto" && mode !== "required")
213
+ fail("Unsupported allowed_tools mode");
214
+ if (!chosen.length)
215
+ fail("allowed_tools must not be empty");
216
+ config.tool_choice = {
217
+ allowed_tools: {
218
+ mode: mode === "required" ? "any" : "auto",
219
+ tools: chosen.map(tool => {
220
+ if (tool.type !== "function" ||
221
+ typeof tool.name !== "string" ||
222
+ !toolNames.has(tool.name))
223
+ fail("tool_choice must refer to a declared function");
224
+ return tool.name;
225
+ }),
226
+ },
227
+ };
228
+ }
229
+ if (config.tool_choice === "any" && !tools.length)
230
+ fail("required tool_choice requires tools");
231
+ }
232
+ const result = {
233
+ model: params.model,
234
+ input,
235
+ store: params.store ?? true,
236
+ stream: params.stream ?? false,
237
+ ...(system.length && { system_instruction: system.join("\n") }),
238
+ ...(tools.length && { tools }),
239
+ ...(Object.keys(config).length && { generation_config: config }),
240
+ };
241
+ const format = params.text?.format;
242
+ if (format != null) {
243
+ if (format.type === "text")
244
+ result.response_format = { type: "text", mime_type: "text/plain" };
245
+ else if (format.type === "json_object")
246
+ result.response_format = { type: "text", mime_type: "application/json" };
247
+ else if (format.type === "json_schema") {
248
+ if (format.strict === true)
249
+ fail("Interactions V1 cannot guarantee text.format.strict=true");
250
+ result.response_format = {
251
+ type: "text",
252
+ mime_type: "application/json",
253
+ schema: structuredClone(object(format.schema, "text.format.schema")),
254
+ };
255
+ }
256
+ else
257
+ fail("Unsupported text.format");
258
+ }
259
+ if (params.metadata != null) {
260
+ const metadata = object(params.metadata, "metadata");
261
+ if (Object.values(metadata).some(value => typeof value !== "string"))
262
+ fail("metadata values must be strings");
263
+ result.labels = Object.fromEntries(Object.entries(metadata).map(([key, value]) => {
264
+ if (typeof value !== "string")
265
+ fail("metadata values must be strings");
266
+ return [key, value];
267
+ }));
268
+ }
269
+ return result;
270
+ }
271
+ function convertContent(raw) {
272
+ const part = object(raw, "content part");
273
+ if (part.type === "input_text" || part.type === "output_text")
274
+ return { type: "text", text: string(part.text, "text") };
275
+ if (part.type === "refusal")
276
+ return { type: "text", text: string(part.refusal, "refusal") };
277
+ if (part.type === "input_image") {
278
+ if (part.file_id != null)
279
+ fail("OpenAI file_id cannot be resolved by Interactions");
280
+ if (part.detail != null && part.detail !== "auto")
281
+ fail("Image detail has no equivalent in Interactions V1");
282
+ return media("image", part.image_url);
283
+ }
284
+ if (part.type === "input_file") {
285
+ if (part.file_id != null)
286
+ fail("OpenAI file_id cannot be resolved by Interactions");
287
+ if (part.file_url != null && part.file_data != null)
288
+ fail("Use either file_url or file_data");
289
+ if (part.file_url != null)
290
+ return media("document", part.file_url);
291
+ const data = nonempty(part.file_data, "file_data");
292
+ if (data.startsWith("data:"))
293
+ return media("document", data);
294
+ const filename = part.filename == null ? undefined : string(part.filename, "filename");
295
+ const mime = filename?.endsWith(".pdf")
296
+ ? "application/pdf"
297
+ : filename?.endsWith(".csv")
298
+ ? "text/csv"
299
+ : undefined;
300
+ if (!mime)
301
+ fail("file_data requires a MIME data URL or .pdf/.csv filename");
302
+ return { type: "document", data, mime_type: mime };
303
+ }
304
+ return fail(`Unsupported Responses content part: ${part.type}`);
305
+ }
306
+ function media(type, raw) {
307
+ const value = nonempty(raw, "media URL");
308
+ if (!value.startsWith("data:"))
309
+ return { type, uri: value };
310
+ const match = /^data:([^;,]+);base64,([\s\S]+)$/.exec(value);
311
+ if (!match)
312
+ fail("Expected a base64 media data URL");
313
+ return { type, mime_type: match[1], data: match[2] };
314
+ }
315
+ function parts(value) {
316
+ if (!Array.isArray(value))
317
+ return fail("Expected an array of content/items");
318
+ return value.map(part => object(part, "part"));
319
+ }
320
+ function object(value, name) {
321
+ if (!value || typeof value !== "object" || Array.isArray(value))
322
+ return fail(`${name} must be an object`);
323
+ return value;
324
+ }
325
+ function string(value, name) {
326
+ if (typeof value !== "string")
327
+ return fail(`${name} must be a string`);
328
+ return value;
329
+ }
330
+ function nonempty(value, name) {
331
+ const result = string(value, name);
332
+ if (!result.trim())
333
+ fail(`${name} must not be empty`);
334
+ return result;
335
+ }
336
+ function parseArguments(value) {
337
+ try {
338
+ return object(JSON.parse(string(value, "arguments")), "arguments");
339
+ }
340
+ catch {
341
+ return fail("Function arguments must be a valid JSON object");
342
+ }
343
+ }
344
+ function fail(message) {
345
+ throw new types_1.InteractionsRequestError(message);
346
+ }
@@ -0,0 +1,49 @@
1
+ import type OpenAI from "openai";
2
+ import { type Interaction, type InteractionCreateParams, type InteractionEvent, type InteractionUsage } from "../interactions/types";
3
+ import { type InteractionResponseUsage } from "../interactions/usage";
4
+ export type InteractionResponse = Omit<OpenAI.Responses.Response, "usage" | "tools" | "tool_choice"> & Partial<Pick<OpenAI.Responses.Response, "tools" | "tool_choice">> & {
5
+ usage: InteractionResponseUsage | null;
6
+ };
7
+ type ReplaceResponse<T> = T extends {
8
+ response: OpenAI.Responses.Response;
9
+ } ? Omit<T, "response"> & {
10
+ response: InteractionResponse;
11
+ } : T;
12
+ export type InteractionResponseStreamEvent = ReplaceResponse<OpenAI.Responses.ResponseStreamEvent>;
13
+ /** Direct Responses ↔ Interactions V1 conversion; only standard target content is returned. */
14
+ export declare class ResponsesToInteractionsConverter {
15
+ private params?;
16
+ private request?;
17
+ private id;
18
+ private model;
19
+ private created;
20
+ private sequence;
21
+ private started;
22
+ private finished;
23
+ private terminal?;
24
+ private usage?;
25
+ private steps;
26
+ private seen;
27
+ convertRequest(params: OpenAI.Responses.ResponseCreateParams): InteractionCreateParams;
28
+ /** Gateways call this after applying the effective request defaults, before reading any response. */
29
+ setEffectiveRequest(request: InteractionCreateParams): void;
30
+ getUsage(): InteractionUsage | undefined;
31
+ convertResponse(response: Interaction): InteractionResponse;
32
+ convertStream(stream: AsyncIterable<InteractionEvent>): AsyncIterable<InteractionResponseStreamEvent>;
33
+ convertStreamEvent(event: InteractionEvent): InteractionResponseStreamEvent[];
34
+ finishStream(): InteractionResponseStreamEvent[];
35
+ private startStep;
36
+ private appendText;
37
+ private reconcile;
38
+ private response;
39
+ private responseConfig;
40
+ private event;
41
+ private identity;
42
+ private newId;
43
+ private checkStatus;
44
+ private unmapped;
45
+ private text;
46
+ private arguments;
47
+ private annotations;
48
+ }
49
+ export {};