-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathlocal-inference-providers.ts
More file actions
258 lines (230 loc) · 7.01 KB
/
Copy pathlocal-inference-providers.ts
File metadata and controls
258 lines (230 loc) · 7.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import { getSQLit, type SQLitClient } from '@jejunetwork/db'
import { decryptAesGcm } from '@jejunetwork/shared'
import { keccak256, toBytes } from 'viem'
import { getConfiguredProviders, type APIProvider } from '../api-marketplace'
import { PROVIDERS_BY_ID } from '../api-marketplace/providers'
import { z } from 'zod'
import {
getModelHintsForProvider,
inferenceNodes,
registerNode,
updateNodeHeartbeat,
} from './inference-node'
const LOCAL_PROVIDER_PREFIX = 'local-provider:'
const HEARTBEAT_INTERVAL_MS = 30000
const SERVICE_ID = 'dws'
const SQLIT_DATABASE_ID = process.env.SQLIT_DATABASE_ID ?? 'dws-core'
const OPENAI_COMPATIBLE_PROVIDERS = [
'openai',
'groq',
'together',
'openrouter',
'fireworks',
'mistral',
'deepseek',
'cerebras',
'perplexity',
'sambanova',
'ai21',
]
let providersInitialized = false
let heartbeatTimer: ReturnType<typeof setInterval> | null = null
const heartbeatAddresses: string[] = []
const providerKeyCache = new Map<string, string>()
const envVarToProviderId = new Map<string, string>(
Array.from(PROVIDERS_BY_ID.values()).map((provider) => [
provider.envVar,
provider.id,
]),
)
const VaultRevealSchema = z.object({
value: z.string(),
})
interface SecretRow {
id: string
encrypted_value: string
expires_at: number | null
}
let sqlitClient: SQLitClient | null = null
function isProviderSupported(provider: APIProvider): boolean {
if (provider.id === 'anthropic') return true
return OPENAI_COMPATIBLE_PROVIDERS.includes(provider.id)
}
export function getProviderKey(providerId: string): string | null {
const provider = PROVIDERS_BY_ID.get(providerId)
if (!provider) return null
const envValue = process.env[provider.envVar]
if (envValue) return envValue
return (
providerKeyCache.get(providerId) ??
providerKeyCache.get(provider.envVar) ??
null
)
}
export function hasProviderKey(providerId: string): boolean {
return getProviderKey(providerId) !== null
}
async function getSQLitClient(): Promise<SQLitClient> {
if (!sqlitClient) {
sqlitClient = getSQLit({
databaseId: SQLIT_DATABASE_ID,
timeoutMs: 30000,
debug: process.env.NODE_ENV !== 'production',
})
const healthy = await sqlitClient.isHealthy()
if (!healthy) {
throw new Error('[Inference] SQLit is required for vault secrets')
}
}
return sqlitClient
}
function getServiceOwner(serviceId: string): string {
const hash = keccak256(toBytes(serviceId))
return `0x${hash.slice(-40)}`.toLowerCase()
}
async function decryptVaultSecret(
id: string,
encryptedValue: string,
): Promise<string> {
const data = new Uint8Array(
atob(encryptedValue)
.split('')
.map((c) => c.charCodeAt(0)),
)
const iv = data.subarray(0, 12)
const authTag = data.subarray(12, 28)
const ciphertext = data.subarray(28)
const derivedKey = new Uint8Array(
Buffer.from(keccak256(toBytes(id)).slice(2), 'hex'),
)
const decryptedBytes = await decryptAesGcm(
ciphertext,
derivedKey,
iv,
authTag,
)
return new TextDecoder().decode(decryptedBytes)
}
async function fetchSecretByNameLocal(name: string): Promise<string | null> {
// Add a 2 second timeout to prevent hanging if SQLit is unavailable
const timeoutPromise = new Promise<null>((_, reject) =>
setTimeout(() => reject(new Error('SQLit query timeout')), 2000),
)
try {
return await Promise.race([
(async () => {
const client = await getSQLitClient()
const owner = getServiceOwner(SERVICE_ID)
const rows = await client.query<SecretRow>(
'SELECT id, encrypted_value, expires_at FROM kms_secrets WHERE name = ? AND owner = ? ORDER BY updated_at DESC LIMIT 1',
[name, owner],
SQLIT_DATABASE_ID,
)
const secret = rows.rows[0]
if (!secret) return null
if (secret.expires_at && secret.expires_at < Date.now()) return null
return decryptVaultSecret(secret.id, secret.encrypted_value)
})(),
timeoutPromise,
])
} catch {
return null
}
}
function buildNodeAddress(providerId: string): string {
return `${LOCAL_PROVIDER_PREFIX}${providerId}`
}
function normalizeBaseUrl(baseUrl: string): string {
if (baseUrl.endsWith('/')) {
return baseUrl.slice(0, -1)
}
return baseUrl
}
function startHeartbeats(): void {
if (heartbeatTimer !== null) return
heartbeatTimer = setInterval(() => {
for (const address of heartbeatAddresses) {
updateNodeHeartbeat(address, 0)
}
}, HEARTBEAT_INTERVAL_MS)
}
async function fetchSecretByName(
baseUrl: string,
name: string,
): Promise<string | null> {
try {
const localValue = await fetchSecretByNameLocal(name)
if (localValue) return localValue
} catch {
// Fall through to HTTP fetch
}
const url = new URL('/kms/vault/secrets/reveal', baseUrl)
const serviceToken =
process.env.KMS_SERVICE_TOKEN ??
process.env.DWS_KMS_SERVICE_TOKEN ??
process.env.SERVICE_AUTH_TOKEN
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-service-id': SERVICE_ID,
...(serviceToken ? { 'x-service-token': serviceToken } : {}),
},
body: JSON.stringify({ name }),
})
if (!response.ok) return null
const revealed = VaultRevealSchema.parse(await response.json())
return revealed.value
}
async function hydrateProviderEnvFromVault(baseUrl: string): Promise<number> {
let loaded = 0
for (const [envVar, providerId] of envVarToProviderId.entries()) {
if (process.env[envVar]) continue
const value = await fetchSecretByName(baseUrl, `dws:${envVar}`)
if (!value) continue
process.env[envVar] = value
providerKeyCache.set(envVar, value)
providerKeyCache.set(providerId, value)
loaded += 1
}
return loaded
}
export async function registerConfiguredInferenceProviders(
baseUrl: string,
): Promise<number> {
if (providersInitialized && heartbeatAddresses.length > 0) return 0
const normalizedBaseUrl = normalizeBaseUrl(baseUrl)
await hydrateProviderEnvFromVault(normalizedBaseUrl)
const configured = getConfiguredProviders()
let registeredCount = 0
for (const provider of configured) {
if (!provider.categories.includes('inference')) continue
if (!isProviderSupported(provider)) continue
if (!hasProviderKey(provider.id)) continue
const address = buildNodeAddress(provider.id)
const addressLower = address.toLowerCase()
if (!inferenceNodes.has(addressLower)) {
registerNode({
address,
name: provider.name,
endpoint: `${normalizedBaseUrl}/compute/providers/${provider.id}`,
capabilities: ['inference'],
models: getModelHintsForProvider(provider.id),
provider: provider.id,
region: 'local',
gpuTier: 0,
maxConcurrent: 20,
isActive: true,
})
registeredCount += 1
}
if (!heartbeatAddresses.includes(address)) {
heartbeatAddresses.push(address)
}
}
if (heartbeatAddresses.length > 0) {
startHeartbeats()
}
providersInitialized = true
return registeredCount
}