generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 223
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support certain providers to customize the base URL. #818
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,6 @@ | ||
import { CustomModel, LangChainParams, ModelConfig } from "@/aiParams"; | ||
import { BUILTIN_CHAT_MODELS, ChatModelProviders } from "@/constants"; | ||
import EncryptionService from "@/encryptionService"; | ||
import { ChatAnthropicWrapped, ProxyChatOpenAI } from "@/langchainWrappers"; | ||
import { HarmBlockThreshold, HarmCategory } from "@google/generative-ai"; | ||
import { ChatCohere } from "@langchain/cohere"; | ||
import { BaseChatModel } from "@langchain/core/language_models/chat_models"; | ||
|
@@ -10,6 +9,35 @@ import { ChatGroq } from "@langchain/groq"; | |
import { ChatOllama } from "@langchain/ollama"; | ||
import { ChatOpenAI } from "@langchain/openai"; | ||
import { Notice } from "obsidian"; | ||
import { omit, safeFetch } from "@/utils"; | ||
import { ChatAnthropic } from "@langchain/anthropic"; | ||
|
||
type ChatConstructorType = new (config: any) => BaseChatModel; | ||
|
||
// Keep the original ProviderConstructMap type | ||
type ChatProviderConstructMap = { | ||
[K in ChatModelProviders]: K extends ChatModelProviders.OPENAI | ||
? typeof ChatOpenAI | ||
: K extends ChatModelProviders.AZURE_OPENAI | ||
? typeof ChatOpenAI | ||
: K extends ChatModelProviders.ANTHROPIC | ||
? typeof ChatAnthropic | ||
: K extends ChatModelProviders.COHEREAI | ||
? typeof ChatCohere | ||
: K extends ChatModelProviders.GOOGLE | ||
? typeof ChatGoogleGenerativeAI | ||
: K extends ChatModelProviders.OPENROUTERAI | ||
? typeof ChatOpenAI | ||
: K extends ChatModelProviders.OLLAMA | ||
? typeof ChatOllama | ||
: K extends ChatModelProviders.LM_STUDIO | ||
? typeof ChatOpenAI | ||
: K extends ChatModelProviders.GROQ | ||
? typeof ChatGroq | ||
: K extends ChatModelProviders.OPENAI_FORMAT | ||
? typeof ChatOpenAI | ||
: never; | ||
}; | ||
|
||
export default class ChatModelManager { | ||
private encryptionService: EncryptionService; | ||
|
@@ -20,12 +48,38 @@ export default class ChatModelManager { | |
string, | ||
{ | ||
hasApiKey: boolean; | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
AIConstructor: new (config: any) => BaseChatModel; | ||
AIConstructor: ChatConstructorType; | ||
vendor: string; | ||
} | ||
>; | ||
|
||
// Use both ProviderConstructMap and restrict keys to ChatModelProviders | ||
private readonly chatModelProvider2Construct: ChatProviderConstructMap = { | ||
[ChatModelProviders.OPENAI]: ChatOpenAI, | ||
[ChatModelProviders.AZURE_OPENAI]: ChatOpenAI, | ||
[ChatModelProviders.ANTHROPIC]: ChatAnthropic, | ||
[ChatModelProviders.COHEREAI]: ChatCohere, | ||
[ChatModelProviders.GOOGLE]: ChatGoogleGenerativeAI, | ||
[ChatModelProviders.OPENROUTERAI]: ChatOpenAI, | ||
[ChatModelProviders.OLLAMA]: ChatOllama, | ||
[ChatModelProviders.LM_STUDIO]: ChatOpenAI, | ||
[ChatModelProviders.GROQ]: ChatGroq, | ||
[ChatModelProviders.OPENAI_FORMAT]: ChatOpenAI, | ||
}; | ||
|
||
private readonly providerApiKeyMap: Record<ChatModelProviders, () => string> = { | ||
[ChatModelProviders.OPENAI]: () => this.getLangChainParams().openAIApiKey, | ||
[ChatModelProviders.GOOGLE]: () => this.getLangChainParams().googleApiKey, | ||
[ChatModelProviders.AZURE_OPENAI]: () => this.getLangChainParams().azureOpenAIApiKey, | ||
[ChatModelProviders.ANTHROPIC]: () => this.getLangChainParams().anthropicApiKey, | ||
[ChatModelProviders.COHEREAI]: () => this.getLangChainParams().cohereApiKey, | ||
[ChatModelProviders.OPENROUTERAI]: () => this.getLangChainParams().openRouterAiApiKey, | ||
[ChatModelProviders.GROQ]: () => this.getLangChainParams().groqApiKey, | ||
[ChatModelProviders.OLLAMA]: () => "default-key", | ||
[ChatModelProviders.LM_STUDIO]: () => "default-key", | ||
[ChatModelProviders.OPENAI_FORMAT]: () => "default-key", | ||
} as const; | ||
|
||
private constructor( | ||
private getLangChainParams: () => LangChainParams, | ||
encryptionService: EncryptionService, | ||
|
@@ -53,40 +107,69 @@ export default class ChatModelManager { | |
private getModelConfig(customModel: CustomModel): ModelConfig { | ||
const decrypt = (key: string) => this.encryptionService.getDecryptedKey(key); | ||
const params = this.getLangChainParams(); | ||
|
||
// Check if the model starts with "o1" | ||
const modelName = customModel.name; | ||
const isO1Model = modelName.startsWith("o1"); | ||
|
||
const baseConfig: ModelConfig = { | ||
modelName: customModel.name, | ||
temperature: params.temperature, | ||
streaming: true, | ||
modelName: modelName, | ||
temperature: isO1Model ? 1 : params.temperature, | ||
streaming: isO1Model ? false : true, | ||
maxRetries: 3, | ||
maxConcurrency: 3, | ||
enableCors: customModel.enableCors, | ||
}; | ||
|
||
const providerConfig = { | ||
type ProviderConstructMap = typeof ChatModelManager.prototype.chatModelProvider2Construct; | ||
const providerConfig: { | ||
[K in keyof ProviderConstructMap]: ConstructorParameters< | ||
ProviderConstructMap[K] | ||
>[0] /*& Record<string, unknown>;*/; | ||
} = { | ||
[ChatModelProviders.OPENAI]: { | ||
modelName: customModel.name, | ||
modelName: modelName, | ||
openAIApiKey: decrypt(customModel.apiKey || params.openAIApiKey), | ||
configuration: { | ||
baseURL: customModel.baseUrl, | ||
fetch: customModel.enableCors ? safeFetch : undefined, | ||
}, | ||
maxTokens: isO1Model ? undefined : params.maxTokens, | ||
// @ts-ignore | ||
maxCompletionTokens: isO1Model ? params.maxTokens : undefined, | ||
// @ts-ignore | ||
openAIOrgId: decrypt(params.openAIOrgId), | ||
maxTokens: params.maxTokens, | ||
}, | ||
[ChatModelProviders.ANTHROPIC]: { | ||
anthropicApiKey: decrypt(customModel.apiKey || params.anthropicApiKey), | ||
modelName: customModel.name, | ||
modelName: modelName, | ||
anthropicApiUrl: customModel.baseUrl, | ||
clientOptions: { | ||
// Required to bypass CORS restrictions | ||
defaultHeaders: { "anthropic-dangerous-direct-browser-access": "true" }, | ||
fetch: customModel.enableCors ? safeFetch : undefined, | ||
}, | ||
}, | ||
[ChatModelProviders.AZURE_OPENAI]: { | ||
maxTokens: params.maxTokens, | ||
azureOpenAIApiKey: decrypt(customModel.apiKey || params.azureOpenAIApiKey), | ||
azureOpenAIApiInstanceName: params.azureOpenAIApiInstanceName, | ||
azureOpenAIApiDeploymentName: params.azureOpenAIApiDeploymentName, | ||
azureOpenAIApiVersion: params.azureOpenAIApiVersion, | ||
configuration: { | ||
baseURL: customModel.baseUrl, | ||
fetch: customModel.enableCors ? safeFetch : undefined, | ||
}, | ||
maxTokens: isO1Model ? undefined : params.maxTokens, | ||
// @ts-ignore | ||
maxCompletionTokens: isO1Model ? params.maxTokens : undefined, | ||
}, | ||
[ChatModelProviders.COHEREAI]: { | ||
apiKey: decrypt(customModel.apiKey || params.cohereApiKey), | ||
model: customModel.name, | ||
model: modelName, | ||
}, | ||
[ChatModelProviders.GOOGLE]: { | ||
apiKey: decrypt(customModel.apiKey || params.googleApiKey), | ||
modelName: customModel.name, | ||
model: modelName, | ||
safetySettings: [ | ||
{ | ||
category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, | ||
|
@@ -105,33 +188,47 @@ export default class ChatModelManager { | |
threshold: HarmBlockThreshold.BLOCK_NONE, | ||
}, | ||
], | ||
baseUrl: customModel.baseUrl, | ||
}, | ||
[ChatModelProviders.OPENROUTERAI]: { | ||
modelName: customModel.name, | ||
modelName: modelName, | ||
openAIApiKey: decrypt(customModel.apiKey || params.openRouterAiApiKey), | ||
openAIProxyBaseUrl: "https://openrouter.ai/api/v1", | ||
configuration: { | ||
baseURL: customModel.baseUrl || "https://openrouter.ai/api/v1", | ||
fetch: customModel.enableCors ? safeFetch : undefined, | ||
}, | ||
}, | ||
[ChatModelProviders.GROQ]: { | ||
apiKey: decrypt(customModel.apiKey || params.groqApiKey), | ||
modelName: customModel.name, | ||
modelName: modelName, | ||
}, | ||
[ChatModelProviders.OLLAMA]: { | ||
// ChatOllama has `model` instead of `modelName`!! | ||
model: customModel.name, | ||
apiKey: customModel.apiKey || "default-key", | ||
model: modelName, | ||
// MUST NOT use /v1 in the baseUrl for ollama | ||
baseUrl: customModel.baseUrl || "http://localhost:11434", | ||
// @ts-ignore | ||
apiKey: customModel.apiKey || "default-key", | ||
}, | ||
[ChatModelProviders.LM_STUDIO]: { | ||
modelName: customModel.name, | ||
modelName: modelName, | ||
openAIApiKey: customModel.apiKey || "default-key", | ||
openAIProxyBaseUrl: customModel.baseUrl || "http://localhost:1234/v1", | ||
configuration: { | ||
baseURL: customModel.baseUrl || "http://localhost:1234/v1", | ||
fetch: customModel.enableCors ? safeFetch : undefined, | ||
}, | ||
}, | ||
[ChatModelProviders.OPENAI_FORMAT]: { | ||
modelName: customModel.name, | ||
modelName: modelName, | ||
openAIApiKey: decrypt(customModel.apiKey || "default-key"), | ||
maxTokens: params.maxTokens, | ||
openAIProxyBaseUrl: customModel.baseUrl || "", | ||
configuration: { | ||
baseURL: customModel.baseUrl, | ||
fetch: customModel.enableCors ? safeFetch : undefined, | ||
dangerouslyAllowBrowser: true, | ||
}, | ||
maxTokens: isO1Model ? undefined : params.maxTokens, | ||
// @ts-ignore | ||
maxCompletionTokens: isO1Model ? params.maxTokens : undefined, | ||
}, | ||
}; | ||
|
||
|
@@ -150,66 +247,35 @@ export default class ChatModelManager { | |
|
||
allModels.forEach((model) => { | ||
if (model.enabled) { | ||
let constructor; | ||
let apiKey; | ||
|
||
switch (model.provider) { | ||
case ChatModelProviders.OPENAI: | ||
constructor = ChatOpenAI; | ||
apiKey = model.apiKey || this.getLangChainParams().openAIApiKey; | ||
break; | ||
case ChatModelProviders.GOOGLE: | ||
constructor = ChatGoogleGenerativeAI; | ||
apiKey = model.apiKey || this.getLangChainParams().googleApiKey; | ||
break; | ||
case ChatModelProviders.AZURE_OPENAI: | ||
constructor = ChatOpenAI; | ||
apiKey = model.apiKey || this.getLangChainParams().azureOpenAIApiKey; | ||
break; | ||
case ChatModelProviders.ANTHROPIC: | ||
constructor = ChatAnthropicWrapped; | ||
apiKey = model.apiKey || this.getLangChainParams().anthropicApiKey; | ||
break; | ||
case ChatModelProviders.COHEREAI: | ||
constructor = ChatCohere; | ||
apiKey = model.apiKey || this.getLangChainParams().cohereApiKey; | ||
break; | ||
case ChatModelProviders.OPENROUTERAI: | ||
constructor = ProxyChatOpenAI; | ||
apiKey = model.apiKey || this.getLangChainParams().openRouterAiApiKey; | ||
break; | ||
case ChatModelProviders.OLLAMA: | ||
constructor = ChatOllama; | ||
apiKey = model.apiKey || "default-key"; | ||
break; | ||
case ChatModelProviders.LM_STUDIO: | ||
constructor = ProxyChatOpenAI; | ||
apiKey = model.apiKey || "default-key"; | ||
break; | ||
case ChatModelProviders.GROQ: | ||
constructor = ChatGroq; | ||
apiKey = model.apiKey || this.getLangChainParams().groqApiKey; | ||
break; | ||
case ChatModelProviders.OPENAI_FORMAT: | ||
constructor = ProxyChatOpenAI; | ||
apiKey = model.apiKey || "default-key"; | ||
break; | ||
default: | ||
console.warn(`Unknown provider: ${model.provider} for model: ${model.name}`); | ||
return; | ||
if (!Object.values(ChatModelProviders).contains(model.provider as ChatModelProviders)) { | ||
console.warn(`Unknown provider: ${model.provider} for model: ${model.name}`); | ||
return; | ||
} | ||
|
||
const constructor = this.getProviderConstructor(model); | ||
const getDefaultApiKey = this.providerApiKeyMap[model.provider as ChatModelProviders]; | ||
|
||
const apiKey = model.apiKey || getDefaultApiKey(); | ||
const modelKey = `${model.name}|${model.provider}`; | ||
modelMap[modelKey] = { | ||
hasApiKey: Boolean(model.apiKey || apiKey), | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
AIConstructor: constructor as any, | ||
AIConstructor: constructor, | ||
vendor: model.provider, | ||
}; | ||
} | ||
}); | ||
} | ||
|
||
getProviderConstructor(model: CustomModel): ChatConstructorType { | ||
const constructor: ChatConstructorType = | ||
this.chatModelProvider2Construct[model.provider as ChatModelProviders]; | ||
if (!constructor) { | ||
console.warn(`Unknown provider: ${model.provider} for model: ${model.name}`); | ||
throw new Error(`Unknown provider: ${model.provider} for model: ${model.name}`); | ||
} | ||
return constructor; | ||
} | ||
|
||
getChatModel(): BaseChatModel { | ||
return ChatModelManager.chatModel; | ||
} | ||
|
@@ -232,7 +298,7 @@ export default class ChatModelManager { | |
const modelConfig = this.getModelConfig(model); | ||
|
||
// MUST update it since chatModelManager is a singleton. | ||
this.getLangChainParams().modelKey = `${model.name}|${model.provider}`; | ||
this.getLangChainParams().modelKey = modelKey; | ||
new Notice(`Setting model: ${modelConfig.modelName}`); | ||
try { | ||
const newModelInstance = new selectedModel.AIConstructor({ | ||
|
@@ -256,4 +322,19 @@ export default class ChatModelManager { | |
async countTokens(inputStr: string): Promise<number> { | ||
return ChatModelManager.chatModel.getNumTokens(inputStr); | ||
} | ||
|
||
async ping(model: CustomModel): Promise<"PONG"> { | ||
model.enableCors = true; // enable CORS for verification | ||
// remove streaming、temperature ...... property | ||
const modelConfig = omit(this.getModelConfig(model), ["streaming", "temperature", "maxTokens"]); | ||
|
||
const aIConstructor = this.getProviderConstructor(model); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
const newModelInstance = new aIConstructor({ | ||
...modelConfig, | ||
}); | ||
|
||
return newModelInstance.invoke("Testing. Just say PONG and nothing else.").then((chunk) => { | ||
return "PONG"; | ||
}); | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What's this, looks scary 🥶
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not just
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@logancyang yeah, It's for type Hints.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if
ChatModelProviders
add new provider,CHAT_PROVIDER_CONSTRUCTORS
don't get any type restriction error. Maybe It's so heavy.