Skip to content
Snippets Groups Projects
Commit df2c01b1 authored by timothycarambat's avatar timothycarambat
Browse files

patch OpenRouter model fetcher when key is not present

parent 2e813846
No related branches found
No related tags found
No related merge requests found
...@@ -8,6 +8,11 @@ const { ...@@ -8,6 +8,11 @@ const {
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const { safeJsonParse } = require("../../http"); const { safeJsonParse } = require("../../http");
const cacheFolder = path.resolve(
process.env.STORAGE_DIR
? path.resolve(process.env.STORAGE_DIR, "models", "openrouter")
: path.resolve(__dirname, `../../../storage/models/openrouter`)
);
class OpenRouterLLM { class OpenRouterLLM {
constructor(embedder = null, modelPreference = null) { constructor(embedder = null, modelPreference = null) {
...@@ -38,12 +43,8 @@ class OpenRouterLLM { ...@@ -38,12 +43,8 @@ class OpenRouterLLM {
this.embedder = !embedder ? new NativeEmbedder() : embedder; this.embedder = !embedder ? new NativeEmbedder() : embedder;
this.defaultTemp = 0.7; this.defaultTemp = 0.7;
const cacheFolder = path.resolve( if (!fs.existsSync(cacheFolder))
process.env.STORAGE_DIR fs.mkdirSync(cacheFolder, { recursive: true });
? path.resolve(process.env.STORAGE_DIR, "models", "openrouter")
: path.resolve(__dirname, `../../../storage/models/openrouter`)
);
fs.mkdirSync(cacheFolder, { recursive: true });
this.cacheModelPath = path.resolve(cacheFolder, "models.json"); this.cacheModelPath = path.resolve(cacheFolder, "models.json");
this.cacheAtPath = path.resolve(cacheFolder, ".cached_at"); this.cacheAtPath = path.resolve(cacheFolder, ".cached_at");
} }
...@@ -52,11 +53,6 @@ class OpenRouterLLM { ...@@ -52,11 +53,6 @@ class OpenRouterLLM {
console.log(`\x1b[36m[${this.constructor.name}]\x1b[0m ${text}`, ...args); console.log(`\x1b[36m[${this.constructor.name}]\x1b[0m ${text}`, ...args);
} }
async init() {
await this.#syncModels();
return this;
}
// This checks if the .cached_at file has a timestamp that is more than 1Week (in millis) // This checks if the .cached_at file has a timestamp that is more than 1Week (in millis)
// from the current date. If it is, then we will refetch the API so that all the models are up // from the current date. If it is, then we will refetch the API so that all the models are up
// to date. // to date.
...@@ -80,37 +76,7 @@ class OpenRouterLLM { ...@@ -80,37 +76,7 @@ class OpenRouterLLM {
this.log( this.log(
"Model cache is not present or stale. Fetching from OpenRouter API." "Model cache is not present or stale. Fetching from OpenRouter API."
); );
await fetch(`${this.basePath}/models`, { await fetchOpenRouterModels();
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then(({ data = [] }) => {
const models = {};
data.forEach((model) => {
models[model.id] = {
id: model.id,
name: model.name,
organization:
model.id.split("/")[0].charAt(0).toUpperCase() +
model.id.split("/")[0].slice(1),
maxLength: model.context_length,
};
});
fs.writeFileSync(this.cacheModelPath, JSON.stringify(models), {
encoding: "utf-8",
});
fs.writeFileSync(this.cacheAtPath, String(Number(new Date())), {
encoding: "utf-8",
});
return models;
})
.catch((e) => {
console.error(e);
return {};
});
return; return;
} }
...@@ -330,7 +296,7 @@ class OpenRouterLLM { ...@@ -330,7 +296,7 @@ class OpenRouterLLM {
try { try {
JSON.parse(message); JSON.parse(message);
validJSON = true; validJSON = true;
} catch {} } catch { }
if (!validJSON) { if (!validJSON) {
// It can be possible that the chunk decoding is running away // It can be possible that the chunk decoding is running away
...@@ -420,6 +386,54 @@ class OpenRouterLLM { ...@@ -420,6 +386,54 @@ class OpenRouterLLM {
} }
} }
async function fetchOpenRouterModels() {
return await fetch(`https://openrouter.ai/api/v1/models`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then(({ data = [] }) => {
const models = {};
data.forEach((model) => {
models[model.id] = {
id: model.id,
name: model.name,
organization:
model.id.split("/")[0].charAt(0).toUpperCase() +
model.id.split("/")[0].slice(1),
maxLength: model.context_length,
};
});
// Cache all response information
if (!fs.existsSync(cacheFolder))
fs.mkdirSync(cacheFolder, { recursive: true });
fs.writeFileSync(
path.resolve(cacheFolder, "models.json"),
JSON.stringify(models),
{
encoding: "utf-8",
}
);
fs.writeFileSync(
path.resolve(cacheFolder, ".cached_at"),
String(Number(new Date())),
{
encoding: "utf-8",
}
);
return models;
})
.catch((e) => {
console.error(e);
return {};
});
}
module.exports = { module.exports = {
OpenRouterLLM, OpenRouterLLM,
fetchOpenRouterModels,
}; };
const { OpenRouterLLM } = require("../AiProviders/openRouter"); const {
OpenRouterLLM,
fetchOpenRouterModels,
} = require("../AiProviders/openRouter");
const { perplexityModels } = require("../AiProviders/perplexity"); const { perplexityModels } = require("../AiProviders/perplexity");
const { togetherAiModels } = require("../AiProviders/togetherAi"); const { togetherAiModels } = require("../AiProviders/togetherAi");
const SUPPORT_CUSTOM_MODELS = [ const SUPPORT_CUSTOM_MODELS = [
...@@ -232,8 +235,7 @@ async function getPerplexityModels() { ...@@ -232,8 +235,7 @@ async function getPerplexityModels() {
} }
async function getOpenRouterModels() { async function getOpenRouterModels() {
const openrouter = await new OpenRouterLLM().init(); const knownModels = await fetchOpenRouterModels();
const knownModels = openrouter.models();
if (!Object.keys(knownModels).length === 0) if (!Object.keys(knownModels).length === 0)
return { models: [], error: null }; return { models: [], error: null };
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment