Skip to content
Back to search

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/pollinations--pollinations/badge.svg)](/listings/pollinations--pollinations)

HTML

<a href="/listings/pollinations--pollinations"><img src="/api/listings/pollinations--pollinations/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

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.mp3

Available 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.

  1. <div align="center">
  2. <picture>
  3. <source media="(prefers-color-scheme: dark)" srcset="packages/ui/src/brand/lockup-horizontal-white.svg" />
  4. <img src="packages/ui/src/brand/lockup-horizontal-black.svg" alt="pollinations.ai" width="100%" />
  5. </picture>
  6. <p><strong>Open-source AI for people who make things.</strong></p>
  7. [![Stars](https://img.shields.io/github/stars/pollinations/pollinations?style=for-the-badge&logo=github)](https://github.com/pollinations/pollinations/stargazers)
  8. [![License](https://img.shields.io/github/license/pollinations/pollinations?style=for-the-badge)](LICENSE)
  9. [![Discord](https://img.shields.io/discord/885844321461485618?style=for-the-badge&logo=discord&label=Discord&color=5865F2)](https://discord.gg/k9F7SyTgqn)
  10. [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)
  11. </div>
  12. <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>
  13. <!-- recent-apps:start -->
  14. ## 🆕 Recent Apps
  15. | Name | Description | Author |
  16. |------|-------------|--------|
  17. | [🎮 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) |
  18. | [🎮 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) |
  19. | [🎮 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) |
  20. | [📚 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) |
  21. | [🎮 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) |
  22. | [🎮 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) |
  23. | [🎮 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) |
  24. | [📚 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) |
  25. | [🖼️ 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) |
  26. | [🖼️ 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) |
  27. [Browse all apps →](https://pollinations.ai/apps)
  28. <!-- recent-apps:end -->
  29. ## 🚀 Unified API
  30. **https://gen.pollinations.ai** provides one API for text, images, audio, video, 3D, and embeddings.
  31. ### What's Included
  32. - **Unified endpoint**: single API at `gen.pollinations.ai` for all generation
  33. - **Prepaid credit**: simple pay-as-you-go, priced in dollars
  34. - **All models, one place**: Flux, GPT, Claude, Gemini, Seedream, and more
  35. - **API keys**: secret keys for model usage, app keys for tracking BYOP apps.
  36. - **CLI**: `npx @pollinations/cli` for humans and AI agents ([source](packages/polli-cli))
  37. - **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
  38. > Get started at [enter.pollinations.ai](https://enter.pollinations.ai) and check out the [API docs](https://gen.pollinations.ai/docs)
  39. ## 🆕 Latest News
  40. <!-- Updated daily by .github/workflows/repo-update-readme.yml from the news index. -->
  41. <!-- news:start -->
  42. - [<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.
  43. - [<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.
  44. - [<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.
  45. - [<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.
  46. - [<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.
  47. - [<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.
  48. - [<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.
  49. - [<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.
  50. - [<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.
  51. - [<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.
  52. <!-- news:end -->
  53. [More news on enter.pollinations.ai →](https://enter.pollinations.ai/news)
  54. ---
  55. ## 🌱 Introduction
  56. [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.
  57. <!-- Updated daily by .github/workflows/repo-update-readme.yml.
  58. Regenerate locally with:
  59. GITHUB_TOKEN=$(gh auth token) node .github/scripts/star-history-chart.mjs -->
  60. <a href="https://star-history.com/#pollinations/pollinations&Date">
  61. <picture>
  62. <source media="(prefers-color-scheme: dark)" srcset=".github/assets/star-history-dark.svg" width="600" />
  63. <source media="(prefers-color-scheme: light)" srcset=".github/assets/star-history-light.svg" width="600" />
  64. <img alt="Star History Chart" src=".github/assets/star-history-light.svg" width="600" />
  65. </picture>
  66. </a>
  67. ## 🚀 Key Features
  68. - 🔓 **100% Open Source**: code, decisions, roadmap all public
  69. - 🤝 **Community-Built**: 500+ projects already using our APIs
  70. - 🌱 **Quests**: complete Quests to add to your balance
  71. - 🖼️ **Image Generation**: Text-to-image and image editing
  72. - 📝 **Text Generation**: Chat, reasoning, vision, function calling, structured outputs
  73. - 🎬 **Video Generation**: Text-to-video and image-to-video
  74. - 🎵 **Audio**: Text-to-speech and speech-to-text
  75. - 🧊 **3D Generation**: Text-to-3D and image-to-3D
  76. - 🎙️ **Real-time API**: OpenAI-compatible WebSocket for streaming conversations
  77. - 🔢 **Embeddings Creation**: Semantic search, retrieval, similarity matching
  78. - 🤖 **Managed Agents**: Turn a prompt, base model, and optional Pollinations tools into a reusable model
  79. - 📦 **Sandboxes**: Cloud Linux computers for you or your agents, opened with SSH or VS Code
  80. - 🌐 **Sites**: Free static hosting at `<name>.pollinations.app`
  81. - 🎣 **_Easy-to-use Packages_** ([Packages](packages/))
  82. ## Guides
  83. | Guide | Purpose |
  84. | --- | --- |
  85. | [Pollinations Pay (BYOP)](https://gen.pollinations.ai/docs#tag/pollinations-pay) | Let users pay from their own balance |
  86. | [Publish an Agent](https://gen.pollinations.ai/docs#tag/publish-an-agent) | Publish a hosted agent |
  87. | [Publish a Model](https://gen.pollinations.ai/docs#tag/publish-a-model) | Connect your model endpoint |
  88. | [Sandboxes](https://gen.pollinations.ai/docs#tag/sandboxes) | Run code in a virtual machine |
  89. | [Sites](https://gen.pollinations.ai/docs#tag/sites) | Host a static site at <name>.pollinations.app |
  90. | [Coding Harnesses](https://gen.pollinations.ai/docs#tag/coding-harnesses) | Connect a coding assistant |
  91. | [MCP Servers](https://gen.pollinations.ai/docs#tag/mcp-servers) | Give agents access to tools |
  92. | [CLI](https://gen.pollinations.ai/docs#tag/cli) | Use Pollinations from a terminal |
  93. ## 🤖 Managed Agents
  94. 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.
  95. - **Private or public**: keep an agent owner-only or publish it after receiving community publisher access.
  96. - **Normal model API**: call a registered agent by its `owner/agent-name` model ID.
  97. - **Dashboard, CLI, or API**: manage agents in [My listings](https://enter.pollinations.ai/my-models), with `polli agents`, or through `/account/agents`.
  98. See [Publish an Agent](./BUILD_YOUR_OWN_AGENT.md) for setup and billing behavior.
  99. ## 🛠️ Coding Harnesses
  100. 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`.
  101. ```bash
  102. npx @pollinations/cli harness dsh on
  103. ```
  104. See [Coding Harnesses](./CODING_HARNESSES.md) for supported harnesses and how to add one.
  105. ## 🧩 Community Models
  106. Community members connect their own OpenAI-compatible text, image, image-editing, and speech-to-text endpoints to Pollinations.
  107. - **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.
  108. - **Automatic fallback routing**: nominate up to three compatible backup models so generations keep moving when an upstream model goes down.
  109. - **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).
  110. For billing details when building apps on top, see [Pollinations Pay](./BRING_YOUR_OWN_POLLEN.md).
  111. ## 🚀 Getting Started
  112. [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/pollinations/pollinations)
  113. ### Quick Start (3 Steps)
  114. 1️⃣ **Get your API key**
  115. Sign up at [enter.pollinations.ai](https://enter.pollinations.ai/keys) to generate your key.
  116. 2️⃣ **Choose what you want to generate**
  117. Pollinations supports:
  118. - 🖼 Images
  119. - 📝 Text
  120. - 🔊 Audio
  121. - 🎬 Video
  122. - 🧊 3D
  123. - 🔢 Embeddings
  124. 3️⃣ **Make your first request**
  125. Use one of the examples below to generate your first AI output in seconds.
  126. ### Image Generation
  127. ```bash
  128. curl -H "Authorization: Bearer YOUR_API_KEY" 'https://gen.pollinations.ai/image/a%20beautiful%20sunset' -o image.jpg
  129. ```
  130. Or visit [pollinations.ai/play](https://pollinations.ai/play) for an interactive experience.
  131. ### Text Generation
  132. ```bash
  133. curl 'https://gen.pollinations.ai/text/Hello%20world?key=YOUR_API_KEY'
  134. ```
  135. ### Audio Generation
  136. **Simple GET endpoint:**
  137. ```bash
  138. curl 'https://gen.pollinations.ai/audio/Hello%20from%20Pollinations?voice=nova&key=YOUR_API_KEY' -o speech.mp3
  139. ```
  140. **OpenAI TTS compatible:**
  141. ```bash
  142. curl 'https://gen.pollinations.ai/v1/audio/speech' \
  143. -H 'Content-Type: application/json' \
  144. -H 'Authorization: Bearer YOUR_API_KEY' \
  145. -d '{"model": "openai/tts-1", "input": "Hello from Pollinations!", "voice": "nova"}' \
  146. -o speech.mp3
  147. ```
  148. Available voices: `alloy`, `echo`, `fable`, `onyx`, `nova`, `shimmer`, plus [30+ ElevenLabs voices](https://gen.pollinations.ai/docs).
  149. **Speech-to-text:**
  150. ```bash
  151. curl 'https://gen.pollinations.ai/v1/audio/transcriptions' \
  152. -H "Authorization: Bearer YOUR_API_KEY" \
  153. -F file=@audio.mp3 \
  154. -F model=openai/whisper-large-v3
  155. ```
  156. ### Video Generation
  157. ```bash
  158. curl 'https://gen.pollinations.ai/video/a%20sunset%20timelapse%20over%20the%20ocean?key=YOUR_API_KEY' -o video.mp4
  159. ```
  160. 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).
  161. ### 3D Generation
  162. ```bash
  163. 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
  164. ```
  165. 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).
  166. ### Embeddings
  167. ```bash
  168. curl 'https://gen.pollinations.ai/v1/embeddings' \
  169. -H 'Content-Type: application/json' \
  170. -H 'Authorization: Bearer YOUR_API_KEY' \
  171. -d '{"model": "openai/text-embedding-3-small", "input": "Hello world!"}'
  172. ```
  173. 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).
  174. ### Pollinations CLI
  175. Generate text, images, audio, video, and more right from your terminal:
  176. ```bash
  177. npx @pollinations/cli gen image "cyberpunk city at night" --model black-forest-labs/flux.1-schnell --output city.png
  178. npx @pollinations/cli gen text "Explain quantum tunneling in one sentence"
  179. npx @pollinations/cli gen audio "Hello world" --voice nova --output speech.mp3
  180. npx @pollinations/cli gen video "a waterfall in slow motion" --duration 5 --output clip.mp4
  181. npx @pollinations/cli gen transcribe speech.mp3
  182. ```
  183. 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.
  184. ### Real-time API
  185. Stream AI responses over an OpenAI-compatible WebSocket:
  186. ```
  187. wss://gen.pollinations.ai/v1/realtime?model=openai/gpt-realtime-2.1&key=sk_YOUR_API_KEY
  188. ```
  189. 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.
  190. ### MCP Servers
  191. Connect Streamable HTTP clients to the hosted Pollinations MCP server:
  192. ```text
  193. https://gen.pollinations.ai/mcp/pollinations
  194. ```
  195. Send your Pollinations API key as an `Authorization: Bearer` header. See the
  196. [MCP Servers documentation](https://gen.pollinations.ai/docs#tag/mcp-servers)
  197. for the full hosted catalog.
  198. ## 🔐 Authentication
  199. Get your API key at [enter.pollinations.ai](https://enter.pollinations.ai/keys)
  200. ### Key Types
  201. | Key | Prefix | Use Case | Rate Limits | Status |
  202. | --------------- | ------ | ------------------------------ | ------------------------ | ------- |
  203. | **App Key** | `pk_` | Identifies your app in Pollinations Pay | Can't authenticate requests | Stable |
  204. | **Secret** | `sk_` | Server-side only | No rate limits | Stable |
  205. > ⚠️ **Never expose `sk_` keys** in client-side code, git repos, or public URLs
  206. > 💡 **Building an app?** Use [Pollinations Pay](./BRING_YOUR_OWN_POLLEN.md): users pay for their own usage, you pay $0
  207. ### Model Restrictions
  208. 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:
  209. - **Allow all models**: key works with any available model
  210. - **Restrict to categories**: e.g. only `image`, or `image` and `text`. A key allows every model in its categories, including models added later
  211. - **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
  212. ### Usage
  213. ```bash
  214. curl 'https://gen.pollinations.ai/image/a%20cat?key=YOUR_KEY'
  215. ```
  216. **Environment variable (best practice):**
  217. ```bash
  218. export POLLINATIONS_API_KEY=sk_...
  219. ```
  220. See [full API docs](APIDOCS.md) for detailed authentication information.
  221. ## 🖥️ How to Use
  222. ### Web Interface
  223. Visit [the playground](https://pollinations.ai/play) to generate content in your browser.
  224. Here are some examples of what you can generate:
  225. <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>
  226. <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>
  227. ## 🛠️ Integration
  228. ### SDK
  229. Check out our [Pollinations SDK](./packages/sdk/README.md) for Node.js, browser, and React integration.
  230. ### OpenAI SDK Compatibility
  231. The API is OpenAI-compatible. Set the base URL in an official OpenAI SDK to `https://gen.pollinations.ai/v1`.
  232. **Node.js:**
  233. ```javascript
  234. import OpenAI from "openai";
  235. const client = new OpenAI({
  236. baseURL: "https://gen.pollinations.ai/v1",
  237. apiKey: "YOUR_API_KEY",
  238. });
  239. const response = await client.chat.completions.create({
  240. model: "openai/gpt-5.4-nano",
  241. messages: [{ role: "user", content: "Hello!" }],
  242. });
  243. console.log(response.choices[0].message.content);
  244. ```
  245. **Python:**
  246. ```python
  247. from openai import OpenAI
  248. client = OpenAI(base_url="https://gen.pollinations.ai/v1", api_key="YOUR_API_KEY")
  249. response = client.chat.completions.create(
  250. model="openai/gpt-5.4-nano",
  251. messages=[{"role": "user", "content": "Hello!"}],
  252. )
  253. print(response.choices[0].message.content)
  254. ```
  255. 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/).
  256. **Vercel AI SDK:**
  257. ```typescript
  258. import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
  259. import { generateText } from "ai";
  260. const pollinations = createOpenAICompatible({
  261. name: "pollinations",
  262. baseURL: "https://gen.pollinations.ai/v1",
  263. apiKey: "YOUR_API_KEY",
  264. });
  265. const { text } = await generateText({
  266. model: pollinations.chatModel("openai/gpt-5.4-nano"),
  267. prompt: "Hello!",
  268. });
  269. console.log(text);
  270. ```
  271. Streaming, image, and embedding examples: [API docs → Vercel AI SDK](APIDOCS.md#-vercel-ai-sdk).
  272. ## Architecture
  273. ```mermaid
  274. %%{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'}}}%%
  275. graph LR
  276. subgraph CLIENTS["Clients / Apps"]
  277. Q[Bots - Discord, Telegram, WhatsApp]
  278. N[30+ Mobile and Web Apps]
  279. A[pollinations.ai Web Frontend]
  280. R[AI Agents - Qwen, Sillytavern, ...]
  281. AI[AI Assistants - Claude]
  282. MCP[MCP Server]
  283. end
  284. AI --> MCP
  285. Q --> GEN
  286. N --> GEN
  287. A --> GEN
  288. R --> GEN
  289. MCP --> GEN
  290. GEN["gen.pollinations.ai: Edge Router + Generation Worker"]:::cfWorker -->|auth and billing| ENTER["enter.pollinations.ai: Auth Gateway + Billing"]:::cfWorker
  291. GEN --> IMG["Image: gen Worker dispatch to providers / GPU backends"]:::cfWorkerLight
  292. IMG --> D["Flux, Z-Image, Seedream, ...: GPU VMs"]:::gpuNode
  293. GEN --> TXT["Text: Portkey multi-provider"]:::provider
  294. GEN --> VID["Video: Wan / Veo / Seedance"]:::provider
  295. GEN --> AUD["Audio: ElevenLabs / OVH (Whisper)"]:::provider
  296. style CLIENTS fill:none,stroke:#888,stroke-width:2px,stroke-dasharray: 5 5
  297. linkStyle default stroke-width:3px,stroke:#00E5FF
  298. classDef cfWorker fill:#E65100,color:#fff,stroke:#FFB300,stroke-width:2px,font-weight:bold
  299. classDef cfWorkerLight fill:#BF360C,color:#fff,stroke:#FFB300,stroke-width:1px
  300. classDef gpuNode fill:#064E3B,stroke:#34D399,color:#ECFDF5,stroke-width:2px
  301. classDef provider fill:#1E3A8A,stroke:#60A5FA,color:#EFF6FF,stroke-width:1px
  302. ```
  303. ## 🔮 Future Developments
  304. We're exploring:
  305. - Digital Twins: Creating interactive AI-driven avatars
  306. - Music Video Generation: Combining AI-generated visuals with music
  307. - Real-time AI-driven Visual Experiences: Projects like our Dreamachine
  308. ## 🌍 Our Vision
  309. We want AI tools to be:
  310. - **Open & Accessible**: Add to your balance by contributing, without a credit card
  311. - **Transparent & Ethical**: Inspect our code and discuss how the platform works
  312. - **Community-Driven**: Build tools with other developers, creators, and AI enthusiasts
  313. - **Interconnected**: Combine models and services through shared APIs
  314. - **Evolving**: Add new capabilities while keeping the platform open and accessible
  315. ## 🤝 Community and Development
  316. You can contribute to pollinations.ai in several ways:
  317. 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.
  318. 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.
  319. 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.
  320. 4. **Community Engagement**: Join our [Discord community](https://discord.gg/k9F7SyTgqn) to:
  321. - Share your creations
  322. - Get support and help others
  323. - Collaborate with fellow AI enthusiasts
  324. - Discuss feature ideas before creating issues
  325. 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).
  326. ## 🗂️ Project Structure
  327. The main folders are:
  328. - [`pollinations.ai/`](./pollinations.ai/): The main React application for the Pollinations.ai website.
  329. - [`gen.pollinations.ai/`](./gen.pollinations.ai/): Cloudflare Worker for API routing, auth handoff, text generation, and caching.
  330. - [`enter.pollinations.ai/`](./enter.pollinations.ai/): Auth gateway and billing: API keys, balances, and top-up checkout.
  331. - [`shared/`](./shared/): Auth, model registries, IP queue, and utilities shared across the services.
  332. - [`apps/`](./apps/): Applications maintained in this repository.
  333. - [`operations/`](./operations/): Internal dashboards, monitoring, economics,
  334. and infrastructure, including the
  335. [GPU fleet](./operations/infrastructure/gpu/GPU_INSTANCES.md).
  336. - [`media.pollinations.ai/`](./media.pollinations.ai/): Media upload service: upload files and get a URL to use with Pollinations models, with public tag galleries.
  337. - [`operations/news/`](./operations/news/): Automated social media pipeline (X, LinkedIn, Instagram, Reddit, Discord).
  338. - [`packages/polli-cli/`](./packages/polli-cli/): The Pollinations CLI for people and AI agents.
  339. - [`packages/sdk/`](./packages/sdk/): SDK NPM library with pollinations ready functions for Pollinations.ai.
  340. - [`packages/mcp/`](./packages/mcp/): Model Context Protocol (MCP) server for AI assistants like Claude to generate images directly.
  341. - [`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).
  342. For development setup and environment management, see [DEVELOP.md](./DEVELOP.md).
  343. ## 🏢 Supported By
  344. > pollinations.ai is supported by:
  345. <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>
  346. - [Perplexity AI](https://www.perplexity.ai/): AI-powered search and conversational answer engine
  347. - [AWS Activate](https://aws.amazon.com/): GPU Cloud Credits
  348. - [io.net](https://io.net/): Decentralized GPU network for AI compute
  349. - [BytePlus](https://www.byteplus.com/): Official ByteDance cloud services and AI solutions
  350. - [Google Cloud for Startups](https://cloud.google.com/): GPU Cloud Credits
  351. - [NVIDIA Inception](https://www.nvidia.com/en-us/deep-learning-ai/startups/): AI startup support
  352. - [Azure (MS for Startups)](https://azure.microsoft.com/): OpenAI credits
  353. - [Cloudflare](https://developers.cloudflare.com/workers-ai/): Put the connectivity cloud to work for you.
  354. - [Scaleway](https://www.scaleway.com/): Europe's empowering cloud provider
  355. - [Modal](https://modal.com/): High-performance AI infrastructure
  356. - [Nebius](https://nebius.com/): AI-optimized cloud infrastructure with NVIDIA GPU clusters
  357. - [OpenAI](https://openai.com/): Frontier AI models and APIs
  358. - [OpenRouter](https://openrouter.ai/): Unified API for LLMs
  359. - [Fireworks AI](https://fireworks.ai/): Fast inference platform for open models
  360. - [Replicate](https://replicate.com/): Run AI models with an API
  361. - [RunPod](https://www.runpod.io/): GPU cloud built for AI workloads
  362. - [OVHcloud](https://www.ovhcloud.com/): European cloud and GPU infrastructure
  363. - [Lambda Labs](https://lambda.ai/): GPU cloud for AI training and inference
  364. - [ElevenLabs](https://elevenlabs.io/): AI voice generation and text-to-speech
  365. - [AssemblyAI](https://www.assemblyai.com/): Speech-to-text and speech understanding models
  366. - [Alibaba Cloud](https://www.alibabacloud.com/): Cloud computing and AI services
  367. ## 💚 Support Us
  368. 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)**.
  369. ## 📣 Stay Connected
  370. [Status](https://model-monitor.pollinations.ai) ·
  371. [News & FAQ](https://enter.pollinations.ai/news) ·
  372. [𝕏 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)
  373. ## 📜 License
  374. pollinations.ai is open-source software licensed under the [MIT license](LICENSE).
  375. ---
  376. Made with ❤️ by the pollinations.ai team
packages/polli-cli/src/harnesses/hermes.ts · Bundled script · 259 lines · 2 findings marked
  1. import { readdirSync, rmdirSync } from "node:fs";
  2. import { join } from "node:path";
  3. import { parseEnv } from "node:util";
  4. import { isMap, parseDocument } from "yaml";
  5. import polliSkill from "../../SKILL.md?raw";
  6. import { BASE_URL } from "../lib/config.js";
  7. import {
  8. commandExists,
  9. readTextIfExists,
  10. removeIfExists,
  11. resolveHomePath,
  12. writeTextAtomic,
  13. } from "./fs.js";
  14. import { resolveHarnessKey } from "./keys.js";
  15. import { fetchHarnessModels } from "./models.js";
  16. import { applyWithSnapshot, restoreOrStrip } from "./snapshot.js";
  17. import type { HarnessAdapter, HarnessContext, HarnessResult } from "./types.js";
  18. const ID = "hermes";
  19. const LABEL = "Hermes Agent";
  20. const PROVIDER = "pollinations";
  21. const DEFAULT_MODEL = "openai/gpt-6-sol";
  22. const KEY_ENV = "POLLI_HERMES_API_KEY";
  23. // Never fold long scalars (the API key) across lines.
  24. const YAML_OUT = { lineWidth: 0 };
  25. /**
  26. * Hermes home: HERMES_HOME wins, else the platform default Hermes itself uses
  27. * (`%LOCALAPPDATA%\hermes` on Windows, `~/.hermes` elsewhere).
  28. */
  29. export const hermesHome = (ctx: HarnessContext) => {
  30. const configured = ctx.env.HERMES_HOME;
  31. if (configured?.trim()) return resolveHomePath(ctx.home, configured);
  32. if (process.platform === "win32") {
  33. const base =
  34. ctx.env.LOCALAPPDATA?.trim() ?? join(ctx.home, "AppData", "Local");
  35. return join(base, "hermes");
  36. }
  37. return join(ctx.home, ".hermes");
  38. };
  39. const configPath = (ctx: HarnessContext) =>
  40. join(hermesHome(ctx), "config.yaml");
  41. const envPath = (ctx: HarnessContext) => join(hermesHome(ctx), ".env");
  42. // Hermes scans $HERMES_HOME/skills/ recursively for SKILL.md files.
  43. const skillDir = (ctx: HarnessContext) =>
  44. join(hermesHome(ctx), "skills", "polli");
  45. const skillPath = (ctx: HarnessContext) => join(skillDir(ctx), "SKILL.md");
  46. const files = (ctx: HarnessContext) => [
  47. configPath(ctx),
  48. envPath(ctx),
  49. skillPath(ctx),
  50. ];
  51. // parseDocument keeps comments and untouched entries intact on rewrite.
  52. const loadYaml = (path: string) => {
  53. const doc = parseDocument(readTextIfExists(path) ?? "");
  54. if (doc.errors.length) throw doc.errors[0];
  55. if (doc.contents === null) doc.contents = doc.createNode({}) as never;
  56. return doc;
  57. };
  58. const readKey = (ctx: HarnessContext) => {
  59. const text = readTextIfExists(envPath(ctx));
  60. if (text === null) return null;
  61. const key = parseEnv(text)[KEY_ENV];
  62. return key || null;
  63. };
  64. const envLine = (key: string) => `${KEY_ENV}=${JSON.stringify(key)}`;
  65. const keyLine = new RegExp(`^\\s*(?:export\\s+)?${KEY_ENV}\\s*=`, "u");
  66. const setEnvKey = (ctx: HarnessContext, key: string) => {
  67. const lines = (readTextIfExists(envPath(ctx)) ?? "").split("\n");
  68. const index = lines.findIndex((line) => keyLine.test(line));
  69. const filtered = lines.filter(
  70. (line, i) => i === index || !keyLine.test(line),
  71. );
  72. if (index === -1) {
  73. const insertAt =
  74. filtered.at(-1) === "" ? filtered.length - 1 : filtered.length;
  75. filtered.splice(insertAt, 0, envLine(key));
  76. } else filtered[index] = envLine(key);
  77. writeTextAtomic(envPath(ctx), filtered.join("\n"), 0o600);
  78. };
  79. const deleteEnvKey = (ctx: HarnessContext) => {
  80. const text = readTextIfExists(envPath(ctx));
  81. if (text === null) return false;
  82. const lines = text.split("\n");
  83. const filtered = lines.filter((line) => !keyLine.test(line));
  84. if (filtered.length === lines.length) return false;
  85. writeTextAtomic(envPath(ctx), filtered.join("\n"), 0o600);
  86. return true;
  87. };
  88. const ownsProvider = (doc: ReturnType<typeof loadYaml>) =>
  89. doc.getIn(["providers", PROVIDER, "api"]) === `${BASE_URL}/v1` &&
  90. doc.getIn(["providers", PROVIDER, "key_env"]) === KEY_ENV;
  91. const writeConfig = (ctx: HarnessContext, model: string) => {
  92. const doc = loadYaml(configPath(ctx));
  93. if (!isMap(doc.contents)) {
  94. throw new Error(`${configPath(ctx)} must contain a YAML mapping`);
  95. }
  96. if (doc.hasIn(["providers", PROVIDER]) && !ownsProvider(doc)) {
  97. throw new Error(
  98. "An existing pollinations provider has different settings; leaving it unchanged.",
  99. );
  100. }
  101. // A named custom provider: Hermes reads the key from key_env and
  102. // discovers the live model catalog from the OpenAI-compatible endpoint.
  103. doc.setIn(["providers", PROVIDER, "name"], "Pollinations");
  104. doc.setIn(["providers", PROVIDER, "api"], `${BASE_URL}/v1`);
  105. doc.setIn(["providers", PROVIDER, "key_env"], KEY_ENV);
  106. doc.setIn(["model", "provider"], PROVIDER);
  107. doc.setIn(["model", "default"], model);
  108. writeTextAtomic(configPath(ctx), doc.toString(YAML_OUT), 0o600);
  109. };
  110. const stripConfig = (ctx: HarnessContext) => {
  111. const doc = loadYaml(configPath(ctx));
  112. if (!isMap(doc.contents)) return false;
  113. let changed = false;
  114. if (!ownsProvider(doc)) return false;
  115. for (const field of ["name", "api", "key_env"]) {
  116. doc.deleteIn(["providers", PROVIDER, field]);
  117. }
  118. const provider = doc.getIn(["providers", PROVIDER]);
  119. if (isMap(provider) && provider.items.length === 0) {
  120. doc.deleteIn(["providers", PROVIDER]);
  121. }
  122. changed = true;
  123. // Only unwind the default when this provider still owns it, so a model the
  124. // user moved to another provider survives.
  125. if (doc.getIn(["model", "provider"]) === PROVIDER) {
  126. doc.deleteIn(["model", "provider"]);
  127. doc.deleteIn(["model", "default"]);
  128. changed = true;
  129. }
  130. if (changed)
  131. writeTextAtomic(configPath(ctx), doc.toString(YAML_OUT), 0o600);
  132. return changed;
  133. };
  134. const writeSkill = (ctx: HarnessContext) => {
  135. if (readTextIfExists(skillPath(ctx)) === null) {
  136. writeTextAtomic(skillPath(ctx), polliSkill, 0o600);
  137. }
  138. };
  139. const stripSkill = (ctx: HarnessContext) => {
  140. if (readTextIfExists(skillPath(ctx)) === polliSkill) {
  141. removeIfExists(skillPath(ctx));
  142. return true;
  143. }
  144. return false;
  145. };
  146. /** Drop the `skills/polli` dir once it is empty, so `off` leaves no trace. */
  147. const cleanupSkillDir = (ctx: HarnessContext) => {
  148. try {
  149. if (readdirSync(skillDir(ctx)).length === 0) rmdirSync(skillDir(ctx));
  150. } catch {
  151. // Directory absent or still holds user files; nothing to clean.
  152. }
  153. };
  154. const result = (ctx: HarnessContext): HarnessResult => {
  155. const doc = loadYaml(configPath(ctx));
  156. const configured =
  157. isMap(doc.contents) &&
  158. ownsProvider(doc) &&
  159. doc.getIn(["model", "provider"]) === PROVIDER &&
  160. readKey(ctx) !== null &&
  161. readTextIfExists(skillPath(ctx)) !== null;
  162. const model = doc.getIn(["model", "default"]);
  163. return {
  164. harness: ID,
  165. label: LABEL,
  166. installed: hermesInstalled(ctx),
  167. configured,
  168. model: configured && typeof model === "string" ? model : undefined,
  169. files: files(ctx),
  170. };
  171. };
  172. interface HermesSettings {
  173. apiKey: string;
  174. model: string;
  175. }
  176. const writeAll = (ctx: HarnessContext, settings: HermesSettings) => {
  177. writeConfig(ctx, settings.model);
  178. setEnvKey(ctx, settings.apiKey);
  179. writeSkill(ctx);
  180. };
  181. const stripAll = (ctx: HarnessContext) => {
  182. if (!ownsProvider(loadYaml(configPath(ctx)))) return false;
  183. let changed = stripConfig(ctx);
  184. changed = deleteEnvKey(ctx) || changed;
  185. changed = stripSkill(ctx) || changed;
  186. return changed;
  187. };
  188. export const configureHermes = (
  189. ctx: HarnessContext,
  190. settings: HermesSettings,
  191. ): HarnessResult => {
  192. applyWithSnapshot(ctx, ID, files(ctx), () => writeAll(ctx, settings));
  193. return result(ctx);
  194. };
  195. export const disableHermes = (ctx: HarnessContext): HarnessResult => {
  196. const outcome = restoreOrStrip(ctx, ID, files(ctx), () => stripAll(ctx));
  197. cleanupSkillDir(ctx);
  198. return { ...result(ctx), configured: false, outcome };
  199. };
  200. const INSTALL_HINT =
  201. process.platform === "win32"
  202. ? "iex (irm https://hermes-agent.nousresearch.com/install.ps1)"
  203. : "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
  204. const hermesInstalled = (ctx: HarnessContext) =>
  205. commandExists("hermes", ctx.env, [
  206. join(hermesHome(ctx), "hermes-agent", "hermes"),
  207. join(hermesHome(ctx), "bin", "hermes"),
  208. ]);
  209. export const hermes = {
  210. id: ID,
  211. label: LABEL,
  212. description: "Configure Hermes Agent to use Pollinations",
  213. restartHint:
  214. "Start a new Hermes session to pick up the provider and skill. Run hermes model to switch models.",
  215. async on(ctx, options) {
  216. if (!hermesInstalled(ctx)) {
  217. throw new Error(
  218. `Hermes Agent was not found. Install it first: ${INSTALL_HINT}`,
  219. );
  220. }
  221. const { model } = await fetchHarnessModels(
  222. options.model ?? DEFAULT_MODEL,
  223. );
  224. const apiKey = await resolveHarnessKey(
  225. { id: ID, label: LABEL, existingKey: readKey(ctx) },
  226. { browser: options.browser },
  227. );
  228. return configureHermes(ctx, { apiKey, model });
  229. },
  230. off: disableHermes,
  231. status: result,
  232. } satisfies HarnessAdapter;
packages/polli-cli/src/harnesses/opencode.ts · Bundled script · 303 lines · 1 finding marked
  1. import { join } from "node:path";
  2. import JSON5 from "json5";
  3. import { BASE_URL } from "../lib/config.js";
  4. import {
  5. commandExists,
  6. readTextIfExists,
  7. removeIfExists,
  8. resolveHomePath,
  9. writeTextAtomic,
  10. } from "./fs.js";
  11. import { resolveHarnessKey } from "./keys.js";
  12. import { fetchHarnessModels } from "./models.js";
  13. import { applyWithSnapshot, restoreOrStrip } from "./snapshot.js";
  14. import type {
  15. HarnessAdapter,
  16. HarnessContext,
  17. HarnessModel,
  18. HarnessResult,
  19. } from "./types.js";
  20. const ID = "opencode";
  21. const LABEL = "OpenCode";
  22. const PROVIDER = "pollinations";
  23. const DEFAULT_MODEL = "openai/gpt-6-sol";
  24. const PROVIDER_NPM = "@ai-sdk/openai-compatible";
  25. /**
  26. * OpenCode's config schema requires `limit.output` alongside `limit.context`
  27. * and rejects the whole file without it ("Configuration is invalid ... Missing
  28. * key ...limit.output"). The models API exposes no output cap, so this is a
  29. * fallback, not a per-model limit.
  30. */
  31. const MAX_OUTPUT_TOKENS = 32768;
  32. /** The 1.x plugin earlier versions of `on` enabled; cleaned up when found. */
  33. const LEGACY_PLUGIN = "opencode-pollinations-plugin";
  34. /**
  35. * OpenCode 1.x and 2.0 both read the 1.x `provider` block: 2.0 normalizes V1
  36. * config in memory and no longer loads 1.x plugins, which is why `on` writes a
  37. * `pollinations` provider instead of enabling `opencode-pollinations-plugin`.
  38. * The block lists the models `on` already fetches, so one config serves both
  39. * versions and the provider's `options.apiKey` is where both read the key.
  40. */
  41. const legacyConfigDir = (ctx: HarnessContext) => {
  42. if (process.platform === "win32") {
  43. return join(ctx.env.APPDATA ?? ctx.home, "pollinations");
  44. }
  45. if (process.platform === "darwin") {
  46. return join(ctx.home, "Library", "Application Support", "pollinations");
  47. }
  48. const xdg = ctx.env.XDG_CONFIG_HOME?.trim();
  49. return join(
  50. xdg ? resolveHomePath(ctx.home, xdg) : join(ctx.home, ".config"),
  51. "pollinations",
  52. );
  53. };
  54. export const opencodeConfigFile = (ctx: HarnessContext) => {
  55. if (ctx.env.OPENCODE_CONFIG?.trim()) {
  56. return resolveHomePath(ctx.home, ctx.env.OPENCODE_CONFIG);
  57. }
  58. const dir = ctx.env.OPENCODE_CONFIG_DIR?.trim()
  59. ? resolveHomePath(ctx.home, ctx.env.OPENCODE_CONFIG_DIR)
  60. : join(ctx.home, ".config", "opencode");
  61. return (
  62. ["opencode.jsonc", "opencode.json", "config.json"]
  63. .map((name) => join(dir, name))
  64. .find((path) => readTextIfExists(path) !== null) ??
  65. join(dir, "opencode.json")
  66. );
  67. };
  68. /** `~/.config/pollinations/config.json`, written by the removed 1.x plugin. */
  69. const legacyKeyFile = (ctx: HarnessContext) =>
  70. join(legacyConfigDir(ctx), "config.json");
  71. const files = (ctx: HarnessContext) => [
  72. opencodeConfigFile(ctx),
  73. legacyKeyFile(ctx),
  74. ];
  75. const readJson = (path: string): Record<string, unknown> | null => {
  76. const text = readTextIfExists(path);
  77. if (text === null) return null;
  78. try {
  79. const parsed = JSON5.parse(text);
  80. if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
  81. return parsed as Record<string, unknown>;
  82. }
  83. } catch (error) {
  84. throw new Error(`Could not parse OpenCode config at ${path}`, {
  85. cause: error,
  86. });
  87. }
  88. throw new Error(`OpenCode config at ${path} must contain an object`);
  89. };
  90. const writeJson = (path: string, data: unknown) =>
  91. writeTextAtomic(path, `${JSON.stringify(data, null, 2)}\n`, 0o600);
  92. const openCodeConfig = (ctx: HarnessContext): Record<string, unknown> =>
  93. readJson(opencodeConfigFile(ctx)) ?? {};
  94. const providersOf = (config: Record<string, unknown>) => {
  95. const providers = config.provider;
  96. return providers !== null && typeof providers === "object"
  97. ? (providers as Record<string, unknown>)
  98. : {};
  99. };
  100. const isOurProvider = (entry: unknown): entry is Record<string, unknown> => {
  101. if (entry === null || typeof entry !== "object") return false;
  102. const options = (entry as Record<string, unknown>).options;
  103. return (
  104. options !== null &&
  105. typeof options === "object" &&
  106. (options as Record<string, unknown>).baseURL === `${BASE_URL}/v1`
  107. );
  108. };
  109. /** The plugin entry `on` used to add, in string or object form. */
  110. const isLegacyPlugin = (entry: unknown) =>
  111. typeof entry === "string"
  112. ? entry === LEGACY_PLUGIN || entry.includes(LEGACY_PLUGIN)
  113. : entry !== null &&
  114. typeof entry === "object" &&
  115. Object.values(entry).some(
  116. (value) =>
  117. typeof value === "string" && value.includes(LEGACY_PLUGIN),
  118. );
  119. const pluginListKey = (config: Record<string, unknown>) =>
  120. Array.isArray(config.plugins) && !Array.isArray(config.plugin)
  121. ? "plugins"
  122. : "plugin";
  123. const removeLegacyPlugin = (config: Record<string, unknown>) => {
  124. const key = pluginListKey(config);
  125. const entries = config[key];
  126. if (!Array.isArray(entries) || !entries.some(isLegacyPlugin)) return false;
  127. const filtered = entries.filter((entry) => !isLegacyPlugin(entry));
  128. if (filtered.length === 0) delete config[key];
  129. else config[key] = filtered;
  130. return true;
  131. };
  132. const readKey = (ctx: HarnessContext): string | null => {
  133. const entry = providersOf(openCodeConfig(ctx))[PROVIDER];
  134. const key = isOurProvider(entry)
  135. ? (entry.options as Record<string, unknown>).apiKey
  136. : undefined;
  137. return typeof key === "string" && key.length > 5 ? key : null;
  138. };
  139. /** Key the removed 1.x plugin stored, reused so `on` need not log in again. */
  140. const legacyKey = (ctx: HarnessContext): string | null => {
  141. const key = readJson(legacyKeyFile(ctx))?.apiKey;
  142. return typeof key === "string" && key.length > 5 ? key : null;
  143. };
  144. /** Drops the removed plugin's key, keeping its other settings (as main did). */
  145. const deleteLegacyKey = (ctx: HarnessContext) => {
  146. const path = legacyKeyFile(ctx);
  147. const config = readJson(path);
  148. if (config === null || config.apiKey === undefined) return false;
  149. delete config.apiKey;
  150. if (Object.keys(config).length === 0) removeIfExists(path);
  151. else writeJson(path, config);
  152. return true;
  153. };
  154. const providerBlock = (models: HarnessModel[], apiKey: string) => ({
  155. npm: PROVIDER_NPM,
  156. name: "Pollinations",
  157. options: { baseURL: `${BASE_URL}/v1`, apiKey },
  158. models: Object.fromEntries(
  159. models.map((model) => [
  160. model.id,
  161. {
  162. name: model.id,
  163. tool_call: true,
  164. limit: {
  165. context: model.contextWindow,
  166. output: Math.min(model.contextWindow, MAX_OUTPUT_TOKENS),
  167. },
  168. modalities: { input: model.input, output: ["text"] },
  169. },
  170. ]),
  171. ),
  172. });
  173. const writeConfig = (
  174. ctx: HarnessContext,
  175. settings: { apiKey: string; model: string; models: HarnessModel[] },
  176. ) => {
  177. const path = opencodeConfigFile(ctx);
  178. const config = openCodeConfig(ctx);
  179. if (typeof config.$schema !== "string") {
  180. config.$schema = "https://opencode.ai/config.json";
  181. }
  182. config.provider = {
  183. ...providersOf(config),
  184. [PROVIDER]: providerBlock(settings.models, settings.apiKey),
  185. };
  186. config.model = `${PROVIDER}/${settings.model}`;
  187. removeLegacyPlugin(config);
  188. writeJson(path, config);
  189. // The provider block above now carries the key.
  190. deleteLegacyKey(ctx);
  191. };
  192. const stripConfig = (ctx: HarnessContext): boolean => {
  193. let changed = false;
  194. const path = opencodeConfigFile(ctx);
  195. const config = readJson(path);
  196. if (config !== null) {
  197. const providers = providersOf(config);
  198. if (isOurProvider(providers[PROVIDER])) {
  199. delete providers[PROVIDER];
  200. if (Object.keys(providers).length === 0) delete config.provider;
  201. else config.provider = providers;
  202. changed = true;
  203. }
  204. if (isOurModel(config.model)) {
  205. delete config.model;
  206. changed = true;
  207. }
  208. if (removeLegacyPlugin(config)) changed = true;
  209. if (changed) writeJson(path, config);
  210. }
  211. if (deleteLegacyKey(ctx)) changed = true;
  212. return changed;
  213. };
  214. const isOurModel = (model: unknown) =>
  215. typeof model === "string" && model.startsWith(`${PROVIDER}/`);
  216. const result = (ctx: HarnessContext): HarnessResult => {
  217. const config = openCodeConfig(ctx);
  218. const model = isOurModel(config.model)
  219. ? (config.model as string).slice(PROVIDER.length + 1)
  220. : undefined;
  221. return {
  222. harness: ID,
  223. label: LABEL,
  224. configured:
  225. isOurProvider(providersOf(config)[PROVIDER]) &&
  226. isOurModel(config.model) &&
  227. readKey(ctx) !== null,
  228. model,
  229. files: files(ctx),
  230. };
  231. };
  232. export const configureOpenCode = (
  233. ctx: HarnessContext,
  234. settings: { apiKey: string; model: string; models: HarnessModel[] },
  235. ): HarnessResult => {
  236. applyWithSnapshot(ctx, ID, files(ctx), () => writeConfig(ctx, settings));
  237. return result(ctx);
  238. };
  239. export const disableOpenCode = (ctx: HarnessContext): HarnessResult => {
  240. const outcome = restoreOrStrip(ctx, ID, files(ctx), () => stripConfig(ctx));
  241. return { ...result(ctx), configured: false, outcome };
  242. };
  243. const openCodeInstalled = (ctx: HarnessContext) =>
  244. commandExists("opencode", ctx.env, [
  245. join(ctx.home, ".opencode", "bin", "opencode"),
  246. ]);
  247. export const opencode = {
  248. id: ID,
  249. label: LABEL,
  250. description: "Configure OpenCode to use Pollinations",
  251. restartHint:
  252. "Restart OpenCode, then pick a Pollinations model with /models. Run `polli mcp install opencode --all` to add the media tools.",
  253. async on(ctx, options) {
  254. if (!openCodeInstalled(ctx)) {
  255. throw new Error(
  256. "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
  257. );
  258. }
  259. const { model, models } = await fetchHarnessModels(
  260. options.model ?? DEFAULT_MODEL,
  261. );
  262. const apiKey = await resolveHarnessKey(
  263. {
  264. id: ID,
  265. label: LABEL,
  266. existingKey: readKey(ctx) ?? legacyKey(ctx),
  267. },
  268. { browser: options.browser },
  269. );
  270. return configureOpenCode(ctx, { apiKey, model, models });
  271. },
  272. off: disableOpenCode,
  273. status: result,
  274. } satisfies HarnessAdapter;
packages/polli-cli/src/harnesses/prime.ts · Bundled script · 234 lines · 1 finding marked
  1. import { join } from "node:path";
  2. import polliSkill from "../../SKILL.md?raw";
  3. import { BASE_URL } from "../lib/config.js";
  4. import {
  5. commandExists,
  6. readTextIfExists,
  7. removeIfExists,
  8. resolveHomePath,
  9. writeTextAtomic,
  10. } from "./fs.js";
  11. import { resolveHarnessKey } from "./keys.js";
  12. import { fetchHarnessModels } from "./models.js";
  13. import { applyWithSnapshot, restoreOrStrip } from "./snapshot.js";
  14. import type {
  15. HarnessAdapter,
  16. HarnessContext,
  17. HarnessModel,
  18. HarnessResult,
  19. } from "./types.js";
  20. const ID = "prime";
  21. const LABEL = "Prime Agent";
  22. const PROVIDER = "pollinations";
  23. const DEFAULT_MODEL = "openai/gpt-6-sol";
  24. /** Prime Agent resolves its agent dir from this override, tilde included. */
  25. export const primeAgentDir = (ctx: HarnessContext) => {
  26. const configured = ctx.env.PRIME_AGENT_CODING_AGENT_DIR;
  27. if (!configured?.trim()) return join(ctx.home, ".prime", "agent");
  28. return resolveHomePath(ctx.home, configured);
  29. };
  30. const modelsPath = (ctx: HarnessContext) =>
  31. join(primeAgentDir(ctx), "models.json");
  32. const authPath = (ctx: HarnessContext) => join(primeAgentDir(ctx), "auth.json");
  33. const settingsPath = (ctx: HarnessContext) =>
  34. join(primeAgentDir(ctx), "settings.json");
  35. const skillPath = (ctx: HarnessContext) =>
  36. join(primeAgentDir(ctx), "skills", "polli", "SKILL.md");
  37. const files = (ctx: HarnessContext) => [
  38. modelsPath(ctx),
  39. authPath(ctx),
  40. settingsPath(ctx),
  41. skillPath(ctx),
  42. ];
  43. const loadJson = (path: string): Record<string, unknown> => {
  44. const text = readTextIfExists(path);
  45. if (!text?.trim()) return {};
  46. return JSON.parse(text) as Record<string, unknown>;
  47. };
  48. const saveJson = (path: string, data: Record<string, unknown>) => {
  49. writeTextAtomic(path, `${JSON.stringify(data, null, 2)}\n`, 0o600);
  50. };
  51. // Compat flags shared with the dsh provider block: gen.pollinations.ai/v1
  52. // speaks standard completions without store/developer-role/strict-mode extras.
  53. const compat = {
  54. supportsStore: false,
  55. supportsDeveloperRole: false,
  56. supportsReasoningEffort: true,
  57. supportsUsageInStreaming: true,
  58. supportsStrictMode: false,
  59. maxTokensField: "max_tokens",
  60. };
  61. const providerEntry = (models: HarnessModel[]) => ({
  62. baseUrl: `${BASE_URL}/v1`,
  63. api: "openai-completions",
  64. // Prime validates custom providers before resolving their auth.json entry.
  65. apiKey: PROVIDER,
  66. compat,
  67. models: models.map((model) => ({
  68. id: model.id,
  69. name: model.id,
  70. input: model.input,
  71. contextWindow: model.contextWindow,
  72. })),
  73. });
  74. interface PrimeModels {
  75. providers?: Record<string, unknown>;
  76. [key: string]: unknown;
  77. }
  78. type PrimeAuth = Record<string, { type?: string; key?: string }>;
  79. interface PrimeSettings {
  80. defaultProvider?: string;
  81. defaultModel?: string;
  82. [key: string]: unknown;
  83. }
  84. const readKey = (ctx: HarnessContext) => {
  85. const auth = loadJson(authPath(ctx)) as PrimeAuth;
  86. const credential = auth[PROVIDER];
  87. return credential?.type === "api_key" && credential.key
  88. ? credential.key
  89. : null;
  90. };
  91. const writeAuth = (ctx: HarnessContext, apiKey: string) => {
  92. const auth = loadJson(authPath(ctx)) as PrimeAuth;
  93. auth[PROVIDER] = { type: "api_key", key: apiKey };
  94. saveJson(authPath(ctx), auth);
  95. };
  96. const deleteAuth = (ctx: HarnessContext) => {
  97. const auth = loadJson(authPath(ctx)) as PrimeAuth;
  98. if (!(PROVIDER in auth)) return false;
  99. delete auth[PROVIDER];
  100. if (Object.keys(auth).length === 0) removeIfExists(authPath(ctx));
  101. else saveJson(authPath(ctx), auth);
  102. return true;
  103. };
  104. const writeConfig = (
  105. ctx: HarnessContext,
  106. models: HarnessModel[],
  107. apiKey: string,
  108. model: string,
  109. ) => {
  110. const doc = loadJson(modelsPath(ctx)) as PrimeModels;
  111. const providers = (doc.providers ?? {}) as Record<string, unknown>;
  112. providers[PROVIDER] = providerEntry(models);
  113. doc.providers = providers;
  114. saveJson(modelsPath(ctx), doc);
  115. writeAuth(ctx, apiKey);
  116. const settings = loadJson(settingsPath(ctx)) as PrimeSettings;
  117. settings.defaultProvider = PROVIDER;
  118. settings.defaultModel = model;
  119. saveJson(settingsPath(ctx), settings);
  120. if (readTextIfExists(skillPath(ctx)) === null) {
  121. writeTextAtomic(skillPath(ctx), polliSkill, 0o600);
  122. }
  123. };
  124. const stripConfig = (ctx: HarnessContext) => {
  125. let changed = false;
  126. const doc = loadJson(modelsPath(ctx)) as PrimeModels;
  127. if (doc?.providers && PROVIDER in doc.providers) {
  128. delete doc.providers[PROVIDER];
  129. if (Object.keys(doc.providers).length === 0) delete doc.providers;
  130. saveJson(modelsPath(ctx), doc);
  131. changed = true;
  132. }
  133. changed = deleteAuth(ctx) || changed;
  134. const settings = loadJson(settingsPath(ctx)) as PrimeSettings;
  135. if (settings && settings.defaultProvider === PROVIDER) {
  136. delete settings.defaultProvider;
  137. delete settings.defaultModel;
  138. saveJson(settingsPath(ctx), settings);
  139. changed = true;
  140. }
  141. if (readTextIfExists(skillPath(ctx)) === polliSkill) {
  142. removeIfExists(skillPath(ctx));
  143. changed = true;
  144. }
  145. return changed;
  146. };
  147. const result = (ctx: HarnessContext): HarnessResult => {
  148. const doc = loadJson(modelsPath(ctx)) as PrimeModels;
  149. const provider = doc?.providers?.[PROVIDER] as
  150. | { baseUrl?: string; api?: string; apiKey?: string }
  151. | undefined;
  152. const settings = loadJson(settingsPath(ctx)) as PrimeSettings;
  153. const model =
  154. settings?.defaultProvider === PROVIDER
  155. ? settings.defaultModel
  156. : undefined;
  157. return {
  158. harness: ID,
  159. label: LABEL,
  160. configured:
  161. provider?.baseUrl === `${BASE_URL}/v1` &&
  162. provider?.api === "openai-completions" &&
  163. provider?.apiKey === PROVIDER &&
  164. readKey(ctx) !== null &&
  165. readTextIfExists(skillPath(ctx)) !== null,
  166. model: typeof model === "string" ? model : undefined,
  167. files: files(ctx),
  168. };
  169. };
  170. export const configurePrime = (
  171. ctx: HarnessContext,
  172. models: HarnessModel[],
  173. apiKey: string,
  174. model: string,
  175. ): HarnessResult => {
  176. applyWithSnapshot(ctx, ID, files(ctx), () =>
  177. writeConfig(ctx, models, apiKey, model),
  178. );
  179. return result(ctx);
  180. };
  181. export const disablePrime = (ctx: HarnessContext): HarnessResult => {
  182. const outcome = restoreOrStrip(ctx, ID, files(ctx), () => stripConfig(ctx));
  183. return { ...result(ctx), configured: false, outcome };
  184. };
  185. export const prime = {
  186. id: ID,
  187. label: LABEL,
  188. description: "Add Pollinations as a custom provider in Prime Agent",
  189. restartHint:
  190. "Models reload when you open /model. Start Prime Agent with: prime-agent",
  191. async on(ctx, options) {
  192. if (!commandExists("prime-agent", ctx.env)) {
  193. throw new Error(
  194. "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
  195. );
  196. }
  197. const { model, models } = await fetchHarnessModels(
  198. options.model ?? DEFAULT_MODEL,
  199. );
  200. const apiKey = await resolveHarnessKey(
  201. { id: ID, label: LABEL, existingKey: readKey(ctx) },
  202. { browser: options.browser },
  203. );
  204. return configurePrime(ctx, models, apiKey, model);
  205. },
  206. off: disablePrime,
  207. status: result,
  208. } satisfies HarnessAdapter;

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.