cherry-studio/src/renderer/src/utils/api.ts
suyao a5e7aa1342
feat: Implement shared provider utilities and API host formatting
- Added provider API host formatting utilities to handle differences between Cherry Studio and AI SDK.
- Introduced functions for formatting provider API hosts, including support for Azure OpenAI and Vertex AI.
- Created a simple API key rotator for managing API key rotation.
- Developed shared provider initialization and mapping utilities for resolving provider IDs.
- Implemented AI SDK configuration utilities for converting Cherry Studio providers to AI SDK configurations.
- Added support for various providers including OpenRouter, Google Vertex AI, and Amazon Bedrock.
- Enhanced error handling and logging in the unified messages service for better debugging.
- Introduced functions for streaming and generating unified messages using AI SDK.
2025-11-27 15:30:19 +08:00

62 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

export {
formatApiHost,
formatAzureOpenAIApiHost,
formatVertexApiHost,
getAiSdkBaseUrl,
hasAPIVersion,
routeToEndpoint,
SUPPORTED_ENDPOINT_LIST,
SUPPORTED_IMAGE_ENDPOINT_LIST,
validateApiHost,
withoutTrailingSlash
} from '@shared/api'
/**
* 格式化 API key 字符串。
*
* @param {string} value - 需要格式化的 API key 字符串。
* @returns {string} 格式化后的 API key 字符串。
*/
export function formatApiKeys(value: string): string {
return value.replaceAll('', ',').replaceAll('\n', ',')
}
/**
* API key 脱敏函数。仅保留部分前后字符,中间用星号代替。
*
* - 长度大于 24保留前、后 8 位。
* - 长度大于 16保留前、后 4 位。
* - 长度大于 8保留前、后 2 位。
* - 其余情况,返回原始密钥。
*
* @param {string} key - 需要脱敏的 API 密钥。
* @returns {string} 脱敏后的密钥字符串。
*/
export function maskApiKey(key: string): string {
if (!key) return ''
if (key.length > 24) {
return `${key.slice(0, 8)}****${key.slice(-8)}`
} else if (key.length > 16) {
return `${key.slice(0, 4)}****${key.slice(-4)}`
} else if (key.length > 8) {
return `${key.slice(0, 2)}****${key.slice(-2)}`
} else {
return key
}
}
/**
* 将 API key 字符串转换为 key 数组。
*
* @param {string} keyStr - 包含 API key 的逗号分隔字符串。
* @returns {string[]} 转换后的数组,每个元素为 API key。
*/
export function splitApiKeyString(keyStr: string): string[] {
return keyStr
.split(/(?<!\\),/)
.map((k) => k.trim())
.map((k) => k.replace(/\\,/g, ','))
.filter((k) => k)
}