Skip to content
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
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions src/LLMProviders/chainManager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CustomModel, LangChainParams, SetChainOptions } from "@/aiParams";
import ChainFactory, { ChainType, Document } from "@/chainFactory";
import { BUILTIN_CHAT_MODELS, USER_SENDER } from "@/constants";
import { AI_SENDER, BUILTIN_CHAT_MODELS, USER_SENDER } from "@/constants";
import EncryptionService from "@/encryptionService";
import {
ChainRunner,
Expand Down Expand Up @@ -317,12 +317,26 @@ export default class ChainManager {
this.validateChatModel();
this.validateChainInitialization();

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const chatModel = (ChainManager.chain as any).last.bound;
const modelName = chatModel.modelName || chatModel.model;
const isO1Model = modelName.startsWith("o1");

// Handle ignoreSystemMessage
if (ignoreSystemMessage) {
const effectivePrompt = ChatPromptTemplate.fromMessages([
if (ignoreSystemMessage || isO1Model) {
let effectivePrompt = ChatPromptTemplate.fromMessages([
new MessagesPlaceholder("history"),
HumanMessagePromptTemplate.fromTemplate("{input}"),
]);

if (isO1Model) {
// Temporary fix:for o1-xx model need to covert systemMessage to aiMessage
effectivePrompt = ChatPromptTemplate.fromMessages([
[AI_SENDER, this.getLangChainParams().systemMessage || ""],
effectivePrompt,
]);
}

this.setChain(this.getLangChainParams().chainType, {
...this.getLangChainParams().options,
prompt: effectivePrompt,
Expand Down Expand Up @@ -351,4 +365,8 @@ export default class ChainManager {
}
}
}

async ping(type: "chat" | "embedding", model: CustomModel): Promise<"PONG"> {
return type === "chat" ? this.chatModelManager.ping(model) : this.embeddingsManager.ping(model);
}
}
227 changes: 154 additions & 73 deletions src/LLMProviders/chatModelManager.ts
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";
Expand All @@ -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 = {
Copy link
Owner

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 🥶

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just

const CHAT_PROVIDER_CONSTRUCTORS = {
  [ChatModelProviders.OPENAI]: ChatOpenAI,
  [ChatModelProviders.AZURE_OPENAI]: ChatOpenAI,
  // ... etc
} as const;

type ChatProviderConstructMap = typeof CHAT_PROVIDER_CONSTRUCTORS;

Copy link
Contributor Author

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.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just

const CHAT_PROVIDER_CONSTRUCTORS = {
  [ChatModelProviders.OPENAI]: ChatOpenAI,
  [ChatModelProviders.AZURE_OPENAI]: ChatOpenAI,
  // ... etc
} as const;

type ChatProviderConstructMap = typeof CHAT_PROVIDER_CONSTRUCTORS;

if ChatModelProviders add new provider, CHAT_PROVIDER_CONSTRUCTORS don't get any type restriction error. Maybe It's so heavy.

[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;
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
},
};

Expand All @@ -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;
}
Expand All @@ -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({
Expand All @@ -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);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

aIConstructor naming is weird.

const newModelInstance = new aIConstructor({
...modelConfig,
});

return newModelInstance.invoke("Testing. Just say PONG and nothing else.").then((chunk) => {
return "PONG";
});
}
}
Loading
Loading