11import { LLMProvider } from './llm.interface' ;
22import { OllamaProvider } from './ollama.provider' ;
33import { OpenAICompatProvider } from './openai-compat.provider' ;
4- import { getDefaultOpenAICompatBaseUrl } from '../../modules/system/llm-provider-registry' ;
4+ import {
5+ getDefaultOpenAICompatBaseUrl ,
6+ getEnvBackedApiKey ,
7+ getEnvBackedBaseUrl ,
8+ } from '../../modules/system/llm-provider-registry' ;
9+
10+ /** 去掉用户误填的「Bearer 」前缀,避免 Authorization 变成 Bearer Bearer … */
11+ function normalizeBearerApiKey ( raw : string ) : string {
12+ const t = raw . trim ( ) ;
13+ if ( ! t ) return '' ;
14+ return t . replace ( / ^ B e a r e r \s + / i, '' ) . trim ( ) ;
15+ }
16+
17+ function resolveOpenAICompatApiKey ( provider : string , explicit ?: string ) : string {
18+ const candidates = [
19+ normalizeBearerApiKey ( explicit ?? '' ) ,
20+ normalizeBearerApiKey ( process . env . LLM_API_KEY ?? '' ) ,
21+ normalizeBearerApiKey ( getEnvBackedApiKey ( provider ) ) ,
22+ ] ;
23+ return candidates . find ( ( k ) => k . length > 0 ) ?? '' ;
24+ }
25+
26+ function resolveOpenAICompatBaseUrl ( provider : string , explicit ?: string ) : string | undefined {
27+ const candidates = [
28+ ( explicit ?? '' ) . trim ( ) ,
29+ ( process . env . LLM_BASE_URL ?? '' ) . trim ( ) ,
30+ getEnvBackedBaseUrl ( provider ) ,
31+ ] ;
32+ const first = candidates . find ( ( u ) => u . length > 0 ) ;
33+ return first ;
34+ }
535
636export interface LLMConfig {
737 provider : string ;
@@ -21,11 +51,17 @@ export function createLLM(config: LLMConfig): LLMProvider {
2151 }
2252
2353 const baseUrl =
24- config . baseUrl ??
54+ resolveOpenAICompatBaseUrl ( provider , config . baseUrl ) ??
2555 getDefaultOpenAICompatBaseUrl ( provider ) ??
2656 ( provider === 'deepseek' ? 'https://api.deepseek.com' : 'https://api.openai.com' ) ;
27- const model = config . model ?? ( provider === 'deepseek' ? 'deepseek-chat' : 'gpt-4o-mini' ) ;
28- const apiKey = config . apiKey ?? '' ;
57+ const modelFromEnv =
58+ ( process . env . LLM_MODEL ?? '' ) . trim ( ) ||
59+ ( provider === 'deepseek' ? ( process . env . DEEPSEEK_MODEL ?? '' ) . trim ( ) : '' ) ;
60+ const model =
61+ ( config . model ?? '' ) . trim ( ) ||
62+ modelFromEnv ||
63+ ( provider === 'deepseek' ? 'deepseek-chat' : 'gpt-4o-mini' ) ;
64+ const apiKey = resolveOpenAICompatApiKey ( provider , config . apiKey ) ;
2965
3066 return new OpenAICompatProvider ( baseUrl , apiKey , model ) ;
3167}
0 commit comments