cloudaxe-opencode/packages/opencode/src/provider/models.ts

70 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-06-05 18:59:07 +00:00
import { Global } from "../global"
import { Log } from "../util/log"
import path from "path"
import { z } from "zod"
2025-06-05 18:59:07 +00:00
export namespace ModelsDev {
const log = Log.create({ service: "models.dev" })
2025-06-10 22:23:19 +00:00
const filepath = path.join(Global.Path.cache, "models.json")
2025-06-05 18:59:07 +00:00
2025-06-13 11:23:12 +00:00
export const Model = z
.object({
name: z.string(),
attachment: z.boolean(),
reasoning: z.boolean(),
temperature: z.boolean(),
tool_call: z.boolean(),
2025-06-13 11:23:12 +00:00
cost: z.object({
input: z.number(),
output: z.number(),
2025-06-18 00:51:25 +00:00
cache_read: z.number().optional(),
cache_write: z.number().optional(),
2025-06-13 11:23:12 +00:00
}),
limit: z.object({
context: z.number(),
output: z.number(),
}),
id: z.string(),
options: z.record(z.any()),
2025-06-13 11:23:12 +00:00
})
.openapi({
ref: "Model.Info",
})
export type Model = z.infer<typeof Model>
2025-06-13 11:23:12 +00:00
export const Provider = z
.object({
2025-06-18 22:56:41 +00:00
api: z.string().optional(),
2025-06-13 11:23:12 +00:00
name: z.string(),
env: z.array(z.string()),
id: z.string(),
npm: z.string().optional(),
2025-06-13 11:23:12 +00:00
models: z.record(Model),
})
.openapi({
ref: "Provider.Info",
})
export type Provider = z.infer<typeof Provider>
2025-06-05 18:59:07 +00:00
export async function get() {
2025-06-10 22:23:19 +00:00
const file = Bun.file(filepath)
const result = await file.json().catch(() => {})
if (result) {
2025-06-05 18:59:07 +00:00
refresh()
return result as Record<string, Provider>
2025-06-05 18:59:07 +00:00
}
await refresh()
return get()
}
async function refresh() {
2025-06-10 22:23:19 +00:00
const file = Bun.file(filepath)
2025-06-05 18:59:07 +00:00
log.info("refreshing")
const result = await fetch("https://models.dev/api.json")
if (!result.ok)
throw new Error(`Failed to fetch models.dev: ${result.statusText}`)
2025-06-10 17:30:08 +00:00
await Bun.write(file, result)
2025-06-05 18:59:07 +00:00
}
}