2023-05-31 16:10:53 +08:00
|
|
|
// src/apiKey.ts
|
|
|
|
|
|
|
|
import { UiUtilWrapper } from './uiUtil';
|
|
|
|
|
|
|
|
export class ApiKeyManager {
|
2023-08-03 15:09:34 +08:00
|
|
|
static async getApiKey(llmType: string = "OpenAI"): Promise<string | undefined> {
|
|
|
|
let apiKey: string|undefined = undefined;
|
|
|
|
|
|
|
|
if (llmType === "OpenAI") {
|
|
|
|
apiKey = await UiUtilWrapper.secretStorageGet("openai_OPENAI_API_KEY");
|
|
|
|
}
|
2023-05-31 16:10:53 +08:00
|
|
|
if (!apiKey) {
|
2023-08-03 15:09:34 +08:00
|
|
|
apiKey = await UiUtilWrapper.secretStorageGet("devchat_OPENAI_API_KEY");
|
2023-05-31 16:10:53 +08:00
|
|
|
}
|
2023-08-03 15:09:34 +08:00
|
|
|
|
2023-05-31 16:10:53 +08:00
|
|
|
if (!apiKey) {
|
2023-08-03 15:09:34 +08:00
|
|
|
if (llmType === "OpenAI") {
|
|
|
|
apiKey = UiUtilWrapper.getConfiguration('DevChat', 'Api_Key_OpenAI');
|
|
|
|
}
|
|
|
|
if (!apiKey) {
|
|
|
|
apiKey = UiUtilWrapper.getConfiguration('DevChat', 'Access_Key_DevChat');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!apiKey) {
|
|
|
|
if (llmType === "OpenAI") {
|
|
|
|
apiKey = process.env.OPENAI_API_KEY;
|
|
|
|
}
|
2023-05-31 16:10:53 +08:00
|
|
|
}
|
|
|
|
return apiKey;
|
|
|
|
}
|
|
|
|
|
|
|
|
static getKeyType(apiKey: string): string | undefined {
|
2023-08-03 10:58:18 +08:00
|
|
|
if (apiKey.startsWith("sk-")) {
|
2023-05-31 16:10:53 +08:00
|
|
|
return "sk";
|
|
|
|
} else if (apiKey.startsWith("DC.")) {
|
|
|
|
return "DC";
|
|
|
|
} else {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-03 15:09:34 +08:00
|
|
|
static async writeApiKeySecret(apiKey: string, llmType: string = "Unknow"): Promise<void> {
|
|
|
|
if (apiKey.startsWith("sk-")) {
|
|
|
|
await UiUtilWrapper.storeSecret("openai_OPENAI_API_KEY", apiKey);
|
|
|
|
} else if (apiKey.startsWith("DC.")) {
|
|
|
|
await UiUtilWrapper.storeSecret("devchat_OPENAI_API_KEY", apiKey);
|
|
|
|
} else {
|
|
|
|
if (llmType === "OpenAI") {
|
|
|
|
await UiUtilWrapper.storeSecret("openai_OPENAI_API_KEY", apiKey);
|
|
|
|
} else if (llmType === "DevChat") {
|
|
|
|
await UiUtilWrapper.storeSecret("devchat_OPENAI_API_KEY", apiKey);
|
|
|
|
}
|
|
|
|
}
|
2023-05-31 16:10:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
static getEndPoint(apiKey: string | undefined): string | undefined {
|
|
|
|
let endPoint = UiUtilWrapper.getConfiguration('DevChat', 'API_ENDPOINT');
|
|
|
|
if (!endPoint) {
|
|
|
|
endPoint = process.env.OPENAI_API_BASE;
|
|
|
|
}
|
|
|
|
if (!endPoint && apiKey?.startsWith("DC.")) {
|
2023-06-06 18:47:22 +08:00
|
|
|
endPoint = "https://api.devchat.ai/v1";
|
2023-05-31 16:10:53 +08:00
|
|
|
}
|
|
|
|
return endPoint;
|
|
|
|
}
|
|
|
|
}
|