Skip to content
Merged
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
1 change: 1 addition & 0 deletions .github/assets/tui-pollinations-model-list.json

Large diffs are not rendered by default.

Binary file added .github/assets/tui-pollinations-model-list.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
201 changes: 201 additions & 0 deletions packages/opencode/src/provider/pollinations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
/**
* Pollinations (`https://gen.pollinations.ai/v1`) is an OpenAI-compatible
* gateway, so chat goes through `@ai-sdk/openai-compatible` unchanged. The
* model list is read live from `GET /v1/models` and narrowed to chat LLMs:
* the text category, text output, the chat-completions endpoint, and never a
* decision model. Decision models also answer chat requests, but they list
* `/alpha/decisions` in `supported_endpoints`.
*
* Prices are published per token in Pollen, the platform's credit unit. They
* are scaled to the per-million figures the rest of the provider layer uses.
*/
import { ModelV2 } from "@opencode-ai/core/model"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { isRecord } from "@/util/record"
import type { Info, Model } from "./provider"

export const POLLINATIONS_PROVIDER_ID = "pollinations"
export const POLLINATIONS_BASE_URL = "https://gen.pollinations.ai/v1"
export const POLLINATIONS_ENV = "POLLINATIONS_API_KEY"

const CHAT_ENDPOINT = "/v1/chat/completions"
const DECISION_ENDPOINT = "/alpha/decisions"
const DEFAULT_CONTEXT = 128_000
const DEFAULT_OUTPUT = 16_384
const PER_MILLION = 1_000_000
const DISCOVERY_TIMEOUT_MS = 5_000

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SUGGESTION: 5-second discovery timeout may be too aggressive

DISCOVERY_TIMEOUT_MS = 5_000 (5 seconds) for fetching /v1/models. On slow or high-latency networks, this could cause silent discovery failures. Consider increasing to 10-15 seconds or making it configurable via env var, matching the Token Harbor pattern which may have similar constraints.


export function providerInfo(): Info {
return {
id: ProviderV2.ID.make(POLLINATIONS_PROVIDER_ID),
name: "Pollinations",
source: "custom",
env: [POLLINATIONS_ENV],
options: {},
models: {},
}
}

type Fetcher = (input: string, init?: RequestInit) => Promise<Response>

export type ModelEntry = {
id: string
name: string
inputModalities: string[]
outputModalities: string[]
tools: boolean
reasoning: boolean
temperature: boolean
contextLength?: number
outputLimit?: number
cost: { input: number; output: number; cacheRead: number; cacheWrite: number }
}

/**
* Keeps only chat LLMs from a `/v1/models` body (`{ data: [...] }`). Image,
* video, audio, embedding, and decision entries are dropped. Community models
* stay in the list, labelled with `community`, and `free` under the rule in
* `isFree`.
*/
export function parseModelList(body: unknown): ModelEntry[] {
const list = isRecord(body) ? body.data : undefined
if (!Array.isArray(list)) return []
const entries = list.flatMap((item) =>
isRecord(item) && typeof item.id === "string" && isChatLLM(item) ? [toEntry(item, item.id)] : [],
)
return [...new Map(entries.map((entry) => [entry.id, entry])).values()]
}

export function toModel(entry: ModelEntry): Model {
return {
id: ModelV2.ID.make(entry.id),
providerID: ProviderV2.ID.make(POLLINATIONS_PROVIDER_ID),
name: entry.name,
family: "",
api: { id: entry.id, url: POLLINATIONS_BASE_URL, npm: "@ai-sdk/openai-compatible" },
status: "active",
headers: {},
options: {},
cost: {
input: entry.cost.input,
output: entry.cost.output,
cache: { read: entry.cost.cacheRead, write: entry.cost.cacheWrite },
},
limit: { context: entry.contextLength ?? DEFAULT_CONTEXT, output: entry.outputLimit ?? DEFAULT_OUTPUT },
capabilities: {
temperature: entry.temperature,
reasoning: entry.reasoning,
attachment: entry.inputModalities.includes("image"),
toolcall: entry.tools,
input: modalities(entry.inputModalities),
output: modalities(entry.outputModalities),
interleaved: false,
},
release_date: "",
variants: {},
}
}

export async function discoverModels(
apiKey: string | undefined,
baseURL = POLLINATIONS_BASE_URL,
fetcher: Fetcher = fetch,
): Promise<Record<string, Model>> {
if (!apiKey) return {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SUGGESTION: Silent failure in discoverModels makes debugging difficult

The discoverModels function catches all errors and returns {} without any logging. While this matches Token Harbor behavior, it makes debugging discovery issues very difficult (network errors, auth failures, API changes all result in empty model list). Consider adding a debug-level log: console.debug("[pollinations] model discovery failed", error) or using a structured logger if available.

const response = await fetcher(`${baseURL.replace(/\/+$/, "")}/models`, {
headers: { Authorization: `Bearer ${apiKey}` },
signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
}).catch(() => undefined)
if (!response?.ok) return {}
const body = await response.json().catch(() => undefined)
return Object.fromEntries(parseModelList(body).map((entry) => [entry.id, toModel(entry)]))
}

function isChatLLM(record: Record<string, unknown>) {
const endpoints = strings(record.supported_endpoints)
return (
record.category === "text" &&
strings(record.output_modalities).includes("text") &&
endpoints.includes(CHAT_ENDPOINT) &&
!endpoints.includes(DECISION_ENDPOINT)
)
}

function toEntry(record: Record<string, unknown>, id: string): ModelEntry {
const pricing = isRecord(record.pricing) ? record.pricing : {}
const capabilities = strings(record.capabilities)
const community = record.community === true
const free = record.paid_only !== true && isFree(record)
const title = typeof record.title === "string" && record.title.trim() ? record.title : id
const labels = [...(community ? ["community"] : []), ...(free ? ["free"] : [])]
const topProvider = isRecord(record.top_provider) ? record.top_provider : {}
return {
id,
name: labels.length ? `${title} (${labels.join(", ")})` : title,
inputModalities: strings(record.input_modalities),
outputModalities: strings(record.output_modalities),
tools: record.tools === true || capabilities.includes("tool_calling"),
reasoning: record.reasoning === true || capabilities.includes("reasoning"),
temperature: strings(record.supported_parameters).includes("temperature"),
contextLength: positive(record.context_length),
outputLimit: positive(topProvider.max_completion_tokens),
cost: {
input: perMillion(pricing.promptTextTokens),
output: perMillion(pricing.completionTextTokens),
cacheRead: perMillion(pricing.promptCachedTokens),
cacheWrite: perMillion(pricing.promptCacheWriteTokens),
},
}
}

/**
* Mirrors the dashboard rule: a model is free when it declares pricing, no
* numeric price is positive (base, variant, or adjustment), and it is not an
* agent. Catalog entries for free models carry only `currency`, so a missing
* price is a zero price here, not an unknown one.
*/
function isFree(record: Record<string, unknown>) {
const pricing = record.pricing
if (record.agent === true || !isRecord(pricing)) return false
const variants = Array.isArray(record.pricing_variants) ? record.pricing_variants : []
const adjustments = Array.isArray(record.pricing_adjustments) ? record.pricing_adjustments : []
return (
!Object.values(pricing).some(isPositive) &&
!variants.some(
(variant) => isRecord(variant) && isRecord(variant.pricing) && Object.values(variant.pricing).some(isPositive),
) &&
!adjustments.some((adjustment) => isRecord(adjustment) && isPositive(adjustment.price))
)
}

function isPositive(value: unknown) {
const number = price(value)
return number !== undefined && number > 0
}

function modalities(list: string[]) {
return {
text: list.includes("text"),
audio: list.includes("audio"),
image: list.includes("image"),
video: list.includes("video"),
pdf: list.includes("pdf"),
}
}

function strings(value: unknown): string[] {
return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []
}

function price(value: unknown) {
const number = typeof value === "string" && value.trim() ? Number(value) : value
return typeof number === "number" && Number.isFinite(number) && number >= 0 ? number : undefined
}

function perMillion(value: unknown) {
return (price(value) ?? 0) * PER_MILLION

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

WARNING: Missing prices default to 0 in cost object

The perMillion function returns 0 when price(value) is undefined (missing/invalid pricing). While the model won't be labeled "free" (the free check requires explicit zero prices), the cost object will show input: 0, output: 0, cache: { read: 0, write: 0 } for unpriced models. This could mislead users into thinking the model is free when it's actually just unpriced/metered. Consider using a sentinel value (e.g., -1) or adding an unknown: true flag to distinguish unpriced from explicitly free.

}

function positive(value: unknown) {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined
}
24 changes: 23 additions & 1 deletion packages/opencode/src/provider/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ import {
TOKENHARBOR_ENV,
TOKENHARBOR_PROVIDER_ID,
} from "./tokenharbor"
import {
discoverModels as discoverPollinationsModels,
POLLINATIONS_BASE_URL,
POLLINATIONS_ENV,
POLLINATIONS_PROVIDER_ID,
providerInfo as pollinationsProviderInfo,
} from "./pollinations"
import {
createQwenWebModel,
providerInfo as qwenWebProviderInfo,
Expand Down Expand Up @@ -1004,13 +1011,27 @@ function custom(dep: CustomDep): Record<string, CustomLoader> {
tokenharbor: Effect.fnUntraced(function* (input: Info) {
const auth = yield* dep.auth(input.id)
const apiKey = auth?.type === "api" ? auth.key : yield* dep.get(TOKENHARBOR_ENV)
const baseURL = ((yield* dep.config()).provider?.[TOKENHARBOR_PROVIDER_ID]?.options?.baseURL as string | undefined) ?? TOKENHARBOR_BASE_URL
const baseURL =
((yield* dep.config()).provider?.[TOKENHARBOR_PROVIDER_ID]?.options?.baseURL as string | undefined) ??
TOKENHARBOR_BASE_URL
return {
autoload: false,
options: { baseURL },
discoverModels: () => discoverTokenHarborModels(apiKey, baseURL),
}
}),
pollinations: Effect.fnUntraced(function* (input: Info) {
const auth = yield* dep.auth(input.id)
const apiKey = auth?.type === "api" ? auth.key : yield* dep.get(POLLINATIONS_ENV)
const baseURL =
((yield* dep.config()).provider?.[POLLINATIONS_PROVIDER_ID]?.options?.baseURL as string | undefined) ??
POLLINATIONS_BASE_URL
return {
autoload: false,
options: { baseURL },
discoverModels: () => discoverPollinationsModels(apiKey, baseURL),
}
}),
"qwen-web": Effect.fnUntraced(function* (input: Info) {
const stored = yield* dep.auth(input.id)
const hasConfig = Boolean((yield* dep.config()).provider?.[QWEN_WEB_PROVIDER_ID])
Expand Down Expand Up @@ -1712,6 +1733,7 @@ const layer = Layer.effect(
// login, authenticated browser profile, or explicit user config).
catalog[ProviderV2.ID.make(QWEN_WEB_PROVIDER_ID)] = qwenWebProviderInfo()
catalog[ProviderV2.ID.make(TOKENHARBOR_PROVIDER_ID)] = tokenHarborProviderInfo()
catalog[ProviderV2.ID.make(POLLINATIONS_PROVIDER_ID)] = pollinationsProviderInfo()
const database = mapValues(catalog, toPublicInfo)

const providers: Record<ProviderV2.ID, Info> = {} as Record<ProviderV2.ID, Info>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ModelsDev } from "@opencode-ai/core/models-dev"
import { Provider } from "@/provider/provider"
import { providerInfo as qwenWebProviderInfo, QWEN_WEB_PROVIDER_ID } from "@/provider/qwen-web"
import { providerInfo as tokenHarborProviderInfo, TOKENHARBOR_PROVIDER_ID } from "@/provider/tokenharbor"
import { providerInfo as pollinationsProviderInfo, POLLINATIONS_PROVIDER_ID } from "@/provider/pollinations"
import { Auth } from "@/auth"

import { APICallError, generateText } from "ai"
Expand Down Expand Up @@ -61,6 +62,7 @@ export const providerHandlers = HttpApiBuilder.group(InstanceHttpApi, "provider"
const builtins: Record<string, () => Parameters<typeof Provider.toPublicInfo>[0]> = {
[QWEN_WEB_PROVIDER_ID]: qwenWebProviderInfo,
[TOKENHARBOR_PROVIDER_ID]: tokenHarborProviderInfo,
[POLLINATIONS_PROVIDER_ID]: pollinationsProviderInfo,
}
const allowedBuiltins = Object.fromEntries(
Object.entries(builtins)
Expand Down Expand Up @@ -133,7 +135,9 @@ export const providerHandlers = HttpApiBuilder.group(InstanceHttpApi, "provider"
(status !== undefined && status >= 500) ||
(APICallError.isInstance(error) && error.isRetryable) ||
Cause.isTimeoutError(error) ||
(!APICallError.isInstance(error) && error instanceof Error && /fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|network/i.test(error.message))
(!APICallError.isInstance(error) &&
error instanceof Error &&
/fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|network/i.test(error.message))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SUGGESTION: Extract network error regex as reusable constant

The regex /fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|network/i for detecting transient network errors appears here and likely elsewhere. Extract it as a module-level constant (e.g., NETWORK_ERROR_REGEX) to avoid duplication and ensure consistent error classification across the codebase.

return Effect.succeed((transient ? "transient" : "error") as "transient" | "error")
}),
)
Expand Down
114 changes: 114 additions & 0 deletions packages/opencode/test/provider/pollinations-provider.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { expect } from "bun:test"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { ProviderV2 } from "@opencode-ai/core/provider"
import { Effect } from "effect"
import { Provider } from "../../src/provider/provider"
import { testEffect } from "../lib/effect"

const POLLINATIONS = ProviderV2.ID.make("pollinations")
const it = testEffect(LayerNode.compile(Provider.node))

const catalog = {
object: "list",
data: [
{
id: "openai/gpt-5.4-nano",
category: "text",
community: false,
title: "GPT-5.4 Nano",
input_modalities: ["text"],
output_modalities: ["text"],
supported_endpoints: ["/v1/chat/completions"],
paid_only: false,
pricing: { promptTextTokens: "0.00000015", completionTextTokens: "0.0000009375" },
tools: true,
},
{
id: "community/open-chat",
category: "text",
community: true,
title: "Open Chat",
input_modalities: ["text"],
output_modalities: ["text"],
supported_endpoints: ["/v1/chat/completions"],
paid_only: false,
pricing: { promptTextTokens: "0", completionTextTokens: "0" },
},
{
id: "liquid/d1",
category: "text",
community: false,
title: "Liquid d1",
input_modalities: ["text"],
output_modalities: ["text"],
supported_endpoints: ["/alpha/decisions", "/v1/chat/completions"],
paid_only: true,
},
{
id: "black-forest-labs/flux.2-pro",
category: "image",
community: false,
title: "FLUX.2 Pro",
input_modalities: ["text"],
output_modalities: ["image"],
supported_endpoints: ["/v1/images/generations"],
paid_only: true,
},
],
}

const server = Bun.serve({
port: 0,
fetch(request) {
if (new URL(request.url).pathname !== "/v1/models") return new Response("missing", { status: 404 })
if (request.headers.get("authorization") !== "Bearer sk_test") return new Response("{}", { status: 401 })
return Response.json(catalog)
},
})

const withKey = <A, E, R>(key: string | undefined, effect: Effect.Effect<A, E, R>) =>
Effect.acquireUseRelease(
Effect.sync(() => {
const previous = process.env.POLLINATIONS_API_KEY
if (key) process.env.POLLINATIONS_API_KEY = key
else delete process.env.POLLINATIONS_API_KEY
return previous
}),
() => effect,
(previous) =>
Effect.sync(() => {
if (previous === undefined) delete process.env.POLLINATIONS_API_KEY
else process.env.POLLINATIONS_API_KEY = previous
}),
)

const config = { provider: { pollinations: { options: { baseURL: `http://localhost:${server.port}/v1` } } } }

it.instance(
"pollinations lists only chat LLMs from /v1/models when a key is set",
() =>
withKey(
"sk_test",
Effect.gen(function* () {
const providers = yield* (yield* Provider.Service).list()
const models = providers[POLLINATIONS].models
expect(Object.keys(models).sort()).toEqual(["community/open-chat", "openai/gpt-5.4-nano"])
expect(models["community/open-chat"].name).toBe("Open Chat (community, free)")
expect(models["openai/gpt-5.4-nano"].api.npm).toBe("@ai-sdk/openai-compatible")
}),
),
{ config },
)

it.instance(
"pollinations stays hidden without a key",
() =>
withKey(
undefined,
Effect.gen(function* () {
const providers = yield* (yield* Provider.Service).list()
expect(providers[POLLINATIONS]).toBeUndefined()
}),
),
{ config },
)
Loading
Loading