Skip to content

Commit 75e8943

Browse files
committed
Use getProviderApiKey helper for API key access
1 parent 4023f53 commit 75e8943

2 files changed

Lines changed: 21 additions & 5 deletions

File tree

web/src/llm-api/avian.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ import { Agent } from 'undici'
22

33
import { PROFIT_MARGIN } from '@codebuff/common/constants/limits'
44
import { getErrorObject } from '@codebuff/common/util/error'
5-
import { env } from '@codebuff/internal/env'
65

76
import {
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
},

web/src/llm-api/helpers.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,30 @@ import {
66
isFreeModeAllowedAgentModel,
77
} from '@codebuff/common/constants/free-agents'
88
import { PROFIT_MARGIN } from '@codebuff/common/old-constants'
9+
import { env } from '@codebuff/internal/env'
910

11+
import type { ServerEnv } from '@codebuff/internal/env-schema'
1012
import type { InsertMessageBigqueryFn } from '@codebuff/common/types/contracts/bigquery'
1113
import type { Logger } from '@codebuff/common/types/contracts/logger'
1214

1315
import 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+
1533
export type UsageData = {
1634
inputTokens: number
1735
outputTokens: number

0 commit comments

Comments
 (0)