init: AI 文生图调用脚本与文档
- gpt-image-t2i / grok-image-t2i:OpenAI 兼容接口文生图脚本 - SKILLS.md:输出规范(统一输出到 output/,按「模型名-时间戳」命名) - 接口与参数说明文档
This commit is contained in:
@@ -0,0 +1 @@
|
||||
.DS_Store
|
||||
@@ -0,0 +1,54 @@
|
||||
# Skills
|
||||
|
||||
本目录提供了调用 AI 文生图接口(text-to-image)的 Python 脚本,供其他 Agent 直接调用,无需自己实现 API 逻辑。
|
||||
|
||||
## 可用脚本
|
||||
|
||||
| 能力 | 脚本路径 | 模型 | 说明 |
|
||||
|------|----------|------|------|
|
||||
| GPT 绘图 | `gpt-image-t2i/generate_image.py` | `gpt-image-2-2K` | 通过 OpenAI 兼容接口生成图片 |
|
||||
| Grok 绘图 | `grok-image-t2i/generate_image.py` | `grok-imagine-image-lite` | 通过 xAI 兼容接口生成图片 |
|
||||
|
||||
两个脚本共用同一个 OpenAI 兼容接口:`https://api.slomerex.xyz/v1/images/generations`,API Key 已硬编码在各自脚本中,Agent 无需处理鉴权。
|
||||
|
||||
## 输出规范(所有 Agent 必须遵守)
|
||||
|
||||
- **输出目录**:本技能产生的所有文件(生成的图片等)统一保存到项目根目录的 `output/` 文件夹中,不要输出到其他位置。
|
||||
- **图片命名格式**:每次生成的图片统一按 `{调用的模型名}-{时间戳}.{后缀名}` 命名,例如:
|
||||
- `gpt-image-2-2K-20260818_143025.png`
|
||||
- `grok-imagine-image-lite-20260818_143025.jpg`
|
||||
- 其中 `{调用的模型名}` 为实际调用的模型名(见上表),`{时间戳}` 使用 `%Y%m%d_%H%M%S` 格式(如 `20260818_143025`),`{后缀名}` 按实际图片类型(`.png` / `.jpg` / `.webp`)。
|
||||
- 脚本默认已按上述规范输出(`output/{模型名}-{时间戳}.{后缀名}`);如需自定义,通过 `-o` 指定,但仍应保持 `output/` 目录与「模型名-时间戳」命名格式。
|
||||
|
||||
## 使用方式
|
||||
|
||||
```bash
|
||||
# 使用默认提示词(脚本内 PROMPT 变量)生成图片
|
||||
python3 gpt-image-t2i/generate_image.py
|
||||
python3 grok-image-t2i/generate_image.py
|
||||
|
||||
# 传入自定义提示词(不传则使用脚本内硬编码的 PROMPT)
|
||||
python3 grok-image-t2i/generate_image.py "a cute cat sitting on a windowsill, soft morning light"
|
||||
|
||||
# 指定输出路径(必须输出到 output/ 文件夹,并按「模型名-时间戳」命名)
|
||||
python3 grok-image-t2i/generate_image.py -o output/grok-imagine-image-lite-20260818_143025.jpg
|
||||
|
||||
# 指定图片尺寸(GPT 支持 1024x1024 / 1536x1024 等)
|
||||
python3 gpt-image-t2i/generate_image.py --size 1536x1024
|
||||
```
|
||||
|
||||
## 命令行参数
|
||||
|
||||
- `prompt`:图片提示词(可选位置参数),不传则使用脚本内硬编码的 `PROMPT`
|
||||
- `--size`:图片尺寸,默认 `1024x1024`
|
||||
- `--output, -o`:输出文件路径,应指向 `output/` 下的文件,并按 `{模型名}-{时间戳}.{后缀名}` 命名(如 `-o output/gpt-image-2-2K-20260818_143025.png`)
|
||||
|
||||
## 自定义提示词
|
||||
|
||||
优先通过命令行参数传入(如 `python3 grok-image-t2i/generate_image.py "你的描述"`);如需修改默认提示词,编辑脚本中的 `PROMPT` 变量即可。建议使用详细、具体的英文描述以获得更好的效果。
|
||||
|
||||
## 注意事项
|
||||
|
||||
- 脚本依赖 Python 标准库(`urllib`、`base64` 等),无需安装第三方包。
|
||||
- 请求图片下载时需要携带浏览器 `User-Agent`,否则接口返回 403(脚本已处理)。
|
||||
- 生成图片通常需要几十秒,脚本设置了 120 秒超时。
|
||||
@@ -0,0 +1,76 @@
|
||||
# GPT 图像生成 API 文档
|
||||
|
||||
## 调用示例
|
||||
|
||||
### gpt-image-2-1K
|
||||
|
||||
```bash
|
||||
curl https://api.slomerex.xyz/v1/chat/completions \
|
||||
-H "Authorization: Bearer $NEW_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "gpt-image-2-1K",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain quantum entanglement in one paragraph."
|
||||
}
|
||||
],
|
||||
"temperature": 0.7
|
||||
}'
|
||||
```
|
||||
|
||||
### gpt-image-2-2K
|
||||
|
||||
```bash
|
||||
curl https://api.slomerex.xyz/v1/chat/completions \
|
||||
-H "Authorization: Bearer $NEW_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "gpt-image-2-2K",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain quantum entanglement in one paragraph."
|
||||
}
|
||||
],
|
||||
"temperature": 0.7
|
||||
}'
|
||||
```
|
||||
|
||||
### gpt-image-2-4K
|
||||
|
||||
```bash
|
||||
curl https://api.slomerex.xyz/v1/chat/completions \
|
||||
-H "Authorization: Bearer $NEW_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "gpt-image-2-4K",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain quantum entanglement in one paragraph."
|
||||
}
|
||||
],
|
||||
"temperature": 0.7
|
||||
}'
|
||||
```
|
||||
|
||||
> 将 `<YOUR_API_KEY>` 替换为令牌设置中的 API Key。
|
||||
|
||||
## 身份验证
|
||||
|
||||
所有请求必须携带 `Authorization: Bearer <TOKEN>` 请求头。Anthropic 格式的端点也接受 `x-api-key` 请求头。
|
||||
|
||||
在「令牌」页面生成 API Key,可以按模型、分组、IP、速率等维度精细化授权。
|
||||
|
||||
## 支持的参数
|
||||
|
||||
| 参数 | 类型 | 默认值 / 范围 | 说明信息 |
|
||||
|------|------|--------------|----------|
|
||||
| prompt | string(必填) | — | 想要生成图像的文字描述 |
|
||||
| size | enum | 1024x1024 | 输出图像尺寸 |
|
||||
| quality | enum | standard | 生成质量预设 |
|
||||
| style | enum | vivid | 画风 |
|
||||
| n | integer | 1(范围 1 ~ 10) | 生成的图像数量 |
|
||||
| response_format | enum | url | 图像结果的返回方式 |
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""调用 gpt-image-2-2K 生成图片的示例脚本"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import datetime
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
|
||||
API_URL = "https://api.slomerex.xyz/v1/images/generations"
|
||||
API_KEY = "sk-zkaPOvLoj1VRFxStvCQkpBXjcDELrgEK0F8Z2Vt9d8SZo8CV"
|
||||
MODEL = "gpt-image-2-2K"
|
||||
|
||||
# 图片描述提示词,直接改这里即可
|
||||
PROMPT = """An ancient steampunk city floating above stormy clouds, with a massive bronze clock tower at its center, the clock face made of glowing blue crystal. Golden "god rays" of sunset pierce through the gaps in the cloud layers, illuminating the intricate gears and pipes on the tower's surface. In the foreground, a small airship is passing through an arch beside the tower, trailing long warm-colored exhaust smoke. Tiny pedestrians holding umbrellas are faintly visible on the streets. Overall color palette features a strong contrast between teal-blue and amber-gold. Cinematic lighting, photorealistic textures, 8K, extremely detailed, with an epic sense of impending storm."""
|
||||
|
||||
|
||||
def generate_image(prompt: str, size: str = "1024x1024", output: str = "output.png"):
|
||||
payload = {
|
||||
"model": MODEL,
|
||||
"prompt": prompt,
|
||||
"size": size,
|
||||
"n": 1,
|
||||
}
|
||||
|
||||
req = urllib.request.Request(
|
||||
API_URL,
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {API_KEY}",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode("utf-8", errors="replace")
|
||||
print(f"HTTP {e.code} 错误: {body}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except urllib.error.URLError as e:
|
||||
print(f"网络错误: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if "data" not in data:
|
||||
print(f"响应中没有 data 字段: {json.dumps(data, ensure_ascii=False)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
out_path = Path(output)
|
||||
for i, item in enumerate(data["data"]):
|
||||
# 优先取 b64_json,否则取 url
|
||||
if item.get("b64_json"):
|
||||
raw = base64.b64decode(item["b64_json"])
|
||||
elif item.get("url"):
|
||||
with urllib.request.urlopen(item["url"], timeout=120) as img_resp:
|
||||
raw = img_resp.read()
|
||||
else:
|
||||
print(f"第 {i} 张图片没有 b64_json / url 字段", file=sys.stderr)
|
||||
continue
|
||||
|
||||
path = out_path if len(data["data"]) == 1 else out_path.with_name(f"{out_path.stem}_{i}{out_path.suffix}")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(raw)
|
||||
print(f"已保存: {path} ({len(raw)} bytes)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="使用 gpt-image-2-2K 生成图片")
|
||||
parser.add_argument("prompt", nargs="?", default=None, help="图片提示词(不传则使用脚本内硬编码的 PROMPT)")
|
||||
parser.add_argument("--size", default="1024x1024", help="图片尺寸,如 1024x1024 / 1536x1024")
|
||||
# 默认输出到项目根目录的 output/ 文件夹,按「模型名-时间戳.后缀名」命名
|
||||
parser.add_argument(
|
||||
"--output", "-o",
|
||||
default=f"output/{MODEL}-{datetime.datetime.now():%Y%m%d_%H%M%S}.png",
|
||||
help="输出文件路径(默认 output/ 目录下「模型名-时间戳.png」)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
generate_image(args.prompt or PROMPT, args.size, args.output)
|
||||
@@ -0,0 +1,38 @@
|
||||
# Grok 图像生成 API 文档
|
||||
|
||||
## 调用示例
|
||||
|
||||
```bash
|
||||
curl https://api.slomerex.xyz/v1/chat/completions \
|
||||
-H "Authorization: Bearer $NEW_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"model": "gpt-image-2-1K",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Explain quantum entanglement in one paragraph."
|
||||
}
|
||||
],
|
||||
"temperature": 0.7
|
||||
}'
|
||||
```
|
||||
|
||||
> 将 `<YOUR_API_KEY>` 替换为令牌设置中的 API Key。
|
||||
|
||||
## 身份验证
|
||||
|
||||
所有请求必须携带 `Authorization: Bearer <TOKEN>` 请求头。Anthropic 格式的端点也接受 `x-api-key` 请求头。
|
||||
|
||||
在「令牌」页面生成 API Key,可以按模型、分组、IP、速率等维度精细化授权。
|
||||
|
||||
## 支持的参数
|
||||
|
||||
| 参数 | 类型 | 默认值 / 范围 | 说明信息 |
|
||||
|------|------|--------------|----------|
|
||||
| prompt | string(必填) | — | 想要生成图像的文字描述 |
|
||||
| size | enum | 1024x1024 | 输出图像尺寸 |
|
||||
| quality | enum | standard | 生成质量预设 |
|
||||
| style | enum | vivid | 画风 |
|
||||
| n | integer | 1(范围 1 ~ 10) | 生成的图像数量 |
|
||||
| response_format | enum | url | 图像结果的返回方式 |
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""调用 grok-imagine-image-lite 生成图片的示例脚本"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import datetime
|
||||
import json
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
|
||||
API_URL = "https://api.slomerex.xyz/v1/images/generations"
|
||||
API_KEY = "sk-f8c4T7gx9Putj039gca11sstL8rTYXr1rSDJmGf6Cg0IhOw8"
|
||||
MODEL = "grok-imagine-image-lite"
|
||||
|
||||
# 图片描述提示词,直接改这里即可
|
||||
PROMPT = """A majestic white-and-gold dragon soaring through a vast sky filled with drifting clouds at golden hour. Its scales glisten under the warm sunset light, and its wings cast soft shadows over a distant misty mountain range below. Cinematic composition, photorealistic textures, volumetric lighting, 8K, extremely detailed."""
|
||||
|
||||
|
||||
def generate_image(prompt: str, size: str = "1024x1024", output: str = "output.png"):
|
||||
payload = {
|
||||
"model": MODEL,
|
||||
"prompt": prompt,
|
||||
"size": size,
|
||||
"n": 1,
|
||||
}
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {API_KEY}",
|
||||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
|
||||
}
|
||||
|
||||
req = urllib.request.Request(
|
||||
API_URL,
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
headers=headers,
|
||||
method="POST",
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode("utf-8", errors="replace")
|
||||
print(f"HTTP {e.code} 错误: {body}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except urllib.error.URLError as e:
|
||||
print(f"网络错误: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if "data" not in data:
|
||||
print(f"响应中没有 data 字段: {json.dumps(data, ensure_ascii=False)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
out_path = Path(output)
|
||||
for i, item in enumerate(data["data"]):
|
||||
# 优先取 b64_json,否则取 url
|
||||
if item.get("b64_json"):
|
||||
raw = base64.b64decode(item["b64_json"])
|
||||
elif item.get("url"):
|
||||
# 图片 URL 需要带浏览器 User-Agent,否则会被服务端拦截(403)
|
||||
img_req = urllib.request.Request(item["url"], headers={"User-Agent": headers["User-Agent"]})
|
||||
with urllib.request.urlopen(img_req, timeout=120) as img_resp:
|
||||
raw = img_resp.read()
|
||||
else:
|
||||
print(f"第 {i} 张图片没有 b64_json / url 字段", file=sys.stderr)
|
||||
continue
|
||||
|
||||
# Grok 默认返回 JPEG,根据 mime_type 修正扩展名
|
||||
ext_map = {"image/jpeg": ".jpg", "image/png": ".png", "image/webp": ".webp"}
|
||||
mime = item.get("mime_type") or item.get("content_type")
|
||||
path = out_path
|
||||
if len(data["data"]) > 1:
|
||||
path = out_path.with_name(f"{out_path.stem}_{i}{out_path.suffix}")
|
||||
if mime and mime in ext_map and path.suffix.lower() != ext_map[mime]:
|
||||
path = path.with_suffix(ext_map[mime])
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(raw)
|
||||
print(f"已保存: {path} ({len(raw)} bytes)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="使用 grok-imagine-image-lite 生成图片")
|
||||
parser.add_argument("prompt", nargs="?", default=None, help="图片提示词(不传则使用脚本内硬编码的 PROMPT)")
|
||||
parser.add_argument("--size", default="1024x1024", help="图片尺寸,如 1024x1024")
|
||||
# 默认输出到项目根目录的 output/ 文件夹,按「模型名-时间戳.后缀名」命名
|
||||
parser.add_argument(
|
||||
"--output", "-o",
|
||||
default=f"output/{MODEL}-{datetime.datetime.now():%Y%m%d_%H%M%S}.png",
|
||||
help="输出文件路径(默认 output/ 目录下「模型名-时间戳.png」,实际后缀按返回的 mime_type 自动修正)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
generate_image(args.prompt or PROMPT, args.size, args.output)
|
||||
Reference in New Issue
Block a user