fix: .env file baseUrl Issue

This commit is contained in:
Anirban Kar 2024-12-18 16:34:18 +05:30
parent fce8999f27
commit 62ebfe51a6
9 changed files with 149 additions and 43 deletions

View File

@ -1 +1 @@
{ "commit": "eb6d4353565be31c6e20bfca2c5aea29e4f45b6d", "version": "0.0.3" } { "commit": "fce8999f27c0affbc762dc90de992b5a759ab325" }

View File

@ -119,6 +119,9 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
useEffect(() => { useEffect(() => {
// Load API keys from cookies on component mount // Load API keys from cookies on component mount
let parsedApiKeys: Record<string, string> | undefined = {};
try { try {
const storedApiKeys = Cookies.get('apiKeys'); const storedApiKeys = Cookies.get('apiKeys');
@ -127,6 +130,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
if (typeof parsedKeys === 'object' && parsedKeys !== null) { if (typeof parsedKeys === 'object' && parsedKeys !== null) {
setApiKeys(parsedKeys); setApiKeys(parsedKeys);
parsedApiKeys = parsedKeys;
} }
} }
} catch (error) { } catch (error) {
@ -155,7 +159,7 @@ export const BaseChat = React.forwardRef<HTMLDivElement, BaseChatProps>(
Cookies.remove('providers'); Cookies.remove('providers');
} }
initializeModelList(providerSettings).then((modelList) => { initializeModelList({ apiKeys: parsedApiKeys, providerSettings }).then((modelList) => {
setModelList(modelList); setModelList(modelList);
}); });

View File

@ -87,7 +87,12 @@ export default function ProvidersTab() {
type="text" type="text"
value={provider.settings.baseUrl || ''} value={provider.settings.baseUrl || ''}
onChange={(e) => { onChange={(e) => {
const newBaseUrl = e.target.value; let newBaseUrl: string | undefined = e.target.value;
if (newBaseUrl && newBaseUrl.trim().length === 0) {
newBaseUrl = undefined;
}
updateProviderSettings(provider.name, { ...provider.settings, baseUrl: newBaseUrl }); updateProviderSettings(provider.name, { ...provider.settings, baseUrl: newBaseUrl });
logStore.logProvider(`Base URL updated for ${provider.name}`, { logStore.logProvider(`Base URL updated for ${provider.name}`, {
provider: provider.name, provider: provider.name,

View File

@ -14,7 +14,7 @@ export default async function handleRequest(
remixContext: EntryContext, remixContext: EntryContext,
_loadContext: AppLoadContext, _loadContext: AppLoadContext,
) { ) {
await initializeModelList(); await initializeModelList({});
const readable = await renderToReadableStream(<RemixServer context={remixContext} url={request.url} />, { const readable = await renderToReadableStream(<RemixServer context={remixContext} url={request.url} />, {
signal: request.signal, signal: request.signal,

View File

@ -3,6 +3,7 @@
* Preventing TS checks with files presented in the video for a better presentation. * Preventing TS checks with files presented in the video for a better presentation.
*/ */
import { env } from 'node:process'; import { env } from 'node:process';
import type { IProviderSetting } from '~/types/model';
export function getAPIKey(cloudflareEnv: Env, provider: string, userApiKeys?: Record<string, string>) { export function getAPIKey(cloudflareEnv: Env, provider: string, userApiKeys?: Record<string, string>) {
/** /**
@ -50,16 +51,30 @@ export function getAPIKey(cloudflareEnv: Env, provider: string, userApiKeys?: Re
} }
} }
export function getBaseURL(cloudflareEnv: Env, provider: string) { export function getBaseURL(cloudflareEnv: Env, provider: string, providerSettings?: Record<string, IProviderSetting>) {
let settingBaseUrl = providerSettings?.[provider].baseUrl;
if (settingBaseUrl && settingBaseUrl.length == 0) {
settingBaseUrl = undefined;
}
switch (provider) { switch (provider) {
case 'Together': case 'Together':
return env.TOGETHER_API_BASE_URL || cloudflareEnv.TOGETHER_API_BASE_URL || 'https://api.together.xyz/v1'; return (
settingBaseUrl ||
env.TOGETHER_API_BASE_URL ||
cloudflareEnv.TOGETHER_API_BASE_URL ||
'https://api.together.xyz/v1'
);
case 'OpenAILike': case 'OpenAILike':
return env.OPENAI_LIKE_API_BASE_URL || cloudflareEnv.OPENAI_LIKE_API_BASE_URL; return settingBaseUrl || env.OPENAI_LIKE_API_BASE_URL || cloudflareEnv.OPENAI_LIKE_API_BASE_URL;
case 'LMStudio': case 'LMStudio':
return env.LMSTUDIO_API_BASE_URL || cloudflareEnv.LMSTUDIO_API_BASE_URL || 'http://localhost:1234'; return (
settingBaseUrl || env.LMSTUDIO_API_BASE_URL || cloudflareEnv.LMSTUDIO_API_BASE_URL || 'http://localhost:1234'
);
case 'Ollama': { case 'Ollama': {
let baseUrl = env.OLLAMA_API_BASE_URL || cloudflareEnv.OLLAMA_API_BASE_URL || 'http://localhost:11434'; let baseUrl =
settingBaseUrl || env.OLLAMA_API_BASE_URL || cloudflareEnv.OLLAMA_API_BASE_URL || 'http://localhost:11434';
if (env.RUNNING_IN_DOCKER === 'true') { if (env.RUNNING_IN_DOCKER === 'true') {
baseUrl = baseUrl.replace('localhost', 'host.docker.internal'); baseUrl = baseUrl.replace('localhost', 'host.docker.internal');

View File

@ -84,6 +84,8 @@ export function getHuggingFaceModel(apiKey: OptionalApiKey, model: string) {
} }
export function getOllamaModel(baseURL: string, model: string) { export function getOllamaModel(baseURL: string, model: string) {
console.log({ baseURL, model });
const ollamaInstance = ollama(model, { const ollamaInstance = ollama(model, {
numCtx: DEFAULT_NUM_CTX, numCtx: DEFAULT_NUM_CTX,
}) as LanguageModelV1 & { config: any }; }) as LanguageModelV1 & { config: any };
@ -140,7 +142,7 @@ export function getPerplexityModel(apiKey: OptionalApiKey, model: string) {
export function getModel( export function getModel(
provider: string, provider: string,
model: string, model: string,
env: Env, serverEnv: Env,
apiKeys?: Record<string, string>, apiKeys?: Record<string, string>,
providerSettings?: Record<string, IProviderSetting>, providerSettings?: Record<string, IProviderSetting>,
) { ) {
@ -148,9 +150,12 @@ export function getModel(
* let apiKey; // Declare first * let apiKey; // Declare first
* let baseURL; * let baseURL;
*/ */
// console.log({provider,model});
const apiKey = getAPIKey(env, provider, apiKeys); // Then assign const apiKey = getAPIKey(serverEnv, provider, apiKeys); // Then assign
const baseURL = providerSettings?.[provider].baseUrl || getBaseURL(env, provider); const baseURL = getBaseURL(serverEnv, provider, providerSettings);
// console.log({apiKey,baseURL});
switch (provider) { switch (provider) {
case 'Anthropic': case 'Anthropic':

View File

@ -151,10 +151,13 @@ export async function streamText(props: {
providerSettings?: Record<string, IProviderSetting>; providerSettings?: Record<string, IProviderSetting>;
promptId?: string; promptId?: string;
}) { }) {
const { messages, env, options, apiKeys, files, providerSettings, promptId } = props; const { messages, env: serverEnv, options, apiKeys, files, providerSettings, promptId } = props;
// console.log({serverEnv});
let currentModel = DEFAULT_MODEL; let currentModel = DEFAULT_MODEL;
let currentProvider = DEFAULT_PROVIDER.name; let currentProvider = DEFAULT_PROVIDER.name;
const MODEL_LIST = await getModelList(apiKeys || {}, providerSettings); const MODEL_LIST = await getModelList({ apiKeys, providerSettings, serverEnv: serverEnv as any });
const processedMessages = messages.map((message) => { const processedMessages = messages.map((message) => {
if (message.role === 'user') { if (message.role === 'user') {
const { model, provider, content } = extractPropertiesFromMessage(message); const { model, provider, content } = extractPropertiesFromMessage(message);
@ -196,7 +199,7 @@ export async function streamText(props: {
} }
return _streamText({ return _streamText({
model: getModel(currentProvider, currentModel, env, apiKeys, providerSettings) as any, model: getModel(currentProvider, currentModel, serverEnv, apiKeys, providerSettings) as any,
system: systemPrompt, system: systemPrompt,
maxTokens: dynamicMaxTokens, maxTokens: dynamicMaxTokens,
messages: convertToCoreMessages(processedMessages as any), messages: convertToCoreMessages(processedMessages as any),

View File

@ -3,7 +3,11 @@ import type { ModelInfo } from '~/utils/types';
export type ProviderInfo = { export type ProviderInfo = {
staticModels: ModelInfo[]; staticModels: ModelInfo[];
name: string; name: string;
getDynamicModels?: (apiKeys?: Record<string, string>, providerSettings?: IProviderSetting) => Promise<ModelInfo[]>; getDynamicModels?: (
apiKeys?: Record<string, string>,
providerSettings?: IProviderSetting,
serverEnv?: Record<string, string>,
) => Promise<ModelInfo[]>;
getApiKeyLink?: string; getApiKeyLink?: string;
labelForGetApiKey?: string; labelForGetApiKey?: string;
icon?: string; icon?: string;

View File

@ -220,7 +220,6 @@ const PROVIDER_LIST: ProviderInfo[] = [
], ],
getApiKeyLink: 'https://huggingface.co/settings/tokens', getApiKeyLink: 'https://huggingface.co/settings/tokens',
}, },
{ {
name: 'OpenAI', name: 'OpenAI',
staticModels: [ staticModels: [
@ -325,26 +324,46 @@ const staticModels: ModelInfo[] = PROVIDER_LIST.map((p) => p.staticModels).flat(
export let MODEL_LIST: ModelInfo[] = [...staticModels]; export let MODEL_LIST: ModelInfo[] = [...staticModels];
export async function getModelList( export async function getModelList(options: {
apiKeys: Record<string, string>, apiKeys?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>, providerSettings?: Record<string, IProviderSetting>;
) { serverEnv?: Record<string, string>;
}) {
const { apiKeys, providerSettings, serverEnv } = options;
// console.log({ providerSettings, serverEnv,env:process.env });
MODEL_LIST = [ MODEL_LIST = [
...( ...(
await Promise.all( await Promise.all(
PROVIDER_LIST.filter( PROVIDER_LIST.filter(
(p): p is ProviderInfo & { getDynamicModels: () => Promise<ModelInfo[]> } => !!p.getDynamicModels, (p): p is ProviderInfo & { getDynamicModels: () => Promise<ModelInfo[]> } => !!p.getDynamicModels,
).map((p) => p.getDynamicModels(apiKeys, providerSettings?.[p.name])), ).map((p) => p.getDynamicModels(apiKeys, providerSettings?.[p.name], serverEnv)),
) )
).flat(), ).flat(),
...staticModels, ...staticModels,
]; ];
return MODEL_LIST; return MODEL_LIST;
} }
async function getTogetherModels(apiKeys?: Record<string, string>, settings?: IProviderSetting): Promise<ModelInfo[]> { async function getTogetherModels(
apiKeys?: Record<string, string>,
settings?: IProviderSetting,
serverEnv: Record<string, string> = {},
): Promise<ModelInfo[]> {
try { try {
const baseUrl = settings?.baseUrl || import.meta.env.TOGETHER_API_BASE_URL || ''; let settingsBaseUrl = settings?.baseUrl;
if (settingsBaseUrl && settingsBaseUrl.length == 0) {
settingsBaseUrl = undefined;
}
const baseUrl =
settingsBaseUrl ||
serverEnv?.TOGETHER_API_BASE_URL ||
process.env.TOGETHER_API_BASE_URL ||
import.meta.env.TOGETHER_API_BASE_URL ||
'';
const provider = 'Together'; const provider = 'Together';
if (!baseUrl) { if (!baseUrl) {
@ -383,8 +402,19 @@ async function getTogetherModels(apiKeys?: Record<string, string>, settings?: IP
} }
} }
const getOllamaBaseUrl = (settings?: IProviderSetting) => { const getOllamaBaseUrl = (settings?: IProviderSetting, serverEnv: Record<string, string> = {}) => {
const defaultBaseUrl = settings?.baseUrl || import.meta.env.OLLAMA_API_BASE_URL || 'http://localhost:11434'; let settingsBaseUrl = settings?.baseUrl;
if (settingsBaseUrl && settingsBaseUrl.length == 0) {
settingsBaseUrl = undefined;
}
const defaultBaseUrl =
settings?.baseUrl ||
serverEnv?.OLLAMA_API_BASE_URL ||
process.env.OLLAMA_API_BASE_URL ||
import.meta.env.OLLAMA_API_BASE_URL ||
'http://localhost:11434';
// Check if we're in the browser // Check if we're in the browser
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
@ -398,9 +428,13 @@ const getOllamaBaseUrl = (settings?: IProviderSetting) => {
return isDocker ? defaultBaseUrl.replace('localhost', 'host.docker.internal') : defaultBaseUrl; return isDocker ? defaultBaseUrl.replace('localhost', 'host.docker.internal') : defaultBaseUrl;
}; };
async function getOllamaModels(apiKeys?: Record<string, string>, settings?: IProviderSetting): Promise<ModelInfo[]> { async function getOllamaModels(
apiKeys?: Record<string, string>,
settings?: IProviderSetting,
serverEnv: Record<string, string> = {},
): Promise<ModelInfo[]> {
try { try {
const baseUrl = getOllamaBaseUrl(settings); const baseUrl = getOllamaBaseUrl(settings, serverEnv);
const response = await fetch(`${baseUrl}/api/tags`); const response = await fetch(`${baseUrl}/api/tags`);
const data = (await response.json()) as OllamaApiResponse; const data = (await response.json()) as OllamaApiResponse;
@ -421,9 +455,21 @@ async function getOllamaModels(apiKeys?: Record<string, string>, settings?: IPro
async function getOpenAILikeModels( async function getOpenAILikeModels(
apiKeys?: Record<string, string>, apiKeys?: Record<string, string>,
settings?: IProviderSetting, settings?: IProviderSetting,
serverEnv: Record<string, string> = {},
): Promise<ModelInfo[]> { ): Promise<ModelInfo[]> {
try { try {
const baseUrl = settings?.baseUrl || import.meta.env.OPENAI_LIKE_API_BASE_URL || ''; let settingsBaseUrl = settings?.baseUrl;
if (settingsBaseUrl && settingsBaseUrl.length == 0) {
settingsBaseUrl = undefined;
}
const baseUrl =
settingsBaseUrl ||
serverEnv.OPENAI_LIKE_API_BASE_URL ||
process.env.OPENAI_LIKE_API_BASE_URL ||
import.meta.env.OPENAI_LIKE_API_BASE_URL ||
'';
if (!baseUrl) { if (!baseUrl) {
return []; return [];
@ -486,9 +532,24 @@ async function getOpenRouterModels(): Promise<ModelInfo[]> {
})); }));
} }
async function getLMStudioModels(_apiKeys?: Record<string, string>, settings?: IProviderSetting): Promise<ModelInfo[]> { async function getLMStudioModels(
_apiKeys?: Record<string, string>,
settings?: IProviderSetting,
serverEnv: Record<string, string> = {},
): Promise<ModelInfo[]> {
try { try {
const baseUrl = settings?.baseUrl || import.meta.env.LMSTUDIO_API_BASE_URL || 'http://localhost:1234'; let settingsBaseUrl = settings?.baseUrl;
if (settingsBaseUrl && settingsBaseUrl.length == 0) {
settingsBaseUrl = undefined;
}
const baseUrl =
settingsBaseUrl ||
serverEnv.LMSTUDIO_API_BASE_URL ||
process.env.LMSTUDIO_API_BASE_URL ||
import.meta.env.LMSTUDIO_API_BASE_URL ||
'http://localhost:1234';
const response = await fetch(`${baseUrl}/v1/models`); const response = await fetch(`${baseUrl}/v1/models`);
const data = (await response.json()) as any; const data = (await response.json()) as any;
@ -503,29 +564,37 @@ async function getLMStudioModels(_apiKeys?: Record<string, string>, settings?: I
} }
} }
async function initializeModelList(providerSettings?: Record<string, IProviderSetting>): Promise<ModelInfo[]> { async function initializeModelList(options: {
let apiKeys: Record<string, string> = {}; env?: Record<string, string>;
providerSettings?: Record<string, IProviderSetting>;
apiKeys?: Record<string, string>;
}): Promise<ModelInfo[]> {
const { providerSettings, apiKeys: providedApiKeys, env } = options;
let apiKeys: Record<string, string> = providedApiKeys || {};
try { if (!providedApiKeys) {
const storedApiKeys = Cookies.get('apiKeys'); try {
const storedApiKeys = Cookies.get('apiKeys');
if (storedApiKeys) { if (storedApiKeys) {
const parsedKeys = JSON.parse(storedApiKeys); const parsedKeys = JSON.parse(storedApiKeys);
if (typeof parsedKeys === 'object' && parsedKeys !== null) { if (typeof parsedKeys === 'object' && parsedKeys !== null) {
apiKeys = parsedKeys; apiKeys = parsedKeys;
}
} }
} catch (error: any) {
logStore.logError('Failed to fetch API keys from cookies', error);
logger.warn(`Failed to fetch apikeys from cookies: ${error?.message}`);
} }
} catch (error: any) {
logStore.logError('Failed to fetch API keys from cookies', error);
logger.warn(`Failed to fetch apikeys from cookies: ${error?.message}`);
} }
MODEL_LIST = [ MODEL_LIST = [
...( ...(
await Promise.all( await Promise.all(
PROVIDER_LIST.filter( PROVIDER_LIST.filter(
(p): p is ProviderInfo & { getDynamicModels: () => Promise<ModelInfo[]> } => !!p.getDynamicModels, (p): p is ProviderInfo & { getDynamicModels: () => Promise<ModelInfo[]> } => !!p.getDynamicModels,
).map((p) => p.getDynamicModels(apiKeys, providerSettings?.[p.name])), ).map((p) => p.getDynamicModels(apiKeys, providerSettings?.[p.name], env)),
) )
).flat(), ).flat(),
...staticModels, ...staticModels,
@ -534,6 +603,7 @@ async function initializeModelList(providerSettings?: Record<string, IProviderSe
return MODEL_LIST; return MODEL_LIST;
} }
// initializeModelList({})
export { export {
getOllamaModels, getOllamaModels,
getOpenAILikeModels, getOpenAILikeModels,