Pollinations.AI — API 文档
全球最易于访问的开放式生成式 AI 平台 🚀
文本、图像和音频 API 直接集成(无需注册)
注册网址:https://auth.pollinations.ai
快速入门
点击下方链接,在浏览器中查看示例:
- 生成图像 🖌️:
https://image.pollinations.ai/prompt/pollinations_logo - 生成文本 ❓:
https://text.pollinations.ai/why_you_should_donate_to_pollinations_ai - 搜索 🔍:
https://text.pollinations.ai/what_are_the_last_pollinations_ai_news?model=searchgpt - 生成音频 🗣️:
https://text.pollinations.ai/respond_with_a_small_hypnosis_urging_to_donate_to_pollinations_its_a_joke?model=openai-audio&voice=nova
摘要 / 导航
生成图像 API 🖼️
1. 文本生成图像 (GET) 🖌️
GET https://image.pollinations.ai/prompt/{prompt}
根据文本描述生成一张图像。
参数:
| 参数 | 必需 | 描述 | 默认值 |
|---|---|---|---|
prompt |
是 | 图像的文本描述。应进行 URL 编码。 | |
model |
否 | 用于生成的模型。参见可用的图像模型。 | flux |
seed |
否 | 用于生成可复现结果的种子。 | |
width |
否 | 生成图像的宽度(像素)。 | 1024 |
height |
否 | 生成图像的高度(像素)。 | 1024 |
image |
否 | 用于图像生成/编辑(kontext模型)的输入图像 URL。 |
|
nologo |
否 | 设置为 true 以禁用 Pollinations 徽标叠加(适用于注册用户)。 |
false |
private |
否 | 设置为 true 以防止图像出现在公共 Feed 中。 |
false |
enhance |
否 | 设置为 true 以使用 LLM 增强提示,使其更详细。 |
false |
safe |
否 | 设置为 true 以启用严格的 NSFW(不适宜工作场所内容)过滤(如果检测到则抛出错误)。 |
false |
referrer |
否* | Referrer URL/标识符。参见Referrer 部分。 |
返回: 图像文件(通常是 JPEG)🖼️
速率限制(每个 IP): 1 个并发请求 / 5 秒间隔(匿名套餐)。更高级别的限制请参见套餐等级。
代码示例: 生成图像 (GET)
cURL:
# 基本提示,保存到文件
curl -o sunset.jpg "https://image.pollinations.ai/prompt/A%20beautiful%20sunset%20over%20the%20ocean"
# 带参数
curl -o sunset_large.jpg "https://image.pollinations.ai/prompt/A%20beautiful%20sunset%20over%20the%20ocean?width=1280&height=720&seed=42&model=flux"
# 使用 kontext 模型进行图像到图像的生成
curl -o logo_cake.png "https://image.pollinations.ai/prompt/bake_a_cake_from_this_logo?model=kontext&image=https://avatars.githubusercontent.com/u/86964862"
Python (requests):
import requests
import urllib.parse
prompt = "A beautiful sunset over the ocean"
params = {
"width": 1280,
"height": 720,
"seed": 42,
"model": "flux",
# "nologo": "true", # 可选,为注册的 referrer/token 设置为 "true"
# "image": "https://example.com/input-image.jpg", # 可选 - 用于图像到图像的生成 (kontext model)
# "referrer": "MyPythonApp" # 可选,用于基于 referrer 的认证
}
encoded_prompt = urllib.parse.quote(prompt)
url = f"https://image.pollinations.ai/prompt/{encoded_prompt}"
try:
# 增加超时时间以适应图像生成
response = requests.get(url, params=params, timeout=300)
response.raise_for_status() # 如果状态码不佳则抛出异常
with open('generated_image.jpg', 'wb') as f:
f.write(response.content)
print("图像已保存为 generated_image.jpg")
except requests.exceptions.RequestException as e:
print(f"获取图像时出错: {e}")
# 可以检查 response.text 获取 API 的错误信息
# if response is not None: print(response.text)
2. 列出可用的图像模型 📜
GET https://image.pollinations.ai/models
描述: 返回可用于生成图像 API 的模型列表。
返回: 包含模型标识符的 JSON 列表。
代码示例: 列出图像模型
cURL:
curl https://image.pollinations.ai/models
Python (requests):
import requests
url = "https://image.pollinations.ai/models"
try:
response = requests.get(url)
response.raise_for_status()
models = response.json()
print("可用的图像模型:")
for model in models:
print(f"- {model}")
except requests.exceptions.RequestException as e:
print(f"获取模型列表时出错: {e}")
生成文本 API 📝
1. 文本生成文本 (GET) 🗣️
GET https://text.pollinations.ai/{prompt}
根据简单的提示生成文本。此端点非常适合直接的文本生成任务。
参数:
| 参数 | 必需 | 描述 | 选项 | 默认值 |
|---|---|---|---|---|
prompt |
是 | 用于 AI 的文本提示。应进行 URL 编码。 | ||
model |
否 | 用于生成的模型。参见可用的文本模型。 | openai, mistral, 等 |
openai |
seed |
否 | 用于生成可复现结果的种子。 | ||
temperature |
否 | 控制输出的随机性。值越高,输出越随机。 | 0.0 到 3.0 |
|
top_p |
否 | 核心采样(Nucleus sampling)参数。通过累积概率控制多样性。 | 0.0 到 1.0 |
|
presence_penalty |
否 | 根据词元(token)是否已在文本中出现来对其进行惩罚。 | -2.0 到 2.0 |
|
frequency_penalty |
否 | 根据词元在文本中出现的频率来对其进行惩罚。 | -2.0 到 2.0 |
|
json |
否 | 设置为 true 以接收格式化为 JSON 字符串的响应。 |
true / false |
false |
system |
否 | 用于指导 AI 行为的系统提示。应进行 URL 编码。 | ||
stream |
否 | 设置为 true 以通过服务器发送事件(SSE)进行流式响应。需处理 data: 块。 |
true / false |
false |
private |
否 | 设置为 true 以防止响应出现在公共 Feed 中。 |
true / false |
false |
referrer |
否* | Referrer URL/标识符。参见Referrer 部分。 |
返回: 生成的文本(纯文本或 JSON 字符串,如果 json=true)📝。如果 stream=true,则返回 SSE 流。
速率限制(每个 IP): 1 个并发请求 / 3 秒间隔(匿名套餐)。更高级别的限制请参见套餐等级。
代码示例: 生成文本 (GET)
CURL:
# 基本提示
curl "https://text.pollinations.ai/What%20is%20the%20capital%20of%20France%3F"
# 带参数 (模型, 种子, 系统提示)
curl "https://text.pollinations.ai/Write%20a%20short%20poem%20about%20robots?model=mistral&seed=123&system=You%20are%20a%20poet"
# 获取 JSON 响应
curl "https://text.pollinations.ai/What%20is%20AI?json=true"
# 流式响应 (原始 SSE 输出)
curl -N "https://text.pollinations.ai/Tell%20me%20a%20very%20long%20story?stream=true"
Python (requests):
import requests
import urllib.parse
import json
prompt = "Explain the theory of relativity simply"
params = {
"model": "openai",
"seed": 42,
# "json": "true", # 可选: 获取 JSON 字符串格式的响应
# "system": "Explain things like I'm five.", # 可选
# "referrer": "MyPythonApp" # 可选,用于基于 referrer 的认证
}
encoded_prompt = urllib.parse.quote(prompt)
encoded_system = urllib.parse.quote(params.get("system", "")) if "system" in params else None
url = f"https://text.pollinations.ai/{encoded_prompt}"
query_params = {k: v for k, v in params.items() if k != "system"} # 如果存在 system,则从查询参数中移除
if encoded_system:
query_params["system"] = encoded_system
try:
response = requests.get(url, params=query_params)
response.raise_for_status()
if params.get("json") == "true":
# 响应是一个 JSON *字符串*,需要解析它
try:
data = json.loads(response.text)
print("响应 (JSON 解析后):", data)
except json.JSONDecodeError:
print("错误: API 返回了无效的 JSON 字符串。")
print("原始响应:", response.text)
else:
print("响应 (纯文本):")
print(response.text)
except requests.exceptions.RequestException as e:
print(f"获取文本时出错: {e}")
# if response is not None: print(response.text)
2. 列出可用的文本模型 📜
GET https://text.pollinations.ai/models
描述: 返回文本生成 API 可用模型的完整列表。这包括支持文本、视觉、音频(语音转文本和文本转语音)以及各种其他功能的模型。它还列出了文本转语音模型的可用音色。
返回: 包含模型标识符和详细信息(例如:功能、相关音色)的 JSON 列表/对象。具体结构可能有所不同,最好检查输出内容。
代码示例: 列出文本模型
cURL:
curl https://text.pollinations.ai/models
Python (requests):
import requests
import json
url = "https://text.pollinations.ai/models"
try:
response = requests.get(url)
response.raise_for_status()
models_data = response.json()
print("可用的文本模型和音色:")
print(json.dumps(models_data, indent=2, ensure_ascii=False))
# 示例:如何根据预期结构解析特定部分:
# 如果 `models_data` 是一个字典列表,你可以提取模型 ID:
# if isinstance(models_data, list):
# model_ids = [m.get('id') for m in models_data if m.get('id')]
# print("\n模型 ID:", model_ids)
# 如果 `models_data` 是一个字典,其中键是模型 ID,值是详细信息:
# if isinstance(models_data, dict):
# print("\n可用音色 (来自 openai-audio 模型详情):")
# openai_audio_details = models_data.get('openai-audio', {})
# if 'voices' in openai_audio_details:
# print(openai_audio_details['voices'])
# else:
# print("openai-audio 模型未列出特定音色,或结构不同。")
except requests.exceptions.RequestException as e:
print(f"获取文本模型列表时出错: {e}")
3. 文本与多模态 (兼容 OpenAI 的 POST) 🧠💬🖼️🎤⚙️
POST https://text.pollinations.ai/openai
提供一个与 OpenAI 兼容的端点,支持包括以下在内的高级功能:
- 聊天补全 (Chat Completions):带有消息历史的标准文本生成。
- 视觉 (Vision):分析图像输入。
- 语音转文本 (Speech-to-Text):转录音频输入。
- 函数调用 (Function Calling):允许模型调用外部工具。
- 流式响应 (Streaming Responses):实时返回部分消息增量。
该端点在输入格式上遵循 OpenAI 聊天补全 API 的规范,比 GET 端点提供了更大的灵活性和更强大的功能。
请求体 (JSON 示例):
{
"model": "openai",
"messages": [
{
"role": "system",
"content": "你是一个有用的助手。"
},
{
"role": "user",
"content": "法国的首都是哪里?"
}
],
"temperature": 0.7,
"stream": true,
"private": false
}
通用请求体参数:
| 参数 | 描述 | 注意 |
|---|---|---|
messages |
一个消息对象数组(role:system, user, assistant)。用于聊天、视觉、语音转文本。 |
大多数任务都需要。 |
model |
模型标识符。参见可用的文本模型。 | 必需。例如 openai (聊天/视觉), openai-large (视觉), claude-hybridspace (视觉), openai-audio (语音转文本)。 |
seed |
用于可复现结果的种子(文本生成)。 | 可选。 |
temperature |
控制输出的随机性。值越高,输出越随机(文本生成)。 | 可选。范围:0.0 到 3.0。 |
top_p |
核心采样参数。通过累积概率控制多样性(文本生成)。 | 可选。范围:0.0 到 1.0。 |
presence_penalty |
根据词元在文本中是否出现来对其进行惩罚(文本生成)。 | 可选。范围:-2.0 到 2.0。 |
frequency_penalty |
根据词元在文本中出现的频率来对其进行惩罚(文本生成)。 | 可选。范围:-2.0 到 2.0。 |
stream |
如果为 true,则使用 SSE 发送部分消息增量(文本生成)。按 OpenAI 流式文档处理数据块。 |
可选,默认为 false。 |
jsonMode / response_format |
设置 response_format={ "type": "json_object" } 以将文本输出限制为有效的 JSON。jsonMode: true 是一个旧的别名。 |
可选。请检查模型兼容性。 |
tools |
模型可以调用的工具(函数)列表(文本生成)。参见 OpenAI 函数调用指南。 | 可选。 |
tool_choice |
控制模型如何使用工具。 | 可选。 |
private |
设置为 true 以防止响应出现在公共 Feed 中。 |
可选,默认为 false。 |
referrer |
Referrer URL/标识符。参见Referrer 部分。 | 可选。 |
代码示例: 基本聊天补全 (POST)
CURL:
curl https://text.pollinations.ai/openai \
-H "Content-Type: application/json" \
-d '{
"model": "openai",
"messages": [{"role": "system", "content": "你是一个有用的助手。"}, {"role": "user", "content": "今天巴黎天气怎么样?"}],
"seed": 42
}'
Python (requests):
import requests
import json
url = "https://text.pollinations.ai/openai"
payload = {
"model": "openai", # 或 "mistral" 等
"messages": [
{"role": "system", "content": "你是一位有帮助的历史学家。"},
{"role": "user", "content": "法国大革命是什么时候开始的?"}
],
"seed": 101,
# "private": True, # 可选
# "referrer": "MyPythonApp" # 可选,用于基于 referrer 的认证
}
headers = {
"Content-Type": "application/json"
}
try:
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
result = response.json()
print("助手:", result['choices'][0]['message']['content'])
# print(json.dumps(result, indent=2)) # 打印完整响应
except requests.exceptions.RequestException as e:
print(f"执行 POST 请求时出错: {e}")
# if response is not None: print(response.text)
代码示例: 流式响应 (POST)
CURL:
# 使用 -N 进行流式传输
curl -N https://text.pollinations.ai/openai \
-H "Content-Type: application/json" \
-d '{
"model": "openai",
"messages": [
{"role": "user", "content": "写一首关于大海的长诗。"}
],
"stream": true
}'
Python (requests 与 SSE):
import requests
import json
import sseclient # pip install sseclient-py
url = "https://text.pollinations.ai/openai"
payload = {
"model": "openai",
"messages": [
{"role": "user", "content": "给我讲一个慢慢展开的故事。"}
],
"stream": True
}
headers = {
"Content-Type": "application/json",
"Accept": "text/event-stream"
}
try:
response = requests.post(url, headers=headers, json=payload, stream=True)
response.raise_for_status()
client = sseclient.SSEClient(response)
full_response = ""
print("流式响应:")
for event in client.events():
if event.data:
try:
# 处理可能的 '[DONE]' 标记
if event.data.strip() == '[DONE]':
print("\n流已结束。")
break
chunk = json.loads(event.data)
content = chunk.get('choices', [{}])[0].get('delta', {}).get('content')
if content:
print(content, end='', flush=True)
full_response += content
except json.JSONDecodeError:
print(f"\n收到非 JSON 数据 (或非 [DONE] 的标记): {event.data}")
print("\n--- 流结束 ---")
# print("完整的流式响应:", full_response)
except requests.exceptions.RequestException as e:
print(f"\n流式请求期间出错: {e}")
except Exception as e:
print(f"\n处理流时出错: {e}")
4. 文本转语音 (GET) 📝➡️🎙️
GET https://text.pollinations.ai/{prompt}?model=openai-audio&voice={voice}
使用简单的 GET 请求从文本生成语音音频。由于 URL 长度限制和直接返回音频文件的特性,此方法最适合短文本片段。
参数:
| 参数 | 必需 | 描述 | 选项 | 默认值 |
|---|---|---|---|---|
prompt |
是 | 要合成的文本。必须进行 URL 编码。 | ||
model |
是 | 必须是 openai-audio 以使用文本转语音功能。 |
openai-audio |
|
voice |
否 | 用于合成的音色。通过列出文本模型查看可用音色。 | 例如 alloy, echo, fable, onyx, nova, shimmer |
alloy |
返回: 音频文件(MP3 格式,Content-Type: audio/mpeg)🎧,直接作为响应体返回。
速率限制: (继承基础文本 API 的限制)。详情请参见套餐等级。
代码示例: 文本转语音 (GET)
cURL:
# 基本的 TTS GET 请求,保存到文件
curl -o hello_audio.mp3 "https://text.pollinations.ai/Hello%20world?model=openai-audio&voice=nova"
# 不同的音色
curl -o welcome_audio.mp3 "https://text.pollinations.ai/Welcome%20to%20Pollinations?model=openai-audio&voice=fable"
Python (requests):
import requests
import urllib.parse
text = "使用 GET 方法生成音频对于短文本来说很简单。"
voice = "echo" # 可选:alloy, echo, fable, onyx, nova, shimmer
output_filename = "generated_audio_get.mp3"
encoded_text = urllib.parse.quote(text)
url = f"https://text.pollinations.ai/{encoded_text}"
params = {
"model": "openai-audio",
"voice": voice
}
try:
response = requests.get(url, params=params)
response.raise_for_status()
# 检查响应内容类型是否表示音频文件
if 'audio/mpeg' in response.headers.get('Content-Type', ''):
with open(output_filename, 'wb') as f:
f.write(response.content)
print(f"音频成功保存为 {output_filename}")
else:
print("错误:期望得到音频响应,但收到了意外的内容类型或数据。")
print(f"Content-Type: {response.headers.get('Content-Type')}")
print("响应体预览(前 200 个字符):", response.text[:200])
except requests.exceptions.RequestException as e:
print(f"执行 TTS GET 请求时出错: {e}")
# if response is not None: print(response.text) # 打印 API 错误以供调试
5. 语音转文本功能 (音频输入) 🎤➡️📝
- 模型:
openai-audio - 如何操作: 在
user角色的消息的content数组中提供 base64 编码的音频数据及其格式。{ "model": "openai-audio", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "转录这个:" }, { "type": "input_audio", "input_audio": { "data": "{base64_audio_string}", "format": "wav" } } ] } ] } - 详情: 此功能与 OpenAI 的音频转录 API 非常相似。请参见 OpenAI 音频指南。
- 返回: 标准的 OpenAI 聊天补全 JSON 响应,其中消息内容包含转录文本。
代码示例: 语音转文本 (音频输入)
Python (requests):
import requests
import base64
import json
url = "https://text.pollinations.ai/openai"
headers = {"Content-Type": "application/json"}
def encode_audio_base64(audio_path):
try:
with open(audio_path, "rb") as audio_file:
return base64.b64encode(audio_file.read()).decode('utf-8')
except FileNotFoundError:
print(f"错误:在 {audio_path} 未找到音频文件")
return None
def transcribe_audio(audio_path, question="转录此音频"):
base64_audio = encode_audio_base64(audio_path)
if not base64_audio:
return None
# 确定音频格式(通过扩展名简单检查)。目前仅支持 WAV 和 MP3。
audio_format = audio_path.split('.')[-1].lower()
supported_formats = ['mp3', 'wav']
if audio_format not in supported_formats:
print(f"警告:可能不支持的音频格式 '{audio_format}'。官方仅支持 {', '.join(supported_formats)}。")
return None # 或者如果需要严格检查则抛出错误
payload = {
"model": "openai-audio",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": question},
{
"type": "input_audio",
"input_audio": {
"data": base64_audio,
"format": audio_format
}
}
]
}
]
# 可选:如果模型支持,可以添加 'language' (ISO-639-1) 等参数
}
try:
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
result = response.json()
transcription = result.get('choices', [{}])[0].get('message', {}).get('content')
return transcription
except requests.exceptions.RequestException as e:
print(f"转录音频时出错: {e}")
# if response is not None: print(response.text) # 显示 API 错误以供调试
return None
# --- 使用示例 (取消注释以运行) ---
# # 将 'path/to/your/audio.wav' 替换为实际的音频文件路径 (例如 'sample.wav' 或 'sample.mp3')
# transcript = transcribe_audio('path/to/your/audio.wav')
# if transcript:
# print("转录结果:", transcript)
# else:
# print("转录失败。")
视觉功能 (图像输入) 🖼️➡️📝
- 模型:
openai,openai-large,claude-hybridspace(请通过列出文本模型查看更新)。 - 如何操作: 在
user角色的消息的content数组中包含图像 URL 或 base64 数据。{ "model": "openai", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "描述这张图片:" }, { "type": "image_url", "image_url": { "url": "data:image/jpeg;base64,{base64_string}" } } ] } ], "max_tokens": 300 } - 详情: 此功能模仿 OpenAI 的视觉 API。完整规范请参见 OpenAI 视觉指南。
- 返回: 标准的 OpenAI 聊天补全 JSON 响应,其中包含文本分析结果。
代码示例: 视觉 (图像输入)
CURL (使用 URL):
# 获取带图像分析的 JSON 响应
curl https://text.pollinations.ai/openai \
-H "Content-Type: application/json" \
-d '{
"model": "openai",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "这张图片里有什么?"},
{"type": "image_url", "image_url": {"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/1024px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"}}
]
}
],
"max_tokens": 300
}'
Python (requests, 使用 URL 和本地文件/base64):
import requests
import base64
import json
url = "https://text.pollinations.ai/openai"
headers = {"Content-Type": "application/json"}
# 辅助函数,将本地图像编码为 base64
def encode_image_base64(image_path):
try:
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
except FileNotFoundError:
print(f"错误:在 {image_path} 未找到图像文件")
return None
# --- 方案 1: 分析来自 URL 的图像 ---
def analyze_image_url(image_url, question="这张图片里有什么?"):
payload = {
"model": "openai", # 确保此模型支持视觉功能
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": question},
{"type": "image_url", "image_url": {"url": image_url}}
]
}
],
"max_tokens": 500 # 可选:限制响应长度
}
try:
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"分析 URL 图像时出错: {e}")
return None
# --- 方案 2: 分析本地图像文件 ---
def analyze_local_image(image_path, question="这张图片里有什么?"):
base64_image = encode_image_base64(image_path)
if not base64_image:
return None
# 确定图像格式(通过扩展名简单检查)
image_format = image_path.split('.')[-1].lower()
if image_format not in ['jpeg', 'jpg', 'png', 'gif', 'webp']:
print(f"警告:可能不支持的图像格式 '{image_format}'。假设为 jpeg。")
image_format = 'jpeg' # 对于未知格式,设为默认值或进行更稳健的处理
payload = {
"model": "openai", # 确保此模型支持视觉功能
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": question},
{
"type": "image_url",
"image_url": {
"url": f"data:image/{image_format};base64,{base64_image}"
}
}
]
}
],
"max_tokens": 500
}
try:
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"分析本地图像时出错: {e}")
# if response is not None: print(response.text) # 显示 API 的错误信息
return None
# --- 使用示例 (取消注释以运行) ---
# result_url = analyze_image_url("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/1024px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg")
# if result_url:
# print("URL 图像分析:", result_url['choices'][0]['message']['content'])
# # 将 'path/to/your/image.jpg' 替换为实际的图像文件路径
# result_local = analyze_local_image('path/to/your/image.jpg', question="描述一下主要主体。")
# if result_local:
# print("本地图像分析:", result_local['choices'][0]['message']['content'])
函数调用 ⚙️
- 模型: 使用列出文本模型端点检查兼容性(例如,
openai模型通常支持此功能)。 - 如何操作: 在请求的
tools参数中定义可用的函数。然后,模型可能会返回一个tool_calls对象,表示它希望调用您定义的一个或多个函数。您的应用程序负责执行这些函数,并在后续的 API 调用中将其结果发送回模型。 - 详情: 此功能与 OpenAI 的函数调用 API 非常相似。有关详细的实现模式,请参阅 OpenAI 函数调用指南。
- 返回: 标准的 OpenAI 聊天补全 JSON 响应。当模型决定使用工具时,响应可能包含
tool_calls,否则返回常规文本响应。
代码示例: 函数调用 (概念性)
注意: 这些示例演示了如何定义工具以及如何解释模型调用函数的请求。您需要在自己的应用程序逻辑中实现实际的函数执行(例如本例中的 get_current_weather)。
cURL (定义工具):
curl https://text.pollinations.ai/openai \
-H "Content-Type: application/json" \
-d '{
"model": "openai",
"messages": [{"role": "user", "content": "波士顿的天气怎么样?"}],
"tools": [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获取给定位置的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市和州,例如 San Francisco, CA"
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
}
],
"tool_choice": "auto"
}'
# 预期响应 (如果模型选择调用该工具) 可能包含:
# ... "choices": [ { "message": { "role": "assistant", "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "get_current_weather", "arguments": "{\"location\": \"Boston, MA\"}" } } ] } } ] ...
Python (requests - 设置和响应处理):
import requests
import json
url = "https://text.pollinations.ai/openai"
headers = {"Content-Type": "application/json"}
# 对话的初始消息
messages = [{"role": "user", "content": "东京的天气怎么样?"}]
# 定义您的应用程序向 AI 模型公开的工具
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获取给定位置的当前天气",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "城市和州,例如 San Francisco, CA"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "default": "celsius"}
},
"required": ["location"]
}
}
}
]
# 初始 API 调用的负载
payload = {
"model": "openai", # 模型必须支持函数调用
"messages": messages,
"tools": tools,
"tool_choice": "auto" # 允许模型决定是调用工具还是直接响应
# 也可以强制指定工具:{"type": "function", "function": {"name": "get_current_weather"}}
}
# --- 你的函数实现 ---
# 这个函数模拟获取天气数据。在实际应用中,
# 它会调用一个真实的天气服务 API。
def execute_get_current_weather(location, unit="celsius"):
print(f"\n--- 正在执行 get_current_weather(location='{location}', unit='{unit}') ---")
# 基于位置的虚拟响应
if "tokyo" in location.lower():
return json.dumps({"location": location, "temperature": "15", "unit": unit, "description": "多云"})
else:
return json.dumps({"location": location, "temperature": "unknown"})
# --- 函数实现结束 ---
try:
print("--- 第一次 API 调用 (用户请求) ---")
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
# 解析第一次 API 调用的 JSON 响应
response_data = response.json()
# 检查模型是否决定调用工具
if response_data.get("choices", [{}])[0].get("message", {}).get("tool_calls"):
print("\n--- 模型请求调用工具 ---")
# 为简单起见,假设只有一个工具调用;如有多个,请遍历 tool_calls
tool_call = response_data["choices"][0]["message"]["tool_calls"][0]
function_name = tool_call["function"]["name"]
function_args = json.loads(tool_call["function"]["arguments"])
if function_name == "get_current_weather":
# 使用模型提供的参数调用你的实际后端函数
function_response_content = execute_get_current_weather(
location=function_args.get("location"),
unit=function_args.get("unit", "celsius") # 处理默认值
)
# 将助手的请求(带有 tool_calls)附加到消息历史中
messages.append(response_data["choices"][0]["message"])
# 将工具的响应附加到消息历史中
messages.append(
{
"tool_call_id": tool_call["id"], # 将工具调用与其结果关联起来至关重要
"role": "tool",
"name": function_name,
"content": function_response_content, # 你执行的函数的实际结果
}
)
# --- 第二次 API 调用 (带有函数结果) ---
print("\n--- 第二次 API 调用 (将函数结果发回给模型) ---")
second_payload = {
"model": "openai",
"messages": messages # 发送更新后的消息历史,包括工具的输出
}
second_response = requests.post(url, headers=headers, json=second_payload)
second_response.raise_for_status()
final_result = second_response.json()
print("\n--- 模型的最终响应 ---")
print(json.dumps(final_result, indent=2, ensure_ascii=False))
print("\n最终助手消息:", final_result['choices'][0]['message']['content'])
else:
print(f"错误:模型请求了一个未知的函数 '{function_name}'")
else:
print("\n--- 模型直接响应 (未调用工具) ---")
print("助手:", response_data['choices'][0]['message']['content'])
except requests.exceptions.RequestException as e:
print(f"函数调用请求期间出错: {e}")
# if response is not None: print(response.text) # 打印 API 错误以供调试
except Exception as e:
print(f"处理过程中发生意外错误: {e}")
通用返回格式 (POST /openai 用于文本/视觉/语音转文本/函数):
- OpenAI 风格的聊天补全响应对象 (JSON)。🤖 这种格式确保了与现有 OpenAI API 客户端的兼容性和集成便利性。
速率限制: (继承基础文本 API 的限制,可能受特定模型约束)。详情请参见套餐等级。
用于 AI 助手的 MCP 服务器 🤖🔧
Pollinations 提供了一个 MCP (模型上下文协议) 服务器,使 AI 助手(如通过 Anthropic 的工具使用功能集成的 Claude)能够通过结构化的工具调用直接生成图像和音频。这允许复杂的工作流,其中 AI 可以自主决定使用创造性或生成性能力。
- 服务器名称:
pollinations-multimodal-api(此名称通常在 AI 助手的配置中用于工具定义)。 - 可用工具:
- 图像工具:
generateImageUrl: 生成一张图像并返回其公开可访问的 URL。generateImage: 生成一张图像并直接在响应中返回 base64 编码的图像数据。listImageModels: 列出所有当前可用的图像生成模型。
- 音频工具:
respondAudio: 从文本提示生成音频响应(用于客户端播放)。sayText: 生成逐字朗读所提供文本的语音。listAudioVoices: 列出所有可用于音频生成的音色。
- 文本工具:
listTextModels: 列出所有当前可用的文本生成模型。
- 通用工具:
listModels: 一个多功能工具,用于列出所有可用模型,并可按类型(如 "image", "text", "audio")进行可选过滤。
- 图像工具:
有关全面的安装和使用说明,包括如何将这些工具集成到各种 AI 助手平台,请参阅专门的 MCP 服务器文档(注意:这是一个占位符链接,假设在仓库的该路径下存在一个 README.md 文件)。
(MCP 集成的代码示例高度依赖于客户端的实现(例如 Claude 工具的使用方式),因此最好在专门的 MCP 文档中详细说明。)
React Hooks ⚛️
@pollinations/react 库提供了便捷的 React Hooks,可轻松将 Pollinations.AI API 集成到您的 React 应用程序中,从而简化状态管理和 API 调用。
安装方法:
npm install @pollinations/react
可用的 Hooks:
-
usePollinationsImage(prompt, options)- 用途: 从文本提示生成图像。
- 选项:
width,height,model,seed,nologo,enhance。这些选项与文本生成图像 GET 端点的参数相对应。 - 返回:
string | null(生成图像的 URL,如果尚未生成或出错则为null)。
-
usePollinationsText(prompt, options)- 用途: 从提示生成文本。
- 选项:
seed,model,systemPrompt。这些选项与文本生成文本 GET 端点的参数一致。 - 返回:
string | null(生成的文本,加载中或出错时为null)。
-
usePollinationsChat(initialMessages, options)- 用途: 使用兼容 OpenAI 的 POST 端点管理对话式聊天流程。
- 选项:
seed,jsonMode,model。这些选项映射到文本与多模态 POST 端点的参数。 - 返回: 一个包含以下内容的对象:
sendUserMessage: (message: { role: 'user', content: string | Array<any> }) => void: 一个向聊天发送新用户消息的函数。messages: Array<{role: string, content: string}>: 对话中当前消息的数组(包括用户和助手的消息)。
文档与演练场:
- README: https://github.com/pollinations/pollinations/blob/master/pollinations-react/README.md
- PLAYGROUND: 在 https://react-hooks.pollinations.ai/ 上实时体验这些 Hooks。
实时 Feed API 🔄
实时 Feed API 提供公开生成内容的服务器发送事件(SSE)流,让您能够实时观察 Pollinations.AI 平台上的创作活动。这些 feed 是只读的,提供了平台活动的动态视图。
1. 图像 Feed 🖼️📈
GET https://image.pollinations.ai/feed
描述: 一个 SSE 流,每当通过 Pollinations.AI 图像 API 生成新的公开图像时,它会发送更新。每个事件包含元数据和新创建图像的 URL。
事件数据示例 (每行 data: 的 JSON):
{
"width": 1024,
"height": 1024,
"seed": 42,
"model": "flux",
"imageURL": "https://image.pollinations.ai/prompt/a_radiant_visage_in_the_style_of_renaissance_painting",
"prompt": "一张文艺复兴画风的容光焕发的脸"
}
代码示例: 图像 Feed (SSE)
cURL:
# 显示原始 SSE 流
curl -N https://image.pollinations.ai/feed
Python (sseclient-py):
import sseclient # pip install sseclient-py
import requests
import json
import time
feed_url = "https://image.pollinations.ai/feed"
def connect_image_feed():
while True: # 循环以在出错时重连
try:
print(f"正在连接到图像 Feed: {feed_url}")
# 使用 stream=True 让 requests 处理 SSE
response = requests.get(feed_url, stream=True, headers={'Accept': 'text/event-stream'})
response.raise_for_status() # 对 HTTP 错误抛出异常
client = sseclient.SSEClient(response)
print("连接已建立。等待新图像...")
for event in client.events():
if event.data:
try:
image_data = json.loads(event.data)
print("\n--- 新图像 ---")
print(f" 提示: {image_data.get('prompt', 'N/A')}")
print(f" URL: {image_data.get('imageURL', 'N/A')}")
print(f" 模型: {image_data.get('model', 'N/A')}, 种子: {image_data.get('seed', 'N/A')}")
# 你可以在这里进一步处理 image_data,例如在 UI 中显示、记录到数据库等。
except json.JSONDecodeError:
print(f"\n从图像 Feed 收到非 JSON 数据: {event.data}")
except requests.exceptions.RequestException as e:
print(f"\n连接图像 Feed 时出错: {e}。10 秒后重连...")
time.sleep(10) # 等待一段时间再尝试重连
except KeyboardInterrupt:
print("\n图像 Feed 被用户中断。正在退出。")
break # 用户手动中断时退出循环
except Exception as e:
print(f"\n图像 Feed 发生意外错误: {e}。10 秒后重连...")
time.sleep(10)
# --- 使用 (取消注释以运行) ---
# connect_image_feed()
2. 文本 Feed 📝📈
GET https://text.pollinations.ai/feed
描述: 一个 SSE 流,每当通过 Pollinations.AI 文本 API 生成新的公开文本响应时,它会发送更新。每个事件包含生成的响应、输入消息和使用的模型。
事件数据示例 (每行 data: 的 JSON):
{
"response": "樱花粉代表温柔、善良和生命的短暂。在日本文化中,它象征着春天、更新和无常之美。",
"model": "openai",
"messages": [
{
"role": "user",
"content": "樱花粉这个颜色代表什么?"
}
]
}
代码示例: 文本 Feed (SSE)
cURL:
# 显示原始 SSE 流
curl -N https://text.pollinations.ai/feed
Python (sseclient-py):
import sseclient # pip install sseclient-py
import requests
import json
import time
feed_url = "https://text.pollinations.ai/feed"
def connect_text_feed():
while True: # 循环以在出错时重连
try:
print(f"正在连接到文本 Feed: {feed_url}")
response = requests.get(feed_url, stream=True, headers={'Accept': 'text/event-stream'})
response.raise_for_status() # 对 HTTP 错误抛出异常
client = sseclient.SSEClient(response)
print("连接已建立。等待新文本响应...")
for event in client.events():
if event.data:
try:
text_data = json.loads(event.data)
print("\n--- 新文本响应 ---")
print(f" 模型: {text_data.get('model', 'N/A')}")
# 获取用户提示,如果 messages 中有的话
user_prompt = "N/A"
if text_data.get('messages') and isinstance(text_data['messages'], list):
for msg in text_data['messages']:
if msg.get('role') == 'user' and msg.get('content'):
user_prompt = (msg['content'] or "")[:100] + ("..." if len(msg['content']) > 100 else "")
break
print(f" 用户提示: {user_prompt}")
# 截断长响应以保持日志整洁
response_preview = (text_data.get('response', 'N/A') or "")[:200]
if len(text_data.get('response', '')) > 200: response_preview += "..."
print(f" 响应: {response_preview}")
# 你可以在这里进一步处理 text_data,例如分析内容、显示等。
except json.JSONDecodeError:
print(f"\n从文本 Feed 收到非 JSON 数据: {event.data}")
except requests.exceptions.RequestException as e:
print(f"\n连接文本 Feed 时出错: {e}。10 秒后重连...")
time.sleep(10) # 等待一段时间再尝试重连
except KeyboardInterrupt:
print("\n文本 Feed 被用户中断。正在退出。")
break # 用户手动中断时退出循环
except Exception as e:
print(f"\n文本 Feed 发生意外错误: {e}。10 秒后重连...")
time.sleep(10)
# --- 使用 (取消注释以运行) ---
# connect_text_feed()
认证与套餐等级 🔑
Pollinations.AI 提供灵活的认证方法,以满足您应用程序的需求。
注意: 对于大多数用例,认证是可选的。但是,注册您的应用程序可以解锁更快的响应时间、更高的速率限制以及对高级功能的访问。
无论您是在构建公共 Web 应用、后端服务还是高流量集成,都可以选择最适合您工作流程的认证方式。
开始使用
访问 auth.pollinations.ai 来:
- 设置并注册您应用程序的 referrer
- 为后端应用程序创建 API 令牌 (token)
- 管理您的认证设置
安全最佳实践:切勿在前端代码中暴露 API 令牌!
前端 Web 应用程序应依赖于基于 referrer 的认证。
认证方法
Referrer
对于直接从浏览器调用我们 API 的前端 Web 应用程序,一个有效的 referrer 就足够了。这是推荐用于 Web 应用程序的认证方法,因为它简单且安全。
- 浏览器会自动发送
Referer标头。 - 或者,您可以在 API 请求中明确添加
?referrer=your-app-identifier以进行更具体的识别。 - 注册的 referrer 会获得更高的速率限制和优先访问权。
- 无需令牌 - 避免暴露敏感凭证,从而确保您的前端安全。
如何使用 Referrer:
- 自动(浏览器):当您的 Web 应用发起 API 调用时,浏览器会自动发送
Referer标头。 - 手动(可选):在 API 请求中添加
?referrer=your-app-identifier以进行更具体的识别。 - 注册:访问 auth.pollinations.ai 注册您的域名以获得更高的速率限制和权益。
带有明确 referrer 的 API 调用示例:
https://image.pollinations.ai/prompt/a%20beautiful%20landscape?referrer=mywebapp.com
令牌 (Token)
对于后端服务、脚本和服务器应用程序,令牌提供了最高优先级的访问权限,是非浏览器环境的推荐方法。可以通过以下任一方式提供令牌:
| 方法 | 描述 | 示例 |
|---|---|---|
| Authorization 标头 | 标准的 Bearer token 方式(推荐) | Authorization: Bearer YOUR_TOKEN |
| 查询参数 | 将令牌作为 URL 参数 | ?token=YOUR_TOKEN |
| 请求体 | 在 POST 请求体中包含令牌 | { "token": "YOUR_TOKEN" } |
Bearer 认证 (推荐用于后端)
Bearer 认证方案是后端应用程序的推荐方法,尤其是在与我们兼容 OpenAI 的端点集成时:
curl https://text.pollinations.ai/openai \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"model": "openai",
"messages": [
{"role": "user", "content": "介绍一下你自己。"}
]
}'
套餐等级与速率限制
Pollinations.AI 提供不同的访问套餐,每个套餐具有不同的速率限制和模型可用性。
| 套餐 | 速率限制 | 模型包 | 描述 |
|---|---|---|---|
| anonymous | 15 秒 | 有限 | 未经认证请求的默认套餐。 |
| Seed | 5 秒 | 标准 | 通过 auth.pollinations.ai 注册的应用程序可访问。 |
| Flower | 3 秒 | 高级 | 增强访问权限,具有更快的速率限制和更广泛的模型选择。 |
| Nectar | 无限制 | 高级 | 无限使用,通常适用于企业或高流量合作伙伴。 |
如何访问不同等级的套餐:
- 获得 Seed 套餐访问权限:访问 auth.pollinations.ai 注册您应用程序的 referrer 或创建一个令牌。
- 更高级别的套餐(Flower 和 Nectar)可通过 auth.pollinations.ai 获得。
API 更新 (自 2025.03.31 起) 📅
为了确保可持续性并明确区分免费和受支持的使用方式:
- 生成图像 的响应可能会显示 Pollinations.AI 的徽标 🖼️。对于注册用户,可以通过在请求参数中设置
nologo=true来禁用此功能。 - 生成文本 的响应可能包含指向 pollinations.ai 的链接 🔗。此行为可能会针对更高级别的套餐进行调整或移除。
为获得最佳体验并避免这些特性:
- Web 应用程序:在 auth.pollinations.ai 注册您的 referrer。
- 后端服务:使用 API 令牌而不是 referrer(参见认证部分)。