Pisces API 文档 Pisces API Documentation
完全兼容 OpenAI API 的智能对话接口,支持多种AI模型和应用集成 OpenAI-compatible API for intelligent conversations with multiple AI models and integrations
快速开始 Quick Start
几分钟内集成AI对话功能到您的应用中 Integrate AI chat features into your app in minutes
OpenAI 兼容 OpenAI Compatible
完全兼容OpenAI API格式,无需修改现有代码 Fully compatible with OpenAI API format, no code changes needed
多种模型 Multiple Models
支持GPT、Claude、Gemini等主流AI模型 Support for GPT, Claude, Gemini and other leading AI models
多模态支持 Multimodal Support
支持文本、图像、语音等多种输入输出格式 Support text, image, speech and other input/output formats
基础信息 Basic Information
API 基础地址 Base URL
https://api.pisces.ink
API 版本 API Version
v1
身份验证 Authentication
Pisces API 使用 API 密钥进行身份验证。您需要在请求头中包含您的 API 密钥。 Pisces API uses API keys for authentication. You need to include your API key in the request headers.
重要提示 Important
请妥善保管您的 API 密钥,不要在客户端代码中暴露。建议使用环境变量存储。 Keep your API keys secure and never expose them in client-side code. Use environment variables for storage.
获取 API 密钥 Getting API Keys
- 登录到您的 控制台
- 进入"密钥管理"页面
- 点击"创建新密钥"按钮
- 选择密钥类型和支付方式
- 复制生成的API密钥
- Log in to your Dashboard
- Go to "API Keys" page
- Click "Create New Key" button
- Select key type and payment method
- Copy the generated API key
使用方式 Usage
在所有API请求中,您需要在 HTTP 头部包含您的API密钥: Include your API key in the HTTP headers for all API requests:
curl -X POST "https://api.pisces.ink/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key-here" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{"role": "user", "content": "Hello!"}
]
}'
可用模型 Available Models
OpenAI GPT 模型
gpt-4o
最新的GPT-4模型,支持多模态
推荐gpt-4o-mini
轻量级GPT-4模型,性价比高
经济实惠gpt-3.5-turbo
经典的GPT-3.5模型
Anthropic Claude 模型
claude-3.5-sonnet
Claude最新模型,智能对话
新版本claude-3-haiku
快速响应的Claude模型
图像生成模型
FLUX-pro-1.1
高质量图像生成
高质量playground-v3
创意图像生成
GPT-Image-1
图像编辑和生成
模型更新
我们定期更新和添加新的AI模型。查看 模型价格页面 获取最新的模型列表和定价信息。
对话聊天 Chat Completions
对话聊天 API 允许您与AI模型进行对话交互。支持文本、图像、文件等多种输入格式。 The Chat Completions API allows you to have conversations with AI models. Supports text, image, file and other input formats.
基础用法 Basic Usage
curl -X POST "https://api.pisces.ink/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key-here" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello! How are you?"}
],
"temperature": 0.7,
"max_tokens": 1000
}'
import openai
client = openai.OpenAI(
api_key="your-api-key-here",
base_url="https://api.pisces.ink/v1"
)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello! How are you?"}
],
temperature=0.7,
max_tokens=1000
)
print(response.choices[0].message.content)
const response = await fetch('https://api.pisces.ink/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-api-key-here'
},
body: JSON.stringify({
model: 'gpt-4o-mini',
messages: [
{role: 'system', content: 'You are a helpful assistant.'},
{role: 'user', content: 'Hello! How are you?'}
],
temperature: 0.7,
max_tokens: 1000
})
});
const data = await response.json();
console.log(data.choices[0].message.content);
多模态输入 Multimodal Input
支持在对话中包含图像和文件: Support including images and files in conversations:
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "这张图片里有什么?"},
{
"type": "image_url",
"image_url": "https://example.com/image.jpg"
},
{
"type": "file_url",
"file_url": "https://example.com/document.pdf"
}
]
}
]
)
流式响应 Streaming Response
启用流式传输以实时接收响应: Enable streaming to receive responses in real-time:
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "写一首关于春天的诗"}
],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
参数说明 Parameters
参数 Parameter | 类型 Type | 必需 Required | 描述 Description |
---|---|---|---|
model | string | 是 | 要使用的模型名称 The model name to use |
messages | array | 是 | 对话消息数组 Array of conversation messages |
temperature | number | 否 | 控制随机性,0-2之间 Controls randomness, between 0-2 |
max_tokens | integer | 否 | 最大输出token数 Maximum number of output tokens |
stream | boolean | 否 | 是否启用流式传输 Whether to enable streaming |
SillyTavern 集成
将 Pisces API 集成到 SillyTavern 角色聊天平台
SillyTavern 是一个流行的AI角色聊天平台。通过配置 Pisces API,您可以使用各种先进的AI模型进行角色对话。
配置步骤
打开 API 连接设置
在 SillyTavern 中,点击顶部的 "API Connections" 或齿轮图标进入设置。
路径:设置 → API 连接 → Chat Completion
选择 API 类型
在 API 类型下拉菜单中选择 "OpenAI"。
配置连接参数
填入以下配置信息:
https://api.pisces.ink/v1
您的Pisces
API密钥
选择模型
在模型下拉菜单中选择您想要使用的模型:
推荐模型
- • gpt-4o (多模态支持)
- • claude-3.5-sonnet (智能对话)
- • gpt-4o-mini (经济实惠)
角色扮演优化
- • claude-3.5-sonnet
- • gpt-4o
测试连接
点击 "Test Message" 按钮测试API连接是否正常。
高级配置建议
参数调优
Temperature: 0.8-1.0
适合角色扮演,增加创意性
Max Response Length: 500-1000
平衡响应长度和成本
Context Size: 4000-8000
保持对话连贯性
Frequency Penalty: 0.7
减少重复内容
常见问题
Q: 无法连接到API怎么办?
A: 请检查API URL是否正确(https://api.pisces.ink/v1),确保API密钥有效,并检查网络连接。
Q: 哪个模型最适合角色扮演?
A: claude-3.5-sonnet 在角色扮演和创意对话方面表现优秀,gpt-4o 在多模态交互方面有优势。
Q: 如何控制使用成本?
A: 使用gpt-4o-mini等轻量模型,设置合理的max_tokens限制,或在控制台设置API密钥的使用额度。
Continue 集成
VS Code 中的AI编程助手
即将推出
Continue 集成指南正在编写中...
OpenAI SDK 使用示例
Pisces API 完全兼容 OpenAI SDK,您可以直接使用 OpenAI 的官方库进行调用。
安装依赖
# Python
pip install openai
# Node.js
npm install openai
Python 示例
import openai
import base64
# Pisces API 配置
api_key = "pisces-xxxx"
base_url = "https://api.pisces.ink"
client = openai.OpenAI(
api_key=api_key,
base_url=base_url + "/v1/",
)
# 文本对话
def text_chat():
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
)
print(response.choices[0].message.content)
# 流式对话
def streaming_chat():
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "write a short poem."}
],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
# 图像生成
def image_generation():
result = client.images.generate(
model="playground-v3",
prompt="A cute kitten",
n=1,
)
image_url = result.data[0].url
print(f"Image URL: {image_url}")
# 图像编辑
def image_edit():
result = client.images.edit(
model="GPT-Image-1",
prompt="上传的图片中添加一个彩虹",
image=open('input.png', 'rb'),
n=1,
)
image_base64 = result.data[0].b64_json
image_bytes = base64.b64decode(image_base64)
with open("output.png", "wb") as f:
f.write(image_bytes)
if __name__ == "__main__":
text_chat()
print("\n" + "="*50 + "\n")
streaming_chat()
print("\n" + "="*50 + "\n")
image_generation()
print("\n" + "="*50 + "\n")
image_edit()
Node.js 示例
const OpenAI = require('openai');
const fs = require('fs');
// Pisces API 配置
const apiKey = "pisces-xxxx";
const baseURL = "https://api.pisces.ink/v1";
const openai = new OpenAI({
apiKey: apiKey,
baseURL: baseURL,
});
// 文本对话
async function textChat() {
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
});
console.log(response.choices[0].message.content);
}
// 流式对话
async function streamingChat() {
const stream = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [
{"role": "user", "content": "write a short poem."}
],
stream: true,
});
for await (const chunk of stream) {
if (chunk.choices[0]?.delta?.content) {
process.stdout.write(chunk.choices[0].delta.content);
}
}
}
// 图像生成
async function imageGeneration() {
const result = await openai.images.generate({
model: "playground-v3",
prompt: "A cute kitten",
n: 1,
});
const imageUrl = result.data[0].url;
console.log(`Image URL: ${imageUrl}`);
}
// 多模态对话
async function multimodalChat() {
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{
role: "user",
content: [
{"type": "text", "text": "这张图片里有什么?"},
{
"type": "image_url",
"image_url": "https://example.com/image.jpg"
}
]
}
],
});
console.log(response.choices[0].message.content);
}
// 主函数
async function main() {
await textChat();
console.log("\n" + "=".repeat(50) + "\n");
await streamingChat();
console.log("\n" + "=".repeat(50) + "\n");
await imageGeneration();
console.log("\n" + "=".repeat(50) + "\n");
await multimodalChat();
}
main().catch(console.error);
环境变量配置
为了安全起见,建议使用环境变量来存储API密钥:
# .env 文件
PISCES_API_KEY=your-pisces-api-key-here
PISCES_BASE_URL=https://api.pisces.ink/v1
# Python 中使用环境变量
import os
from dotenv import load_dotenv
load_dotenv()
client = openai.OpenAI(
api_key=os.getenv("PISCES_API_KEY"),
base_url=os.getenv("PISCES_BASE_URL"),
)
LangChain 集成示例
LangChain 是一个强大的框架,用于构建基于大语言模型的应用程序。Pisces API 可以轻松集成到 LangChain 中。
安装依赖
pip install langchain-openai langchain
基础配置
from langchain_openai import ChatOpenAI
from langchain.schema import HumanMessage, SystemMessage
# Pisces API 配置
api_key = "pisces-xxxx"
base_url = "https://api.pisces.ink"
# 配置 LangChain
llm = ChatOpenAI(
model_name="gpt-4o-mini",
api_key=api_key,
openai_api_base=base_url + "/v1",
default_headers={"Authorization": "Bearer Pisces"},
streaming=True,
)
# 基础对话
messages = [
SystemMessage(content="You are a helpful assistant."),
HumanMessage(content="Hello!")
]
response = llm(messages)
print(response.content)
使用 Prompt Templates
from langchain.prompts import PromptTemplate, ChatPromptTemplate
from langchain.chains import LLMChain
# 简单的 Prompt Template
template = """
You are a poetry expert. Write a {style} poem about {topic}.
Poem:
"""
prompt = PromptTemplate(
input_variables=["style", "topic"],
template=template
)
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run(style="haiku", topic="spring flowers")
print(result)
# Chat Prompt Template
chat_prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant that translates {input_language} to {output_language}."),
("human", "{text}")
])
chain = LLMChain(llm=llm, prompt=chat_prompt)
result = chain.run(
input_language="English",
output_language="Chinese",
text="Hello, how are you?"
)
print(result)
流式处理
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
# 配置流式输出
llm_streaming = ChatOpenAI(
model_name="gpt-4o-mini",
api_key=api_key,
openai_api_base=base_url + "/v1",
default_headers={"Authorization": "Bearer Pisces"},
streaming=True,
callbacks=[StreamingStdOutCallbackHandler()]
)
# 流式对话
messages = [
HumanMessage(content="Tell me a story about artificial intelligence.")
]
response = llm_streaming(messages)
对话记忆
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
# 创建对话记忆
memory = ConversationBufferMemory()
# 创建对话链
conversation = ConversationChain(
llm=llm,
memory=memory,
verbose=True
)
# 进行多轮对话
response1 = conversation.predict(input="Hi, my name is Alice.")
print(response1)
response2 = conversation.predict(input="What's my name?")
print(response2)
# 查看对话历史
print(conversation.memory.buffer)
智能代理 (Agents)
from langchain.agents import AgentType, initialize_agent, load_tools
from langchain.tools import DuckDuckGoSearchRun
# 加载工具
search = DuckDuckGoSearchRun()
tools = [search]
# 初始化代理
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
# 使用代理
response = agent.run("What's the weather like in Beijing today?")
print(response)
RAG (检索增强生成)
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import FAISS
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains import RetrievalQA
from langchain.document_loaders import TextLoader
# 配置 Embeddings (使用 Pisces API)
embeddings = OpenAIEmbeddings(
openai_api_key=api_key,
openai_api_base=base_url + "/v1"
)
# 加载和分割文档
loader = TextLoader("your_document.txt")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
# 创建向量存储
vectorstore = FAISS.from_documents(texts, embeddings)
# 创建 RAG 链
qa_chain = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=vectorstore.as_retriever()
)
# 问答
query = "What is the main topic of the document?"
response = qa_chain.run(query)
print(response)
HTTP Requests 示例
如果您不使用官方SDK,也可以直接通过 HTTP 请求调用 Pisces API。以下是不同编程语言的示例。
Python (requests)
import requests
import json
import base64
# Pisces API 配置
api_key = "pisces-xxxx"
base_url = "https://api.pisces.ink"
# API 端点
chat_url = base_url + "/v1/chat/completions"
image_gen_url = base_url + "/v1/images/generations"
image_edit_url = base_url + "/v1/images/edits"
def text_chat():
"""文本对话"""
response = requests.post(chat_url, json={
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
"model": "gpt-4o-mini",
"api_key": api_key
})
result = response.json()
content = result["choices"][0]["message"]["content"]
usage = result["usage"]["total_tokens"]
print(f"Response: {content}")
print(f"Tokens used: {usage}")
def multimodal_chat():
"""多模态对话"""
response = requests.post(chat_url, json={
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "这张图片里有什么?"},
{
"type": "image_url",
"image_url": "https://example.com/image.jpg"
}
]
}
],
"model": "gpt-4o",
"api_key": api_key
})
result = response.json()
print(result["choices"][0]["message"]["content"])
def streaming_chat():
"""流式对话"""
response = requests.post(chat_url, json={
"messages": [
{"role": "user", "content": "写一首关于春天的诗"}
],
"model": "gpt-4o-mini",
"api_key": api_key,
"stream": True
}, stream=True)
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith("data: "):
if line.strip() == "data: [DONE]":
break
json_data = json.loads(line[6:])
if 'choices' in json_data and json_data['choices']:
delta = json_data['choices'][0].get('delta', {})
if 'content' in delta:
print(delta['content'], end="", flush=True)
def image_generation():
"""图像生成"""
response = requests.post(image_gen_url, json={
"prompt": "A beautiful sunset over the ocean",
"model": "FLUX-pro-1.1",
"n": 1,
"size": "1024x1024",
"api_key": api_key
})
result = response.json()
if "data" in result:
image_url = result["data"][0]["url"]
print(f"Generated image URL: {image_url}")
# 如果返回 base64 格式
if "b64_json" in result["data"][0]:
image_base64 = result["data"][0]["b64_json"]
image_bytes = base64.b64decode(image_base64)
with open("generated_image.png", "wb") as f:
f.write(image_bytes)
print("Image saved as generated_image.png")
def image_editing():
"""图像编辑"""
# 读取并编码图像文件
with open("input.png", "rb") as f:
image_data = base64.b64encode(f.read()).decode()
images = [f"data:image/png;base64,{image_data}"]
response = requests.post(image_edit_url, json={
"prompt": "在图片中添加一只小猫",
"image": images,
"model": "GPT-Image-1",
"n": 1,
"size": "1024x1024",
"api_key": api_key
})
result = response.json()
if "data" in result:
image_base64 = result["data"][0]["b64_json"]
image_bytes = base64.b64decode(image_base64)
with open("edited_image.png", "wb") as f:
f.write(image_bytes)
print("Edited image saved as edited_image.png")
if __name__ == "__main__":
print("=== 文本对话 ===")
text_chat()
print("\n=== 多模态对话 ===")
multimodal_chat()
print("\n=== 流式对话 ===")
streaming_chat()
print("\n=== 图像生成 ===")
image_generation()
print("\n=== 图像编辑 ===")
image_editing()
JavaScript/Node.js
const axios = require('axios');
const fs = require('fs');
// Pisces API 配置
const apiKey = "pisces-xxxx";
const baseURL = "https://api.pisces.ink";
// API 端点
const chatURL = `${baseURL}/v1/chat/completions`;
const imageGenURL = `${baseURL}/v1/images/generations`;
// 文本对话
async function textChat() {
try {
const response = await axios.post(chatURL, {
messages: [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
model: "gpt-4o-mini",
api_key: apiKey
});
const content = response.data.choices[0].message.content;
const usage = response.data.usage.total_tokens;
console.log(`Response: ${content}`);
console.log(`Tokens used: ${usage}`);
} catch (error) {
console.error('Error:', error.response?.data || error.message);
}
}
// 流式对话
async function streamingChat() {
try {
const response = await axios({
method: 'post',
url: chatURL,
data: {
messages: [
{"role": "user", "content": "写一首关于春天的诗"}
],
model: "gpt-4o-mini",
api_key: apiKey,
stream: true
},
responseType: 'stream'
});
response.data.on('data', (chunk) => {
const lines = chunk.toString().split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
if (line.trim() === 'data: [DONE]') {
return;
}
try {
const jsonData = JSON.parse(line.slice(6));
if (jsonData.choices && jsonData.choices[0].delta.content) {
process.stdout.write(jsonData.choices[0].delta.content);
}
} catch (e) {
// 忽略解析错误
}
}
}
});
} catch (error) {
console.error('Error:', error.response?.data || error.message);
}
}
// 图像生成
async function imageGeneration() {
try {
const response = await axios.post(imageGenURL, {
prompt: "A beautiful sunset over the ocean",
model: "FLUX-pro-1.1",
n: 1,
size: "1024x1024",
api_key: apiKey
});
if (response.data.data) {
const imageUrl = response.data.data[0].url;
console.log(`Generated image URL: ${imageUrl}`);
// 如果返回 base64 格式
if (response.data.data[0].b64_json) {
const imageBase64 = response.data.data[0].b64_json;
const imageBuffer = Buffer.from(imageBase64, 'base64');
fs.writeFileSync('generated_image.png', imageBuffer);
console.log('Image saved as generated_image.png');
}
}
} catch (error) {
console.error('Error:', error.response?.data || error.message);
}
}
// 多模态对话
async function multimodalChat() {
try {
const response = await axios.post(chatURL, {
messages: [
{
role: "user",
content: [
{"type": "text", "text": "这张图片里有什么?"},
{
"type": "image_url",
"image_url": "https://example.com/image.jpg"
}
]
}
],
model: "gpt-4o",
api_key: apiKey
});
console.log(response.data.choices[0].message.content);
} catch (error) {
console.error('Error:', error.response?.data || error.message);
}
}
// 主函数
async function main() {
console.log("=== 文本对话 ===");
await textChat();
console.log("\n=== 多模态对话 ===");
await multimodalChat();
console.log("\n=== 流式对话 ===");
await streamingChat();
console.log("\n=== 图像生成 ===");
await imageGeneration();
}
main().catch(console.error);
cURL
# 文本对话
curl -X POST "https://api.pisces.ink/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key-here" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
],
"temperature": 0.7,
"max_tokens": 1000
}'
# 流式对话
curl -X POST "https://api.pisces.ink/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key-here" \
-d '{
"model": "gpt-4o-mini",
"messages": [
{"role": "user", "content": "写一首诗"}
],
"stream": true
}'
# 图像生成
curl -X POST "https://api.pisces.ink/v1/images/generations" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key-here" \
-d '{
"prompt": "A beautiful sunset over the ocean",
"model": "FLUX-pro-1.1",
"n": 1,
"size": "1024x1024"
}'
# 多模态对话
curl -X POST "https://api.pisces.ink/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key-here" \
-d '{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "这张图片里有什么?"},
{
"type": "image_url",
"image_url": "https://example.com/image.jpg"
}
]
}
]
}'
PHP
[
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => 'Hello!']
],
'model' => 'gpt-4o-mini',
'api_key' => $apiKey
];
$options = [
'http' => [
'header' => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
],
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($chatURL, false, $context);
$response = json_decode($result, true);
if ($response) {
echo "Response: " . $response['choices'][0]['message']['content'] . "\n";
echo "Tokens used: " . $response['usage']['total_tokens'] . "\n";
}
}
// 图像生成
function imageGeneration($apiKey, $baseURL) {
$imageGenURL = $baseURL . "/v1/images/generations";
$data = [
'prompt' => 'A beautiful sunset over the ocean',
'model' => 'FLUX-pro-1.1',
'n' => 1,
'size' => '1024x1024',
'api_key' => $apiKey
];
$options = [
'http' => [
'header' => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
],
'method' => 'POST',
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($imageGenURL, false, $context);
$response = json_decode($result, true);
if ($response && isset($response['data'])) {
echo "Generated image URL: " . $response['data'][0]['url'] . "\n";
}
}
// 执行示例
textChat($apiKey, $chatURL);
imageGeneration($apiKey, $baseURL);
?>
图像生成 Image Generation
Pisces API 支持多种图像生成和编辑功能,包括文本到图像生成、图像编辑等。 Pisces API supports various image generation and editing features, including text-to-image generation and image editing.
文本到图像生成 Text to Image Generation
import openai
client = openai.OpenAI(
api_key="your-api-key-here",
base_url="https://api.pisces.ink/v1"
)
# 图像生成
response = client.images.generate(
model="FLUX-pro-1.1",
prompt="A futuristic city with flying cars and neon lights",
n=1,
size="1024x1024",
quality="high"
)
image_url = response.data[0].url
print(f"Generated image URL: {image_url}")
# 保存图像
import requests
from PIL import Image
from io import BytesIO
image_response = requests.get(image_url)
image = Image.open(BytesIO(image_response.content))
image.save("generated_image.png")
图像编辑 Image Editing
import base64
# 图像编辑
result = client.images.edit(
model="GPT-Image-1",
prompt="在图片中添加一只可爱的小猫咪",
image=open('original_image.png', 'rb'),
n=1,
size="1024x1024"
)
# 保存编辑后的图像
image_base64 = result.data[0].b64_json
image_bytes = base64.b64decode(image_base64)
with open("edited_image.png", "wb") as f:
f.write(image_bytes)
print("Image edited and saved as edited_image.png")
支持的图像模型 Supported Image Models
FLUX-pro-1.1
最新的高质量图像生成模型
- • 支持多种尺寸比例
- • 高质量输出
- • 快速生成
GPT-Image-1
专业的图像编辑和生成模型
- • 图像编辑能力
- • 细节处理优秀
- • 遮罩支持
参数说明 Parameters
参数 Parameter | 类型 Type | 描述 Description |
---|---|---|
prompt | string | 描述要生成图像的文本提示 Text description of the image to generate |
model | string | 使用的图像生成模型 Image generation model to use |
size | string | 图像尺寸(如:1024x1024) Image size (e.g., 1024x1024) |
n | integer | 生成图像的数量(1-4) Number of images to generate (1-4) |
quality | string | 图像质量(low, medium, high) Image quality (low, medium, high) |
语音合成 Text to Speech
即将推出
语音合成功能正在开发中...
错误处理 Error Handling
了解常见的错误码和如何处理它们。 Learn about common error codes and how to handle them.
常见错误码 Common Error Codes
状态码 | 错误类型 | 描述 |
---|---|---|
400 | Bad Request | 请求参数错误或格式不正确 |
401 | Unauthorized | API密钥无效或未提供 |
403 | Forbidden | 余额不足或权限不够 |
429 | Rate Limit | 请求频率过高 |
500 | Server Error | 服务器内部错误 |
错误处理示例 Error Handling Examples
import openai
from openai import OpenAIError
client = openai.OpenAI(
api_key="your-api-key-here",
base_url="https://api.pisces.ink/v1"
)
def safe_api_call():
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Hello!"}
]
)
return response.choices[0].message.content
except openai.AuthenticationError as e:
print(f"身份验证失败: {e}")
return None
except openai.RateLimitError as e:
print(f"请求频率过高: {e}")
# 可以实现重试逻辑
return None
except openai.BadRequestError as e:
print(f"请求参数错误: {e}")
return None
except openai.APIConnectionError as e:
print(f"网络连接错误: {e}")
return None
except OpenAIError as e:
print(f"API错误: {e}")
return None
except Exception as e:
print(f"未知错误: {e}")
return None
# 使用示例
result = safe_api_call()
if result:
print(f"Success: {result}")
else:
print("API调用失败")
常见问题 Frequently Asked Questions
Q: 如何获取API密钥?
A: 登录到 控制台,进入"密钥管理"页面,点击"创建新密钥"即可生成API密钥。
Q: 支持哪些编程语言?
A: 由于我们的API完全兼容OpenAI格式,所以支持所有主流编程语言,包括Python、JavaScript、Go、Java、PHP、C#等。
Q: 如何控制使用成本?
A: 可以在控制台设置API密钥的使用额度,选择性价比更高的模型(如gpt-4o-mini),或设置合理的max_tokens参数。
Q: 支持流式传输吗?
A: 是的,我们支持流式传输。在请求中设置 "stream": true 即可启用流式传输功能。
Q: 遇到问题如何获得支持?
A: 可以加入我们的QQ群:523024031【除酒馆外其他业务】、729405765【酒馆专群】获取技术支持和帮助。