@donotdev/functions 0.1.0 → 0.1.1
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/guidelines/FUNCTIONS.md +9 -0
- package/guidelines/VERCEL.md +260 -0
- package/lib/firebase/billing/createCheckoutSession.d.ts +10 -13
- package/lib/firebase/index.js +3 -3
- package/lib/firebase/index.js.map +4 -4
- package/lib/shared/ai/classifyAIError.d.ts +35 -0
- package/lib/shared/ai/costTracker.d.ts +20 -0
- package/lib/shared/ai/createAIRoute.d.ts +20 -0
- package/lib/shared/ai/index.d.ts +6 -0
- package/lib/shared/ai/resolveModelTier.d.ts +14 -0
- package/lib/shared/billing/createCheckout.d.ts +8 -2
- package/lib/shared/email/createEmailRoute.d.ts +30 -0
- package/lib/shared/email/index.d.ts +3 -0
- package/lib/shared/email/provider.d.ts +30 -0
- package/lib/shared/email/resendProvider.d.ts +22 -0
- package/lib/shared/github.d.ts +5 -0
- package/lib/shared/index.d.ts +2 -0
- package/lib/shared/index.js +4 -3
- package/lib/shared/index.js.map +4 -4
- package/lib/shared/logger.d.ts +2 -0
- package/lib/shared/oauth/exchangeToken.d.ts +1 -0
- package/lib/shared/oauth/grantAccess.d.ts +1 -0
- package/lib/shared/utils/internal/idempotency.d.ts +1 -0
- package/lib/supabase/ai/createAIFunction.d.ts +30 -0
- package/lib/supabase/auth/removeCustomClaims.d.ts +1 -1
- package/lib/supabase/auth/setCustomClaims.d.ts +12 -4
- package/lib/supabase/billing/changePlan.d.ts +1 -1
- package/lib/supabase/crud/aggregate.d.ts +1 -0
- package/lib/supabase/crud/create.d.ts +1 -0
- package/lib/supabase/crud/delete.d.ts +1 -0
- package/lib/supabase/crud/get.d.ts +1 -0
- package/lib/supabase/crud/list.d.ts +1 -0
- package/lib/supabase/crud/update.d.ts +1 -0
- package/lib/supabase/edgeFunction.d.ts +56 -0
- package/lib/supabase/email/createEmailFunction.d.ts +31 -0
- package/lib/supabase/index.d.ts +8 -0
- package/lib/supabase/index.js +3 -2
- package/lib/supabase/index.js.map +4 -4
- package/lib/vercel/api/ai/chat.d.ts +29 -0
- package/lib/vercel/api/ai/index.d.ts +1 -0
- package/lib/vercel/api/index.d.ts +1 -0
- package/lib/vercel/api/index.js +3 -2
- package/lib/vercel/api/index.js.map +4 -4
- package/package.json +38 -5
- package/src/firebase/billing/createCheckoutSession.ts +79 -187
- package/src/firebase/oauth/exchangeToken.ts +4 -4
- package/src/firebase/oauth/refreshToken.ts +4 -4
- package/src/shared/ai/__tests__/costTracker.test.ts +121 -0
- package/src/shared/ai/classifyAIError.ts +163 -0
- package/src/shared/ai/costTracker.ts +51 -0
- package/src/shared/ai/createAIRoute.ts +397 -0
- package/src/shared/ai/index.ts +8 -0
- package/src/shared/ai/resolveModelTier.ts +58 -0
- package/src/shared/billing/createCheckout.ts +153 -8
- package/src/shared/billing/helpers/subscriptionManagement.ts +9 -0
- package/src/shared/billing/idempotency.ts +5 -0
- package/src/shared/email/createEmailRoute.ts +81 -0
- package/src/shared/email/index.ts +5 -0
- package/src/shared/email/provider.ts +31 -0
- package/src/shared/email/resendProvider.ts +56 -0
- package/src/shared/errorHandling.ts +10 -4
- package/src/shared/github.ts +38 -0
- package/src/shared/index.ts +2 -0
- package/src/shared/logger.ts +2 -0
- package/src/shared/oauth/exchangeToken.ts +1 -0
- package/src/shared/oauth/grantAccess.ts +1 -0
- package/src/shared/utils/internal/idempotency.ts +1 -0
- package/src/shared/utils/internal/rateLimiter.ts +6 -3
- package/src/shared/validation.ts +1 -1
- package/src/supabase/ai/createAIFunction.ts +75 -0
- package/src/supabase/auth/removeCustomClaims.ts +38 -2
- package/src/supabase/auth/setCustomClaims.ts +66 -5
- package/src/supabase/baseFunction.ts +26 -2
- package/src/supabase/billing/changePlan.ts +6 -1
- package/src/supabase/billing/createCheckoutSession.ts +16 -2
- package/src/supabase/crud/aggregate.ts +1 -0
- package/src/supabase/crud/create.ts +1 -0
- package/src/supabase/crud/delete.ts +1 -0
- package/src/supabase/crud/get.ts +1 -0
- package/src/supabase/crud/list.ts +1 -0
- package/src/supabase/crud/update.ts +1 -0
- package/src/supabase/edgeFunction.ts +195 -0
- package/src/supabase/email/createEmailFunction.ts +75 -0
- package/src/supabase/index.ts +12 -0
- package/src/supabase/oauth/exchangeToken.ts +38 -7
- package/src/supabase/oauth/refreshToken.ts +4 -5
- package/src/supabase/registerCrudFunctions.ts +29 -41
- package/src/supabase/utils/idempotency.ts +6 -2
- package/src/vercel/api/ai/chat.ts +77 -0
- package/src/vercel/api/ai/index.ts +1 -0
- package/src/vercel/api/billing/create-checkout-session.ts +27 -4
- package/src/vercel/api/billing/webhook-handler.ts +8 -1
- package/src/vercel/api/index.ts +1 -0
- package/src/vercel/api/oauth/exchange-token.ts +24 -1
- package/src/vercel/api/utils/cors.ts +6 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// packages/functions/src/shared/ai/classifyAIError.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview AI Error Classifier
|
|
5
|
+
* @description Classifies Anthropic API errors into actionable categories
|
|
6
|
+
* for structured error responses in edge functions.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.6.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
// =============================================================================
|
|
14
|
+
// Types
|
|
15
|
+
// =============================================================================
|
|
16
|
+
|
|
17
|
+
/** Actionable error category for AI provider failures. */
|
|
18
|
+
export type AIErrorCode =
|
|
19
|
+
| 'rate_limited'
|
|
20
|
+
| 'overloaded'
|
|
21
|
+
| 'auth_error'
|
|
22
|
+
| 'credits_exhausted'
|
|
23
|
+
| 'network'
|
|
24
|
+
| 'internal';
|
|
25
|
+
|
|
26
|
+
/** Result of classifying an AI provider error with retry and severity metadata. */
|
|
27
|
+
export interface ClassifiedAIError {
|
|
28
|
+
code: AIErrorCode;
|
|
29
|
+
retryable: boolean;
|
|
30
|
+
retryAfterMs?: number;
|
|
31
|
+
severity: 'transient' | 'critical';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// =============================================================================
|
|
35
|
+
// Classifier
|
|
36
|
+
// =============================================================================
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Classify an error from an Anthropic API call into an actionable category.
|
|
40
|
+
*
|
|
41
|
+
* | HTTP/Error | Category | Retryable | Severity |
|
|
42
|
+
* |------------------|--------------------|-----------|------------|
|
|
43
|
+
* | 429 | rate_limited | yes | transient |
|
|
44
|
+
* | 529 / 503 | overloaded | yes | transient |
|
|
45
|
+
* | 401 | auth_error | no | critical |
|
|
46
|
+
* | 402 / credits | credits_exhausted | no | critical |
|
|
47
|
+
* | Network/timeout | network | yes | transient |
|
|
48
|
+
* | Other 5xx | internal | no | critical |
|
|
49
|
+
*/
|
|
50
|
+
export function classifyAIError(err: unknown): ClassifiedAIError {
|
|
51
|
+
const status = extractStatus(err);
|
|
52
|
+
const message = extractMessage(err);
|
|
53
|
+
|
|
54
|
+
// 429 - Rate limited
|
|
55
|
+
if (status === 429) {
|
|
56
|
+
return {
|
|
57
|
+
code: 'rate_limited',
|
|
58
|
+
retryable: true,
|
|
59
|
+
retryAfterMs: extractRetryAfter(err) ?? 5_000,
|
|
60
|
+
severity: 'transient',
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 529 / 503 - Overloaded
|
|
65
|
+
if (status === 529 || status === 503) {
|
|
66
|
+
return {
|
|
67
|
+
code: 'overloaded',
|
|
68
|
+
retryable: true,
|
|
69
|
+
retryAfterMs: extractRetryAfter(err) ?? 10_000,
|
|
70
|
+
severity: 'transient',
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 401 - Auth error
|
|
75
|
+
if (status === 401) {
|
|
76
|
+
return { code: 'auth_error', retryable: false, severity: 'critical' };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 402 or insufficient credits
|
|
80
|
+
if (status === 402 || message.includes('insufficient') || message.includes('credit')) {
|
|
81
|
+
return { code: 'credits_exhausted', retryable: false, severity: 'critical' };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Network / timeout errors (no HTTP status)
|
|
85
|
+
if (
|
|
86
|
+
!status &&
|
|
87
|
+
(message.includes('fetch') ||
|
|
88
|
+
message.includes('network') ||
|
|
89
|
+
message.includes('ECONNREFUSED') ||
|
|
90
|
+
message.includes('ETIMEDOUT') ||
|
|
91
|
+
message.includes('timeout') ||
|
|
92
|
+
message.includes('aborted') ||
|
|
93
|
+
err instanceof TypeError)
|
|
94
|
+
) {
|
|
95
|
+
return {
|
|
96
|
+
code: 'network',
|
|
97
|
+
retryable: true,
|
|
98
|
+
retryAfterMs: 3_000,
|
|
99
|
+
severity: 'transient',
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Everything else
|
|
104
|
+
return { code: 'internal', retryable: false, severity: 'critical' };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Map a classified error code to an HTTP status for the edge function response.
|
|
109
|
+
*/
|
|
110
|
+
export function mapClassifiedToHTTP(code: AIErrorCode): number {
|
|
111
|
+
switch (code) {
|
|
112
|
+
case 'rate_limited': return 429;
|
|
113
|
+
case 'overloaded': return 503;
|
|
114
|
+
case 'auth_error': return 502;
|
|
115
|
+
case 'credits_exhausted': return 502;
|
|
116
|
+
case 'network': return 502;
|
|
117
|
+
case 'internal': return 500;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// =============================================================================
|
|
122
|
+
// Helpers
|
|
123
|
+
// =============================================================================
|
|
124
|
+
|
|
125
|
+
function extractStatus(err: unknown): number | undefined {
|
|
126
|
+
if (err && typeof err === 'object') {
|
|
127
|
+
// Anthropic SDK errors have .status
|
|
128
|
+
if ('status' in err && typeof (err as any).status === 'number') {
|
|
129
|
+
return (err as any).status;
|
|
130
|
+
}
|
|
131
|
+
// Some errors nest status in .error
|
|
132
|
+
if ('error' in err && typeof (err as any).error?.status === 'number') {
|
|
133
|
+
return (err as any).error.status;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function extractMessage(err: unknown): string {
|
|
140
|
+
if (err instanceof Error) return err.message.toLowerCase();
|
|
141
|
+
if (typeof err === 'string') return err.toLowerCase();
|
|
142
|
+
if (err && typeof err === 'object' && 'message' in err) {
|
|
143
|
+
return String((err as any).message).toLowerCase();
|
|
144
|
+
}
|
|
145
|
+
return '';
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function extractRetryAfter(err: unknown): number | undefined {
|
|
149
|
+
if (err && typeof err === 'object') {
|
|
150
|
+
// Anthropic SDK puts headers on the error
|
|
151
|
+
const headers = (err as any).headers;
|
|
152
|
+
if (headers) {
|
|
153
|
+
const retryAfter = typeof headers.get === 'function'
|
|
154
|
+
? headers.get('retry-after')
|
|
155
|
+
: headers['retry-after'];
|
|
156
|
+
if (retryAfter) {
|
|
157
|
+
const seconds = Number(retryAfter);
|
|
158
|
+
if (!Number.isNaN(seconds)) return seconds * 1000;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// packages/functions/src/shared/ai/costTracker.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview Server-Side Cost Calculator
|
|
5
|
+
* @description Calculate per-request AI costs using SSOT pricing from `@donotdev/core`.
|
|
6
|
+
* Cost records are written async by platform wrappers (Supabase, Vercel, Firebase).
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.1.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { AICostResult, AIUsage } from '@donotdev/core/server';
|
|
14
|
+
import { AI_TOKEN_PRICING, DEFAULT_AI_MARKUP } from '@donotdev/core/server';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Calculate cost from token usage for a given model.
|
|
18
|
+
*
|
|
19
|
+
* @param usage - Token usage counts
|
|
20
|
+
* @param model - Model ID (must exist in AI_TOKEN_PRICING)
|
|
21
|
+
* @param markup - Markup multiplier (default: 4.0)
|
|
22
|
+
* @returns Cost breakdown with provider and billed amounts
|
|
23
|
+
* @throws Error if model is not in pricing table
|
|
24
|
+
*/
|
|
25
|
+
export function calculateCost(
|
|
26
|
+
usage: AIUsage,
|
|
27
|
+
model: string,
|
|
28
|
+
markup: number = DEFAULT_AI_MARKUP
|
|
29
|
+
): AICostResult {
|
|
30
|
+
const pricing = AI_TOKEN_PRICING[model];
|
|
31
|
+
if (!pricing) {
|
|
32
|
+
throw new Error(`Unknown model for cost calculation: ${model}`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const promptCost = (usage.promptTokens / 1_000_000) * pricing.promptPer1M;
|
|
36
|
+
const completionCost =
|
|
37
|
+
(usage.completionTokens / 1_000_000) * pricing.completionPer1M;
|
|
38
|
+
const providerCost = promptCost + completionCost;
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
providerCost,
|
|
42
|
+
billedCost: providerCost * markup,
|
|
43
|
+
markup,
|
|
44
|
+
breakdown: {
|
|
45
|
+
promptTokens: usage.promptTokens,
|
|
46
|
+
completionTokens: usage.completionTokens,
|
|
47
|
+
promptCost,
|
|
48
|
+
completionCost,
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
// packages/functions/src/shared/ai/createAIRoute.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview AI Route Handler (Vercel AI SDK)
|
|
5
|
+
* @description Platform-agnostic handler for AI chat requests using Vercel AI SDK.
|
|
6
|
+
* Handles auth (via platform wrapper), rate limiting (Upstash), streaming, and cost tracking.
|
|
7
|
+
*
|
|
8
|
+
* @version 0.1.0
|
|
9
|
+
* @since 0.1.0
|
|
10
|
+
* @author AMBROISE PARK Consulting
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { streamText, generateText, tool, jsonSchema } from 'ai';
|
|
14
|
+
import type { LanguageModel, CoreTool } from 'ai';
|
|
15
|
+
|
|
16
|
+
import type {
|
|
17
|
+
AIChatRequest,
|
|
18
|
+
AICostConfig,
|
|
19
|
+
AICostRecord,
|
|
20
|
+
AIRateLimitConfig,
|
|
21
|
+
AIRouteConfig,
|
|
22
|
+
AIToolDefinition,
|
|
23
|
+
AIUsage,
|
|
24
|
+
} from '@donotdev/core/server';
|
|
25
|
+
import { AI_MODELS, validateAIChatRequest } from '@donotdev/core/server';
|
|
26
|
+
|
|
27
|
+
import { calculateCost } from './costTracker.js';
|
|
28
|
+
|
|
29
|
+
// =============================================================================
|
|
30
|
+
// Types
|
|
31
|
+
// =============================================================================
|
|
32
|
+
|
|
33
|
+
/** Per-request options passed to the AI route handler. */
|
|
34
|
+
export interface AIRouteOptions {
|
|
35
|
+
/** Authenticated user ID */
|
|
36
|
+
userId: string;
|
|
37
|
+
/** Request ID for cost tracking */
|
|
38
|
+
requestId?: string;
|
|
39
|
+
/** Callback to persist cost record (platform-specific) */
|
|
40
|
+
onCostRecord?: (record: AICostRecord) => Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Provider factory map - lazily creates provider instances */
|
|
44
|
+
type ProviderFactory = (apiKey: string) => LanguageModel;
|
|
45
|
+
|
|
46
|
+
// =============================================================================
|
|
47
|
+
// Provider Resolution
|
|
48
|
+
// =============================================================================
|
|
49
|
+
|
|
50
|
+
/** Lazily import and create provider models */
|
|
51
|
+
async function resolveModel(
|
|
52
|
+
provider: string,
|
|
53
|
+
model: string
|
|
54
|
+
): Promise<LanguageModel> {
|
|
55
|
+
const factories: Record<string, () => Promise<ProviderFactory>> = {
|
|
56
|
+
anthropic: async () => {
|
|
57
|
+
const { createAnthropic } = await import('@ai-sdk/anthropic');
|
|
58
|
+
return (apiKey: string) => createAnthropic({ apiKey })(model);
|
|
59
|
+
},
|
|
60
|
+
openai: async () => {
|
|
61
|
+
const { createOpenAI } = await import('@ai-sdk/openai');
|
|
62
|
+
return (apiKey: string) => createOpenAI({ apiKey })(model);
|
|
63
|
+
},
|
|
64
|
+
google: async () => {
|
|
65
|
+
const { createGoogleGenerativeAI } = await import('@ai-sdk/google');
|
|
66
|
+
return (apiKey: string) =>
|
|
67
|
+
createGoogleGenerativeAI({ apiKey })(model);
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const factory = factories[provider];
|
|
72
|
+
if (!factory) {
|
|
73
|
+
throw new Error(`Unsupported AI provider: ${provider}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const apiKey = getAIApiKey(provider);
|
|
77
|
+
const createModel = await factory();
|
|
78
|
+
return createModel(apiKey);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// =============================================================================
|
|
82
|
+
// Rate Limiting (reused from old handler)
|
|
83
|
+
// =============================================================================
|
|
84
|
+
|
|
85
|
+
const DEFAULT_RATE_LIMIT: AIRateLimitConfig = {
|
|
86
|
+
maxRequests: 30,
|
|
87
|
+
windowMs: 60_000,
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
let rateLimiter: {
|
|
91
|
+
check: (userId: string, config: AIRateLimitConfig) => Promise<void>;
|
|
92
|
+
} | null = null;
|
|
93
|
+
|
|
94
|
+
async function getRateLimiter() {
|
|
95
|
+
if (rateLimiter) return rateLimiter;
|
|
96
|
+
|
|
97
|
+
const redisUrl = getEnv('UPSTASH_REDIS_REST_URL');
|
|
98
|
+
const redisToken = getEnv('UPSTASH_REDIS_REST_TOKEN');
|
|
99
|
+
|
|
100
|
+
if (!redisUrl || !redisToken) {
|
|
101
|
+
console.warn(
|
|
102
|
+
'[AI] UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN not set. Rate limiting disabled.'
|
|
103
|
+
);
|
|
104
|
+
rateLimiter = { check: async () => {} };
|
|
105
|
+
return rateLimiter;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
try {
|
|
109
|
+
const { Ratelimit } = await import('@upstash/ratelimit');
|
|
110
|
+
const { Redis } = await import('@upstash/redis');
|
|
111
|
+
|
|
112
|
+
const redis = new Redis({ url: redisUrl, token: redisToken });
|
|
113
|
+
const limiters = new Map<string, InstanceType<typeof Ratelimit>>();
|
|
114
|
+
|
|
115
|
+
rateLimiter = {
|
|
116
|
+
check: async (userId: string, config: AIRateLimitConfig) => {
|
|
117
|
+
const key = `${config.maxRequests}:${config.windowMs}`;
|
|
118
|
+
let rl = limiters.get(key);
|
|
119
|
+
if (!rl) {
|
|
120
|
+
rl = new Ratelimit({
|
|
121
|
+
redis,
|
|
122
|
+
limiter: Ratelimit.slidingWindow(
|
|
123
|
+
config.maxRequests,
|
|
124
|
+
`${config.windowMs}ms`
|
|
125
|
+
),
|
|
126
|
+
prefix: 'ai_rl',
|
|
127
|
+
});
|
|
128
|
+
limiters.set(key, rl);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const result = await rl.limit(userId);
|
|
132
|
+
if (!result.success) {
|
|
133
|
+
throw new Error(
|
|
134
|
+
`Rate limit exceeded. Maximum ${config.maxRequests} requests per ${config.windowMs / 1000}s.`
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
return rateLimiter;
|
|
140
|
+
} catch (err) {
|
|
141
|
+
console.warn(
|
|
142
|
+
'[AI] Failed to initialize Upstash rate limiter:',
|
|
143
|
+
err instanceof Error ? err.message : err
|
|
144
|
+
);
|
|
145
|
+
rateLimiter = { check: async () => {} };
|
|
146
|
+
return rateLimiter;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// =============================================================================
|
|
151
|
+
// Tool Conversion (JSON Schema → Vercel AI SDK tool)
|
|
152
|
+
// =============================================================================
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Convert framework tool definitions to Vercel AI SDK tools.
|
|
156
|
+
* Uses `jsonSchema()` from the AI SDK to pass JSON Schema directly (no zod dependency).
|
|
157
|
+
* Merges request-level tools with config-level tools (request takes precedence).
|
|
158
|
+
*/
|
|
159
|
+
function resolveTools(
|
|
160
|
+
requestTools?: Record<string, AIToolDefinition>,
|
|
161
|
+
configTools?: Record<string, AIToolDefinition>
|
|
162
|
+
): Record<string, CoreTool> | undefined {
|
|
163
|
+
const merged = { ...configTools, ...requestTools };
|
|
164
|
+
if (Object.keys(merged).length === 0) return undefined;
|
|
165
|
+
|
|
166
|
+
const sdkTools: Record<string, CoreTool> = {};
|
|
167
|
+
for (const [name, def] of Object.entries(merged)) {
|
|
168
|
+
sdkTools[name] = tool({
|
|
169
|
+
description: def.description,
|
|
170
|
+
parameters: jsonSchema(def.parameters),
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
return sdkTools;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// =============================================================================
|
|
177
|
+
// Core Handler
|
|
178
|
+
// =============================================================================
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Handle an AI chat request using Vercel AI SDK.
|
|
182
|
+
* Supports both streaming (returns SSE Response) and non-streaming (returns JSON).
|
|
183
|
+
*
|
|
184
|
+
* @param request - Validated AI chat request
|
|
185
|
+
* @param config - Route configuration
|
|
186
|
+
* @param options - Per-request options (userId, cost callback)
|
|
187
|
+
* @returns Response (SSE stream or JSON)
|
|
188
|
+
*/
|
|
189
|
+
export async function handleAIRequest(
|
|
190
|
+
request: AIChatRequest,
|
|
191
|
+
config: AIRouteConfig,
|
|
192
|
+
options: AIRouteOptions
|
|
193
|
+
): Promise<Response> {
|
|
194
|
+
// Validate request
|
|
195
|
+
const validation = validateAIChatRequest(request);
|
|
196
|
+
if (!validation.success) {
|
|
197
|
+
return jsonError(
|
|
198
|
+
`Invalid AI request: ${validation.issues?.map((i) => i.message).join(', ')}`,
|
|
199
|
+
400
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Resolve provider + model
|
|
204
|
+
const provider = request.provider || config.provider || 'anthropic';
|
|
205
|
+
const providerModels = AI_MODELS[provider as keyof typeof AI_MODELS];
|
|
206
|
+
const model =
|
|
207
|
+
request.model || config.model || providerModels?.default || 'claude-sonnet-4-20250514';
|
|
208
|
+
|
|
209
|
+
// Validate model against allowed list
|
|
210
|
+
if (providerModels) {
|
|
211
|
+
const allowed = providerModels.models as readonly string[];
|
|
212
|
+
if (!allowed.includes(model)) {
|
|
213
|
+
return jsonError(
|
|
214
|
+
`Model '${model}' is not allowed for provider '${provider}'. Allowed: ${allowed.join(', ')}`,
|
|
215
|
+
400
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Rate limit
|
|
221
|
+
try {
|
|
222
|
+
const rl = await getRateLimiter();
|
|
223
|
+
await rl.check(
|
|
224
|
+
options.userId,
|
|
225
|
+
config.rateLimitConfig || DEFAULT_RATE_LIMIT
|
|
226
|
+
);
|
|
227
|
+
} catch (err) {
|
|
228
|
+
return jsonError(
|
|
229
|
+
err instanceof Error ? err.message : 'Rate limit exceeded',
|
|
230
|
+
429
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Resolve AI SDK model
|
|
235
|
+
let languageModel: LanguageModel;
|
|
236
|
+
try {
|
|
237
|
+
languageModel = await resolveModel(provider, model);
|
|
238
|
+
} catch (err) {
|
|
239
|
+
return jsonError(
|
|
240
|
+
`Failed to initialize provider: ${err instanceof Error ? err.message : String(err)}`,
|
|
241
|
+
500
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Build messages for AI SDK
|
|
246
|
+
const systemMessages = request.messages
|
|
247
|
+
.filter((m) => m.role === 'system')
|
|
248
|
+
.map((m) => m.content);
|
|
249
|
+
const systemPrompt =
|
|
250
|
+
request.systemPrompt ||
|
|
251
|
+
config.systemPrompt ||
|
|
252
|
+
(systemMessages.length > 0 ? systemMessages.join('\n') : undefined);
|
|
253
|
+
|
|
254
|
+
const messages = request.messages
|
|
255
|
+
.filter((m) => m.role !== 'system')
|
|
256
|
+
.map((m) => ({
|
|
257
|
+
role: m.role as 'user' | 'assistant',
|
|
258
|
+
content: m.content,
|
|
259
|
+
}));
|
|
260
|
+
|
|
261
|
+
const maxTokens = request.maxTokens || config.maxTokens || 4096;
|
|
262
|
+
const temperature = request.temperature ?? config.temperature ?? 0.7;
|
|
263
|
+
const requestId = options.requestId || crypto.randomUUID();
|
|
264
|
+
|
|
265
|
+
// Resolve tools (request-level overrides config-level)
|
|
266
|
+
const tools = resolveTools(request.tools, config.tools);
|
|
267
|
+
|
|
268
|
+
// Cost tracking helper
|
|
269
|
+
const recordCost = async (usage: AIUsage) => {
|
|
270
|
+
if (!options.onCostRecord) return;
|
|
271
|
+
|
|
272
|
+
const markup = config.cost?.markup ?? 4.0;
|
|
273
|
+
const cost = calculateCost(usage, model, markup);
|
|
274
|
+
|
|
275
|
+
const record: AICostRecord = {
|
|
276
|
+
userId: options.userId,
|
|
277
|
+
model,
|
|
278
|
+
provider,
|
|
279
|
+
usage,
|
|
280
|
+
providerCost: cost.providerCost,
|
|
281
|
+
billedCost: cost.billedCost,
|
|
282
|
+
markup,
|
|
283
|
+
timestamp: new Date().toISOString(),
|
|
284
|
+
requestId,
|
|
285
|
+
};
|
|
286
|
+
|
|
287
|
+
// Non-blocking - don't let cost recording failure break the response
|
|
288
|
+
options.onCostRecord(record).catch((err) => {
|
|
289
|
+
console.error('[AI] Failed to record cost:', err);
|
|
290
|
+
});
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
// Streaming vs non-streaming
|
|
294
|
+
if (request.stream !== false) {
|
|
295
|
+
// Streaming (default)
|
|
296
|
+
const result = streamText({
|
|
297
|
+
model: languageModel,
|
|
298
|
+
messages,
|
|
299
|
+
system: systemPrompt,
|
|
300
|
+
maxTokens,
|
|
301
|
+
temperature,
|
|
302
|
+
tools,
|
|
303
|
+
onFinish: async ({ usage }: { usage: any }) => {
|
|
304
|
+
await recordCost({
|
|
305
|
+
promptTokens: usage.promptTokens,
|
|
306
|
+
completionTokens: usage.completionTokens,
|
|
307
|
+
totalTokens: usage.promptTokens + usage.completionTokens,
|
|
308
|
+
});
|
|
309
|
+
},
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
return result.toDataStreamResponse();
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Non-streaming
|
|
316
|
+
const result = await generateText({
|
|
317
|
+
model: languageModel,
|
|
318
|
+
messages,
|
|
319
|
+
system: systemPrompt,
|
|
320
|
+
maxTokens,
|
|
321
|
+
temperature,
|
|
322
|
+
tools,
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
const usage: AIUsage = {
|
|
326
|
+
promptTokens: result.usage.promptTokens,
|
|
327
|
+
completionTokens: result.usage.completionTokens,
|
|
328
|
+
totalTokens: result.usage.promptTokens + result.usage.completionTokens,
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
await recordCost(usage);
|
|
332
|
+
|
|
333
|
+
// Extract tool calls from result
|
|
334
|
+
const toolCalls = result.toolCalls?.map((tc: any) => ({
|
|
335
|
+
id: tc.toolCallId,
|
|
336
|
+
name: tc.toolName,
|
|
337
|
+
args: tc.args,
|
|
338
|
+
})) ?? [];
|
|
339
|
+
|
|
340
|
+
return new Response(
|
|
341
|
+
JSON.stringify({
|
|
342
|
+
message: {
|
|
343
|
+
role: 'assistant',
|
|
344
|
+
content: result.text,
|
|
345
|
+
},
|
|
346
|
+
usage,
|
|
347
|
+
finishReason: result.finishReason,
|
|
348
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
349
|
+
model,
|
|
350
|
+
provider,
|
|
351
|
+
}),
|
|
352
|
+
{
|
|
353
|
+
status: 200,
|
|
354
|
+
headers: { 'Content-Type': 'application/json' },
|
|
355
|
+
}
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// =============================================================================
|
|
360
|
+
// Helpers
|
|
361
|
+
// =============================================================================
|
|
362
|
+
|
|
363
|
+
function jsonError(message: string, status: number): Response {
|
|
364
|
+
return new Response(JSON.stringify({ error: message }), {
|
|
365
|
+
status,
|
|
366
|
+
headers: { 'Content-Type': 'application/json' },
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function getEnv(name: string): string | undefined {
|
|
371
|
+
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
372
|
+
return (globalThis as any).Deno?.env?.get(name);
|
|
373
|
+
}
|
|
374
|
+
return typeof process !== 'undefined' ? process.env[name] : undefined;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function getAIApiKey(provider: string): string {
|
|
378
|
+
const providerKeyMap: Record<string, string> = {
|
|
379
|
+
anthropic: 'ANTHROPIC_API_KEY',
|
|
380
|
+
openai: 'OPENAI_API_KEY',
|
|
381
|
+
google: 'GOOGLE_AI_API_KEY',
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
const providerKey = providerKeyMap[provider];
|
|
385
|
+
if (providerKey) {
|
|
386
|
+
const key = getEnv(providerKey);
|
|
387
|
+
if (key) return key;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
const key = getEnv('AI_API_KEY');
|
|
391
|
+
if (!key) {
|
|
392
|
+
throw new Error(
|
|
393
|
+
`Missing API key. Set ${providerKey || 'AI_API_KEY'} environment variable.`
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
return key;
|
|
397
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// packages/functions/src/shared/ai/index.ts
|
|
2
|
+
|
|
3
|
+
export { handleAIRequest } from './createAIRoute.js';
|
|
4
|
+
export type { AIRouteOptions } from './createAIRoute.js';
|
|
5
|
+
export { calculateCost } from './costTracker.js';
|
|
6
|
+
export { resolveModelForTier } from './resolveModelTier.js';
|
|
7
|
+
export { classifyAIError, mapClassifiedToHTTP } from './classifyAIError.js';
|
|
8
|
+
export type { AIErrorCode, ClassifiedAIError } from './classifyAIError.js';
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// packages/functions/src/shared/ai/resolveModelTier.ts
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @fileoverview AI Model Tier Resolver
|
|
5
|
+
* @description Resolves the model ID for a given tier via env var chain.
|
|
6
|
+
* Resolution: per-function env → per-tier env → static SSOT.
|
|
7
|
+
* Cross-runtime: Deno (edge functions) + Node (Vercel/Firebase).
|
|
8
|
+
*
|
|
9
|
+
* @version 0.1.0
|
|
10
|
+
* @since 0.6.0
|
|
11
|
+
* @author AMBROISE PARK Consulting
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { AI_TIERS } from '@donotdev/core/server';
|
|
15
|
+
import type { AITierId } from '@donotdev/core/server';
|
|
16
|
+
|
|
17
|
+
// =============================================================================
|
|
18
|
+
// Env helper (Deno + Node cross-runtime)
|
|
19
|
+
// =============================================================================
|
|
20
|
+
|
|
21
|
+
function getEnv(name: string): string | undefined {
|
|
22
|
+
if (typeof globalThis !== 'undefined' && 'Deno' in globalThis) {
|
|
23
|
+
return (globalThis as any).Deno?.env?.get(name);
|
|
24
|
+
}
|
|
25
|
+
return typeof process !== 'undefined' ? process.env[name] : undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// =============================================================================
|
|
29
|
+
// Resolver
|
|
30
|
+
// =============================================================================
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Resolve the AI model ID for a given tier.
|
|
34
|
+
*
|
|
35
|
+
* Resolution chain (first non-empty wins):
|
|
36
|
+
* 1. `AI_MODEL_<FUNCTION_NAME>` env var (per-function override)
|
|
37
|
+
* 2. `AI_TIER_<TIER>` env var (per-tier override)
|
|
38
|
+
* 3. `AI_TIERS.<TIER>.defaultModel` (static SSOT from constants)
|
|
39
|
+
*
|
|
40
|
+
* @param tier - The tier ID ('fast', 'standard', 'premium')
|
|
41
|
+
* @param functionName - Optional function name for per-function env var lookup
|
|
42
|
+
* @returns The resolved model ID string
|
|
43
|
+
*/
|
|
44
|
+
export function resolveModelForTier(tier: AITierId, functionName?: string): string {
|
|
45
|
+
// 1. Per-function env var: AI_MODEL_BRAINSTORM, AI_MODEL_SPEC_CHAT, etc.
|
|
46
|
+
if (functionName) {
|
|
47
|
+
const perFn = getEnv(`AI_MODEL_${functionName.toUpperCase()}`);
|
|
48
|
+
if (perFn) return perFn;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// 2. Per-tier env var: AI_TIER_FAST, AI_TIER_STANDARD, AI_TIER_PREMIUM
|
|
52
|
+
const perTier = getEnv(`AI_TIER_${tier.toUpperCase()}`);
|
|
53
|
+
if (perTier) return perTier;
|
|
54
|
+
|
|
55
|
+
// 3. Static SSOT
|
|
56
|
+
const tierConfig = Object.values(AI_TIERS).find(t => t.id === tier);
|
|
57
|
+
return tierConfig?.defaultModel ?? AI_TIERS.STANDARD.defaultModel;
|
|
58
|
+
}
|