/ src / lib / server / ollama-runtime.ts
ollama-runtime.ts
 1  import { stripOllamaCloudModelSuffix } from '@/lib/ollama-model'
 2  import { isOllamaCloudEndpoint, normalizeOllamaCloudEndpoint, resolveStoredOllamaMode } from '@/lib/ollama-mode'
 3  import { PROVIDER_DEFAULTS } from '@/lib/providers/provider-defaults'
 4  
 5  const OLLAMA_CLOUD_KEY_ENV_VARS = ['OLLAMA_API_KEY', 'OLLAMA_CLOUD_API_KEY'] as const
 6  
 7  function clean(value: string | null | undefined): string | null {
 8    if (typeof value !== 'string') return null
 9    const trimmed = value.trim()
10    return trimmed || null
11  }
12  
13  export function resolveOllamaCloudApiKey(explicitApiKey?: string | null): string | null {
14    const explicit = clean(explicitApiKey)
15    if (explicit && explicit !== 'ollama') return explicit
16    for (const envName of OLLAMA_CLOUD_KEY_ENV_VARS) {
17      const candidate = clean(process.env[envName])
18      if (candidate) return candidate
19    }
20    return null
21  }
22  
23  export function resolveOllamaRuntimeConfig(input: {
24    model?: string | null
25    ollamaMode?: string | null
26    apiKey?: string | null
27    apiEndpoint?: string | null
28  }): {
29    model: string
30    useCloud: boolean
31    apiKey: string | null
32    endpoint: string
33  } {
34    const rawModel = clean(input.model) || ''
35    const explicitApiKey = clean(input.apiKey)
36    const explicitEndpoint = clean(input.apiEndpoint)
37    const ollamaMode = resolveStoredOllamaMode({
38      ollamaMode: input.ollamaMode ?? null,
39      apiEndpoint: explicitEndpoint,
40    })
41    const cloudApiKey = resolveOllamaCloudApiKey(explicitApiKey)
42    const useCloud = ollamaMode === 'cloud'
43    const endpoint = useCloud
44      ? normalizeOllamaCloudEndpoint(isOllamaCloudEndpoint(explicitEndpoint) ? explicitEndpoint! : PROVIDER_DEFAULTS.ollamaCloud)
45      : (explicitEndpoint && !isOllamaCloudEndpoint(explicitEndpoint) ? explicitEndpoint : PROVIDER_DEFAULTS.ollama)
46  
47    return {
48      model: useCloud ? (stripOllamaCloudModelSuffix(rawModel) || rawModel) : rawModel,
49      useCloud,
50      apiKey: useCloud ? cloudApiKey : null,
51      endpoint,
52    }
53  }