File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -2,11 +2,11 @@ import { Agent } from 'undici'
22
33import { PROFIT_MARGIN } from '@codebuff/common/constants/limits'
44import { getErrorObject } from '@codebuff/common/util/error'
5- import { env } from '@codebuff/internal/env'
65
76import {
87 consumeCreditsForMessage ,
98 extractRequestMetadata ,
9+ getProviderApiKey ,
1010 insertMessageToBigQuery ,
1111} from './helpers'
1212
@@ -83,14 +83,12 @@ function createAvianRequest(params: {
8383 avianBody . stream_options = { include_usage : true }
8484 }
8585
86- if ( ! env . AVIAN_API_KEY ) {
87- throw new Error ( 'AVIAN_API_KEY is not configured' )
88- }
86+ const apiKey = getProviderApiKey ( 'AVIAN_API_KEY' )
8987
9088 return fetch ( `${ AVIAN_BASE_URL } /chat/completions` , {
9189 method : 'POST' ,
9290 headers : {
93- Authorization : `Bearer ${ env . AVIAN_API_KEY } ` ,
91+ Authorization : `Bearer ${ apiKey } ` ,
9492 'Content-Type' : 'application/json' ,
9593 'x-session-affinity' : sessionId ,
9694 } ,
Original file line number Diff line number Diff line change @@ -6,12 +6,30 @@ import {
66 isFreeModeAllowedAgentModel ,
77} from '@codebuff/common/constants/free-agents'
88import { PROFIT_MARGIN } from '@codebuff/common/old-constants'
9+ import { env } from '@codebuff/internal/env'
910
11+ import type { ServerEnv } from '@codebuff/internal/env-schema'
1012import type { InsertMessageBigqueryFn } from '@codebuff/common/types/contracts/bigquery'
1113import type { Logger } from '@codebuff/common/types/contracts/logger'
1214
1315import type { ChatCompletionRequestBody } from './types'
1416
17+ /** Known provider API key names in the env schema. */
18+ type ProviderApiKeyName = Extract < keyof ServerEnv , `${string } _API_KEY`>
19+
20+ /**
21+ * Retrieve a provider API key from the validated env, throwing a clear error
22+ * if the key is missing or empty. Centralises the "is it configured?" check
23+ * so individual provider modules don't need to guard against undefined.
24+ */
25+ export function getProviderApiKey ( name : ProviderApiKeyName ) : string {
26+ const value = env [ name ]
27+ if ( ! value ) {
28+ throw new Error ( `${ name } is not configured` )
29+ }
30+ return value
31+ }
32+
1533export type UsageData = {
1634 inputTokens : number
1735 outputTokens : number
You can’t perform that action at this time.
0 commit comments