@saturn-universe/model 0.0.0-stage → 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/LICENSE +661 -0
- package/dist/codec.d.ts +12 -0
- package/dist/codec.js +129 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +36 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +540 -0
- package/dist/provider-errors.d.ts +13 -0
- package/dist/provider-errors.js +170 -0
- package/dist/sdk-adapter.d.ts +33 -0
- package/dist/sdk-adapter.js +315 -0
- package/dist/sdk-messages.d.ts +23 -0
- package/dist/sdk-messages.js +154 -0
- package/dist/wire.d.ts +61 -0
- package/dist/wire.js +481 -0
- package/package.json +21 -3
- package/README.md +0 -3
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
2
|
+
import { APICallError, StreamProviderError } from 'ai';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { GatewayError } from './errors.js';
|
|
5
|
+
const transportCode = /^(?:E(?:CONNRESET|TIMEDOUT|CONNREFUSED|PIPE|HOSTUNREACH|NETUNREACH|NOTFOUND|AI_AGAIN|CONNABORTED|ADDRNOTAVAIL)|UND_ERR_(?:SOCKET|CONNECT_TIMEOUT|HEADERS_TIMEOUT|BODY_TIMEOUT|ABORTED|RESPONSE_STATUS_CODE)|CERT_HAS_EXPIRED|UNABLE_TO_VERIFY_LEAF_SIGNATURE|DEPTH_ZERO_SELF_SIGNED_CERT|SELF_SIGNED_CERT_IN_CHAIN)$/;
|
|
6
|
+
const transportMessage = /\b(?:fetch failed|terminated|other side closed|socket hang up|connection (?:reset|refused|closed)|(?:connect|headers|body|connection) timeout(?: error)?|read ECONNRESET|connect (?:ECONNREFUSED|ETIMEDOUT)|getaddrinfo (?:ENOTFOUND|EAI_AGAIN))\b/i;
|
|
7
|
+
export function transportFailure(error, details, secrets) {
|
|
8
|
+
const causes = [];
|
|
9
|
+
const seen = new Set();
|
|
10
|
+
let underlyingCode;
|
|
11
|
+
for (let cause = error; cause && typeof cause === 'object' && !seen.has(cause) && causes.length < 8;) {
|
|
12
|
+
seen.add(cause);
|
|
13
|
+
const { code, message, cause: nested } = cause;
|
|
14
|
+
const safeCode = typeof code === 'string' && transportCode.test(code) ? code : undefined;
|
|
15
|
+
if (safeCode)
|
|
16
|
+
underlyingCode = safeCode;
|
|
17
|
+
const redacted = providerDiagnostic(message, secrets, 4096);
|
|
18
|
+
causes.push({
|
|
19
|
+
...(safeCode ? { code: safeCode } : {}),
|
|
20
|
+
message: transportMessage.exec(redacted)?.[0] ?? 'Transport exception',
|
|
21
|
+
});
|
|
22
|
+
cause = nested;
|
|
23
|
+
}
|
|
24
|
+
return new GatewayError('transport', true, true, undefined, undefined, {
|
|
25
|
+
cause: error,
|
|
26
|
+
details: {
|
|
27
|
+
...details,
|
|
28
|
+
...(underlyingCode ? { underlyingCode } : {}),
|
|
29
|
+
...(causes.length ? { causes } : {}),
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
const errorEnvelope = z.object({ error: z.unknown().optional() });
|
|
34
|
+
const diagnosticFields = z.object({
|
|
35
|
+
code: z.string().nullish().catch(undefined),
|
|
36
|
+
type: z.string().nullish().catch(undefined),
|
|
37
|
+
status: z.string().nullish().catch(undefined),
|
|
38
|
+
param: z.string().nullish().catch(undefined),
|
|
39
|
+
message: z.string().nullish().catch(undefined),
|
|
40
|
+
});
|
|
41
|
+
function readDiagnostic(value) {
|
|
42
|
+
const error = errorEnvelope.safeParse(value).data?.error ?? value;
|
|
43
|
+
const diagnostic = diagnosticFields.safeParse(error).data;
|
|
44
|
+
const plainText = typeof error === 'string';
|
|
45
|
+
return { ...diagnostic, message: plainText ? error : diagnostic?.message, plainText };
|
|
46
|
+
}
|
|
47
|
+
function providerDiagnostic(value, secrets, limit) {
|
|
48
|
+
if (typeof value !== 'string')
|
|
49
|
+
return '';
|
|
50
|
+
const redact = (text) => {
|
|
51
|
+
for (const secret of [...secrets].sort((a, b) => b.length - a.length))
|
|
52
|
+
if (secret)
|
|
53
|
+
text = text.replaceAll(secret, '[REDACTED]');
|
|
54
|
+
return text;
|
|
55
|
+
};
|
|
56
|
+
const clean = stripVTControlCharacters(redact(value))
|
|
57
|
+
.replace(/\s+/gu, ' ')
|
|
58
|
+
.replace(/[\p{Cc}\p{Cf}]/gu, '')
|
|
59
|
+
.trim();
|
|
60
|
+
return redact(clean)
|
|
61
|
+
.replace(/\b(?:Bearer|Basic)\s+[^\s"'<>]+|\b[a-z][\w+.-]*:\/\/[^\s"'<>]+/gi, '[REDACTED]')
|
|
62
|
+
.replace(/\b(?:sk-[\w-]{8,}|AIza[\w-]{20,})\b/g, '[REDACTED]')
|
|
63
|
+
.replace(/\b(api[ _-]?key|access[ _-]?token|secret|password)\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1=[REDACTED]')
|
|
64
|
+
.slice(0, limit);
|
|
65
|
+
}
|
|
66
|
+
const overflowCodes = new Set([
|
|
67
|
+
'contextlengthexceeded',
|
|
68
|
+
'contextwindowexceeded',
|
|
69
|
+
'contextexceeded',
|
|
70
|
+
'contextoverflow',
|
|
71
|
+
'requesttoolarge',
|
|
72
|
+
'prompttoolong',
|
|
73
|
+
'inputtoolong',
|
|
74
|
+
'inputtokencountexceeded',
|
|
75
|
+
'toomanyinputtokens',
|
|
76
|
+
'toomanytokens',
|
|
77
|
+
]);
|
|
78
|
+
const overflowMessages = [
|
|
79
|
+
/\b(?:max(?:imum)?|model(?:'s)?)\s+(?:allowed\s+)?context (?:length|window|size|limit)\b/i,
|
|
80
|
+
/\bcontext (?:length|window|size|limit)\b.{0,48}\b(?:exceeded|overflow|too (?:long|large))\b/i,
|
|
81
|
+
/\b(?:input|prompt|conversation|request messages?) (?:is |are )?too (?:long|large)\b/i,
|
|
82
|
+
/\btoo many (?:input |prompt )?tokens\b/i,
|
|
83
|
+
/\b(?:input|prompt|conversation|messages|(?:total|request) tokens)\b[^.!?]{0,100}\b(?:exceeds?|exceeding|longer than|greater than|over) (?:the )?(?:(?:model(?:'s)? )?(?:maximum|max|allowed)\b|(?:model(?:'s)? )?context\b|\d+\s*tokens\b)/i,
|
|
84
|
+
/\b(?:exceed(?:s|ed|ing)?|over)\s+(?:the )?(?:(?:model(?:'s)? )?(?:maximum|max|allowed)\s+)?(?:context (?:length|window|size|limit)|(?:prompt |input )token (?:limit|count))\b/i,
|
|
85
|
+
];
|
|
86
|
+
function errorCode(diagnostic, status) {
|
|
87
|
+
const codes = [diagnostic.code, diagnostic.type, diagnostic.status].map((code) => code?.toLowerCase() ?? '');
|
|
88
|
+
const has = (...values) => codes.some((code) => values.includes(code));
|
|
89
|
+
if (codes.some((code) => overflowCodes.has(code.replace(/[^a-z\d]/g, ''))))
|
|
90
|
+
return 'context_overflow';
|
|
91
|
+
if (status === 401 ||
|
|
92
|
+
status === 403 ||
|
|
93
|
+
has('invalid_api_key', 'authentication_error', 'permission_denied', 'insufficient_permissions', 'unauthenticated'))
|
|
94
|
+
return 'auth';
|
|
95
|
+
if (status === 429 ||
|
|
96
|
+
has('rate_limit_exceeded', 'rate_limit_error', 'insufficient_quota', 'resource_exhausted'))
|
|
97
|
+
return 'rate_limit';
|
|
98
|
+
const message = diagnostic.message?.slice(0, 4096).replace(/\s+/gu, ' ') ?? '';
|
|
99
|
+
if (overflowMessages.some((pattern) => pattern.test(message)))
|
|
100
|
+
return 'context_overflow';
|
|
101
|
+
if ((status !== undefined && status >= 500) ||
|
|
102
|
+
has('server_error', 'internal_server_error', 'internal_error', 'overloaded_error', 'unavailable'))
|
|
103
|
+
return 'provider_internal';
|
|
104
|
+
return status !== undefined || has('invalid_request_error', 'invalid_request', 'invalid_argument')
|
|
105
|
+
? 'invalid_request'
|
|
106
|
+
: 'provider_internal';
|
|
107
|
+
}
|
|
108
|
+
function rejectsTools({ message, code, param }) {
|
|
109
|
+
if (code === 'tools_not_supported' ||
|
|
110
|
+
(param === 'tools' &&
|
|
111
|
+
['unsupported_parameter', 'unknown_parameter', 'unrecognized_parameter'].includes(code ?? '')))
|
|
112
|
+
return true;
|
|
113
|
+
return /\b(?:does not support|doesn't support|do not support|unknown (?:parameter|field)|unrecognized (?:parameter|field)|unsupported (?:parameter|field))\W+(?:the\s+)?(?:tools\b|tool calling\b|function calling\b)|\b(?:tools|tool calling|function calling)\W+(?:(?:parameter|field|is|are)\W+)*(?:not supported|unsupported|not allowed)\b/i.test(message?.slice(0, 4096) ?? '');
|
|
114
|
+
}
|
|
115
|
+
export function providerFailure(value, { status, retry, secrets = [], hasTools } = {}) {
|
|
116
|
+
const diagnostic = readDiagnostic(value);
|
|
117
|
+
const code = errorCode(diagnostic, status);
|
|
118
|
+
const is4xx = status !== undefined && status >= 400 && status < 500;
|
|
119
|
+
let message;
|
|
120
|
+
if (is4xx && (!diagnostic.plainText || code === 'context_overflow')) {
|
|
121
|
+
const providerCode = providerDiagnostic(diagnostic.code ?? diagnostic.status, secrets, 64);
|
|
122
|
+
const parameter = providerDiagnostic(diagnostic.param, secrets, 64);
|
|
123
|
+
const reason = providerDiagnostic(diagnostic.message, secrets, 400);
|
|
124
|
+
const fields = [providerCode, parameter && `param=${parameter}`, reason].filter(Boolean);
|
|
125
|
+
if (fields.length)
|
|
126
|
+
message = `HTTP ${status} · ${fields.join(' · ')}`.slice(0, 400);
|
|
127
|
+
}
|
|
128
|
+
if (hasTools && (status === undefined || is4xx) && code !== 'context_overflow' && rejectsTools(diagnostic))
|
|
129
|
+
return new GatewayError('unsupported_capability', false, false, undefined, ['The configured model or endpoint does not support tool calling.', message]
|
|
130
|
+
.filter(Boolean)
|
|
131
|
+
.join(' ')
|
|
132
|
+
.slice(0, 400));
|
|
133
|
+
const delay = retry === undefined || retry === null
|
|
134
|
+
? undefined
|
|
135
|
+
: /^\d+(\.\d+)?$/.test(retry)
|
|
136
|
+
? Number(retry) * 1000
|
|
137
|
+
: Math.max(0, Date.parse(retry) - Date.now());
|
|
138
|
+
return new GatewayError(code, code === 'rate_limit' || code === 'provider_internal' || code === 'context_overflow', false, delay !== undefined && Number.isSafeInteger(Math.ceil(delay)) ? Math.ceil(delay) : undefined, message);
|
|
139
|
+
}
|
|
140
|
+
/** Provider errors embedded in an otherwise successful SDK stream. */
|
|
141
|
+
export function sdkProviderFailure(error, secrets, hasTools) {
|
|
142
|
+
if (StreamProviderError.isInstance(error))
|
|
143
|
+
return providerFailure(error.data ?? error, { status: error.statusCode, secrets, hasTools });
|
|
144
|
+
if (APICallError.isInstance(error)) {
|
|
145
|
+
let value = error.data;
|
|
146
|
+
if (value === undefined && error.responseBody) {
|
|
147
|
+
try {
|
|
148
|
+
value = JSON.parse(error.responseBody);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
value = error.responseBody;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return providerFailure(value ?? error.message, {
|
|
155
|
+
status: error.statusCode,
|
|
156
|
+
retry: error.responseHeaders?.['retry-after'],
|
|
157
|
+
secrets,
|
|
158
|
+
hasTools,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
if (error && typeof error === 'object' && !(error instanceof Error)) {
|
|
162
|
+
const diagnostic = readDiagnostic(error);
|
|
163
|
+
if (diagnostic.code || diagnostic.type || diagnostic.status || diagnostic.message) {
|
|
164
|
+
const status = z.object({ statusCode: z.number().int().min(400).max(599).optional() }).safeParse(error)
|
|
165
|
+
.data?.statusCode;
|
|
166
|
+
return providerFailure(error, { status, secrets, hasTools });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return error;
|
|
170
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { generateText } from 'ai';
|
|
2
|
+
import type { ContentPart, FinishReason, LanguageModelUsage, TextStreamPart, ToolSet } from 'ai';
|
|
3
|
+
import type { ModelCapabilities, ModelFailureDetails, ModelInvocationOptions, ModelRequest, ModelResponse, ModelStreamEvent } from '@saturn-universe/core';
|
|
4
|
+
import { GatewayError } from './errors.js';
|
|
5
|
+
import { type SdkProtocol } from './sdk-messages.js';
|
|
6
|
+
interface Connection {
|
|
7
|
+
protocol: SdkProtocol;
|
|
8
|
+
baseURL: string;
|
|
9
|
+
apiKey: string;
|
|
10
|
+
headers: Record<string, string>;
|
|
11
|
+
secrets: readonly string[];
|
|
12
|
+
}
|
|
13
|
+
interface RequestLifecycle {
|
|
14
|
+
signal: AbortSignal;
|
|
15
|
+
details(): ModelFailureDetails;
|
|
16
|
+
onActivity(phase?: ModelFailureDetails['phase']): void;
|
|
17
|
+
}
|
|
18
|
+
interface SdkCapture {
|
|
19
|
+
error?: GatewayError;
|
|
20
|
+
}
|
|
21
|
+
export declare function createSdkSettings(request: ModelRequest, connection: Connection, capabilities: ModelCapabilities, lifecycle: RequestLifecycle, transport: typeof fetch, capture: SdkCapture, invocation: ModelInvocationOptions, streaming: boolean): Parameters<typeof generateText>[0];
|
|
22
|
+
interface SdkResponse {
|
|
23
|
+
text: string;
|
|
24
|
+
content: readonly ContentPart<ToolSet>[];
|
|
25
|
+
usage: LanguageModelUsage;
|
|
26
|
+
response: {
|
|
27
|
+
id: string;
|
|
28
|
+
};
|
|
29
|
+
finishReason: FinishReason;
|
|
30
|
+
}
|
|
31
|
+
export declare function sdkStreamProgress(request: ModelRequest, secrets: readonly string[], publish: (event: ModelStreamEvent) => void): (part: TextStreamPart<ToolSet>) => void;
|
|
32
|
+
export declare function acceptSdkResponse(request: ModelRequest, protocol: SdkProtocol, sdk: SdkResponse, secrets: readonly string[]): ModelResponse;
|
|
33
|
+
export {};
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { createAnthropic } from '@ai-sdk/anthropic';
|
|
2
|
+
import { getModelCapabilities as anthropicCapabilities } from '@ai-sdk/anthropic/internal';
|
|
3
|
+
import { createGoogleGenerativeAI } from '@ai-sdk/google';
|
|
4
|
+
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
|
|
5
|
+
import { jsonSchema, Output, stepCountIs } from 'ai';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { geminiModelPath } from '@saturn-universe/core';
|
|
8
|
+
import { decodeToolCalls, digest } from './codec.js';
|
|
9
|
+
import { GatewayError } from './errors.js';
|
|
10
|
+
import { parseJson, replayOptions, sdkMessages } from './sdk-messages.js';
|
|
11
|
+
import { providerFailure, transportFailure } from './provider-errors.js';
|
|
12
|
+
import { maxCaptureBytes, observeBody, readBounded } from './wire.js';
|
|
13
|
+
function endpoint(connection, modelId, streaming) {
|
|
14
|
+
const baseURL = connection.baseURL.replace(/\/$/, '');
|
|
15
|
+
if (connection.protocol === 'openai-chat')
|
|
16
|
+
return new URL(baseURL + '/chat/completions');
|
|
17
|
+
if (connection.protocol === 'anthropic')
|
|
18
|
+
return new URL(baseURL + '/messages');
|
|
19
|
+
const path = geminiModelPath(modelId);
|
|
20
|
+
if (path === undefined)
|
|
21
|
+
throw new GatewayError('invalid_request');
|
|
22
|
+
return new URL(baseURL + '/' + path + (streaming ? ':streamGenerateContent?alt=sse' : ':generateContent'));
|
|
23
|
+
}
|
|
24
|
+
function sdkFetch(url, lifecycle, transport, capture, secrets, hasTools) {
|
|
25
|
+
let sent = false;
|
|
26
|
+
const failTransport = (error) => {
|
|
27
|
+
if (lifecycle.signal.aborted)
|
|
28
|
+
return lifecycle.signal.reason;
|
|
29
|
+
capture.error = transportFailure(error, lifecycle.details(), secrets);
|
|
30
|
+
return capture.error;
|
|
31
|
+
};
|
|
32
|
+
return async (input, init) => {
|
|
33
|
+
if (sent || init?.method !== 'POST' || new URL(String(input)).href !== url.href)
|
|
34
|
+
throw new GatewayError('protocol');
|
|
35
|
+
sent = true;
|
|
36
|
+
let response;
|
|
37
|
+
try {
|
|
38
|
+
response = await transport(input, { ...init, signal: lifecycle.signal, redirect: 'error' });
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
throw failTransport(error);
|
|
42
|
+
}
|
|
43
|
+
lifecycle.signal.throwIfAborted();
|
|
44
|
+
lifecycle.onActivity('awaiting_first_frame');
|
|
45
|
+
let bytes = 0;
|
|
46
|
+
const body = response.body
|
|
47
|
+
? observeBody(response.body, failTransport).pipeThrough(new TransformStream({
|
|
48
|
+
transform(chunk, controller) {
|
|
49
|
+
bytes += chunk.byteLength;
|
|
50
|
+
if (bytes > maxCaptureBytes) {
|
|
51
|
+
capture.error = new GatewayError('invalid_output');
|
|
52
|
+
throw capture.error;
|
|
53
|
+
}
|
|
54
|
+
lifecycle.onActivity('stream_idle');
|
|
55
|
+
controller.enqueue(chunk);
|
|
56
|
+
},
|
|
57
|
+
}))
|
|
58
|
+
: null;
|
|
59
|
+
if (!response.ok) {
|
|
60
|
+
const raw = await readBounded(body).catch((error) => {
|
|
61
|
+
if (lifecycle.signal.aborted || capture.error)
|
|
62
|
+
throw error;
|
|
63
|
+
return '';
|
|
64
|
+
});
|
|
65
|
+
const value = parseJson(raw) ?? raw;
|
|
66
|
+
const status = response.status;
|
|
67
|
+
capture.error = providerFailure(value, {
|
|
68
|
+
status,
|
|
69
|
+
retry: response.headers.get('retry-after'),
|
|
70
|
+
secrets,
|
|
71
|
+
hasTools,
|
|
72
|
+
});
|
|
73
|
+
throw capture.error;
|
|
74
|
+
}
|
|
75
|
+
return new Response(body, { status: response.status, headers: response.headers });
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
const reasoningEfforts = z.enum(['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
|
|
79
|
+
const thinkingBudgets = { minimal: 1024, low: 1024, medium: 4096, high: 8192, xhigh: 16384, max: 32768 };
|
|
80
|
+
export function createSdkSettings(request, connection, capabilities, lifecycle, transport, capture, invocation, streaming) {
|
|
81
|
+
const { protocol, baseURL, apiKey, secrets } = connection;
|
|
82
|
+
const modelId = request.model.modelId;
|
|
83
|
+
const headers = new Headers(connection.headers);
|
|
84
|
+
if (invocation.promptCacheOnly) {
|
|
85
|
+
headers.delete('session_id');
|
|
86
|
+
headers.delete('conversation_id');
|
|
87
|
+
headers.delete('x-codex-turn-state');
|
|
88
|
+
}
|
|
89
|
+
const provider = {
|
|
90
|
+
baseURL: new URL(baseURL).href.replace(/\/$/, ''),
|
|
91
|
+
apiKey,
|
|
92
|
+
headers: Object.fromEntries(headers),
|
|
93
|
+
fetch: sdkFetch(endpoint(connection, modelId, streaming), lifecycle, transport, capture, secrets, request.tools.length > 0),
|
|
94
|
+
};
|
|
95
|
+
const effort = request.responsesOptions.reasoning?.effort;
|
|
96
|
+
const parallel = request.responsesOptions.parallelToolCalls;
|
|
97
|
+
const mappedEffort = reasoningEfforts.safeParse(effort);
|
|
98
|
+
if (effort !== undefined && protocol !== 'openai-chat' && !mappedEffort.success)
|
|
99
|
+
throw new GatewayError('unsupported_capability');
|
|
100
|
+
let maxOutputTokens = request.maxOutputTokens;
|
|
101
|
+
let thinking;
|
|
102
|
+
if (protocol === 'anthropic' && mappedEffort.success) {
|
|
103
|
+
const caps = anthropicCapabilities(modelId);
|
|
104
|
+
if (mappedEffort.data !== 'none' && !caps.supportsAdaptiveThinking && !caps.rejectsBudgetThinking) {
|
|
105
|
+
const budgetTokens = Math.min(thinkingBudgets[mappedEffort.data], maxOutputTokens - 1);
|
|
106
|
+
if (budgetTokens < 1024)
|
|
107
|
+
throw new GatewayError('unsupported_capability');
|
|
108
|
+
thinking = { type: 'enabled', budgetTokens };
|
|
109
|
+
// The Anthropic adapter adds thinking tokens to the visible output limit.
|
|
110
|
+
maxOutputTokens -= budgetTokens;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const model = protocol === 'openai-chat'
|
|
114
|
+
? createOpenAICompatible({
|
|
115
|
+
...provider,
|
|
116
|
+
name: 'saturn',
|
|
117
|
+
includeUsage: true,
|
|
118
|
+
supportsStructuredOutputs: capabilities.structuredOutput,
|
|
119
|
+
}).chatModel(modelId)
|
|
120
|
+
: protocol === 'anthropic'
|
|
121
|
+
? createAnthropic(provider).languageModel(modelId)
|
|
122
|
+
: createGoogleGenerativeAI(provider).languageModel(modelId);
|
|
123
|
+
const providerOptions = protocol === 'openai-chat'
|
|
124
|
+
? {
|
|
125
|
+
saturn: {
|
|
126
|
+
...(effort === undefined ? {} : { reasoningEffort: effort }),
|
|
127
|
+
...(parallel === undefined ? {} : { parallel_tool_calls: parallel }),
|
|
128
|
+
},
|
|
129
|
+
}
|
|
130
|
+
: protocol === 'anthropic'
|
|
131
|
+
? {
|
|
132
|
+
anthropic: {
|
|
133
|
+
...(thinking ? { thinking } : {}),
|
|
134
|
+
...(parallel === undefined ? {} : { disableParallelToolUse: !parallel }),
|
|
135
|
+
},
|
|
136
|
+
}
|
|
137
|
+
: capabilities.responses.reasoningModel
|
|
138
|
+
? { google: { thinkingConfig: { includeThoughts: effort !== 'none' } } }
|
|
139
|
+
: {};
|
|
140
|
+
return {
|
|
141
|
+
model,
|
|
142
|
+
...sdkMessages(request, protocol),
|
|
143
|
+
tools: Object.fromEntries(request.tools.map((tool) => [
|
|
144
|
+
tool.wireName,
|
|
145
|
+
{ description: tool.description, inputSchema: jsonSchema(tool.inputSchema), strict: false },
|
|
146
|
+
])),
|
|
147
|
+
maxRetries: 0,
|
|
148
|
+
stopWhen: stepCountIs(1),
|
|
149
|
+
abortSignal: lifecycle.signal,
|
|
150
|
+
maxOutputTokens,
|
|
151
|
+
providerOptions,
|
|
152
|
+
...(mappedEffort.success && protocol !== 'openai-chat' && !thinking
|
|
153
|
+
? { reasoning: mappedEffort.data }
|
|
154
|
+
: {}),
|
|
155
|
+
...(request.temperature === undefined ? {} : { temperature: request.temperature }),
|
|
156
|
+
...(request.output.kind === 'json'
|
|
157
|
+
? { output: Output.object({ schema: jsonSchema(request.output.schema), name: request.output.name }) }
|
|
158
|
+
: {}),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
function checkSecrets(value, secrets) {
|
|
162
|
+
if (secrets.some((secret) => value.includes(secret)))
|
|
163
|
+
throw new GatewayError('invalid_output');
|
|
164
|
+
}
|
|
165
|
+
export function sdkStreamProgress(request, secrets, publish) {
|
|
166
|
+
let textIndex = 0;
|
|
167
|
+
const indices = new Map();
|
|
168
|
+
const recent = new Map();
|
|
169
|
+
const retain = Math.max(0, ...secrets.map((secret) => secret.length - 1));
|
|
170
|
+
return (part) => {
|
|
171
|
+
const requestId = request.id;
|
|
172
|
+
if (part.type === 'text-start')
|
|
173
|
+
indices.set(part.id, textIndex++);
|
|
174
|
+
if (part.type === 'text-delta' || part.type === 'reasoning-delta') {
|
|
175
|
+
const deltaKey = part.type + ':' + part.id;
|
|
176
|
+
const window = (recent.get(deltaKey) ?? '') + part.text;
|
|
177
|
+
checkSecrets(window, secrets);
|
|
178
|
+
if (retain > 0)
|
|
179
|
+
recent.set(deltaKey, window.slice(-retain));
|
|
180
|
+
publish(part.type === 'text-delta'
|
|
181
|
+
? { type: 'text_delta', requestId, index: indices.get(part.id) ?? 0, text: part.text }
|
|
182
|
+
: { type: 'reasoning_summary_delta', requestId, text: part.text });
|
|
183
|
+
}
|
|
184
|
+
if (part.type === 'tool-input-delta' || part.type === 'tool-call' || part.type === 'start-step')
|
|
185
|
+
publish({
|
|
186
|
+
type: 'activity',
|
|
187
|
+
requestId,
|
|
188
|
+
stage: part.type,
|
|
189
|
+
bytes: part.type === 'tool-input-delta' ? part.delta.length : 0,
|
|
190
|
+
});
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
export function acceptSdkResponse(request, protocol, sdk, secrets) {
|
|
194
|
+
const id = sdk.response.id;
|
|
195
|
+
checkSecrets(id, secrets);
|
|
196
|
+
checkSecrets(sdk.text, secrets);
|
|
197
|
+
const outputItems = [];
|
|
198
|
+
for (const part of sdk.content) {
|
|
199
|
+
const itemId = id + ':' + outputItems.length;
|
|
200
|
+
const replay = replayOptions(protocol, 'providerMetadata' in part ? part.providerMetadata : undefined);
|
|
201
|
+
const metadata = replay ? { provider_options: replay } : {};
|
|
202
|
+
switch (part.type) {
|
|
203
|
+
case 'text':
|
|
204
|
+
outputItems.push({
|
|
205
|
+
kind: 'message',
|
|
206
|
+
value: {
|
|
207
|
+
type: 'message',
|
|
208
|
+
role: 'assistant',
|
|
209
|
+
id: itemId,
|
|
210
|
+
content: [{ type: 'output_text', text: part.text, ...metadata }],
|
|
211
|
+
},
|
|
212
|
+
});
|
|
213
|
+
break;
|
|
214
|
+
case 'reasoning':
|
|
215
|
+
outputItems.push({
|
|
216
|
+
kind: 'reasoning',
|
|
217
|
+
value: {
|
|
218
|
+
type: 'reasoning',
|
|
219
|
+
id: itemId,
|
|
220
|
+
summary: [{ type: 'summary_text', text: part.text }],
|
|
221
|
+
...metadata,
|
|
222
|
+
},
|
|
223
|
+
});
|
|
224
|
+
break;
|
|
225
|
+
case 'tool-call':
|
|
226
|
+
outputItems.push({
|
|
227
|
+
kind: 'function_call',
|
|
228
|
+
value: {
|
|
229
|
+
type: 'function_call',
|
|
230
|
+
id: itemId,
|
|
231
|
+
call_id: part.toolCallId,
|
|
232
|
+
name: part.toolName,
|
|
233
|
+
arguments: part.invalid && typeof part.input === 'string' ? part.input : JSON.stringify(part.input ?? {}),
|
|
234
|
+
...metadata,
|
|
235
|
+
},
|
|
236
|
+
});
|
|
237
|
+
break;
|
|
238
|
+
case 'source':
|
|
239
|
+
case 'custom':
|
|
240
|
+
break;
|
|
241
|
+
default:
|
|
242
|
+
throw new GatewayError('unsupported_item');
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
JSON.stringify(outputItems, (key, value) => {
|
|
246
|
+
checkSecrets(key, secrets);
|
|
247
|
+
if (typeof value === 'string')
|
|
248
|
+
checkSecrets(value, secrets);
|
|
249
|
+
return value;
|
|
250
|
+
});
|
|
251
|
+
if (sdk.finishReason === 'error' || sdk.finishReason === 'interrupted')
|
|
252
|
+
throw new GatewayError('protocol');
|
|
253
|
+
const toolCalls = decodeToolCalls(request, outputItems);
|
|
254
|
+
if (sdk.finishReason === 'tool-calls' && !toolCalls.length)
|
|
255
|
+
throw new GatewayError('invalid_output');
|
|
256
|
+
const finishReason = sdk.finishReason === 'length'
|
|
257
|
+
? 'length'
|
|
258
|
+
: sdk.finishReason === 'content-filter'
|
|
259
|
+
? 'content_filter'
|
|
260
|
+
: toolCalls.length
|
|
261
|
+
? 'tool_calls'
|
|
262
|
+
: 'stop';
|
|
263
|
+
const turnDisposition = toolCalls.length
|
|
264
|
+
? 'tool_calls'
|
|
265
|
+
: sdk.finishReason === 'stop' && sdk.text.trim()
|
|
266
|
+
? 'final'
|
|
267
|
+
: 'continue';
|
|
268
|
+
let structuredOutput;
|
|
269
|
+
if (request.output.kind === 'json' && turnDisposition === 'final') {
|
|
270
|
+
const parsed = z.json().safeParse(parseJson(sdk.text));
|
|
271
|
+
if (!parsed.success || !z.fromJSONSchema(request.output.schema).safeParse(parsed.data).success)
|
|
272
|
+
throw new GatewayError('invalid_output');
|
|
273
|
+
structuredOutput = parsed.data;
|
|
274
|
+
}
|
|
275
|
+
const usage = sdk.usage;
|
|
276
|
+
const tokenCount = z.number().int().nonnegative().safe();
|
|
277
|
+
const input = tokenCount.safeParse(usage.inputTokens).data;
|
|
278
|
+
const output = tokenCount.safeParse(usage.outputTokens).data;
|
|
279
|
+
const cached = tokenCount.safeParse(usage.inputTokenDetails.cacheReadTokens).data;
|
|
280
|
+
const reasoning = tokenCount.safeParse(usage.outputTokenDetails.reasoningTokens).data;
|
|
281
|
+
return {
|
|
282
|
+
requestId: request.id,
|
|
283
|
+
providerResponseId: id,
|
|
284
|
+
content: sdk.content.flatMap((part) => part.type === 'text' ? [{ type: 'text', text: part.text }] : []),
|
|
285
|
+
toolCalls,
|
|
286
|
+
...(structuredOutput === undefined ? {} : { structuredOutput }),
|
|
287
|
+
turnDisposition,
|
|
288
|
+
finishReason,
|
|
289
|
+
usage: {
|
|
290
|
+
inputTokens: input ?? request.budget.estimatedInputTokens,
|
|
291
|
+
outputTokens: output ?? request.maxOutputTokens,
|
|
292
|
+
accuracy: input === undefined || output === undefined ? 'estimated' : 'reported',
|
|
293
|
+
...(cached !== undefined && input !== undefined && cached <= input
|
|
294
|
+
? { cachedInputTokens: cached }
|
|
295
|
+
: {}),
|
|
296
|
+
...(reasoning !== undefined && output !== undefined && reasoning <= output
|
|
297
|
+
? { reasoningTokens: reasoning }
|
|
298
|
+
: {}),
|
|
299
|
+
},
|
|
300
|
+
continuation: {
|
|
301
|
+
version: 1,
|
|
302
|
+
protocol,
|
|
303
|
+
binding: request.binding,
|
|
304
|
+
epochId: request.responses.epochId,
|
|
305
|
+
responseId: id,
|
|
306
|
+
sourceRequestId: request.id,
|
|
307
|
+
requestInputDigest: request.responses.fullInputDigest,
|
|
308
|
+
configurationDigest: request.responses.configurationDigest,
|
|
309
|
+
outputItems,
|
|
310
|
+
outputDigest: digest(outputItems.map((item) => item.value)),
|
|
311
|
+
providerMetadata: { responseId: id },
|
|
312
|
+
capture: { source: 'sdk', complete: true },
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { ModelMessage } from 'ai';
|
|
2
|
+
import type { ModelRequest, ProviderProtocol } from '@saturn-universe/core';
|
|
3
|
+
export type SdkProtocol = Exclude<ProviderProtocol, 'openai-responses'>;
|
|
4
|
+
export declare function parseJson(value: string): unknown;
|
|
5
|
+
type ReplayOptions = {
|
|
6
|
+
google: {
|
|
7
|
+
thoughtSignature: string;
|
|
8
|
+
};
|
|
9
|
+
} | {
|
|
10
|
+
anthropic: {
|
|
11
|
+
signature: string;
|
|
12
|
+
};
|
|
13
|
+
} | {
|
|
14
|
+
anthropic: {
|
|
15
|
+
redactedData: string;
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
export declare function replayOptions(protocol: SdkProtocol, metadata: unknown): ReplayOptions | undefined;
|
|
19
|
+
export declare function sdkMessages(request: ModelRequest, protocol: SdkProtocol): {
|
|
20
|
+
system: string;
|
|
21
|
+
messages: ModelMessage[];
|
|
22
|
+
};
|
|
23
|
+
export {};
|