@tuturuuu/ai 0.3.0 → 0.5.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/package.json +41 -41
- package/src/api-key-hash.ts +44 -1
- package/src/chat/google/reasoning-settings.ts +16 -0
- package/src/chat/google/route.ts +10 -20
- package/src/studio/auth.ts +73 -0
- package/src/studio/errors.ts +58 -0
- package/src/studio/metering.ts +247 -0
- package/src/studio/request.ts +13 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tuturuuu/ai",
|
|
3
3
|
"license": "MIT",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.5.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/tutur3u/platform",
|
|
@@ -22,34 +22,34 @@
|
|
|
22
22
|
"type-check": "tsc --project tsconfig.typecheck.json"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@ai-sdk/amazon-bedrock": "^5.0.
|
|
26
|
-
"@ai-sdk/anthropic": "^4.0.
|
|
27
|
-
"@ai-sdk/azure": "^4.0.
|
|
28
|
-
"@ai-sdk/cerebras": "^3.0.
|
|
29
|
-
"@ai-sdk/cohere": "^4.0.
|
|
30
|
-
"@ai-sdk/deepgram": "^3.0.
|
|
31
|
-
"@ai-sdk/deepinfra": "^3.0.
|
|
32
|
-
"@ai-sdk/deepseek": "^3.0.
|
|
33
|
-
"@ai-sdk/elevenlabs": "^3.0.
|
|
34
|
-
"@ai-sdk/fal": "^3.0.
|
|
35
|
-
"@ai-sdk/fireworks": "^3.0.
|
|
36
|
-
"@ai-sdk/gateway": "^4.0.
|
|
37
|
-
"@ai-sdk/gladia": "^3.0.
|
|
38
|
-
"@ai-sdk/google": "^4.0.
|
|
39
|
-
"@ai-sdk/google-vertex": "^5.0.
|
|
40
|
-
"@ai-sdk/groq": "^4.0.
|
|
41
|
-
"@ai-sdk/hume": "^3.0.
|
|
42
|
-
"@ai-sdk/lmnt": "^3.0.
|
|
43
|
-
"@ai-sdk/luma": "^3.0.
|
|
44
|
-
"@ai-sdk/mistral": "^4.0.
|
|
45
|
-
"@ai-sdk/openai": "^4.0.
|
|
46
|
-
"@ai-sdk/openai-compatible": "^3.0.
|
|
47
|
-
"@ai-sdk/perplexity": "^4.0.
|
|
48
|
-
"@ai-sdk/react": "^4.0.
|
|
49
|
-
"@ai-sdk/replicate": "^3.0.
|
|
50
|
-
"@ai-sdk/revai": "^3.0.
|
|
51
|
-
"@ai-sdk/togetherai": "^3.0.
|
|
52
|
-
"@ai-sdk/xai": "^4.0.
|
|
25
|
+
"@ai-sdk/amazon-bedrock": "^5.0.29",
|
|
26
|
+
"@ai-sdk/anthropic": "^4.0.18",
|
|
27
|
+
"@ai-sdk/azure": "^4.0.20",
|
|
28
|
+
"@ai-sdk/cerebras": "^3.0.14",
|
|
29
|
+
"@ai-sdk/cohere": "^4.0.12",
|
|
30
|
+
"@ai-sdk/deepgram": "^3.0.12",
|
|
31
|
+
"@ai-sdk/deepinfra": "^3.0.14",
|
|
32
|
+
"@ai-sdk/deepseek": "^3.0.13",
|
|
33
|
+
"@ai-sdk/elevenlabs": "^3.0.13",
|
|
34
|
+
"@ai-sdk/fal": "^3.0.13",
|
|
35
|
+
"@ai-sdk/fireworks": "^3.0.15",
|
|
36
|
+
"@ai-sdk/gateway": "^4.0.27",
|
|
37
|
+
"@ai-sdk/gladia": "^3.0.12",
|
|
38
|
+
"@ai-sdk/google": "^4.0.23",
|
|
39
|
+
"@ai-sdk/google-vertex": "^5.0.27",
|
|
40
|
+
"@ai-sdk/groq": "^4.0.13",
|
|
41
|
+
"@ai-sdk/hume": "^3.0.12",
|
|
42
|
+
"@ai-sdk/lmnt": "^3.0.12",
|
|
43
|
+
"@ai-sdk/luma": "^3.0.13",
|
|
44
|
+
"@ai-sdk/mistral": "^4.0.14",
|
|
45
|
+
"@ai-sdk/openai": "^4.0.19",
|
|
46
|
+
"@ai-sdk/openai-compatible": "^3.0.14",
|
|
47
|
+
"@ai-sdk/perplexity": "^4.0.13",
|
|
48
|
+
"@ai-sdk/react": "^4.0.39",
|
|
49
|
+
"@ai-sdk/replicate": "^3.0.13",
|
|
50
|
+
"@ai-sdk/revai": "^3.0.12",
|
|
51
|
+
"@ai-sdk/togetherai": "^3.0.15",
|
|
52
|
+
"@ai-sdk/xai": "^4.0.18",
|
|
53
53
|
"@beeper/chat-adapter-matrix": "^0.2.0",
|
|
54
54
|
"@bitbasti/chat-adapter-webex": "^0.1.0",
|
|
55
55
|
"@chat-adapter/discord": "^4.34.0",
|
|
@@ -75,16 +75,16 @@
|
|
|
75
75
|
"@streamdown/code": "^1.1.1",
|
|
76
76
|
"@streamdown/math": "^1.0.2",
|
|
77
77
|
"@streamdown/mermaid": "^1.0.2",
|
|
78
|
-
"@tuturuuu/google": "0.0
|
|
79
|
-
"@tuturuuu/internal-api": "0.
|
|
80
|
-
"@tuturuuu/supabase": "0.
|
|
81
|
-
"@tuturuuu/utils": "0.
|
|
82
|
-
"@vercel/sandbox": "^2.
|
|
78
|
+
"@tuturuuu/google": "0.1.0",
|
|
79
|
+
"@tuturuuu/internal-api": "0.23.0",
|
|
80
|
+
"@tuturuuu/supabase": "0.5.0",
|
|
81
|
+
"@tuturuuu/utils": "0.19.0",
|
|
82
|
+
"@vercel/sandbox": "^2.8.0",
|
|
83
83
|
"@zernio/chat-sdk-adapter": "^0.4.0",
|
|
84
|
-
"ai": "^7.0.
|
|
84
|
+
"ai": "^7.0.36",
|
|
85
85
|
"bash-tool": "^1.3.18",
|
|
86
86
|
"chat": "^4.34.0",
|
|
87
|
-
"chat-adapter-baileys": "^2.0
|
|
87
|
+
"chat-adapter-baileys": "^2.1.0",
|
|
88
88
|
"chat-adapter-blooio": "^0.1.0",
|
|
89
89
|
"chat-adapter-imessage": "^1.1.0",
|
|
90
90
|
"chat-adapter-mattermost": "^1.1.3",
|
|
@@ -92,18 +92,18 @@
|
|
|
92
92
|
"chat-adapter-zalo": "^0.1.0",
|
|
93
93
|
"chat-state-cloudflare-do": "^0.2.0",
|
|
94
94
|
"chat-state-mysql": "^0.1.0",
|
|
95
|
-
"dayjs": "^1.11.
|
|
96
|
-
"next": "^16.3.0-preview.
|
|
95
|
+
"dayjs": "^1.11.21",
|
|
96
|
+
"next": "^16.3.0-preview.9",
|
|
97
97
|
"qrcode": "^1.5.4",
|
|
98
|
-
"react": "^19.2.
|
|
99
|
-
"react-dom": "^19.2.
|
|
98
|
+
"react": "^19.2.8",
|
|
99
|
+
"react-dom": "^19.2.8",
|
|
100
100
|
"streamdown": "^2.5.0",
|
|
101
101
|
"uuid": "^14.0.1",
|
|
102
102
|
"zca-js": "^2.1.2",
|
|
103
103
|
"zod": "^4.4.3"
|
|
104
104
|
},
|
|
105
105
|
"devDependencies": {
|
|
106
|
-
"@tuturuuu/types": "0.
|
|
106
|
+
"@tuturuuu/types": "0.22.0",
|
|
107
107
|
"@tuturuuu/typescript-config": "0.1.1",
|
|
108
108
|
"@types/node": "^26.1.1",
|
|
109
109
|
"@types/qrcode": "^1.5.6",
|
package/src/api-key-hash.ts
CHANGED
|
@@ -1,8 +1,51 @@
|
|
|
1
|
-
import { scrypt, timingSafeEqual } from 'node:crypto';
|
|
1
|
+
import { randomBytes, scrypt, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { promisify } from 'node:util';
|
|
3
3
|
|
|
4
4
|
const scryptAsync = promisify(scrypt);
|
|
5
5
|
const KEY_DERIVATION_LENGTH = 64;
|
|
6
|
+
const AI_KEY_PREFIX = 'ttr_ai_';
|
|
7
|
+
const KEY_LOOKUP_BYTES = 8;
|
|
8
|
+
const KEY_SECRET_BYTES = 32;
|
|
9
|
+
|
|
10
|
+
export type GeneratedAiApiKey = {
|
|
11
|
+
hash: string;
|
|
12
|
+
prefix: string;
|
|
13
|
+
secret: string;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export async function hashApiKey(key: string): Promise<string> {
|
|
17
|
+
const salt = randomBytes(16).toString('hex');
|
|
18
|
+
const derivedKey = (await scryptAsync(
|
|
19
|
+
key,
|
|
20
|
+
salt,
|
|
21
|
+
KEY_DERIVATION_LENGTH
|
|
22
|
+
)) as Buffer;
|
|
23
|
+
|
|
24
|
+
return `${salt}:${derivedKey.toString('hex')}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function generateAiApiKey(): Promise<GeneratedAiApiKey> {
|
|
28
|
+
const prefix = `${AI_KEY_PREFIX}${randomBytes(KEY_LOOKUP_BYTES).toString('hex')}`;
|
|
29
|
+
const secret = `${prefix}_${randomBytes(KEY_SECRET_BYTES).toString('base64url')}`;
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
hash: await hashApiKey(secret),
|
|
33
|
+
prefix,
|
|
34
|
+
secret,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function extractAiApiKeyPrefix(key: string): string | null {
|
|
39
|
+
if (!key.startsWith(AI_KEY_PREFIX)) return null;
|
|
40
|
+
|
|
41
|
+
const separatorIndex = key.indexOf('_', AI_KEY_PREFIX.length);
|
|
42
|
+
if (separatorIndex === -1) return null;
|
|
43
|
+
|
|
44
|
+
const prefix = key.slice(0, separatorIndex);
|
|
45
|
+
return prefix.length === AI_KEY_PREFIX.length + KEY_LOOKUP_BYTES * 2
|
|
46
|
+
? prefix
|
|
47
|
+
: null;
|
|
48
|
+
}
|
|
6
49
|
|
|
7
50
|
export async function validateApiKeyHash(
|
|
8
51
|
key: string,
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type ChatThinkingMode = 'fast' | 'thinking';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Use the AI SDK's provider-neutral reasoning effort so each Google model
|
|
5
|
+
* receives the configuration it supports. The Google provider maps `none` to
|
|
6
|
+
* a zero budget for Gemini 2.5 and to `minimal` for Gemini 3, while `high`
|
|
7
|
+
* uses the model's supported high-effort setting.
|
|
8
|
+
*/
|
|
9
|
+
export function resolveChatReasoningSettings(mode: ChatThinkingMode) {
|
|
10
|
+
const includeThoughts = mode === 'thinking';
|
|
11
|
+
|
|
12
|
+
return {
|
|
13
|
+
effort: includeThoughts ? ('high' as const) : ('none' as const),
|
|
14
|
+
includeThoughts,
|
|
15
|
+
};
|
|
16
|
+
}
|
package/src/chat/google/route.ts
CHANGED
|
@@ -31,6 +31,7 @@ import {
|
|
|
31
31
|
import { ChatRequestBodySchema, mapToUIMessages } from './chat-request-schema';
|
|
32
32
|
import { systemInstruction } from './default-system-instruction';
|
|
33
33
|
import { prepareMiraToolStep } from './mira-step-preparation';
|
|
34
|
+
import { resolveChatReasoningSettings } from './reasoning-settings';
|
|
34
35
|
import {
|
|
35
36
|
type AiRouteAuthResult,
|
|
36
37
|
isInternalTuturuuuAiUser,
|
|
@@ -51,8 +52,6 @@ import {
|
|
|
51
52
|
persistAssistantResponse,
|
|
52
53
|
} from './stream-finish-persistence';
|
|
53
54
|
|
|
54
|
-
type ThinkingMode = 'fast' | 'thinking';
|
|
55
|
-
|
|
56
55
|
function splitSystemMessages(messages: ModelMessage[]) {
|
|
57
56
|
const systemMessages: string[] = [];
|
|
58
57
|
const nonSystemMessages: ModelMessage[] = [];
|
|
@@ -144,8 +143,7 @@ export function createPOST(
|
|
|
144
143
|
observabilityContext,
|
|
145
144
|
taskBoardContext,
|
|
146
145
|
} = parsedBody.data;
|
|
147
|
-
const thinkingMode:
|
|
148
|
-
rawThinkingMode === 'thinking' ? 'thinking' : 'fast';
|
|
146
|
+
const thinkingMode = rawThinkingMode === 'thinking' ? 'thinking' : 'fast';
|
|
149
147
|
|
|
150
148
|
if (!messages) {
|
|
151
149
|
console.error('Missing messages');
|
|
@@ -461,20 +459,7 @@ export function createPOST(
|
|
|
461
459
|
wsId: billingWsId ?? normalizedWsId,
|
|
462
460
|
});
|
|
463
461
|
|
|
464
|
-
|
|
465
|
-
const modelLower = resolvedModelId.toLowerCase();
|
|
466
|
-
const supportsThinking =
|
|
467
|
-
modelLower.includes('gemini-2.5') || modelLower.includes('gemini-3');
|
|
468
|
-
const thinkingConfig = supportsThinking
|
|
469
|
-
? thinkingMode === 'thinking'
|
|
470
|
-
? { thinkingConfig: { includeThoughts: true } }
|
|
471
|
-
: {
|
|
472
|
-
thinkingConfig: {
|
|
473
|
-
thinkingBudget: 0,
|
|
474
|
-
includeThoughts: false,
|
|
475
|
-
},
|
|
476
|
-
}
|
|
477
|
-
: {};
|
|
462
|
+
const reasoningSettings = resolveChatReasoningSettings(thinkingMode);
|
|
478
463
|
const forceRenderUi = shouldForceRenderUiForLatestUserMessage(
|
|
479
464
|
promptMessages.messages
|
|
480
465
|
);
|
|
@@ -540,6 +525,7 @@ export function createPOST(
|
|
|
540
525
|
maxRetries: 0,
|
|
541
526
|
model: resolvedGatewayModel,
|
|
542
527
|
messages: promptMessages.messages,
|
|
528
|
+
reasoning: reasoningSettings.effort,
|
|
543
529
|
system: mergeSystemInstructions(
|
|
544
530
|
isMiraMode && miraSystemPrompt ? miraSystemPrompt : systemInstruction,
|
|
545
531
|
promptMessages.system
|
|
@@ -561,7 +547,9 @@ export function createPOST(
|
|
|
561
547
|
}),
|
|
562
548
|
providerOptions: {
|
|
563
549
|
google: {
|
|
564
|
-
|
|
550
|
+
thinkingConfig: {
|
|
551
|
+
includeThoughts: reasoningSettings.includeThoughts,
|
|
552
|
+
},
|
|
565
553
|
safetySettings: [
|
|
566
554
|
{
|
|
567
555
|
category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
|
|
@@ -582,7 +570,9 @@ export function createPOST(
|
|
|
582
570
|
],
|
|
583
571
|
},
|
|
584
572
|
vertex: {
|
|
585
|
-
|
|
573
|
+
thinkingConfig: {
|
|
574
|
+
includeThoughts: reasoningSettings.includeThoughts,
|
|
575
|
+
},
|
|
586
576
|
safetySettings: [
|
|
587
577
|
{
|
|
588
578
|
category: 'HARM_CATEGORY_HARASSMENT',
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { createAdminClient } from '@tuturuuu/supabase/next/server';
|
|
2
|
+
import type { Tables } from '@tuturuuu/types';
|
|
3
|
+
import { extractAiApiKeyPrefix, validateApiKeyHash } from '../api-key-hash';
|
|
4
|
+
import { AiStudioError } from './errors';
|
|
5
|
+
|
|
6
|
+
export type AiStudioApiKey = Tables<
|
|
7
|
+
{ schema: 'private' },
|
|
8
|
+
'ai_studio_api_keys'
|
|
9
|
+
>;
|
|
10
|
+
|
|
11
|
+
export type AiStudioCredential = {
|
|
12
|
+
apiKey: AiStudioApiKey;
|
|
13
|
+
actorId: string;
|
|
14
|
+
workspaceId: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
function readBearerToken(request: Request): string {
|
|
18
|
+
const authorization = request.headers.get('authorization');
|
|
19
|
+
if (!authorization?.startsWith('Bearer ')) {
|
|
20
|
+
throw new AiStudioError('A Tuturuuu AI API key is required.', {
|
|
21
|
+
code: 'invalid_api_key',
|
|
22
|
+
status: 401,
|
|
23
|
+
type: 'authentication_error',
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return authorization.slice('Bearer '.length).trim();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function authenticateAiStudioRequest(
|
|
31
|
+
request: Request
|
|
32
|
+
): Promise<AiStudioCredential> {
|
|
33
|
+
const secret = readBearerToken(request);
|
|
34
|
+
const prefix = extractAiApiKeyPrefix(secret);
|
|
35
|
+
if (!prefix) {
|
|
36
|
+
throw new AiStudioError('The supplied API key is invalid.', {
|
|
37
|
+
code: 'invalid_api_key',
|
|
38
|
+
status: 401,
|
|
39
|
+
type: 'authentication_error',
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const sbAdmin = await createAdminClient({ noCookie: true });
|
|
44
|
+
const { data: apiKey, error } = await sbAdmin
|
|
45
|
+
.schema('private')
|
|
46
|
+
.from('ai_studio_api_keys')
|
|
47
|
+
.select('*')
|
|
48
|
+
.eq('prefix', prefix)
|
|
49
|
+
.maybeSingle();
|
|
50
|
+
|
|
51
|
+
const expired =
|
|
52
|
+
apiKey?.expires_at && new Date(apiKey.expires_at).getTime() <= Date.now();
|
|
53
|
+
const valid =
|
|
54
|
+
apiKey &&
|
|
55
|
+
!error &&
|
|
56
|
+
!apiKey.revoked_at &&
|
|
57
|
+
!expired &&
|
|
58
|
+
(await validateApiKeyHash(secret, apiKey.secret_hash));
|
|
59
|
+
|
|
60
|
+
if (!valid || !apiKey.created_by) {
|
|
61
|
+
throw new AiStudioError('The supplied API key is invalid or inactive.', {
|
|
62
|
+
code: 'invalid_api_key',
|
|
63
|
+
status: 401,
|
|
64
|
+
type: 'authentication_error',
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
apiKey,
|
|
70
|
+
actorId: apiKey.created_by,
|
|
71
|
+
workspaceId: apiKey.ws_id,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
export type AiStudioErrorCode =
|
|
2
|
+
| 'invalid_api_key'
|
|
3
|
+
| 'insufficient_credits'
|
|
4
|
+
| 'invalid_request_error'
|
|
5
|
+
| 'model_not_found'
|
|
6
|
+
| 'rate_limit_exceeded'
|
|
7
|
+
| 'server_error';
|
|
8
|
+
|
|
9
|
+
export class AiStudioError extends Error {
|
|
10
|
+
readonly code: AiStudioErrorCode;
|
|
11
|
+
readonly status: number;
|
|
12
|
+
readonly type: string;
|
|
13
|
+
|
|
14
|
+
constructor(
|
|
15
|
+
message: string,
|
|
16
|
+
{
|
|
17
|
+
code,
|
|
18
|
+
status,
|
|
19
|
+
type = 'invalid_request_error',
|
|
20
|
+
}: {
|
|
21
|
+
code: AiStudioErrorCode;
|
|
22
|
+
status: number;
|
|
23
|
+
type?: string;
|
|
24
|
+
}
|
|
25
|
+
) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = 'AiStudioError';
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.status = status;
|
|
30
|
+
this.type = type;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function toOpenAiError(error: unknown, requestId?: string) {
|
|
35
|
+
const studioError =
|
|
36
|
+
error instanceof AiStudioError
|
|
37
|
+
? error
|
|
38
|
+
: new AiStudioError('The request could not be completed.', {
|
|
39
|
+
code: 'server_error',
|
|
40
|
+
status: 500,
|
|
41
|
+
type: 'server_error',
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
return Response.json(
|
|
45
|
+
{
|
|
46
|
+
error: {
|
|
47
|
+
code: studioError.code,
|
|
48
|
+
message: studioError.message,
|
|
49
|
+
param: null,
|
|
50
|
+
type: studioError.type,
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
status: studioError.status,
|
|
55
|
+
headers: requestId ? { 'x-request-id': requestId } : undefined,
|
|
56
|
+
}
|
|
57
|
+
);
|
|
58
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { createAdminClient } from '@tuturuuu/supabase/next/server';
|
|
2
|
+
import type { Json } from '@tuturuuu/types';
|
|
3
|
+
import { AiStudioError } from './errors';
|
|
4
|
+
|
|
5
|
+
export type AiStudioRunReservation = {
|
|
6
|
+
reservationId: string;
|
|
7
|
+
runId: string;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export type ExternalAiStudioRun = {
|
|
11
|
+
runId: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export type AiStudioUsageCost = {
|
|
15
|
+
billedCredits: number;
|
|
16
|
+
providerCostUsd: number;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type CalculateAiStudioUsageCostInput = {
|
|
20
|
+
imageCount?: number;
|
|
21
|
+
inputTokens?: number;
|
|
22
|
+
modelId: string;
|
|
23
|
+
outputTokens?: number;
|
|
24
|
+
reasoningTokens?: number;
|
|
25
|
+
searchCount?: number;
|
|
26
|
+
workspaceId: string;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export async function calculateAiStudioUsageCost(
|
|
30
|
+
input: CalculateAiStudioUsageCostInput
|
|
31
|
+
): Promise<AiStudioUsageCost> {
|
|
32
|
+
const sbAdmin = await createAdminClient({ noCookie: true });
|
|
33
|
+
const { data, error } = await sbAdmin
|
|
34
|
+
.schema('private')
|
|
35
|
+
.rpc('calculate_ai_studio_usage_cost', {
|
|
36
|
+
p_image_count: input.imageCount ?? 0,
|
|
37
|
+
p_input_tokens: input.inputTokens ?? 0,
|
|
38
|
+
p_model_id: input.modelId,
|
|
39
|
+
p_output_tokens: input.outputTokens ?? 0,
|
|
40
|
+
p_reasoning_tokens: input.reasoningTokens ?? 0,
|
|
41
|
+
p_search_count: input.searchCount ?? 0,
|
|
42
|
+
p_ws_id: input.workspaceId,
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const cost = data?.[0];
|
|
46
|
+
if (error || !cost) {
|
|
47
|
+
throw new AiStudioError('AI usage cost could not be calculated.', {
|
|
48
|
+
code: 'server_error',
|
|
49
|
+
status: 500,
|
|
50
|
+
type: 'server_error',
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
billedCredits: Number(cost.billed_credits),
|
|
56
|
+
providerCostUsd: Number(cost.provider_cost_usd),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export type BeginAiStudioRunInput = {
|
|
61
|
+
actorId: string;
|
|
62
|
+
apiKeyId: string;
|
|
63
|
+
feature: string;
|
|
64
|
+
idempotencyKey?: string | null;
|
|
65
|
+
metadata?: Json;
|
|
66
|
+
modelId: string;
|
|
67
|
+
requestId: string;
|
|
68
|
+
reservedCredits: number;
|
|
69
|
+
workspaceId: string;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
function reservationError(code: string | null): AiStudioError {
|
|
73
|
+
if (code === 'MODEL_NOT_ALLOWED') {
|
|
74
|
+
return new AiStudioError('This model is not enabled for the workspace.', {
|
|
75
|
+
code: 'model_not_found',
|
|
76
|
+
status: 404,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
if (code === 'RATE_LIMIT_EXCEEDED') {
|
|
80
|
+
return new AiStudioError('The API key rate limit has been reached.', {
|
|
81
|
+
code: 'rate_limit_exceeded',
|
|
82
|
+
status: 429,
|
|
83
|
+
type: 'rate_limit_error',
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
if (
|
|
87
|
+
code === 'KEY_BUDGET_EXCEEDED' ||
|
|
88
|
+
code === 'WORKSPACE_BUDGET_EXCEEDED' ||
|
|
89
|
+
code === 'INSUFFICIENT_CREDITS'
|
|
90
|
+
) {
|
|
91
|
+
return new AiStudioError('The workspace has insufficient AI credits.', {
|
|
92
|
+
code: 'insufficient_credits',
|
|
93
|
+
status: 402,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return new AiStudioError('The request could not reserve AI credits.', {
|
|
98
|
+
code: 'server_error',
|
|
99
|
+
status: 500,
|
|
100
|
+
type: 'server_error',
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function beginAiStudioRun(
|
|
105
|
+
input: BeginAiStudioRunInput
|
|
106
|
+
): Promise<AiStudioRunReservation> {
|
|
107
|
+
const sbAdmin = await createAdminClient({ noCookie: true });
|
|
108
|
+
const { data, error } = await sbAdmin
|
|
109
|
+
.schema('private')
|
|
110
|
+
.rpc('begin_ai_studio_run', {
|
|
111
|
+
p_api_key_id: input.apiKeyId,
|
|
112
|
+
p_feature: input.feature,
|
|
113
|
+
p_idempotency_key: input.idempotencyKey ?? undefined,
|
|
114
|
+
p_metadata: input.metadata,
|
|
115
|
+
p_model_id: input.modelId,
|
|
116
|
+
p_request_id: input.requestId,
|
|
117
|
+
p_reserved_credits: input.reservedCredits,
|
|
118
|
+
p_user_id: input.actorId,
|
|
119
|
+
p_ws_id: input.workspaceId,
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
const result = data?.[0];
|
|
123
|
+
if (error || !result?.success || !result.run_id || !result.reservation_id) {
|
|
124
|
+
throw reservationError(result?.error_code ?? null);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
reservationId: result.reservation_id,
|
|
129
|
+
runId: result.run_id,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export type BeginExternalAiStudioRunInput = {
|
|
134
|
+
actorId: string;
|
|
135
|
+
externalAppId: string;
|
|
136
|
+
feature: string;
|
|
137
|
+
idempotencyKey?: string | null;
|
|
138
|
+
metadata?: Json;
|
|
139
|
+
modelId: string;
|
|
140
|
+
requestId: string;
|
|
141
|
+
workspaceId: string;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
export async function beginExternalAiStudioRun(
|
|
145
|
+
input: BeginExternalAiStudioRunInput
|
|
146
|
+
): Promise<ExternalAiStudioRun> {
|
|
147
|
+
const sbAdmin = await createAdminClient({ noCookie: true });
|
|
148
|
+
const { data, error } = await sbAdmin
|
|
149
|
+
.schema('private')
|
|
150
|
+
.rpc('begin_external_ai_studio_run', {
|
|
151
|
+
p_external_app_id: input.externalAppId,
|
|
152
|
+
p_feature: input.feature,
|
|
153
|
+
p_idempotency_key: input.idempotencyKey ?? undefined,
|
|
154
|
+
p_metadata: input.metadata,
|
|
155
|
+
p_model_id: input.modelId,
|
|
156
|
+
p_request_id: input.requestId,
|
|
157
|
+
p_user_id: input.actorId,
|
|
158
|
+
p_ws_id: input.workspaceId,
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
const result = data?.[0];
|
|
162
|
+
if (error || !result?.success || !result.run_id) {
|
|
163
|
+
throw reservationError(result?.error_code ?? null);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return { runId: result.run_id };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export type SettleAiStudioRunInput = {
|
|
170
|
+
actualCredits: number;
|
|
171
|
+
embeddingUnits?: number;
|
|
172
|
+
errorClass?: string | null;
|
|
173
|
+
errorMessage?: string | null;
|
|
174
|
+
firstTokenLatencyMs?: number | null;
|
|
175
|
+
imageUnits?: number;
|
|
176
|
+
inputTokens?: number;
|
|
177
|
+
latencyMs?: number | null;
|
|
178
|
+
metadata?: Json;
|
|
179
|
+
outputTokens?: number;
|
|
180
|
+
providerCostUsd?: number;
|
|
181
|
+
reasoningTokens?: number;
|
|
182
|
+
runId: string;
|
|
183
|
+
status: 'aborted' | 'failed' | 'succeeded';
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
export async function settleAiStudioRun(
|
|
187
|
+
input: SettleAiStudioRunInput
|
|
188
|
+
): Promise<void> {
|
|
189
|
+
const sbAdmin = await createAdminClient({ noCookie: true });
|
|
190
|
+
const { data, error } = await sbAdmin
|
|
191
|
+
.schema('private')
|
|
192
|
+
.rpc('settle_ai_studio_run', {
|
|
193
|
+
p_actual_credits: input.actualCredits,
|
|
194
|
+
p_embedding_units: input.embeddingUnits ?? 0,
|
|
195
|
+
p_error_class: input.errorClass ?? undefined,
|
|
196
|
+
p_error_message: input.errorMessage ?? undefined,
|
|
197
|
+
p_first_token_latency_ms: input.firstTokenLatencyMs ?? undefined,
|
|
198
|
+
p_image_units: input.imageUnits ?? 0,
|
|
199
|
+
p_input_tokens: input.inputTokens ?? 0,
|
|
200
|
+
p_latency_ms: input.latencyMs ?? undefined,
|
|
201
|
+
p_metadata: input.metadata,
|
|
202
|
+
p_output_tokens: input.outputTokens ?? 0,
|
|
203
|
+
p_provider_cost_usd: input.providerCostUsd ?? 0,
|
|
204
|
+
p_reasoning_tokens: input.reasoningTokens ?? 0,
|
|
205
|
+
p_run_id: input.runId,
|
|
206
|
+
p_status: input.status,
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
if (error || !data?.[0]?.success) {
|
|
210
|
+
throw new AiStudioError('AI usage could not be settled.', {
|
|
211
|
+
code: 'server_error',
|
|
212
|
+
status: 500,
|
|
213
|
+
type: 'server_error',
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export async function settleExternalAiStudioRun(
|
|
219
|
+
input: Omit<SettleAiStudioRunInput, 'actualCredits'>
|
|
220
|
+
): Promise<void> {
|
|
221
|
+
const sbAdmin = await createAdminClient({ noCookie: true });
|
|
222
|
+
const { data, error } = await sbAdmin
|
|
223
|
+
.schema('private')
|
|
224
|
+
.rpc('settle_external_ai_studio_run', {
|
|
225
|
+
p_embedding_units: input.embeddingUnits ?? 0,
|
|
226
|
+
p_error_class: input.errorClass ?? undefined,
|
|
227
|
+
p_error_message: input.errorMessage ?? undefined,
|
|
228
|
+
p_first_token_latency_ms: input.firstTokenLatencyMs ?? undefined,
|
|
229
|
+
p_image_units: input.imageUnits ?? 0,
|
|
230
|
+
p_input_tokens: input.inputTokens ?? 0,
|
|
231
|
+
p_latency_ms: input.latencyMs ?? undefined,
|
|
232
|
+
p_metadata: input.metadata,
|
|
233
|
+
p_output_tokens: input.outputTokens ?? 0,
|
|
234
|
+
p_provider_cost_usd: input.providerCostUsd ?? 0,
|
|
235
|
+
p_reasoning_tokens: input.reasoningTokens ?? 0,
|
|
236
|
+
p_run_id: input.runId,
|
|
237
|
+
p_status: input.status,
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
if (error || !data?.[0]?.success) {
|
|
241
|
+
throw new AiStudioError('External-app AI usage could not be settled.', {
|
|
242
|
+
code: 'server_error',
|
|
243
|
+
status: 500,
|
|
244
|
+
type: 'server_error',
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export function getAiStudioRequestId(request: Request): string {
|
|
4
|
+
return request.headers.get('x-request-id')?.slice(0, 128) || randomUUID();
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function getIdempotencyKey(request: Request): string | null {
|
|
8
|
+
return request.headers.get('idempotency-key')?.slice(0, 255) || null;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function getRequestDurationMs(startedAt: number): number {
|
|
12
|
+
return Math.max(0, Math.round(performance.now() - startedAt));
|
|
13
|
+
}
|