fix(llm): add runtime UA headers for openai-compatible requests

This commit is contained in:
digua
2026-04-14 22:52:51 +08:00
committed by digua
parent 65923982ac
commit 726396733a
2 changed files with 30 additions and 0 deletions
+2
View File
@@ -11,6 +11,7 @@ import type { LLMProvider, ProviderInfo, AIServiceConfig, AIConfigStore } from '
import { MAX_CONFIG_COUNT } from './types'
import { aiLogger } from '../logger'
import { encryptApiKey, decryptApiKey, isEncrypted } from './crypto'
import { buildChatLabUserAgentHeaders } from '../../utils/httpHeaders'
import { t } from '../../i18n'
import { completeSimple, type Model as PiModel } from '@mariozechner/pi-ai'
@@ -452,6 +453,7 @@ export function buildPiModel(config: AIServiceConfig): PiModel<'openai-completio
api: 'openai-completions',
provider: config.provider,
baseUrl,
headers: config.provider === 'openai-compatible' ? buildChatLabUserAgentHeaders() : undefined,
reasoning: config.isReasoningModel ?? false,
input: ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+28
View File
@@ -0,0 +1,28 @@
import { app, session } from 'electron'
export function buildChatLabUserAgentHeaders(): Record<string, string> {
const chatLabVersion = (() => {
try {
return app.getVersion() || 'dev'
} catch {
return 'dev'
}
})()
const chatLabTag = `ChatLab/${chatLabVersion}`
const runtimeUA = (() => {
try {
return session.defaultSession.getUserAgent()
} catch {
// 默认会话未就绪时使用 Electron 级别回退 UA
return app.userAgentFallback || ''
}
})()
const userAgent = runtimeUA.includes(chatLabTag) ? runtimeUA : `${runtimeUA} ${chatLabTag}`.trim()
return {
// 使用运行时真实 UA,并附加 ChatLab 版本标识,避免网关按 UA 策略拦截。
'User-Agent': userAgent,
'X-ChatLab-Client': chatLabTag,
}
}