pollinations
Your Friendly Open-Source Gen-AI Platform
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/pollinations/pollinations with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/pollinations/pollinations'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/pollinations--pollinations)HTML
<a href="/listings/pollinations--pollinations"><img src="/api/listings/pollinations--pollinations/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Quick Start (3 Steps)
1️⃣ **Get your API key** Sign up at [enter.pollinations.ai](https://enter.pollinations.ai/keys) to generate your key.
2️⃣ **Choose what you want to generate** Pollinations supports: - 🖼 Images - 📝 Text - 🔊 Audio - 🎬 Video - 🧊 3D - 🔢 Embeddings
3️⃣ **Make your first request** Use one of the examples below to generate your first AI output in seconds.
Image Generation
curl -H "Authorization: Bearer YOUR_API_KEY" 'https://gen.pollinations.ai/image/a%20beautiful%20sunset' -o image.jpg
Or visit [pollinations.ai/play](https://pollinations.ai/play) for an interactive experience.
Text Generation
curl 'https://gen.pollinations.ai/text/Hello%20world?key=YOUR_API_KEY'
Audio Generation
**Simple GET endpoint:**
curl 'https://gen.pollinations.ai/audio/Hello%20from%20Pollinations?voice=nova&key=YOUR_API_KEY' -o speech.mp3
**OpenAI TTS compatible:**
curl 'https://gen.pollinations.ai/v1/audio/speech' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-d '{"model": "openai/tts-1", "input": "Hello from Pollinations!", "voice": "nova"}' \
-o speech.mp3Available voices: `alloy`, `echo`, `fable`, `onyx`, `nova`, `shimmer`, plus [30+ ElevenLabs voices](https://gen.pollinations.ai/docs).
**Speech-to-text:**
curl 'https://gen.pollinations.ai/v1/audio/transcriptions' \ -H "Authorization: Bearer YOUR_API_KEY" \ -F file=@audio.mp3 \ -F model=openai/whisper-large-v3
Video Generation
curl 'https://gen.pollinations.ai/video/a%20sunset%20timelapse%20over%20the%20ocean?key=YOUR_API_KEY' -o video.mp4
Use `duration` to set video length, `aspectRatio` for orientation, and `image[0]`/`image[1]` to pass start/end reference frames. See available video models and capabilities at [gen.pollinations.ai/video/models](https://gen.pollinations.ai/video/models).
3D Generation
curl 'https://gen.pollinations.ai/3d/a%20low-poly%20treasure%20chest?model=microsoft/trellis-2&resolution=low&key=YOUR_API_KEY&image=IMAGE_URL' -o model.glb
Pass reference image URL(s) via the `image` parameter for image-to-3D models (put `image=` last in the URL, or URL-encode it). See available 3D models at [gen.pollinations.ai/3d/models](https://gen.pollinations.ai/3d/models).
Embeddings
curl 'https://gen.pollinations.ai/v1/embeddings' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-d '{"model": "openai/text-embedding-3-small", "input": "Hello world!"}'Pass a string or an array of up to 32 strings (text or multimodal content parts). See available embedding models at [gen.pollinations.ai/embeddings/models](https://gen.pollinations.ai/embeddings/models).
Pollinations CLI
Generate text, images, audio, video, and more right from your terminal:
npx @pollinations/cli gen image "cyberpunk city at night" --model black-forest-labs/flux.1-schnell --output city.png npx @pollinations/cli gen text "Explain quantum tunneling in one sentence" npx @pollinations/cli gen audio "Hello world" --voice nova --output speech.mp3 npx @pollinations/cli gen video "a waterfall in slow motion" --duration 5 --output clip.mp4 npx @pollinations/cli gen transcribe speech.mp3
Install globally and use the shorter `polli` command: `npm install -g @pollinations/cli`. Run `polli models` to list models, `polli auth login` to authenticate, and `polli docs` for the full API reference in your terminal.
Real-time API
Stream AI responses over an OpenAI-compatible WebSocket:
wss://gen.pollinations.ai/v1/realtime?model=openai/gpt-realtime-2.1&key=sk_YOUR_API_KEY
Browser clients pass a user-authorized key from [Pollinations Pay](BRING_YOUR_OWN_POLLEN.md) as a query parameter (`?key=`); server clients can use the `Authorization: Bearer` header instead.
MCP Servers
Connect Streamable HTTP clients to the hosted Pollinations MCP server:
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
README.md · README · 544 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <div align="center">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="packages/ui/src/brand/lockup-horizontal-white.svg" />
- <img src="packages/ui/src/brand/lockup-horizontal-black.svg" alt="pollinations.ai" width="100%" />
- </picture>
- <p><strong>Open-source AI for people who make things.</strong></p>
- [](https://github.com/pollinations/pollinations/stargazers)
- [](LICENSE)
- [](https://discord.gg/k9F7SyTgqn)
- [Website](https://pollinations.ai) · [Dashboard](https://enter.pollinations.ai) · [Playground](https://pollinations.ai/play) · [Guides](#guides) · [API Docs](APIDOCS.md) · [For AI Agents](https://gen.pollinations.ai/llms.txt) · [Discord](https://discord.gg/k9F7SyTgqn)
- </div>
- <p align="center"><img src="https://media.pollinations.ai/eb3be88cf66d7491" alt="Pixel art cozy hackerspace: robot at terminal, nomnom creature eating code, bee with glasses" width="800" /></p>
- <!-- recent-apps:start -->
- ## 🆕 Recent Apps
- | Name | Description | Author |
- |------|-------------|--------|
- | [🎮 Decision Arena — Grid Rush](https://decisionarena.edgeone.cool) | A game that AI models play. Decision models on Pollinations play Grid Rush, a deterministic snake-like collection game, and you watch them race. | [@NamanSoni78](https://github.com/NamanSoni78) |
- | [🎮 Herd Check](https://patbing.github.io/herd-check) | Nine models get one question that code can answer. See the anonymous vote, pick the answer you trust, then reveal who was right. 66 recorded rounds: the herd never lost. BYOP. | [@patbing](https://github.com/patbing) |
- | [🎮 Schelling Table](https://tomdacatto.github.io/pollinations-schelling-table) | A game AI agents play over MCP: each picks one option in secret and scores for matching others. Connect any MCP agent, or use your balance to seat Pollinations models. | [@tomdacatto](https://github.com/tomdacatto) |
- | [📚 Where It Slips](https://tomdacatto.github.io/pollinations-where-it-slips) | A tiny real computer written in code checks a model playing it: every step is diffed cell by cell, so you see where each model first slips. You pay from your own balance. | [@tomdacatto](https://github.com/tomdacatto) |
- | [🎮 Idle Hands](https://tomdacatto.github.io/pollinations-idle-hands) | Put up to four Pollinations models on a small island with nothing to do. Plain code runs the world and counts what each one did; a timeline shows every turn. You pay from your own balance. | [@tomdacatto](https://github.com/tomdacatto) |
- | [🎮 Read On](https://patbing.github.io/read-on) | Three paragraphs on one topic: one by a person before LLMs, two by a model, one told to write plainly. Find the person, blind. A slop-score detector plays the same round against you. BYOP. | [@patbing](https://github.com/patbing) |
- | [🎮 Under Oath](https://patbing.github.io/under-oath) | One AI keeps a sealed word, another gets 20 yes/no questions. Code judges the guess, a referee model re-checks every answer, a hash seals the word. Race the Asker. BYOP. | [@patbing](https://github.com/patbing) |
- | [📚 Science Explainer](https://mhmdrizki803-boop.github.io/science-explainer) | Name a science topic and a Pollinations model writes rival explanations, each with a prediction. You run observations and the explanations that fail are falsified. Pay from your own balance. | [@mhmdrizki803-boop](https://github.com/mhmdrizki803-boop) |
- | [🖼️ AI Wallpaper Generator for Phone](https://www.androidponsel.com/wallpaper-generator) | Free AI phone wallpaper generator with device-specific resolution, prompt enhancement via Dialagram LLM, 8 style presets, and curated gallery. Uses Flux Schnell via Pollinations image API. | [@slrdone](https://github.com/slrdone) |
- | [🖼️ Cover Studio](https://polli-cover-studio.surge.sh) | Turns a title, an author and one line of premise into a finished 1600x2400 book cover. Pollinations paints the artwork, the page sets the type, and you download the PNG. | [@mikeymontaz7-dotcom](https://github.com/mikeymontaz7-dotcom) |
- [Browse all apps →](https://pollinations.ai/apps)
- <!-- recent-apps:end -->
- ## 🚀 Unified API
- **https://gen.pollinations.ai** provides one API for text, images, audio, video, 3D, and embeddings.
- ### What's Included
- - **Unified endpoint**: single API at `gen.pollinations.ai` for all generation
- - **Prepaid credit**: simple pay-as-you-go, priced in dollars
- - **All models, one place**: Flux, GPT, Claude, Gemini, Seedream, and more
- - **API keys**: secret keys for model usage, app keys for tracking BYOP apps.
- - **CLI**: `npx @pollinations/cli` for humans and AI agents ([source](packages/polli-cli))
- - **Agent discovery**: [gen.pollinations.ai/llms.txt](https://gen.pollinations.ai/llms.txt) indexes the CLI skill, MCP server catalog, OpenAPI schema, and Agent Skills in one request
- > Get started at [enter.pollinations.ai](https://enter.pollinations.ai) and check out the [API docs](https://gen.pollinations.ai/docs)
- ## 🆕 Latest News
- <!-- Updated daily by .github/workflows/repo-update-readme.yml from the news index. -->
- <!-- news:start -->
- - [<img src="https://img.shields.io/badge/Model-8b5cf6?style=flat-square" alt="Model" align="top"> **Hy4 Flash joins text**](https://enter.pollinations.ai/models?q=tencent/hy4-flash) <sub>Nov 17</sub><br>Use `tencent/hy4-flash` for text and image input, reasoning, and tools. It is paid-only and has a listed context length of 1,024,000 tokens.
- - [<img src="https://img.shields.io/badge/Model-8b5cf6?style=flat-square" alt="Model" align="top"> **DeepSeek Flash gains Quest access**](https://enter.pollinations.ai/models) <sub>Nov 17</sub><br>DeepSeek V4.1 Flash 1017 now accepts Quest balance as well as paid balance, with a 60 requests-per-minute per-user limit.
- - [<img src="https://img.shields.io/badge/Model-8b5cf6?style=flat-square" alt="Model" align="top"> **GPT-6.2 Astra arrives**](https://enter.pollinations.ai/models?q=openai/gpt-6.2-astra) <sub>Nov 17</sub><br>Use paid-only `openai/gpt-6.2-astra` with text or image input, tools, and reasoning. It accepts up to 10 reference images and has a 1,050,000-token context; long-context pricing applies to the full request above 272,000 tokens.
- - [<img src="https://img.shields.io/badge/Model-8b5cf6?style=flat-square" alt="Model" align="top"> **GPT-6.2 Sol arrives**](https://enter.pollinations.ai/models?q=openai/gpt-6.2-sol) <sub>Nov 17</sub><br>Use paid-only `openai/gpt-6.2-sol` with text or image input, tools, and reasoning. It has a 1,050,000-token context; long-context pricing applies to the full request above 272,000 tokens.
- - [<img src="https://img.shields.io/badge/Model-8b5cf6?style=flat-square" alt="Model" align="top"> **MAI Image Flash arrives**](https://enter.pollinations.ai/models?q=microsoft/mai-image-2.7-flash) <sub>Nov 17</sub><br>Generate or edit images with `microsoft/mai-image-2.7-flash`, using up to five reference images for edits.
- - [<img src="https://img.shields.io/badge/Model-8b5cf6?style=flat-square" alt="Model" align="top"> **MAI Image 2.7 arrives**](https://enter.pollinations.ai/models?q=microsoft/mai-image-2.7) <sub>Nov 17</sub><br>Generate images from text or edit them with up to five reference images using `microsoft/mai-image-2.7`. It accepts Quest or paid balance.
- - [<img src="https://img.shields.io/badge/Model-8b5cf6?style=flat-square" alt="Model" align="top"> **Microsoft decision model arrives**](https://enter.pollinations.ai/models?q=microsoft/microsoft-decision-1.1) <sub>Nov 17</sub><br>Use `microsoft/microsoft-decision-1.1` to get typed choices and a probability for each fixed option through `/alpha/decisions` or `/v1/chat/completions`. It accepts Quest or paid balance and text-only requests.
- - [<img src="https://img.shields.io/badge/Model-8b5cf6?style=flat-square" alt="Model" align="top"> **Liquid d1.2 joins decisions**](https://enter.pollinations.ai/models?q=liquid/d1.2) <sub>Nov 17</sub><br>Send text or JSON state to `liquid/d1.2` and get structured choices, scores, and probabilities through `/alpha/decisions` or `/v1/chat/completions`. It uses paid balance.
- - [<img src="https://img.shields.io/badge/Model-8b5cf6?style=flat-square" alt="Model" align="top"> **ZONOS3-Mini speech arrives**](https://enter.pollinations.ai/models?q=zyphra/zonos3-mini) <sub>Nov 17</sub><br>Turn text into MP3 or PCM speech with paid-only `zyphra/zonos3-mini` using the `alloy` voice. Requests accept up to 10,000 text characters and a 64 KiB payload.
- - [<img src="https://img.shields.io/badge/Feature-f59e0b?style=flat-square" alt="Feature" align="top"> **Give Sonilo a video**](https://pollinations.ai/play) <sub>Nov 17</sub><br>Upload a reference video in Play and use `sonilo/sonilo-1.1-sfx` to add sound effects. Play shows the `reference_video` field in its API example.
- <!-- news:end -->
- [More news on enter.pollinations.ai →](https://enter.pollinations.ai/news)
- ---
- ## 🌱 Introduction
- [pollinations.ai](https://pollinations.ai) is an open-source generative AI platform based in Berlin, used by 500+ community projects. It provides APIs for text, image, video, audio, 3D, and embeddings generation. Our code and development discussions are public. Supporters help fund the project.
- <!-- Updated daily by .github/workflows/repo-update-readme.yml.
- Regenerate locally with:
- GITHUB_TOKEN=$(gh auth token) node .github/scripts/star-history-chart.mjs -->
- <a href="https://star-history.com/#pollinations/pollinations&Date">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset=".github/assets/star-history-dark.svg" width="600" />
- <source media="(prefers-color-scheme: light)" srcset=".github/assets/star-history-light.svg" width="600" />
- <img alt="Star History Chart" src=".github/assets/star-history-light.svg" width="600" />
- </picture>
- </a>
- ## 🚀 Key Features
- - 🔓 **100% Open Source**: code, decisions, roadmap all public
- - 🤝 **Community-Built**: 500+ projects already using our APIs
- - 🌱 **Quests**: complete Quests to add to your balance
- - 🖼️ **Image Generation**: Text-to-image and image editing
- - 📝 **Text Generation**: Chat, reasoning, vision, function calling, structured outputs
- - 🎬 **Video Generation**: Text-to-video and image-to-video
- - 🎵 **Audio**: Text-to-speech and speech-to-text
- - 🧊 **3D Generation**: Text-to-3D and image-to-3D
- - 🎙️ **Real-time API**: OpenAI-compatible WebSocket for streaming conversations
- - 🔢 **Embeddings Creation**: Semantic search, retrieval, similarity matching
- - 🤖 **Managed Agents**: Turn a prompt, base model, and optional Pollinations tools into a reusable model
- - 📦 **Sandboxes**: Cloud Linux computers for you or your agents, opened with SSH or VS Code
- - 🌐 **Sites**: Free static hosting at `<name>.pollinations.app`
- - 🎣 **_Easy-to-use Packages_** ([Packages](packages/))
- ## Guides
- | Guide | Purpose |
- | --- | --- |
- | [Pollinations Pay (BYOP)](https://gen.pollinations.ai/docs#tag/pollinations-pay) | Let users pay from their own balance |
- | [Publish an Agent](https://gen.pollinations.ai/docs#tag/publish-an-agent) | Publish a hosted agent |
- | [Publish a Model](https://gen.pollinations.ai/docs#tag/publish-a-model) | Connect your model endpoint |
- | [Sandboxes](https://gen.pollinations.ai/docs#tag/sandboxes) | Run code in a virtual machine |
- | [Sites](https://gen.pollinations.ai/docs#tag/sites) | Host a static site at <name>.pollinations.app |
- | [Coding Harnesses](https://gen.pollinations.ai/docs#tag/coding-harnesses) | Connect a coding assistant |
- | [MCP Servers](https://gen.pollinations.ai/docs#tag/mcp-servers) | Give agents access to tools |
- | [CLI](https://gen.pollinations.ai/docs#tag/cli) | Use Pollinations from a terminal |
- ## 🤖 Managed Agents
- Build a reusable text agent without hosting an agent server. Choose a system prompt and base model, optionally give it Pollinations tools, then call it through the same OpenAI-compatible API as any other model.
- - **Private or public**: keep an agent owner-only or publish it after receiving community publisher access.
- - **Normal model API**: call a registered agent by its `owner/agent-name` model ID.
- - **Dashboard, CLI, or API**: manage agents in [My listings](https://enter.pollinations.ai/my-models), with `polli agents`, or through `/account/agents`.
- See [Publish an Agent](./BUILD_YOUR_OWN_AGENT.md) for setup and billing behavior.
- ## 🛠️ Coding Harnesses
- Run tools such as Bloom CLI, DeepSeek Harness, Hermes Agent, Mistral Vibe, OpenCode, Pi, Prime Agent, and tgpt on Pollinations models. `polli harness` edits the tool's own config so it calls Pollinations with a dedicated key, and restores it on `off`.
- ```bash
- npx @pollinations/cli harness dsh on
- ```
- See [Coding Harnesses](./CODING_HARNESSES.md) for supported harnesses and how to add one.
- ## 🧩 Community Models
- Community members connect their own OpenAI-compatible text, image, image-editing, and speech-to-text endpoints to Pollinations.
- - **Host your own model**: follow [Publish a Model](./BRING_YOUR_OWN_MODEL.md) to test and register an upstream endpoint, then keep it private or publish it to the catalog.
- - **Automatic fallback routing**: nominate up to three compatible backup models so generations keep moving when an upstream model goes down.
- - **Discover and monitor**: browse community models via [gen.pollinations.ai/v1/models](https://gen.pollinations.ai/v1/models) and watch live health and community leaderboards at [model-monitor.pollinations.ai](https://model-monitor.pollinations.ai).
- For billing details when building apps on top, see [Pollinations Pay](./BRING_YOUR_OWN_POLLEN.md).
- ## 🚀 Getting Started
- [](https://deepwiki.com/pollinations/pollinations)
- ### Quick Start (3 Steps)
- 1️⃣ **Get your API key**
- Sign up at [enter.pollinations.ai](https://enter.pollinations.ai/keys) to generate your key.
- 2️⃣ **Choose what you want to generate**
- Pollinations supports:
- - 🖼 Images
- - 📝 Text
- - 🔊 Audio
- - 🎬 Video
- - 🧊 3D
- - 🔢 Embeddings
- 3️⃣ **Make your first request**
- Use one of the examples below to generate your first AI output in seconds.
- ### Image Generation
- ```bash
- curl -H "Authorization: Bearer YOUR_API_KEY" 'https://gen.pollinations.ai/image/a%20beautiful%20sunset' -o image.jpg
- ```
- Or visit [pollinations.ai/play](https://pollinations.ai/play) for an interactive experience.
- ### Text Generation
- ```bash
- curl 'https://gen.pollinations.ai/text/Hello%20world?key=YOUR_API_KEY'
- ```
- ### Audio Generation
- **Simple GET endpoint:**
- ```bash
- curl 'https://gen.pollinations.ai/audio/Hello%20from%20Pollinations?voice=nova&key=YOUR_API_KEY' -o speech.mp3
- ```
- **OpenAI TTS compatible:**
- ```bash
- curl 'https://gen.pollinations.ai/v1/audio/speech' \
- -H 'Content-Type: application/json' \
- -H 'Authorization: Bearer YOUR_API_KEY' \
- -d '{"model": "openai/tts-1", "input": "Hello from Pollinations!", "voice": "nova"}' \
- -o speech.mp3
- ```
- Available voices: `alloy`, `echo`, `fable`, `onyx`, `nova`, `shimmer`, plus [30+ ElevenLabs voices](https://gen.pollinations.ai/docs).
- **Speech-to-text:**
- ```bash
- curl 'https://gen.pollinations.ai/v1/audio/transcriptions' \
- -H "Authorization: Bearer YOUR_API_KEY" \
- -F file=@audio.mp3 \
- -F model=openai/whisper-large-v3
- ```
- ### Video Generation
- ```bash
- curl 'https://gen.pollinations.ai/video/a%20sunset%20timelapse%20over%20the%20ocean?key=YOUR_API_KEY' -o video.mp4
- ```
- Use `duration` to set video length, `aspectRatio` for orientation, and `image[0]`/`image[1]` to pass start/end reference frames. See available video models and capabilities at [gen.pollinations.ai/video/models](https://gen.pollinations.ai/video/models).
- ### 3D Generation
- ```bash
- curl 'https://gen.pollinations.ai/3d/a%20low-poly%20treasure%20chest?model=microsoft/trellis-2&resolution=low&key=YOUR_API_KEY&image=IMAGE_URL' -o model.glb
- ```
- Pass reference image URL(s) via the `image` parameter for image-to-3D models (put `image=` last in the URL, or URL-encode it). See available 3D models at [gen.pollinations.ai/3d/models](https://gen.pollinations.ai/3d/models).
- ### Embeddings
- ```bash
- curl 'https://gen.pollinations.ai/v1/embeddings' \
- -H 'Content-Type: application/json' \
- -H 'Authorization: Bearer YOUR_API_KEY' \
- -d '{"model": "openai/text-embedding-3-small", "input": "Hello world!"}'
- ```
- Pass a string or an array of up to 32 strings (text or multimodal content parts). See available embedding models at [gen.pollinations.ai/embeddings/models](https://gen.pollinations.ai/embeddings/models).
- ### Pollinations CLI
- Generate text, images, audio, video, and more right from your terminal:
- ```bash
- npx @pollinations/cli gen image "cyberpunk city at night" --model black-forest-labs/flux.1-schnell --output city.png
- npx @pollinations/cli gen text "Explain quantum tunneling in one sentence"
- npx @pollinations/cli gen audio "Hello world" --voice nova --output speech.mp3
- npx @pollinations/cli gen video "a waterfall in slow motion" --duration 5 --output clip.mp4
- npx @pollinations/cli gen transcribe speech.mp3
- ```
- Install globally and use the shorter `polli` command: `npm install -g @pollinations/cli`. Run `polli models` to list models, `polli auth login` to authenticate, and `polli docs` for the full API reference in your terminal.
- ### Real-time API
- Stream AI responses over an OpenAI-compatible WebSocket:
- ```
- wss://gen.pollinations.ai/v1/realtime?model=openai/gpt-realtime-2.1&key=sk_YOUR_API_KEY
- ```
- Browser clients pass a user-authorized key from [Pollinations Pay](BRING_YOUR_OWN_POLLEN.md) as a query parameter (`?key=`); server clients can use the `Authorization: Bearer` header instead.
- ### MCP Servers
- Connect Streamable HTTP clients to the hosted Pollinations MCP server:
- ```text
- https://gen.pollinations.ai/mcp/pollinations
- ```
- Send your Pollinations API key as an `Authorization: Bearer` header. See the
- [MCP Servers documentation](https://gen.pollinations.ai/docs#tag/mcp-servers)
- for the full hosted catalog.
- ## 🔐 Authentication
- Get your API key at [enter.pollinations.ai](https://enter.pollinations.ai/keys)
- ### Key Types
- | Key | Prefix | Use Case | Rate Limits | Status |
- | --------------- | ------ | ------------------------------ | ------------------------ | ------- |
- | **App Key** | `pk_` | Identifies your app in Pollinations Pay | Can't authenticate requests | Stable |
- | **Secret** | `sk_` | Server-side only | No rate limits | Stable |
- > ⚠️ **Never expose `sk_` keys** in client-side code, git repos, or public URLs
- > 💡 **Building an app?** Use [Pollinations Pay](./BRING_YOUR_OWN_POLLEN.md): users pay for their own usage, you pay $0
- ### Model Restrictions
- Each API key can be scoped to model categories or specific models. When creating a key at [enter.pollinations.ai](https://enter.pollinations.ai/keys), you can:
- - **Allow all models**: key works with any available model
- - **Restrict to categories**: e.g. only `image`, or `image` and `text`. A key allows every model in its categories, including models added later
- - **Restrict to specific models**: through the [API](APIDOCS.md) or `polli keys update <id> --models black-forest-labs/flux.1-schnell tongyi-mai/z-image-turbo`; a model ID allows only that model
- ### Usage
- ```bash
- curl 'https://gen.pollinations.ai/image/a%20cat?key=YOUR_KEY'
- ```
- **Environment variable (best practice):**
- ```bash
- export POLLINATIONS_API_KEY=sk_...
- ```
- See [full API docs](APIDOCS.md) for detailed authentication information.
- ## 🖥️ How to Use
- ### Web Interface
- Visit [the playground](https://pollinations.ai/play) to generate content in your browser.
- Here are some examples of what you can generate:
- <p align="center"><img src="https://media.pollinations.ai/9e0df3b04d27666c" alt="Pixel art robot and bee in a cozy digital garden: Stardew Valley style" width="800" /></p>
- <p align="center"><img src="https://media.pollinations.ai/ec34c8a3c45c42d9" alt="Robot holding generated image saying I CAN SEE, nomnom creature eating prompt text" width="800" /></p>
- ## 🛠️ Integration
- ### SDK
- Check out our [Pollinations SDK](./packages/sdk/README.md) for Node.js, browser, and React integration.
- ### OpenAI SDK Compatibility
- The API is OpenAI-compatible. Set the base URL in an official OpenAI SDK to `https://gen.pollinations.ai/v1`.
- **Node.js:**
- ```javascript
- import OpenAI from "openai";
- const client = new OpenAI({
- baseURL: "https://gen.pollinations.ai/v1",
- apiKey: "YOUR_API_KEY",
- });
- const response = await client.chat.completions.create({
- model: "openai/gpt-5.4-nano",
- messages: [{ role: "user", content: "Hello!" }],
- });
- console.log(response.choices[0].message.content);
- ```
- **Python:**
- ```python
- from openai import OpenAI
- client = OpenAI(base_url="https://gen.pollinations.ai/v1", api_key="YOUR_API_KEY")
- response = client.chat.completions.create(
- model="openai/gpt-5.4-nano",
- messages=[{"role": "user", "content": "Hello!"}],
- )
- print(response.choices[0].message.content)
- ```
- Other OpenAI SDKs work too: [Go](https://github.com/openai/openai-go), [Java](https://github.com/openai/openai-java), [.NET](https://github.com/openai/openai-dotnet), [Rust (async-openai, community)](https://github.com/64bit/async-openai), plus compatible frameworks like [Vercel AI SDK](https://ai-sdk.dev/).
- **Vercel AI SDK:**
- ```typescript
- import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
- import { generateText } from "ai";
- const pollinations = createOpenAICompatible({
- name: "pollinations",
- baseURL: "https://gen.pollinations.ai/v1",
- apiKey: "YOUR_API_KEY",
- });
- const { text } = await generateText({
- model: pollinations.chatModel("openai/gpt-5.4-nano"),
- prompt: "Hello!",
- });
- console.log(text);
- ```
- Streaming, image, and embedding examples: [API docs → Vercel AI SDK](APIDOCS.md#-vercel-ai-sdk).
- ## Architecture
- ```mermaid
- %%{init: {'theme': 'dark', 'themeVariables': { 'background': '#1a1a1a', 'primaryColor': '#2a2a2a', 'primaryBorderColor': '#555555', 'primaryTextColor': '#eeeeee', 'lineColor': '#00e5ff', 'clusterBkg': 'transparent', 'clusterBorder': '#888888', 'fontSize': '13px', 'fontFamily': 'Inter, system-ui, sans-serif'}}}%%
- graph LR
- subgraph CLIENTS["Clients / Apps"]
- Q[Bots - Discord, Telegram, WhatsApp]
- N[30+ Mobile and Web Apps]
- A[pollinations.ai Web Frontend]
- R[AI Agents - Qwen, Sillytavern, ...]
- AI[AI Assistants - Claude]
- MCP[MCP Server]
- end
- AI --> MCP
- Q --> GEN
- N --> GEN
- A --> GEN
- R --> GEN
- MCP --> GEN
- GEN["gen.pollinations.ai: Edge Router + Generation Worker"]:::cfWorker -->|auth and billing| ENTER["enter.pollinations.ai: Auth Gateway + Billing"]:::cfWorker
- GEN --> IMG["Image: gen Worker dispatch to providers / GPU backends"]:::cfWorkerLight
- IMG --> D["Flux, Z-Image, Seedream, ...: GPU VMs"]:::gpuNode
- GEN --> TXT["Text: Portkey multi-provider"]:::provider
- GEN --> VID["Video: Wan / Veo / Seedance"]:::provider
- GEN --> AUD["Audio: ElevenLabs / OVH (Whisper)"]:::provider
- style CLIENTS fill:none,stroke:#888,stroke-width:2px,stroke-dasharray: 5 5
- linkStyle default stroke-width:3px,stroke:#00E5FF
- classDef cfWorker fill:#E65100,color:#fff,stroke:#FFB300,stroke-width:2px,font-weight:bold
- classDef cfWorkerLight fill:#BF360C,color:#fff,stroke:#FFB300,stroke-width:1px
- classDef gpuNode fill:#064E3B,stroke:#34D399,color:#ECFDF5,stroke-width:2px
- classDef provider fill:#1E3A8A,stroke:#60A5FA,color:#EFF6FF,stroke-width:1px
- ```
- ## 🔮 Future Developments
- We're exploring:
- - Digital Twins: Creating interactive AI-driven avatars
- - Music Video Generation: Combining AI-generated visuals with music
- - Real-time AI-driven Visual Experiences: Projects like our Dreamachine
- ## 🌍 Our Vision
- We want AI tools to be:
- - **Open & Accessible**: Add to your balance by contributing, without a credit card
- - **Transparent & Ethical**: Inspect our code and discuss how the platform works
- - **Community-Driven**: Build tools with other developers, creators, and AI enthusiasts
- - **Interconnected**: Combine models and services through shared APIs
- - **Evolving**: Add new capabilities while keeping the platform open and accessible
- ## 🤝 Community and Development
- You can contribute to pollinations.ai in several ways:
- 1. **Coding Assistant**: [Create a GitHub issue](https://github.com/pollinations/pollinations/issues/new) describing a feature for the Polli assistant to work on. You can propose a change without writing code.
- 2. **Project Submissions**: Have you built something with pollinations.ai? [Use our app submission template](https://github.com/pollinations/pollinations/issues/new?template=app-submission.yml) to share it with the community and get it featured in our README.
- 3. **Feature Requests & Bug Reports**: Have an idea or found a bug? [Open an issue](https://github.com/pollinations/pollinations/issues/new) and let us know. Our team and the Polli assistant will review it.
- 4. **Community Engagement**: Join our [Discord community](https://discord.gg/k9F7SyTgqn) to:
- - Share your creations
- - Get support and help others
- - Collaborate with fellow AI enthusiasts
- - Discuss feature ideas before creating issues
- For any questions or support, please visit our [Discord channel](https://discord.gg/k9F7SyTgqn) or create an issue on our [GitHub repository](https://github.com/pollinations/pollinations).
- ## 🗂️ Project Structure
- The main folders are:
- - [`pollinations.ai/`](./pollinations.ai/): The main React application for the Pollinations.ai website.
- - [`gen.pollinations.ai/`](./gen.pollinations.ai/): Cloudflare Worker for API routing, auth handoff, text generation, and caching.
- - [`enter.pollinations.ai/`](./enter.pollinations.ai/): Auth gateway and billing: API keys, balances, and top-up checkout.
- - [`shared/`](./shared/): Auth, model registries, IP queue, and utilities shared across the services.
- - [`apps/`](./apps/): Applications maintained in this repository.
- - [`operations/`](./operations/): Internal dashboards, monitoring, economics,
- and infrastructure, including the
- [GPU fleet](./operations/infrastructure/gpu/GPU_INSTANCES.md).
- - [`media.pollinations.ai/`](./media.pollinations.ai/): Media upload service: upload files and get a URL to use with Pollinations models, with public tag galleries.
- - [`operations/news/`](./operations/news/): Automated social media pipeline (X, LinkedIn, Instagram, Reddit, Discord).
- - [`packages/polli-cli/`](./packages/polli-cli/): The Pollinations CLI for people and AI agents.
- - [`packages/sdk/`](./packages/sdk/): SDK NPM library with pollinations ready functions for Pollinations.ai.
- - [`packages/mcp/`](./packages/mcp/): Model Context Protocol (MCP) server for AI assistants like Claude to generate images directly.
- - [`opencode-pollinations-plugin`](https://github.com/fkom13/opencode-pollinations-plugin): A community plugin that connects OpenCode to Pollinations models, built by [@fkom13](https://github.com/fkom13).
- For development setup and environment management, see [DEVELOP.md](./DEVELOP.md).
- ## 🏢 Supported By
- > pollinations.ai is supported by:
- <p align="center"><img src="https://media.pollinations.ai/3f7405eb2d6f57b7" alt="Pixel art garden shelf: supporter plants in labeled pots, robot watering, bee with watering can" width="800" /></p>
- - [Perplexity AI](https://www.perplexity.ai/): AI-powered search and conversational answer engine
- - [AWS Activate](https://aws.amazon.com/): GPU Cloud Credits
- - [io.net](https://io.net/): Decentralized GPU network for AI compute
- - [BytePlus](https://www.byteplus.com/): Official ByteDance cloud services and AI solutions
- - [Google Cloud for Startups](https://cloud.google.com/): GPU Cloud Credits
- - [NVIDIA Inception](https://www.nvidia.com/en-us/deep-learning-ai/startups/): AI startup support
- - [Azure (MS for Startups)](https://azure.microsoft.com/): OpenAI credits
- - [Cloudflare](https://developers.cloudflare.com/workers-ai/): Put the connectivity cloud to work for you.
- - [Scaleway](https://www.scaleway.com/): Europe's empowering cloud provider
- - [Modal](https://modal.com/): High-performance AI infrastructure
- - [Nebius](https://nebius.com/): AI-optimized cloud infrastructure with NVIDIA GPU clusters
- - [OpenAI](https://openai.com/): Frontier AI models and APIs
- - [OpenRouter](https://openrouter.ai/): Unified API for LLMs
- - [Fireworks AI](https://fireworks.ai/): Fast inference platform for open models
- - [Replicate](https://replicate.com/): Run AI models with an API
- - [RunPod](https://www.runpod.io/): GPU cloud built for AI workloads
- - [OVHcloud](https://www.ovhcloud.com/): European cloud and GPU infrastructure
- - [Lambda Labs](https://lambda.ai/): GPU cloud for AI training and inference
- - [ElevenLabs](https://elevenlabs.io/): AI voice generation and text-to-speech
- - [AssemblyAI](https://www.assemblyai.com/): Speech-to-text and speech understanding models
- - [Alibaba Cloud](https://www.alibabacloud.com/): Cloud computing and AI services
- ## 💚 Support Us
- The best way to support pollinations.ai is by using our product! Get your API key and start building at **[enter.pollinations.ai](https://enter.pollinations.ai/keys)**.
- ## 📣 Stay Connected
- [Status](https://model-monitor.pollinations.ai) ·
- [News & FAQ](https://enter.pollinations.ai/news) ·
- [𝕏 Twitter](https://x.com/pollinations_ai) · [Instagram](https://instagram.com/pollinations_ai) · [LinkedIn](https://www.linkedin.com/company/pollinations-ai) · [Facebook](https://facebook.com/pollinations) · [Reddit](https://www.reddit.com/r/pollinations_ai/) · [YouTube](https://www.youtube.com/c/pollinations)
- ## 📜 License
- pollinations.ai is open-source software licensed under the [MIT license](LICENSE).
- ---
- Made with ❤️ by the pollinations.ai team
packages/polli-cli/src/harnesses/hermes.ts · Bundled script · 259 lines · 2 findings marked
- import { readdirSync, rmdirSync } from "node:fs";
- import { join } from "node:path";
- import { parseEnv } from "node:util";
- import { isMap, parseDocument } from "yaml";
- import polliSkill from "../../SKILL.md?raw";
- import { BASE_URL } from "../lib/config.js";
- import {
- commandExists,
- readTextIfExists,
- removeIfExists,
- resolveHomePath,
- writeTextAtomic,
- } from "./fs.js";
- import { resolveHarnessKey } from "./keys.js";
- import { fetchHarnessModels } from "./models.js";
- import { applyWithSnapshot, restoreOrStrip } from "./snapshot.js";
- import type { HarnessAdapter, HarnessContext, HarnessResult } from "./types.js";
- const ID = "hermes";
- const LABEL = "Hermes Agent";
- const PROVIDER = "pollinations";
- const DEFAULT_MODEL = "openai/gpt-6-sol";
- const KEY_ENV = "POLLI_HERMES_API_KEY";
- // Never fold long scalars (the API key) across lines.
- const YAML_OUT = { lineWidth: 0 };
- /**
- * Hermes home: HERMES_HOME wins, else the platform default Hermes itself uses
- * (`%LOCALAPPDATA%\hermes` on Windows, `~/.hermes` elsewhere).
- */
- export const hermesHome = (ctx: HarnessContext) => {
- const configured = ctx.env.HERMES_HOME;
- if (configured?.trim()) return resolveHomePath(ctx.home, configured);
- if (process.platform === "win32") {
- const base =
- ctx.env.LOCALAPPDATA?.trim() ?? join(ctx.home, "AppData", "Local");
- return join(base, "hermes");
- }
- return join(ctx.home, ".hermes");
- };
- const configPath = (ctx: HarnessContext) =>
- join(hermesHome(ctx), "config.yaml");
- const envPath = (ctx: HarnessContext) => join(hermesHome(ctx), ".env");
- // Hermes scans $HERMES_HOME/skills/ recursively for SKILL.md files.
- const skillDir = (ctx: HarnessContext) =>
- join(hermesHome(ctx), "skills", "polli");
- const skillPath = (ctx: HarnessContext) => join(skillDir(ctx), "SKILL.md");
- const files = (ctx: HarnessContext) => [
- configPath(ctx),
- envPath(ctx),
- skillPath(ctx),
- ];
- // parseDocument keeps comments and untouched entries intact on rewrite.
- const loadYaml = (path: string) => {
- const doc = parseDocument(readTextIfExists(path) ?? "");
- if (doc.errors.length) throw doc.errors[0];
- if (doc.contents === null) doc.contents = doc.createNode({}) as never;
- return doc;
- };
- const readKey = (ctx: HarnessContext) => {
- const text = readTextIfExists(envPath(ctx));
- if (text === null) return null;
- const key = parseEnv(text)[KEY_ENV];
- return key || null;
- };
- const envLine = (key: string) => `${KEY_ENV}=${JSON.stringify(key)}`;
- const keyLine = new RegExp(`^\\s*(?:export\\s+)?${KEY_ENV}\\s*=`, "u");
- const setEnvKey = (ctx: HarnessContext, key: string) => {
- const lines = (readTextIfExists(envPath(ctx)) ?? "").split("\n");
- const index = lines.findIndex((line) => keyLine.test(line));
- const filtered = lines.filter(
- (line, i) => i === index || !keyLine.test(line),
- );
- if (index === -1) {
- const insertAt =
- filtered.at(-1) === "" ? filtered.length - 1 : filtered.length;
- filtered.splice(insertAt, 0, envLine(key));
- } else filtered[index] = envLine(key);
- writeTextAtomic(envPath(ctx), filtered.join("\n"), 0o600);
- };
- const deleteEnvKey = (ctx: HarnessContext) => {
- const text = readTextIfExists(envPath(ctx));
- if (text === null) return false;
- const lines = text.split("\n");
- const filtered = lines.filter((line) => !keyLine.test(line));
- if (filtered.length === lines.length) return false;
- writeTextAtomic(envPath(ctx), filtered.join("\n"), 0o600);
- return true;
- };
- const ownsProvider = (doc: ReturnType<typeof loadYaml>) =>
- doc.getIn(["providers", PROVIDER, "api"]) === `${BASE_URL}/v1` &&
- doc.getIn(["providers", PROVIDER, "key_env"]) === KEY_ENV;
- const writeConfig = (ctx: HarnessContext, model: string) => {
- const doc = loadYaml(configPath(ctx));
- if (!isMap(doc.contents)) {
- throw new Error(`${configPath(ctx)} must contain a YAML mapping`);
- }
- if (doc.hasIn(["providers", PROVIDER]) && !ownsProvider(doc)) {
- throw new Error(
- "An existing pollinations provider has different settings; leaving it unchanged.",
- );
- }
- // A named custom provider: Hermes reads the key from key_env and
- // discovers the live model catalog from the OpenAI-compatible endpoint.
- doc.setIn(["providers", PROVIDER, "name"], "Pollinations");
- doc.setIn(["providers", PROVIDER, "api"], `${BASE_URL}/v1`);
- doc.setIn(["providers", PROVIDER, "key_env"], KEY_ENV);
- doc.setIn(["model", "provider"], PROVIDER);
- doc.setIn(["model", "default"], model);
- writeTextAtomic(configPath(ctx), doc.toString(YAML_OUT), 0o600);
- };
- const stripConfig = (ctx: HarnessContext) => {
- const doc = loadYaml(configPath(ctx));
- if (!isMap(doc.contents)) return false;
- let changed = false;
- if (!ownsProvider(doc)) return false;
- for (const field of ["name", "api", "key_env"]) {
- doc.deleteIn(["providers", PROVIDER, field]);
- }
- const provider = doc.getIn(["providers", PROVIDER]);
- if (isMap(provider) && provider.items.length === 0) {
- doc.deleteIn(["providers", PROVIDER]);
- }
- changed = true;
- // Only unwind the default when this provider still owns it, so a model the
- // user moved to another provider survives.
- if (doc.getIn(["model", "provider"]) === PROVIDER) {
- doc.deleteIn(["model", "provider"]);
- doc.deleteIn(["model", "default"]);
- changed = true;
- }
- if (changed)
- writeTextAtomic(configPath(ctx), doc.toString(YAML_OUT), 0o600);
- return changed;
- };
- const writeSkill = (ctx: HarnessContext) => {
- if (readTextIfExists(skillPath(ctx)) === null) {
- writeTextAtomic(skillPath(ctx), polliSkill, 0o600);
- }
- };
- const stripSkill = (ctx: HarnessContext) => {
- if (readTextIfExists(skillPath(ctx)) === polliSkill) {
- removeIfExists(skillPath(ctx));
- return true;
- }
- return false;
- };
- /** Drop the `skills/polli` dir once it is empty, so `off` leaves no trace. */
- const cleanupSkillDir = (ctx: HarnessContext) => {
- try {
- if (readdirSync(skillDir(ctx)).length === 0) rmdirSync(skillDir(ctx));
- } catch {
- // Directory absent or still holds user files; nothing to clean.
- }
- };
- const result = (ctx: HarnessContext): HarnessResult => {
- const doc = loadYaml(configPath(ctx));
- const configured =
- isMap(doc.contents) &&
- ownsProvider(doc) &&
- doc.getIn(["model", "provider"]) === PROVIDER &&
- readKey(ctx) !== null &&
- readTextIfExists(skillPath(ctx)) !== null;
- const model = doc.getIn(["model", "default"]);
- return {
- harness: ID,
- label: LABEL,
- installed: hermesInstalled(ctx),
- configured,
- model: configured && typeof model === "string" ? model : undefined,
- files: files(ctx),
- };
- };
- interface HermesSettings {
- apiKey: string;
- model: string;
- }
- const writeAll = (ctx: HarnessContext, settings: HermesSettings) => {
- writeConfig(ctx, settings.model);
- setEnvKey(ctx, settings.apiKey);
- writeSkill(ctx);
- };
- const stripAll = (ctx: HarnessContext) => {
- if (!ownsProvider(loadYaml(configPath(ctx)))) return false;
- let changed = stripConfig(ctx);
- changed = deleteEnvKey(ctx) || changed;
- changed = stripSkill(ctx) || changed;
- return changed;
- };
- export const configureHermes = (
- ctx: HarnessContext,
- settings: HermesSettings,
- ): HarnessResult => {
- applyWithSnapshot(ctx, ID, files(ctx), () => writeAll(ctx, settings));
- return result(ctx);
- };
- export const disableHermes = (ctx: HarnessContext): HarnessResult => {
- const outcome = restoreOrStrip(ctx, ID, files(ctx), () => stripAll(ctx));
- cleanupSkillDir(ctx);
- return { ...result(ctx), configured: false, outcome };
- };
- const INSTALL_HINT =
- process.platform === "win32"
- ? "iex (irm https://hermes-agent.nousresearch.com/install.ps1)"
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 225 on GitHub
- : "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash";
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 226 on GitHub
- const hermesInstalled = (ctx: HarnessContext) =>
- commandExists("hermes", ctx.env, [
- join(hermesHome(ctx), "hermes-agent", "hermes"),
- join(hermesHome(ctx), "bin", "hermes"),
- ]);
- export const hermes = {
- id: ID,
- label: LABEL,
- description: "Configure Hermes Agent to use Pollinations",
- restartHint:
- "Start a new Hermes session to pick up the provider and skill. Run hermes model to switch models.",
- async on(ctx, options) {
- if (!hermesInstalled(ctx)) {
- throw new Error(
- `Hermes Agent was not found. Install it first: ${INSTALL_HINT}`,
- );
- }
- const { model } = await fetchHarnessModels(
- options.model ?? DEFAULT_MODEL,
- );
- const apiKey = await resolveHarnessKey(
- { id: ID, label: LABEL, existingKey: readKey(ctx) },
- { browser: options.browser },
- );
- return configureHermes(ctx, { apiKey, model });
- },
- off: disableHermes,
- status: result,
- } satisfies HarnessAdapter;
packages/polli-cli/src/harnesses/opencode.ts · Bundled script · 303 lines · 1 finding marked
- import { join } from "node:path";
- import JSON5 from "json5";
- import { BASE_URL } from "../lib/config.js";
- import {
- commandExists,
- readTextIfExists,
- removeIfExists,
- resolveHomePath,
- writeTextAtomic,
- } from "./fs.js";
- import { resolveHarnessKey } from "./keys.js";
- import { fetchHarnessModels } from "./models.js";
- import { applyWithSnapshot, restoreOrStrip } from "./snapshot.js";
- import type {
- HarnessAdapter,
- HarnessContext,
- HarnessModel,
- HarnessResult,
- } from "./types.js";
- const ID = "opencode";
- const LABEL = "OpenCode";
- const PROVIDER = "pollinations";
- const DEFAULT_MODEL = "openai/gpt-6-sol";
- const PROVIDER_NPM = "@ai-sdk/openai-compatible";
- /**
- * OpenCode's config schema requires `limit.output` alongside `limit.context`
- * and rejects the whole file without it ("Configuration is invalid ... Missing
- * key ...limit.output"). The models API exposes no output cap, so this is a
- * fallback, not a per-model limit.
- */
- const MAX_OUTPUT_TOKENS = 32768;
- /** The 1.x plugin earlier versions of `on` enabled; cleaned up when found. */
- const LEGACY_PLUGIN = "opencode-pollinations-plugin";
- /**
- * OpenCode 1.x and 2.0 both read the 1.x `provider` block: 2.0 normalizes V1
- * config in memory and no longer loads 1.x plugins, which is why `on` writes a
- * `pollinations` provider instead of enabling `opencode-pollinations-plugin`.
- * The block lists the models `on` already fetches, so one config serves both
- * versions and the provider's `options.apiKey` is where both read the key.
- */
- const legacyConfigDir = (ctx: HarnessContext) => {
- if (process.platform === "win32") {
- return join(ctx.env.APPDATA ?? ctx.home, "pollinations");
- }
- if (process.platform === "darwin") {
- return join(ctx.home, "Library", "Application Support", "pollinations");
- }
- const xdg = ctx.env.XDG_CONFIG_HOME?.trim();
- return join(
- xdg ? resolveHomePath(ctx.home, xdg) : join(ctx.home, ".config"),
- "pollinations",
- );
- };
- export const opencodeConfigFile = (ctx: HarnessContext) => {
- if (ctx.env.OPENCODE_CONFIG?.trim()) {
- return resolveHomePath(ctx.home, ctx.env.OPENCODE_CONFIG);
- }
- const dir = ctx.env.OPENCODE_CONFIG_DIR?.trim()
- ? resolveHomePath(ctx.home, ctx.env.OPENCODE_CONFIG_DIR)
- : join(ctx.home, ".config", "opencode");
- return (
- ["opencode.jsonc", "opencode.json", "config.json"]
- .map((name) => join(dir, name))
- .find((path) => readTextIfExists(path) !== null) ??
- join(dir, "opencode.json")
- );
- };
- /** `~/.config/pollinations/config.json`, written by the removed 1.x plugin. */
- const legacyKeyFile = (ctx: HarnessContext) =>
- join(legacyConfigDir(ctx), "config.json");
- const files = (ctx: HarnessContext) => [
- opencodeConfigFile(ctx),
- legacyKeyFile(ctx),
- ];
- const readJson = (path: string): Record<string, unknown> | null => {
- const text = readTextIfExists(path);
- if (text === null) return null;
- try {
- const parsed = JSON5.parse(text);
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
- return parsed as Record<string, unknown>;
- }
- } catch (error) {
- throw new Error(`Could not parse OpenCode config at ${path}`, {
- cause: error,
- });
- }
- throw new Error(`OpenCode config at ${path} must contain an object`);
- };
- const writeJson = (path: string, data: unknown) =>
- writeTextAtomic(path, `${JSON.stringify(data, null, 2)}\n`, 0o600);
- const openCodeConfig = (ctx: HarnessContext): Record<string, unknown> =>
- readJson(opencodeConfigFile(ctx)) ?? {};
- const providersOf = (config: Record<string, unknown>) => {
- const providers = config.provider;
- return providers !== null && typeof providers === "object"
- ? (providers as Record<string, unknown>)
- : {};
- };
- const isOurProvider = (entry: unknown): entry is Record<string, unknown> => {
- if (entry === null || typeof entry !== "object") return false;
- const options = (entry as Record<string, unknown>).options;
- return (
- options !== null &&
- typeof options === "object" &&
- (options as Record<string, unknown>).baseURL === `${BASE_URL}/v1`
- );
- };
- /** The plugin entry `on` used to add, in string or object form. */
- const isLegacyPlugin = (entry: unknown) =>
- typeof entry === "string"
- ? entry === LEGACY_PLUGIN || entry.includes(LEGACY_PLUGIN)
- : entry !== null &&
- typeof entry === "object" &&
- Object.values(entry).some(
- (value) =>
- typeof value === "string" && value.includes(LEGACY_PLUGIN),
- );
- const pluginListKey = (config: Record<string, unknown>) =>
- Array.isArray(config.plugins) && !Array.isArray(config.plugin)
- ? "plugins"
- : "plugin";
- const removeLegacyPlugin = (config: Record<string, unknown>) => {
- const key = pluginListKey(config);
- const entries = config[key];
- if (!Array.isArray(entries) || !entries.some(isLegacyPlugin)) return false;
- const filtered = entries.filter((entry) => !isLegacyPlugin(entry));
- if (filtered.length === 0) delete config[key];
- else config[key] = filtered;
- return true;
- };
- const readKey = (ctx: HarnessContext): string | null => {
- const entry = providersOf(openCodeConfig(ctx))[PROVIDER];
- const key = isOurProvider(entry)
- ? (entry.options as Record<string, unknown>).apiKey
- : undefined;
- return typeof key === "string" && key.length > 5 ? key : null;
- };
- /** Key the removed 1.x plugin stored, reused so `on` need not log in again. */
- const legacyKey = (ctx: HarnessContext): string | null => {
- const key = readJson(legacyKeyFile(ctx))?.apiKey;
- return typeof key === "string" && key.length > 5 ? key : null;
- };
- /** Drops the removed plugin's key, keeping its other settings (as main did). */
- const deleteLegacyKey = (ctx: HarnessContext) => {
- const path = legacyKeyFile(ctx);
- const config = readJson(path);
- if (config === null || config.apiKey === undefined) return false;
- delete config.apiKey;
- if (Object.keys(config).length === 0) removeIfExists(path);
- else writeJson(path, config);
- return true;
- };
- const providerBlock = (models: HarnessModel[], apiKey: string) => ({
- npm: PROVIDER_NPM,
- name: "Pollinations",
- options: { baseURL: `${BASE_URL}/v1`, apiKey },
- models: Object.fromEntries(
- models.map((model) => [
- model.id,
- {
- name: model.id,
- tool_call: true,
- limit: {
- context: model.contextWindow,
- output: Math.min(model.contextWindow, MAX_OUTPUT_TOKENS),
- },
- modalities: { input: model.input, output: ["text"] },
- },
- ]),
- ),
- });
- const writeConfig = (
- ctx: HarnessContext,
- settings: { apiKey: string; model: string; models: HarnessModel[] },
- ) => {
- const path = opencodeConfigFile(ctx);
- const config = openCodeConfig(ctx);
- if (typeof config.$schema !== "string") {
- config.$schema = "https://opencode.ai/config.json";
- }
- config.provider = {
- ...providersOf(config),
- [PROVIDER]: providerBlock(settings.models, settings.apiKey),
- };
- config.model = `${PROVIDER}/${settings.model}`;
- removeLegacyPlugin(config);
- writeJson(path, config);
- // The provider block above now carries the key.
- deleteLegacyKey(ctx);
- };
- const stripConfig = (ctx: HarnessContext): boolean => {
- let changed = false;
- const path = opencodeConfigFile(ctx);
- const config = readJson(path);
- if (config !== null) {
- const providers = providersOf(config);
- if (isOurProvider(providers[PROVIDER])) {
- delete providers[PROVIDER];
- if (Object.keys(providers).length === 0) delete config.provider;
- else config.provider = providers;
- changed = true;
- }
- if (isOurModel(config.model)) {
- delete config.model;
- changed = true;
- }
- if (removeLegacyPlugin(config)) changed = true;
- if (changed) writeJson(path, config);
- }
- if (deleteLegacyKey(ctx)) changed = true;
- return changed;
- };
- const isOurModel = (model: unknown) =>
- typeof model === "string" && model.startsWith(`${PROVIDER}/`);
- const result = (ctx: HarnessContext): HarnessResult => {
- const config = openCodeConfig(ctx);
- const model = isOurModel(config.model)
- ? (config.model as string).slice(PROVIDER.length + 1)
- : undefined;
- return {
- harness: ID,
- label: LABEL,
- configured:
- isOurProvider(providersOf(config)[PROVIDER]) &&
- isOurModel(config.model) &&
- readKey(ctx) !== null,
- model,
- files: files(ctx),
- };
- };
- export const configureOpenCode = (
- ctx: HarnessContext,
- settings: { apiKey: string; model: string; models: HarnessModel[] },
- ): HarnessResult => {
- applyWithSnapshot(ctx, ID, files(ctx), () => writeConfig(ctx, settings));
- return result(ctx);
- };
- export const disableOpenCode = (ctx: HarnessContext): HarnessResult => {
- const outcome = restoreOrStrip(ctx, ID, files(ctx), () => stripConfig(ctx));
- return { ...result(ctx), configured: false, outcome };
- };
- const openCodeInstalled = (ctx: HarnessContext) =>
- commandExists("opencode", ctx.env, [
- join(ctx.home, ".opencode", "bin", "opencode"),
- ]);
- export const opencode = {
- id: ID,
- label: LABEL,
- description: "Configure OpenCode to use Pollinations",
- restartHint:
- "Restart OpenCode, then pick a Pollinations model with /models. Run `polli mcp install opencode --all` to add the media tools.",
- async on(ctx, options) {
- if (!openCodeInstalled(ctx)) {
- throw new Error(
- "OpenCode was not found. Install it first: curl -fsSL https://opencode.ai/install | bash",
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 284 on GitHub
- );
- }
- const { model, models } = await fetchHarnessModels(
- options.model ?? DEFAULT_MODEL,
- );
- const apiKey = await resolveHarnessKey(
- {
- id: ID,
- label: LABEL,
- existingKey: readKey(ctx) ?? legacyKey(ctx),
- },
- { browser: options.browser },
- );
- return configureOpenCode(ctx, { apiKey, model, models });
- },
- off: disableOpenCode,
- status: result,
- } satisfies HarnessAdapter;
packages/polli-cli/src/harnesses/prime.ts · Bundled script · 234 lines · 1 finding marked
- import { join } from "node:path";
- import polliSkill from "../../SKILL.md?raw";
- import { BASE_URL } from "../lib/config.js";
- import {
- commandExists,
- readTextIfExists,
- removeIfExists,
- resolveHomePath,
- writeTextAtomic,
- } from "./fs.js";
- import { resolveHarnessKey } from "./keys.js";
- import { fetchHarnessModels } from "./models.js";
- import { applyWithSnapshot, restoreOrStrip } from "./snapshot.js";
- import type {
- HarnessAdapter,
- HarnessContext,
- HarnessModel,
- HarnessResult,
- } from "./types.js";
- const ID = "prime";
- const LABEL = "Prime Agent";
- const PROVIDER = "pollinations";
- const DEFAULT_MODEL = "openai/gpt-6-sol";
- /** Prime Agent resolves its agent dir from this override, tilde included. */
- export const primeAgentDir = (ctx: HarnessContext) => {
- const configured = ctx.env.PRIME_AGENT_CODING_AGENT_DIR;
- if (!configured?.trim()) return join(ctx.home, ".prime", "agent");
- return resolveHomePath(ctx.home, configured);
- };
- const modelsPath = (ctx: HarnessContext) =>
- join(primeAgentDir(ctx), "models.json");
- const authPath = (ctx: HarnessContext) => join(primeAgentDir(ctx), "auth.json");
- const settingsPath = (ctx: HarnessContext) =>
- join(primeAgentDir(ctx), "settings.json");
- const skillPath = (ctx: HarnessContext) =>
- join(primeAgentDir(ctx), "skills", "polli", "SKILL.md");
- const files = (ctx: HarnessContext) => [
- modelsPath(ctx),
- authPath(ctx),
- settingsPath(ctx),
- skillPath(ctx),
- ];
- const loadJson = (path: string): Record<string, unknown> => {
- const text = readTextIfExists(path);
- if (!text?.trim()) return {};
- return JSON.parse(text) as Record<string, unknown>;
- };
- const saveJson = (path: string, data: Record<string, unknown>) => {
- writeTextAtomic(path, `${JSON.stringify(data, null, 2)}\n`, 0o600);
- };
- // Compat flags shared with the dsh provider block: gen.pollinations.ai/v1
- // speaks standard completions without store/developer-role/strict-mode extras.
- const compat = {
- supportsStore: false,
- supportsDeveloperRole: false,
- supportsReasoningEffort: true,
- supportsUsageInStreaming: true,
- supportsStrictMode: false,
- maxTokensField: "max_tokens",
- };
- const providerEntry = (models: HarnessModel[]) => ({
- baseUrl: `${BASE_URL}/v1`,
- api: "openai-completions",
- // Prime validates custom providers before resolving their auth.json entry.
- apiKey: PROVIDER,
- compat,
- models: models.map((model) => ({
- id: model.id,
- name: model.id,
- input: model.input,
- contextWindow: model.contextWindow,
- })),
- });
- interface PrimeModels {
- providers?: Record<string, unknown>;
- [key: string]: unknown;
- }
- type PrimeAuth = Record<string, { type?: string; key?: string }>;
- interface PrimeSettings {
- defaultProvider?: string;
- defaultModel?: string;
- [key: string]: unknown;
- }
- const readKey = (ctx: HarnessContext) => {
- const auth = loadJson(authPath(ctx)) as PrimeAuth;
- const credential = auth[PROVIDER];
- return credential?.type === "api_key" && credential.key
- ? credential.key
- : null;
- };
- const writeAuth = (ctx: HarnessContext, apiKey: string) => {
- const auth = loadJson(authPath(ctx)) as PrimeAuth;
- auth[PROVIDER] = { type: "api_key", key: apiKey };
- saveJson(authPath(ctx), auth);
- };
- const deleteAuth = (ctx: HarnessContext) => {
- const auth = loadJson(authPath(ctx)) as PrimeAuth;
- if (!(PROVIDER in auth)) return false;
- delete auth[PROVIDER];
- if (Object.keys(auth).length === 0) removeIfExists(authPath(ctx));
- else saveJson(authPath(ctx), auth);
- return true;
- };
- const writeConfig = (
- ctx: HarnessContext,
- models: HarnessModel[],
- apiKey: string,
- model: string,
- ) => {
- const doc = loadJson(modelsPath(ctx)) as PrimeModels;
- const providers = (doc.providers ?? {}) as Record<string, unknown>;
- providers[PROVIDER] = providerEntry(models);
- doc.providers = providers;
- saveJson(modelsPath(ctx), doc);
- writeAuth(ctx, apiKey);
- const settings = loadJson(settingsPath(ctx)) as PrimeSettings;
- settings.defaultProvider = PROVIDER;
- settings.defaultModel = model;
- saveJson(settingsPath(ctx), settings);
- if (readTextIfExists(skillPath(ctx)) === null) {
- writeTextAtomic(skillPath(ctx), polliSkill, 0o600);
- }
- };
- const stripConfig = (ctx: HarnessContext) => {
- let changed = false;
- const doc = loadJson(modelsPath(ctx)) as PrimeModels;
- if (doc?.providers && PROVIDER in doc.providers) {
- delete doc.providers[PROVIDER];
- if (Object.keys(doc.providers).length === 0) delete doc.providers;
- saveJson(modelsPath(ctx), doc);
- changed = true;
- }
- changed = deleteAuth(ctx) || changed;
- const settings = loadJson(settingsPath(ctx)) as PrimeSettings;
- if (settings && settings.defaultProvider === PROVIDER) {
- delete settings.defaultProvider;
- delete settings.defaultModel;
- saveJson(settingsPath(ctx), settings);
- changed = true;
- }
- if (readTextIfExists(skillPath(ctx)) === polliSkill) {
- removeIfExists(skillPath(ctx));
- changed = true;
- }
- return changed;
- };
- const result = (ctx: HarnessContext): HarnessResult => {
- const doc = loadJson(modelsPath(ctx)) as PrimeModels;
- const provider = doc?.providers?.[PROVIDER] as
- | { baseUrl?: string; api?: string; apiKey?: string }
- | undefined;
- const settings = loadJson(settingsPath(ctx)) as PrimeSettings;
- const model =
- settings?.defaultProvider === PROVIDER
- ? settings.defaultModel
- : undefined;
- return {
- harness: ID,
- label: LABEL,
- configured:
- provider?.baseUrl === `${BASE_URL}/v1` &&
- provider?.api === "openai-completions" &&
- provider?.apiKey === PROVIDER &&
- readKey(ctx) !== null &&
- readTextIfExists(skillPath(ctx)) !== null,
- model: typeof model === "string" ? model : undefined,
- files: files(ctx),
- };
- };
- export const configurePrime = (
- ctx: HarnessContext,
- models: HarnessModel[],
- apiKey: string,
- model: string,
- ): HarnessResult => {
- applyWithSnapshot(ctx, ID, files(ctx), () =>
- writeConfig(ctx, models, apiKey, model),
- );
- return result(ctx);
- };
- export const disablePrime = (ctx: HarnessContext): HarnessResult => {
- const outcome = restoreOrStrip(ctx, ID, files(ctx), () => stripConfig(ctx));
- return { ...result(ctx), configured: false, outcome };
- };
- export const prime = {
- id: ID,
- label: LABEL,
- description: "Add Pollinations as a custom provider in Prime Agent",
- restartHint:
- "Models reload when you open /model. Start Prime Agent with: prime-agent",
- async on(ctx, options) {
- if (!commandExists("prime-agent", ctx.env)) {
- throw new Error(
- "Prime Agent was not found. Install it first: curl -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh",
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 218 on GitHub
- );
- }
- const { model, models } = await fetchHarnessModels(
- options.model ?? DEFAULT_MODEL,
- );
- const apiKey = await resolveHarnessKey(
- { id: ID, label: LABEL, existingKey: readKey(ctx) },
- { browser: options.browser },
- );
- return configurePrime(ctx, models, apiKey, model);
- },
- off: disablePrime,
- status: result,
- } satisfies HarnessAdapter;
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.