@rackrot/pi-bifrost 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +74 -2
- package/package.json +40 -5
- package/src/config-schema.ts +66 -0
- package/src/config.ts +51 -0
- package/src/index.ts +69 -0
- package/src/models-dev.ts +145 -0
- package/src/models.ts +138 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 rackrot
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,75 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @rackrot/pi-bifrost
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Registers a [Bifrost](https://github.com/maximhq/bifrost) gateway as one pi provider, `bifrost`.
|
|
4
|
+
Every upstream behind the gateway shows up as `bifrost/<provider>/<model>`, for chat and decision
|
|
5
|
+
models. Facts the gateway's `/v1/models` does not report (context window, output limit, price,
|
|
6
|
+
image input, reasoning) come from [models.dev](https://models.dev).
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pi install npm:@rackrot/pi-bifrost
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Config (global `~/.pi/agent/rackrot/config.json(c)` only)
|
|
15
|
+
|
|
16
|
+
```json
|
|
17
|
+
{
|
|
18
|
+
"bifrost": {
|
|
19
|
+
"baseUrl": "https://bifrost.example.com",
|
|
20
|
+
"apiKeyEnv": "BIFROST_VK",
|
|
21
|
+
"models": {
|
|
22
|
+
"openrouter-decision/typesafe/jev-1.14": { "type": "decision" },
|
|
23
|
+
"anthropic/claude-haiku-5-5": { "api": "openai-responses" }
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- `baseUrl`: the gateway. The project layer is ignored, because this names the host that receives the key.
|
|
30
|
+
- `apiKeyEnv`: environment variable holding a Bifrost virtual key (default `BIFROST_VK`), sent as a bearer token. The dashboard login does not work for inference.
|
|
31
|
+
- `models`: models to add, keyed by the gateway's `provider/model` id, for ones `/v1/models` does not list, such as decision models. An entry for a listed model overrides what the gateway and models.dev report. Fields: `type` (`chat` or `decision`), `name`, `api` (`openai-completions` default, or `openai-responses`), `reasoning`, `input`, `contextWindow`, `maxTokens`, `cost` (US dollars per million tokens).
|
|
32
|
+
|
|
33
|
+
## Embedding, reranking and decisions for search
|
|
34
|
+
|
|
35
|
+
Core's shared `retrieval` block already talks to Bifrost; no extension is needed for it. Embedding
|
|
36
|
+
and reranking use the `http` provider on the gateway's `/v1`, and decisions use the `typesafe`
|
|
37
|
+
provider on its `/typesafe` route, with the same virtual key:
|
|
38
|
+
|
|
39
|
+
```json
|
|
40
|
+
{
|
|
41
|
+
"retrieval": {
|
|
42
|
+
"embedding": {
|
|
43
|
+
"provider": "http",
|
|
44
|
+
"baseUrl": "https://bifrost.example.com/v1",
|
|
45
|
+
"model": "llama/qwen3-embedding-4b",
|
|
46
|
+
"apiKeyEnv": "BIFROST_VK"
|
|
47
|
+
},
|
|
48
|
+
"reranker": {
|
|
49
|
+
"provider": "http",
|
|
50
|
+
"baseUrl": "https://bifrost.example.com/v1",
|
|
51
|
+
"model": "llama/qwen3-reranker-0.6b",
|
|
52
|
+
"apiKeyEnv": "BIFROST_VK"
|
|
53
|
+
},
|
|
54
|
+
"decision": {
|
|
55
|
+
"enabled": true,
|
|
56
|
+
"provider": "typesafe",
|
|
57
|
+
"baseUrl": "https://bifrost.example.com/typesafe",
|
|
58
|
+
"model": "openrouter-decision/typesafe/jev-1.14",
|
|
59
|
+
"apiKeyEnv": "BIFROST_VK"
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Changing the embedding model re-embeds stored vectors. Decision models are not listed by `/v1/models`;
|
|
66
|
+
use the id of the Bifrost provider that serves them, here `openrouter-decision/…`.
|
|
67
|
+
|
|
68
|
+
## Behavior
|
|
69
|
+
|
|
70
|
+
- Models are listed at startup. A gateway that is unreachable then leaves the provider unregistered, with a notice at session start.
|
|
71
|
+
- Each fact is taken from the config entry, else the gateway, else models.dev, else a default (128k context, 16k output, text input, free).
|
|
72
|
+
- Embedding, reranking and speech models are left out of the chat list.
|
|
73
|
+
- Decision models use pi's `openai-decisions` classifier API, which matches the gateway's `/v1/decisions`.
|
|
74
|
+
- The models.dev index is cached for a day at `<agent dir>/rackrot/models-dev.json`; a failed refresh uses the old cache.
|
|
75
|
+
- Failover between accounts and providers is the gateway's job: configure it in Bifrost.
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@rackrot/pi-bifrost",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Bifrost gateway as one pi provider: chat, responses and decision models, with missing model facts filled from models.dev",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi-extension"
|
|
9
|
+
],
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"files": [
|
|
12
|
+
"src",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node --test test/*.test.ts"
|
|
17
|
+
},
|
|
18
|
+
"pi": {
|
|
19
|
+
"extensions": [
|
|
20
|
+
"./src/index.ts"
|
|
21
|
+
]
|
|
22
|
+
},
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
25
|
+
"@rackrot/pi-core": "*"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@rackrot/pi-core": "workspace:*"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/rackrot/pi-tools.git",
|
|
36
|
+
"directory": "packages/bifrost"
|
|
37
|
+
},
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=24"
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { type Fragment, globalOnly, obj, record } from "@rackrot/pi-core/config-schema";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import { DEFAULT_KEY_ENV } from "./config.ts";
|
|
4
|
+
|
|
5
|
+
const num = (description: string) => Type.Optional(Type.Number({ minimum: 0, description }));
|
|
6
|
+
|
|
7
|
+
export const bifrostSchema: Fragment = {
|
|
8
|
+
bifrost: globalOnly(
|
|
9
|
+
obj(
|
|
10
|
+
{
|
|
11
|
+
baseUrl: Type.Optional(
|
|
12
|
+
Type.String({ description: "Gateway URL, for example `https://bifrost.example.com`." }),
|
|
13
|
+
),
|
|
14
|
+
apiKeyEnv: Type.Optional(
|
|
15
|
+
Type.String({
|
|
16
|
+
default: DEFAULT_KEY_ENV,
|
|
17
|
+
description: "Name of the environment variable holding a Bifrost virtual key.",
|
|
18
|
+
}),
|
|
19
|
+
),
|
|
20
|
+
models: Type.Optional(
|
|
21
|
+
record(
|
|
22
|
+
"^[^/\\s]+/\\S+$",
|
|
23
|
+
obj(
|
|
24
|
+
{
|
|
25
|
+
type: Type.Optional(
|
|
26
|
+
Type.Union([Type.Literal("chat"), Type.Literal("decision")], {
|
|
27
|
+
description: "`decision` registers a decision model. Default `chat`.",
|
|
28
|
+
}),
|
|
29
|
+
),
|
|
30
|
+
name: Type.Optional(Type.String()),
|
|
31
|
+
api: Type.Optional(
|
|
32
|
+
Type.Union(
|
|
33
|
+
[Type.Literal("openai-completions"), Type.Literal("openai-responses")],
|
|
34
|
+
{
|
|
35
|
+
description: "Chat wire protocol. Default `openai-completions`.",
|
|
36
|
+
},
|
|
37
|
+
),
|
|
38
|
+
),
|
|
39
|
+
reasoning: Type.Optional(Type.Boolean()),
|
|
40
|
+
input: Type.Optional(
|
|
41
|
+
Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")])),
|
|
42
|
+
),
|
|
43
|
+
contextWindow: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
44
|
+
maxTokens: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
45
|
+
cost: Type.Optional(
|
|
46
|
+
obj(
|
|
47
|
+
{
|
|
48
|
+
input: num("US dollars per million input tokens."),
|
|
49
|
+
output: num("US dollars per million output tokens."),
|
|
50
|
+
cacheRead: num("US dollars per million cache-read tokens."),
|
|
51
|
+
cacheWrite: num("US dollars per million cache-write tokens."),
|
|
52
|
+
},
|
|
53
|
+
"Price per million tokens.",
|
|
54
|
+
),
|
|
55
|
+
),
|
|
56
|
+
},
|
|
57
|
+
"Facts for one model.",
|
|
58
|
+
),
|
|
59
|
+
"Models to add, keyed by `provider/model`, for ones `/v1/models` does not list (decision models). Entries for listed models override what the gateway and models.dev report.",
|
|
60
|
+
),
|
|
61
|
+
),
|
|
62
|
+
},
|
|
63
|
+
"The Bifrost gateway: its URL, the variable holding the virtual key, and extra models.",
|
|
64
|
+
),
|
|
65
|
+
),
|
|
66
|
+
};
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { configPath, readConfig } from "@rackrot/pi-core/config";
|
|
2
|
+
|
|
3
|
+
/** Per-model facts set in config. They add models the gateway does not list and win over every other source. */
|
|
4
|
+
export interface ModelOverride {
|
|
5
|
+
/** `decision` registers a decision model; the default is `chat`. */
|
|
6
|
+
type?: "chat" | "decision";
|
|
7
|
+
name?: string;
|
|
8
|
+
/** Chat only: `openai-completions` (default) or `openai-responses`. */
|
|
9
|
+
api?: "openai-completions" | "openai-responses";
|
|
10
|
+
reasoning?: boolean;
|
|
11
|
+
input?: ("text" | "image")[];
|
|
12
|
+
contextWindow?: number;
|
|
13
|
+
maxTokens?: number;
|
|
14
|
+
/** US dollars per million tokens. */
|
|
15
|
+
cost?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface BifrostConfig {
|
|
19
|
+
baseUrl: string;
|
|
20
|
+
/** Name of the environment variable holding the virtual key. Keys are never stored in config. */
|
|
21
|
+
apiKeyEnv: string;
|
|
22
|
+
/** Keyed by the gateway's `provider/model` id. */
|
|
23
|
+
models: Record<string, ModelOverride>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const DEFAULT_KEY_ENV = "BIFROST_VK";
|
|
27
|
+
|
|
28
|
+
const isObj = (v: unknown): v is Record<string, unknown> =>
|
|
29
|
+
!!v && typeof v === "object" && !Array.isArray(v);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The `bifrost` block of the global config, or `undefined` without a base URL. The project layer is
|
|
33
|
+
* never read: the block names the host that receives the key.
|
|
34
|
+
*/
|
|
35
|
+
export function parseConfig(global: Record<string, unknown>): BifrostConfig | undefined {
|
|
36
|
+
const raw = isObj(global.bifrost) ? global.bifrost : {};
|
|
37
|
+
if (typeof raw.baseUrl !== "string" || !raw.baseUrl.trim()) return undefined;
|
|
38
|
+
return {
|
|
39
|
+
baseUrl: raw.baseUrl.trim().replace(/\/+$/, ""),
|
|
40
|
+
apiKeyEnv: typeof raw.apiKeyEnv === "string" && raw.apiKeyEnv ? raw.apiKeyEnv : DEFAULT_KEY_ENV,
|
|
41
|
+
models: isObj(raw.models)
|
|
42
|
+
? (Object.fromEntries(Object.entries(raw.models).filter(([, v]) => isObj(v))) as Record<
|
|
43
|
+
string,
|
|
44
|
+
ModelOverride
|
|
45
|
+
>)
|
|
46
|
+
: {},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const loadConfig = (cwd: string, agentDir?: string) =>
|
|
51
|
+
parseConfig(readConfig(configPath("global", cwd, agentDir)));
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { type ExtensionAPI, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { registerConfigSection } from "@rackrot/pi-core/config-ui";
|
|
4
|
+
import { loadConfig } from "./config.ts";
|
|
5
|
+
import { fetchGatewayModels, toProviderModels } from "./models.ts";
|
|
6
|
+
import { loadModelsDev } from "./models-dev.ts";
|
|
7
|
+
|
|
8
|
+
const PROVIDER = "bifrost";
|
|
9
|
+
|
|
10
|
+
export default async function (pi: ExtensionAPI) {
|
|
11
|
+
registerConfigSection({
|
|
12
|
+
id: "bifrost",
|
|
13
|
+
label: "Bifrost",
|
|
14
|
+
example: {
|
|
15
|
+
bifrost: {
|
|
16
|
+
baseUrl: "https://bifrost.example.com",
|
|
17
|
+
apiKeyEnv: "BIFROST_VK",
|
|
18
|
+
models: { "openrouter-decision/typesafe/jev-1.14": { type: "decision" } },
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
fields: [
|
|
22
|
+
{
|
|
23
|
+
path: ["bifrost", "baseUrl"],
|
|
24
|
+
label: "Gateway URL",
|
|
25
|
+
description: "Global config only. Extra models are edited in the config file.",
|
|
26
|
+
kind: "text",
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
path: ["bifrost", "apiKeyEnv"],
|
|
30
|
+
label: "Virtual key variable",
|
|
31
|
+
description: "Name of the environment variable holding the key (default BIFROST_VK).",
|
|
32
|
+
kind: "text",
|
|
33
|
+
},
|
|
34
|
+
],
|
|
35
|
+
summary: (ctx) => {
|
|
36
|
+
const c = loadConfig(ctx.cwd);
|
|
37
|
+
return c ? `${c.baseUrl}, ${Object.keys(c.models).length} extra models` : "not configured";
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
const config = loadConfig(process.cwd());
|
|
42
|
+
if (!config) return;
|
|
43
|
+
const key = process.env[config.apiKeyEnv];
|
|
44
|
+
if (!key) {
|
|
45
|
+
pi.on("session_start", (_e, ctx) =>
|
|
46
|
+
ctx.ui.notify(`bifrost: $${config.apiKeyEnv} is not set`, "warning"),
|
|
47
|
+
);
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const cache = join(getAgentDir(), "rackrot");
|
|
52
|
+
try {
|
|
53
|
+
const [gateway, dev] = await Promise.all([
|
|
54
|
+
fetchGatewayModels(config.baseUrl, key),
|
|
55
|
+
loadModelsDev(join(cache, "models-dev.json")),
|
|
56
|
+
]);
|
|
57
|
+
pi.registerProvider(PROVIDER, {
|
|
58
|
+
name: "Bifrost",
|
|
59
|
+
baseUrl: `${config.baseUrl}/v1`,
|
|
60
|
+
apiKey: `$${config.apiKeyEnv}`,
|
|
61
|
+
api: "openai-completions",
|
|
62
|
+
models: toProviderModels(gateway, dev, config.models),
|
|
63
|
+
});
|
|
64
|
+
} catch (e) {
|
|
65
|
+
pi.on("session_start", (_e, ctx) =>
|
|
66
|
+
ctx.ui.notify(`bifrost: cannot list models: ${(e as Error).message}`, "error"),
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { writeTextAtomic } from "@rackrot/pi-core/json";
|
|
4
|
+
|
|
5
|
+
/** Prices that apply once a request's input passes `inputTokensAbove`, as pi's `cost.tiers`. */
|
|
6
|
+
export interface CostTier {
|
|
7
|
+
inputTokensAbove: number;
|
|
8
|
+
input: number;
|
|
9
|
+
output: number;
|
|
10
|
+
cacheRead: number;
|
|
11
|
+
cacheWrite: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** What is kept of a models.dev entry. Prices are US dollars per million tokens. */
|
|
15
|
+
export interface DevModel {
|
|
16
|
+
reasoning?: boolean;
|
|
17
|
+
input?: ("text" | "image")[];
|
|
18
|
+
/** False when the model does not produce text, such as an embedding model. */
|
|
19
|
+
textOutput?: boolean;
|
|
20
|
+
contextWindow?: number;
|
|
21
|
+
maxTokens?: number;
|
|
22
|
+
cost?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };
|
|
23
|
+
tiers?: CostTier[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** `providerId/modelId` to its facts. */
|
|
27
|
+
export type DevIndex = Record<string, DevModel>;
|
|
28
|
+
|
|
29
|
+
const URL_ = "https://models.dev/api.json";
|
|
30
|
+
const MAX_AGE_MS = 24 * 3600_000;
|
|
31
|
+
|
|
32
|
+
/** models.dev provider ids for gateway providers whose ids differ. Others match by model id alone. */
|
|
33
|
+
const PROVIDER_MAP: Record<string, string> = { gemini: "google" };
|
|
34
|
+
|
|
35
|
+
interface RawModel {
|
|
36
|
+
reasoning?: boolean;
|
|
37
|
+
modalities?: { input?: string[]; output?: string[] };
|
|
38
|
+
limit?: { context?: number; output?: number };
|
|
39
|
+
cost?: {
|
|
40
|
+
input?: number;
|
|
41
|
+
output?: number;
|
|
42
|
+
cache_read?: number;
|
|
43
|
+
cache_write?: number;
|
|
44
|
+
tiers?: {
|
|
45
|
+
input?: number;
|
|
46
|
+
output?: number;
|
|
47
|
+
cache_read?: number;
|
|
48
|
+
cache_write?: number;
|
|
49
|
+
tier?: { type?: string; size?: number };
|
|
50
|
+
}[];
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function buildIndex(raw: Record<string, { models?: Record<string, RawModel> }>): DevIndex {
|
|
55
|
+
const out: DevIndex = {};
|
|
56
|
+
for (const [pid, p] of Object.entries(raw)) {
|
|
57
|
+
for (const [mid, m] of Object.entries(p.models ?? {})) {
|
|
58
|
+
out[`${pid}/${mid}`] = {
|
|
59
|
+
reasoning: m.reasoning,
|
|
60
|
+
input: m.modalities?.input?.filter(
|
|
61
|
+
(i): i is "text" | "image" => i === "text" || i === "image",
|
|
62
|
+
),
|
|
63
|
+
textOutput: m.modalities?.output?.includes("text"),
|
|
64
|
+
contextWindow: m.limit?.context,
|
|
65
|
+
maxTokens: m.limit?.output,
|
|
66
|
+
cost: m.cost && {
|
|
67
|
+
input: m.cost.input,
|
|
68
|
+
output: m.cost.output,
|
|
69
|
+
cacheRead: m.cost.cache_read,
|
|
70
|
+
cacheWrite: m.cost.cache_write,
|
|
71
|
+
},
|
|
72
|
+
tiers: m.cost?.tiers
|
|
73
|
+
?.filter((t) => t.tier?.type === "context" && t.tier.size)
|
|
74
|
+
.map((t) => ({
|
|
75
|
+
inputTokensAbove: t.tier?.size as number,
|
|
76
|
+
input: t.input ?? 0,
|
|
77
|
+
output: t.output ?? 0,
|
|
78
|
+
cacheRead: t.cache_read ?? 0,
|
|
79
|
+
cacheWrite: t.cache_write ?? 0,
|
|
80
|
+
})),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const bare = new WeakMap<DevIndex, Map<string, DevModel>>();
|
|
88
|
+
|
|
89
|
+
/** Model id (lowercase, without provider) to its first entry. */
|
|
90
|
+
function bareIds(index: DevIndex): Map<string, DevModel> {
|
|
91
|
+
let m = bare.get(index);
|
|
92
|
+
if (!m) {
|
|
93
|
+
m = new Map();
|
|
94
|
+
for (const [k, v] of Object.entries(index)) {
|
|
95
|
+
const id = k.slice(k.indexOf("/") + 1).toLowerCase();
|
|
96
|
+
if (!m.has(id)) m.set(id, v);
|
|
97
|
+
}
|
|
98
|
+
bare.set(index, m);
|
|
99
|
+
}
|
|
100
|
+
return m;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Facts for a gateway model id (`provider/model`). The matching models.dev provider is tried first,
|
|
105
|
+
* then any provider listing the same model id, then the last path segment of the id.
|
|
106
|
+
*/
|
|
107
|
+
export function lookup(index: DevIndex, id: string): DevModel | undefined {
|
|
108
|
+
const slash = id.indexOf("/");
|
|
109
|
+
const provider = id.slice(0, slash);
|
|
110
|
+
const model = id.slice(slash + 1);
|
|
111
|
+
const direct = index[`${PROVIDER_MAP[provider] ?? provider}/${model}`];
|
|
112
|
+
if (direct) return direct;
|
|
113
|
+
const byId = bareIds(index);
|
|
114
|
+
return (
|
|
115
|
+
byId.get(model.toLowerCase()) ?? byId.get(model.slice(model.lastIndexOf("/") + 1).toLowerCase())
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The cached index when under a day old, else a fresh fetch; a failed fetch falls back to any cache, else empty. */
|
|
120
|
+
export async function loadModelsDev(
|
|
121
|
+
cachePath: string,
|
|
122
|
+
fetchFn: typeof fetch = fetch,
|
|
123
|
+
): Promise<DevIndex> {
|
|
124
|
+
const cached = () => {
|
|
125
|
+
try {
|
|
126
|
+
return JSON.parse(readFileSync(cachePath, "utf8")) as DevIndex;
|
|
127
|
+
} catch {
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
if (existsSync(cachePath) && Date.now() - statSync(cachePath).mtimeMs < MAX_AGE_MS) {
|
|
132
|
+
const c = cached();
|
|
133
|
+
if (c) return c;
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
const res = await fetchFn(URL_, { signal: AbortSignal.timeout(15_000) });
|
|
137
|
+
if (!res.ok) throw new Error(`models.dev ${res.status}`);
|
|
138
|
+
const index = buildIndex((await res.json()) as never);
|
|
139
|
+
mkdirSync(dirname(cachePath), { recursive: true });
|
|
140
|
+
writeTextAtomic(cachePath, JSON.stringify(index));
|
|
141
|
+
return index;
|
|
142
|
+
} catch {
|
|
143
|
+
return cached() ?? {};
|
|
144
|
+
}
|
|
145
|
+
}
|
package/src/models.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import type { ProviderModelConfig } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ModelOverride } from "./config.ts";
|
|
3
|
+
import { type DevIndex, type DevModel, lookup } from "./models-dev.ts";
|
|
4
|
+
|
|
5
|
+
/** The fields of `/v1/models` entries that are used. Pricing is dollars per token, as strings. */
|
|
6
|
+
export interface GatewayModel {
|
|
7
|
+
id: string;
|
|
8
|
+
name?: string;
|
|
9
|
+
context_length?: number;
|
|
10
|
+
max_input_tokens?: number;
|
|
11
|
+
max_output_tokens?: number;
|
|
12
|
+
pricing?: Record<string, string | undefined>;
|
|
13
|
+
reasoning?: object;
|
|
14
|
+
supported_methods?: string[];
|
|
15
|
+
architecture?: { input_modalities?: string[] };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const DEFAULT_CONTEXT = 128_000;
|
|
19
|
+
const DEFAULT_MAX_TOKENS = 16_384;
|
|
20
|
+
const DEFAULT_DECISION_CONTEXT = 32_000;
|
|
21
|
+
const NOT_CHAT = /embed|rerank|decision/i;
|
|
22
|
+
const ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
23
|
+
|
|
24
|
+
/** Every model of the gateway, following `next_page_token`. */
|
|
25
|
+
export async function fetchGatewayModels(
|
|
26
|
+
baseUrl: string,
|
|
27
|
+
key: string,
|
|
28
|
+
fetchFn: typeof fetch = fetch,
|
|
29
|
+
): Promise<GatewayModel[]> {
|
|
30
|
+
const out: GatewayModel[] = [];
|
|
31
|
+
let token: string | undefined;
|
|
32
|
+
do {
|
|
33
|
+
const url = new URL("/v1/models", baseUrl);
|
|
34
|
+
url.searchParams.set("page_size", "1000");
|
|
35
|
+
if (token) url.searchParams.set("page_token", token);
|
|
36
|
+
const res = await fetchFn(url, {
|
|
37
|
+
headers: { authorization: `Bearer ${key}` },
|
|
38
|
+
signal: AbortSignal.timeout(15_000),
|
|
39
|
+
});
|
|
40
|
+
if (!res.ok) throw new Error(`${url.pathname} ${res.status}`);
|
|
41
|
+
const body = (await res.json()) as { data?: GatewayModel[]; next_page_token?: string };
|
|
42
|
+
out.push(...(body.data ?? []));
|
|
43
|
+
token = body.next_page_token || undefined;
|
|
44
|
+
} while (token);
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const perMillion = (v: string | undefined) => {
|
|
49
|
+
const n = Number(v);
|
|
50
|
+
return v !== undefined && Number.isFinite(n) ? Number((n * 1e6).toPrecision(10)) : undefined;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const pick = <T>(...vs: (T | undefined)[]) => vs.find((v) => v !== undefined);
|
|
54
|
+
|
|
55
|
+
/** Models that are not chat models: embeddings, rerankers, decision models, or ones that produce no text. */
|
|
56
|
+
const isChat = (m: GatewayModel, dev?: DevModel) =>
|
|
57
|
+
!NOT_CHAT.test(m.id) &&
|
|
58
|
+
(!m.supported_methods?.length || m.supported_methods.includes("generateContent")) &&
|
|
59
|
+
dev?.textOutput !== false;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The pi model for each gateway model that chats, plus every `overrides` entry. Each fact comes from
|
|
63
|
+
* the override, else the gateway, else models.dev, else a fixed default.
|
|
64
|
+
*/
|
|
65
|
+
export function toProviderModels(
|
|
66
|
+
gateway: GatewayModel[],
|
|
67
|
+
dev: DevIndex,
|
|
68
|
+
overrides: Record<string, ModelOverride>,
|
|
69
|
+
): ProviderModelConfig[] {
|
|
70
|
+
const listed = new Set(gateway.map((m) => m.id));
|
|
71
|
+
const out: ProviderModelConfig[] = [];
|
|
72
|
+
for (const m of gateway) {
|
|
73
|
+
const o = overrides[m.id];
|
|
74
|
+
const d = lookup(dev, m.id);
|
|
75
|
+
if (o?.type === "decision" || (!o && !isChat(m, d))) continue;
|
|
76
|
+
out.push(chat(m.id, m, d, o));
|
|
77
|
+
}
|
|
78
|
+
for (const [id, o] of Object.entries(overrides)) {
|
|
79
|
+
if (o.type === "decision") out.push(decision(id, o));
|
|
80
|
+
else if (!listed.has(id)) out.push(chat(id, undefined, lookup(dev, id), o));
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function chat(
|
|
86
|
+
id: string,
|
|
87
|
+
m: GatewayModel | undefined,
|
|
88
|
+
d: DevModel | undefined,
|
|
89
|
+
o: ModelOverride | undefined,
|
|
90
|
+
): ProviderModelConfig {
|
|
91
|
+
const price = m?.pricing;
|
|
92
|
+
const input = perMillion(price?.prompt);
|
|
93
|
+
const output = perMillion(price?.completion);
|
|
94
|
+
// Tiers are models.dev's, so use them only where the gateway's base price is the same one.
|
|
95
|
+
const tiers =
|
|
96
|
+
!o?.cost && d?.tiers?.length && (input === undefined || input === d.cost?.input)
|
|
97
|
+
? d.tiers
|
|
98
|
+
: undefined;
|
|
99
|
+
return {
|
|
100
|
+
id,
|
|
101
|
+
name: o?.name ?? m?.name ?? id,
|
|
102
|
+
api: o?.api ?? "openai-completions",
|
|
103
|
+
reasoning: pick(o?.reasoning, m?.reasoning ? true : undefined, d?.reasoning) ?? false,
|
|
104
|
+
input: pick(
|
|
105
|
+
o?.input,
|
|
106
|
+
m?.architecture?.input_modalities?.filter(
|
|
107
|
+
(i): i is "text" | "image" => i === "text" || i === "image",
|
|
108
|
+
),
|
|
109
|
+
d?.input,
|
|
110
|
+
) ?? ["text"],
|
|
111
|
+
cost: {
|
|
112
|
+
input: pick(o?.cost?.input, input, d?.cost?.input) ?? 0,
|
|
113
|
+
output: pick(o?.cost?.output, output, d?.cost?.output) ?? 0,
|
|
114
|
+
cacheRead:
|
|
115
|
+
pick(o?.cost?.cacheRead, perMillion(price?.input_cache_read), d?.cost?.cacheRead) ?? 0,
|
|
116
|
+
cacheWrite:
|
|
117
|
+
pick(o?.cost?.cacheWrite, perMillion(price?.input_cache_write), d?.cost?.cacheWrite) ?? 0,
|
|
118
|
+
...(tiers && { tiers }),
|
|
119
|
+
},
|
|
120
|
+
contextWindow:
|
|
121
|
+
pick(o?.contextWindow, m?.context_length, m?.max_input_tokens, d?.contextWindow) ??
|
|
122
|
+
DEFAULT_CONTEXT,
|
|
123
|
+
maxTokens: pick(o?.maxTokens, m?.max_output_tokens, d?.maxTokens) ?? DEFAULT_MAX_TOKENS,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Decision models are not listed by the gateway. Pi's `openai-decisions` API matches `/v1/decisions`. */
|
|
128
|
+
function decision(id: string, o: ModelOverride): ProviderModelConfig {
|
|
129
|
+
return {
|
|
130
|
+
type: "classifier",
|
|
131
|
+
id,
|
|
132
|
+
name: o.name ?? id,
|
|
133
|
+
api: "openai-decisions",
|
|
134
|
+
input: o.input ?? ["text"],
|
|
135
|
+
cost: { ...ZERO_COST, ...o.cost },
|
|
136
|
+
contextWindow: o.contextWindow ?? DEFAULT_DECISION_CONTEXT,
|
|
137
|
+
};
|
|
138
|
+
}
|