# Skill: 小窗便利店 — AI 能力聚合平台

> 统一入口调用 7+ 供应商、1400+ 模型。你描述需求，平台自动匹配供应商、生成协议、执行调用。密钥在服务端，你只需要 protocol_id + input。

## 快速开始（30 秒上手）

```bash
# 第 1 步：协商（免费，不需要登录）
curl -X POST https://test-aiapi.callai.online/api/negotiate \
  -H 'Content-Type: application/json' \
  -d '{"request_description": "把中文翻译成英文"}'
# → {"protocol_id": "translate-zh-en", "protocol": {...}}

# 第 2 步：执行（需要 X-Api-Key 或 Bearer token）
curl -X POST https://test-aiapi.callai.online/api/execute \
  -H 'Content-Type: application/json' \
  -H 'X-Api-Key: aiapi_{你的key}' \
  -d '{"protocol_id": "translate-zh-en", "input": {"text": "今天天气真好"}}'
# → {"output": {...}, "billing": {"charged": 1}, "performance": {"latency_ms": 1200}}
```

核心规则：
- **协商免费**，随便试
- **protocol_id 永久有效**，存好反复用
- **密钥安全**，所有 API Key 在服务端
- **精确计费**，按上游 API 实际用量计费（token/图片/字符/秒）× 1.2 加价。BYOK 自带密钥仅收 1 分路由费。失败自动退款

---

## 全部端点

| 端点 | 方法 | 鉴权 | 说明 |
|------|------|------|------|
| `/api/negotiate` | POST | 无 | 描述需求，AI 生成调用协议 |
| `/api/execute` | POST | X-Api-Key / Bearer / X-Service-Key | 按协议执行 API 调用 |
| `/api/capabilities` | GET | 无 | 查看供应商能力列表 |
| `/api/capabilities?id=google` | GET | 无 | 查看单个供应商详情 |
| `/api/protocols` | GET | 无 | 查看已保存的协议列表 |
| `/api/protocols?id=xxx` | GET | 无 | 查看单个协议详情 |
| `/api/health` | GET | 无 | 执行引擎健康检查 |
| `/api/health-report` | GET | 无 | 供应商健康监测报告 |
| `/api/models?provider=google` | GET | 无 | 实时模型列表（按品类分组，10 分钟缓存） |
| `/api/execute?async=true` | POST | X-Api-Key / Bearer / X-Service-Key | 异步执行，立即返回 task_id |
| `/api/tasks/{task_id}` | GET | 同上 | 查询异步任务状态和结果 |
| `/api/help` | GET | 无 | 按需发现（topic 参数渐进式返回能力信息） |
| `/api/help?topic=recipes` | GET | 无 | 全部配方索引（含 input_schema） |
| `/api/help?topic=recipe&id=xxx` | GET | 无 | 单个��方详情 |
| `/api/files/upload` | POST | Bearer / X-Service-Key | 上传文件到 OSS 图床 |
| `/api/keys` | GET/POST/PUT/DELETE | X-Api-Key / Bearer | 用户 BYOK 密钥管理 |
| `/api/keys/apikey` | GET/POST/DELETE | X-Api-Key / Bearer | Agent API Key 管理 |
| `/api/usage` | GET | Bearer | 调用记录查询 |

基础 URL: `https://test-aiapi.callai.online`

---

## 鉴权方式

### 方式一：X-Api-Key（推荐，面向 Agent）

在控制台生成 API Key，请求时携带 `X-Api-Key: aiapi_{key}`。无需 SMS 登录，按量扣费。

```bash
curl -X POST https://test-aiapi.callai.online/api/execute \
  -H 'X-Api-Key: aiapi_your_key_here' \
  -H 'Content-Type: application/json' \
  -d '{"protocol_id": "translate-zh-en", "input": {"text": "hello"}}'
```

生成方式：登录 [控制台](https://static2.callai.online/test-aiapi-store/console.html) → 密钥 Tab → 生成 API Key

### 方式二：用户 JWT Token（面向终端用户）

用户通过手机号登录获取 token，请求时携带 `Authorization: Bearer {token}`。余额不足返回 402。

### 方式三：X-Service-Key（仅限内部服务）

平台内部可信服务间调用，免登录、免扣费。**密钥由管理员单独分发，不在此文档公开。**

```bash
curl -X POST https://test-aiapi.callai.online/api/execute \
  -H 'Content-Type: application/json' \
  -H 'X-Service-Key: <管理员分发>' \
  -d '{"protocol_id": "translate-zh-en", "input": {"text": "你好"}}'
```

外部 Agent 请使用 X-Api-Key 方式，不要使用 X-Service-Key。

---

## 自带密钥 (BYOK)

用自己的供应商 API Key 调用，仅收 1 分/次路由费（平台密钥按类别定价）。3 步完成：

### 第 1 步：上传密钥（与账号绑定）

```bash
curl -X POST https://test-aiapi.callai.online/api/keys \
  -H 'X-Api-Key: aiapi_your_key' \
  -H 'Content-Type: application/json' \
  -d '{"provider": "google", "value": "AIzaSy...", "display_name": "My Google Key"}'
# → {"key_id": "xxx", "provider": "google", "masked_value": "AIz***Sy.."}
```

密钥加密存储，与你的账号绑定。每个供应商只能绑定一个密钥。

### 第 2 步：正常调用（自动使用你的密钥）

```bash
curl -X POST https://test-aiapi.callai.online/api/execute \
  -H 'X-Api-Key: aiapi_your_key' \
  -H 'Content-Type: application/json' \
  -d '{"protocol_id": "translate-zh-en", "input": {"text": "你好"}}'
# → billing.key_type 为 "customer" 表示用了你的密钥，charged: 0
```

执行引擎自动检测协议要访问哪个供应商，优先查你绑定的密钥。找到就用你的（免计费），没找到才 fallback 到平台密钥（按次计费）。

### 第 3 步：管理密钥

```bash
# 查看已绑定的密钥
curl https://test-aiapi.callai.online/api/keys \
  -H 'X-Api-Key: aiapi_your_key'

# 删除密钥
curl -X DELETE https://test-aiapi.callai.online/api/keys \
  -H 'X-Api-Key: aiapi_your_key' \
  -H 'Content-Type: application/json' \
  -d '{"key_id": "xxx"}'

# 更新密钥值
curl -X PUT https://test-aiapi.callai.online/api/keys \
  -H 'X-Api-Key: aiapi_your_key' \
  -H 'Content-Type: application/json' \
  -d '{"key_id": "xxx", "value": "new_key_value"}'
```

### 密钥优先级

**用户密钥 > 平台密钥**。用户密钥收 1 分/次路由费，平台密钥按上游实际用量精确计费（token × 费率 × 1.2）。失败自动全额退款。

### 支持的 provider

`yunwu`, `tuzi`, `dashscope`, `volcengine`, `minimax`, `siliconflow`, `deepseek`, `google`, `anthropic`, `openai`, `replicate`, `elevenlabs`

---

## 使用方式

### 方式一：协商 + 执行（不确定用什么供应商时）

```bash
# 协商 — 描述你要做什么，越具体越好
curl -X POST https://test-aiapi.callai.online/api/negotiate \
  -H 'Content-Type: application/json' \
  -d '{"request_description": "用 Gemini 生成一张图片，支持传入参考图做编辑"}'
```

协商返回一个 protocol，里面包含 `input_schema`（你需要传什么参数）和 `steps`（执行步骤）。

### 方式二：直接执行已有协议（知道 protocol_id 时）

```bash
curl -X POST https://test-aiapi.callai.online/api/execute \
  -H 'Content-Type: application/json' \
  -H 'X-Api-Key: aiapi_your_key_here' \
  -d '{"protocol_id": "translate-zh-en", "input": {"text": "你好世界"}}'
```

### 方式三：异步执行（图像/视频等耗时任务）

不想等 20-30 秒？加 `?async=true` 立即拿到 task_id，后台执行，轮询获取结果。

```bash
# 第 1 步：提交（立即返回 202）
curl -X POST 'https://test-aiapi.callai.online/api/execute?async=true' \
  -H 'Content-Type: application/json' \
  -H 'X-Api-Key: aiapi_your_key' \
  -d '{"protocol_id": "recipe-google-image-gen-gemini-flash", "input": {"prompt": "赛博朋克城市", "aspect_ratio": "16:9"}}'
# → {"async": true, "task_id": "task_62afe494dbfa4810", "poll_url": "/api/tasks/task_62afe494dbfa4810"}

# 第 2 步：轮询（每 3-5 秒查一次）
curl 'https://test-aiapi.callai.online/api/tasks/task_62afe494dbfa4810' \
  -H 'X-Api-Key: aiapi_your_key'
# 执行中 → {"status": "running"}
# 完成   → {"status": "succeeded", "output": {"candidates": [{"content": {"parts": [...]}}]}}
# 失败   → {"status": "failed", "error": "..."}
```

适合:
- 图像生成/编辑（10-30s）
- 视频生成（1-5min）
- 批量任务并发提交（支持多任务同时执行）
- 不希望长连接阻塞的场景

注意:
- 与同步执行共享鉴权和计费逻辑
- 大输出（>500KB，如图像 base64）自动存 OSS，轮询时加 `?full=true` 获取完整结果
- 任务记录保留 7 天

### 方式四：内联协议（自己构造协议，最灵活）

不需要协商，直接在请求体里传完整 protocol。适合你已经知道 API 格式的场景。

```bash
curl -X POST https://test-aiapi.callai.online/api/execute \
  -H 'Content-Type: application/json' \
  -H 'X-Api-Key: aiapi_your_key_here' \
  -d '{
    "protocol": {
      "protocol_id": "inline-demo",
      "pipeline": {
        "steps": [{
          "step_id": "s1",
          "action": "http_request",
          "config": {
            "method": "POST",
            "url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent",
            "headers": {
              "x-goog-api-key": "{{secrets.google_api_key}}",
              "Content-Type": "application/json"
            },
            "body": {
              "contents": [{"parts": [{"text": "{{input.prompt}}"}]}],
              "generationConfig": {"maxOutputTokens": 200}
            }
          },
          "timeout_ms": 120000
        }],
        "input_schema": {},
        "output_schema": {}
      }
    },
    "input": {"prompt": "Hello, Gemini!"}
  }'
```

---

## 已验证可直接使用的协议

### 文本翻译

```json
{"protocol_id": "translate-zh-en", "input": {"text": "今天天气真好"}}
```
供应商: DashScope qwen-plus, 延迟 ~1s

### 语音合成 (TTS)

```json
{"protocol_id": "tts-minimax-zh-mp3", "input": {"text": "你好世界"}}
```
供应商: MiniMax speech-2.8-hd, 300+ 音色可选

### 图像生成 (Gemini 原生，推荐)

```json
{"protocol_id": "recipe-google-image-gen-gemini-flash", "input": {"prompt": "一只穿着宇航服的猫", "aspect_ratio": "16:9"}}
```
供应商: Google Gemini 3.1 Flash Image, 14种宽高比, 512-4K, 延迟 ~6s

### 图像编辑 (Gemini 原生)

```json
{"protocol_id": "recipe-google-image-edit-gemini-flash", "input": {"image_oss_key": "test-aiapi/files/photo.jpg", "prompt": "变成卡通风格"}}
```
供应商: Google Gemini 3.1 Flash Image, 自然语言编辑无需mask, 延迟 ~8s

### 风格迁移 (双参考图)

```json
{"protocol_id": "recipe-google-image-style-transfer", "input": {"subject_oss_key": "test-aiapi/files/subject.jpg", "style_oss_key": "test-aiapi/files/style.jpg"}}
```
供应商: Google Gemini 3.1 Flash Image, 延迟 ~10s

### 图像生成 (Imagen 4.0，仅英文纯文生图)

```json
{"protocol_id": "image-generate-imagen4", "input": {"prompt": "a cute lobster in a neon store"}}
```
供应商: Google Imagen 4.0, 仅英文, 无编辑能力, 延迟 ~8s

---

## 供应商能力总览

| 供应商 | 模型数 | 核心能力 | 特色 |
|--------|--------|---------|------|
| Google Gemini | 48+ | 对话/图像生成/图像理解/视频/TTS/Embedding | 原生多模态, SSE 流式, Files API |
| 云雾 AI | 600+ | 对话/图像/视频/TTS/STT/Embedding | 模型最多, 支持 GPT/Claude/Gemini |
| 兔子 AI | 731+ | 对话/图像/视频/TTS/STT/Embedding | OpenAI 兼容格式 |
| DashScope | 218+ | 对话/VL 视觉/Qwen 图像/Embedding | 阿里自有, 低延迟 |
| 火山引擎 | 111+ | 对话/Seedream 图像/Seedance 视频 | 字节自有 |
| MiniMax | - | 对话/TTS(300+音色)/视频/音乐 | 中文 TTS 最佳 |
| SiliconFlow | 68+ | 对话/FLUX 图像/TTS/Embedding | 开源模型, 性价比高 |

查看完整能力：`GET https://test-aiapi.callai.online/api/capabilities`

查看实时模型列表：`GET https://test-aiapi.callai.online/api/models?provider=google`

```bash
# 查询 Google 实时可用模型（49 个，按品类分组，10 分钟缓存）
curl -s 'https://test-aiapi.callai.online/api/models?provider=google'
# → {"total": 49, "categories": {"text_multimodal": {...}, "image_generation": {...}, ...}}

# 不带 provider 参数返回可查询的供应商列表
curl -s 'https://test-aiapi.callai.online/api/models'
# → {"available_providers": ["google"]}
```

---

## Gemini API 完整能力（重点）

平台已实现 Google Gemini API 的全面转发，包括以下所有能力。底层通过新加坡常驻 ECS 节点代理，连接池复用，平均延迟 ~1.3s。

### 文本生成

```json
{
  "protocol": {
    "protocol_id": "gemini-text",
    "pipeline": {"steps": [{
      "step_id": "s1", "action": "http_request",
      "config": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent",
        "headers": {"x-goog-api-key": "{{secrets.google_api_key}}", "Content-Type": "application/json"},
        "body": {
          "contents": [{"parts": [{"text": "{{input.prompt}}"}]}],
          "generationConfig": {"maxOutputTokens": {{input.max_tokens | default:1000}}}
        }
      },
      "timeout_ms": 120000
    }], "input_schema": {}, "output_schema": {}}
  },
  "input": {"prompt": "你的问题"}
}
```

可用模型:
- `gemini-3.1-pro-preview` — 最强推理, 100 万上下文
- `gemini-3-flash-preview` — 快速思考, 性价比最优
- `gemini-3.1-flash-lite-preview` — 最低成本
- `gemini-2.5-pro` / `gemini-2.5-flash` — 稳定版

Gemini 3 专有参数:
- `generationConfig.thinkingConfig.thinkingLevel`: `minimal` / `low` / `medium` / `high`
- `system_instruction.parts[].text`: System Prompt
- `generationConfig.responseMimeType`: `"application/json"` 强制 JSON 输出

### 图像理解（传入图片让 Gemini 分析）

小图直接 base64 内嵌，大图通过 Files API 上传后引用。

```json
{
  "protocol": {
    "protocol_id": "gemini-vision",
    "pipeline": {"steps": [{
      "step_id": "s1", "action": "http_request",
      "config": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent",
        "headers": {"x-goog-api-key": "{{secrets.google_api_key}}", "Content-Type": "application/json"},
        "body": {
          "contents": [{
            "parts": [
              {"inline_data": {"mime_type": "image/jpeg", "data": "{{input.image_base64}}"}},
              {"text": "{{input.prompt}}"}
            ]
          }]
        }
      },
      "timeout_ms": 120000
    }], "input_schema": {}, "output_schema": {}}
  },
  "input": {
    "image_base64": "<base64编码的图片>",
    "prompt": "描述这张图片的内容"
  }
}
```

使用 OSS 文件引用（推荐，保留交错结构）:

在 `body.contents[].parts[]` 中用 `ossData` 引用 OSS 文件，AIAPI 预处理时原地替换：

```json
{
  "input": {
    "body": {
      "contents": [{
        "parts": [
          {"text": "参考这个风格"},
          {"ossData": {"ossKey": "test-aiapi/files/style.jpg", "mimeType": "image/jpeg"}},
          {"text": "画这个角色"},
          {"ossData": {"ossKey": "test-aiapi/files/char.jpg", "mimeType": "image/jpeg"}},
          {"text": "生成一张插画"}
        ]
      }]
    }
  }
}
```

AIAPI 自动将每个 `ossData` 原地替换为：
- **< 50KB**: `inlineData`（base64 内嵌）
- **>= 50KB**: `fileData`（Files API，零 base64 膨胀，最大 2GB）

交错结构完美保留：`[text] [fileData:style] [text] [fileData:char] [text]`

> 旧方式 `oss_images` 向后兼容，但会丢失交错结构（所有图片统一插入 parts 最前面）。新代码请用 `ossData`。

### Gemini 原生图像生成与编辑

文字生图、图片编辑、风格迁移、多参考图合成。响应中图片以 base64 PNG 返回。

**模型推荐:**
| 模型 | 场景 | 分辨率 | 参考图上限 |
|------|------|--------|-----------|
| `gemini-3.1-flash-image-preview` | 生产首选，快速高效 | 512-4K | 14张 |
| `gemini-3-pro-image-preview` | 最高质量，复杂文字渲染 | 1K-4K | 11张 |

**文生图（已验证配方，推荐直接用）:**
```json
{"protocol_id": "recipe-google-image-gen-gemini-flash", "input": {"prompt": "一只穿着宇航服的猫", "aspect_ratio": "16:9", "image_size": "2K"}}
```

**图像编辑（已验证配方，推荐直接用）:**
```json
{
  "protocol_id": "recipe-google-image-edit-gemini-flash",
  "input": {
    "image_oss_key": "test-aiapi/files/photo.jpg",
    "prompt": "把背景替换为海边日落，保持人物不变",
    "aspect_ratio": "1:1"
  }
}
```

**风格迁移（已验证配方）:**
```json
{
  "protocol_id": "recipe-google-image-style-transfer",
  "input": {
    "subject_oss_key": "test-aiapi/files/subject.jpg",
    "style_oss_key": "test-aiapi/files/style-ref.jpg",
    "extra_instructions": "保持人物面部特征"
  }
}
```

**内联构造（最灵活）:**
```json
{
  "protocol": {
    "protocol_id": "gemini-image-edit",
    "pipeline": {"steps": [{
      "step_id": "s1", "action": "http_request",
      "config": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent",
        "headers": {"x-goog-api-key": "{{secrets.google_api_key}}", "Content-Type": "application/json"},
        "body": {
          "contents": [{"parts": [
            {"ossData": {"ossKey": "{{input.image_oss_key}}", "mimeType": "image/jpeg"}},
            {"text": "{{input.prompt}}"}
          ]}],
          "generationConfig": {
            "responseModalities": ["TEXT", "IMAGE"],
            "imageConfig": {"aspectRatio": "{{input.aspect_ratio | default:1:1}}"}
          }
        }
      },
      "timeout_ms": 120000
    }], "input_schema": {}, "output_schema": {}}
  },
  "input": {"image_oss_key": "test-aiapi/files/photo.jpg", "prompt": "变成水彩画风格"}
}
```

**响应结构:**
```json
{
  "output": {
    "candidates": [{
      "content": {
        "parts": [
          {"text": "已完成编辑...", "thoughtSignature": "SIG_1"},
          {"inlineData": {"mimeType": "image/png", "data": "<base64 PNG>"}, "thoughtSignature": "SIG_2"}
        ]
      }
    }]
  }
}
```

**编辑指令最佳实践:**
- 背景替换: "把背景替换为{场景}，保持前景主体不变"
- 风格转换: "转为{风格}风格，保持构图和人物不变"
- 元素添加: "在{位置}添加{物体}，光照与原图一致"
- 元素移除: "移除{位置}的{物体}，自然填充背景"
- 文字修改: "把图中'{原文}'改为'{新文字}'，保持字体和大小"

**imageConfig 参数:**
- `aspectRatio`: 1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3, 4:5, 5:4, 21:9, 1:4, 4:1, 1:8, 8:1
- `imageSize`: 512, 1K, 2K, 4K (512 仅 3.1 Flash)
- `numberOfImages`: 1-4
- `personGeneration`: dont_allow, allow_adult, allow_all

> 注意事项:
> - 编辑不需要 mask，用自然语言描述编辑区域即可
> - Imagen 4.0 **不支持**编辑，仅文生图
> - **图片引用不去重**: parts 中同一张图出现 N 次 = N 个槽位 + N 倍 token，Google 不做去重
> - 一次只改一处效果最好，复杂修改拆成多轮
> - 指令中加"保持 XXX 不变"减少意外修改

### Context Caching（重复 prompt 降本）

对重复使用的 system prompt / 大文档 / 参考资料，用 Context Caching 缓存到 Google 服务端，后续请求引用缓存，token 打折 50-90%。

> 限制: `-image-preview` 图像模型不支持 `createCachedContent`（Google API 返回 404）。Context Caching 仅适用于标准文本/视觉模型（gemini-3-flash-preview, gemini-3.1-pro-preview 等）。

**适用场景:** 同一 system prompt 高频调用、大文档反复查询分析。

**规则:**
- 最小 token: Flash 1024, Pro 4096
- TTL 默认 1 小时（格式 `"3600s"`）
- 存储费 ~$4.50/M tokens/小时
- 支持模型: `gemini-3-flash-preview`, `gemini-3.1-pro-preview`, `gemini-2.5-flash` 等标准模型
- **不支持**: `gemini-3.x-image-preview` 图像模型

### Imagen 4.0 图像生成（独立体系）

```json
{
  "protocol": {
    "protocol_id": "imagen4",
    "pipeline": {"steps": [{
      "step_id": "s1", "action": "http_request",
      "config": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/v1beta/models/imagen-4.0-generate-001:predict",
        "headers": {"x-goog-api-key": "{{secrets.google_api_key}}", "Content-Type": "application/json"},
        "body": {
          "instances": [{"prompt": "{{input.prompt}}"}],
          "parameters": {"sampleCount": {{input.count | default:1}}}
        }
      },
      "timeout_ms": 120000
    }], "input_schema": {}, "output_schema": {}}
  },
  "input": {"prompt": "Robot holding a red skateboard", "count": 1}
}
```

Imagen vs Gemini 图像生成:
- Imagen: 纯文生图, 最高画质, 仅英文, 最多 4 张
- Gemini: 文生图 + 图片编辑 + 多参考图, 支持中文, 支持 4K

### SSE 流式传输（新能力）

平台支持 Gemini API 的 SSE 流式输出，底层通过新加坡常驻节点自动转发。适合需要实时显示生成过程的场景（如打字机效果）。

**通过 executor 执行流式请求:**

在协议的 URL 中使用 `streamGenerateContent` 端点即可，executor 会自动通过 SSE 通道转发:

```json
{
  "protocol": {
    "protocol_id": "gemini-stream",
    "pipeline": {"steps": [{
      "step_id": "s1", "action": "http_request",
      "config": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:streamGenerateContent?alt=sse",
        "headers": {"x-goog-api-key": "{{secrets.google_api_key}}", "Content-Type": "application/json"},
        "body": {
          "contents": [{"parts": [{"text": "{{input.prompt}}"}]}],
          "generationConfig": {"maxOutputTokens": 500}
        }
      },
      "timeout_ms": 300000
    }], "input_schema": {}, "output_schema": {}}
  },
  "input": {"prompt": "写一首关于春天的诗"}
}
```

流式响应中每个 chunk 格式:
```
data: {"candidates":[{"content":{"parts":[{"text":"春风拂面..."}]}}]}
```

注意: 使用 `generateContent`（非 stream）端点时，系统返回完整 JSON；使用 `streamGenerateContent` 端点时，系统逐 chunk 透传 SSE 数据。两者都由 executor 自动处理路由。

### 文件上传

先上传文件到 OSS 图床，获取 `oss_key`，然后在 parts 中用 `ossData` 引用。

```bash
# 上传图片到 OSS
curl -X POST https://test-aiapi.callai.online/api/files/upload \
  -H 'Content-Type: application/json' \
  -H 'X-Api-Key: aiapi_your_key' \
  -d '{
    "data": "<base64编码的图片>",
    "mime_type": "image/jpeg"
  }'
# → {"oss_key": "test-aiapi/files/20260401/abc123.jpg", "url": "https://static2.callai.online/test-aiapi/files/..."}

# 在 parts 中用 ossData 引用（保留位置）
curl -X POST https://test-aiapi.callai.online/api/execute \
  -H 'X-Api-Key: aiapi_your_key' \
  -d '{
    "protocol": {"protocol_id": "inline", "pipeline": {"steps": [...]}},
    "input": {
      "body": {"contents": [{"parts": [
        {"text": "描述这张图"},
        {"ossData": {"ossKey": "test-aiapi/files/20260401/abc123.jpg", "mimeType": "image/jpeg"}}
      ]}]}
    }
  }'
```

支持类型: JPEG, PNG, GIF, WebP, BMP, MP3, WAV, MP4, PDF (最大 20MB)

---

## 协议模板变量

在 protocol 的 config 中使用 `{{}}` 引用变量:

| 语法 | 来源 | 示例 |
|------|------|------|
| `{{input.xxx}}` | 调用方传入的 input 参数 | `{{input.prompt}}` |
| `{{secrets.xxx}}` | 服务端存储的 API Key | `{{secrets.google_api_key}}` |
| `{{steps.s1.xxx}}` | 前序步骤的输出 | `{{steps.s1.translation}}` |
| `{{input.xxx \| default:val}}` | 带默认值 | `{{input.model \| default:gemini-3-flash-preview}}` |

可用的 secrets 名:
- `google_api_key` — Google Gemini / Imagen
- `yunwu_api_key` — 云雾 AI
- `tuzi_api_key` — 兔子 AI
- `dashscope_api_key` — 阿里云 DashScope
- `volcengine_api_key` — 火山引擎
- `minimax_api_key` — MiniMax
- `siliconflow_api_key` — SiliconFlow
- `deepseek_api_key` — DeepSeek
- `anthropic_api_key` — Anthropic

---

## 协商技巧

描述越具体，结果越好:

```
差:   "语音"
好:   "把中文文字转成语音 MP3"
更好: "把中文文字转成语音 MP3，用 MiniMax 的 speech-2.8-hd，女声，语速稍慢"
```

多步任务直接说完整流程:
```json
{"request_description": "1.用 Gemini 理解用户上传的图片 2.根据理解结果生成英文描述 3.用描述生成一张新图"}
```

---

## 执行响应结构

成功响应:
```json
{
  "protocol_id": "translate-zh-en",
  "output": { ... },
  "steps": [
    {"step_id": "s1", "status": "ok", "result": { ... }}
  ],
  "billing": {
    "charged": 1,
    "balance": 99,
    "key_type": "platform",
    "provider": "dashscope",
    "category": "chat",
    "pricing_source": "mapped",
    "model": "qwen-plus",
    "markup": 1.2,
    "upstream_cost": {
      "billing_type": "per_token",
      "usage": {"input_tokens": 34, "output_tokens": 12, "cached_tokens": 0},
      "rates": {"input": 0.8, "output": 2.0},
      "unit": "CNY/1M_tokens",
      "cost_cny": 0.000051
    }
  },
  "performance": {
    "latency_ms": 1200,
    "step_count": 1
  }
}
```

关键字段:
- `output` — 最后一个步骤的输出（通常是你需要的结果）
- `billing.charged` — 本次扣费（分），= 上游成本 × 1.2 向上取整，最低 1 分
- `billing.upstream_cost` — 上游成本明细（模型/用量/费率/成本），可与上游 API 文档一一对应
- `billing.pricing_source` — 定价来源: `mapped`(精确映射) / `category_default` / `fallback`(兜底)
- `performance.latency_ms` — 执行耗时

---

## 错误处理

| HTTP 状态 | 错误类型 | 含义 | 应对 |
|-----------|---------|------|------|
| 200 | - | 执行成功 | 读取 output |
| 401 | unauthorized | 未登录/token 过期 | 换有效 token 或用 X-Service-Key |
| 402 | insufficient_balance | 余额不足 | 充值: https://static2.callai.online/test-aiapi-store/index.html |
| 404 | protocol_not_found | 协议 ID 错误 | 检查 protocol_id 或重新协商 |
| 500 | step_failed | 上游 API 错误 | 查看 message 字段排查，可能是模型不可用或参数错误 |
| 504 | timeout | 超时 | 协商 ~10-30s，执行 ~1-120s，图像生成较慢 |

step_failed 时 message 中通常包含上游 API 的原始错误，如:
- `HTTP 400: INVALID_ARGUMENT` — 参数格式错误
- `HTTP 429: RESOURCE_EXHAUSTED` — 配额用尽
- `HTTP 404: model not found` — 模型名错误

---

## 架构速览

```
你的 Agent
    ↓ POST /api/negotiate (免费)
[协商 Agent] — Gemini 3.0 Flash 自动匹配供应商生成协议
    ↓ protocol_id
    ↓ POST /api/execute (Bearer token)
[执行引擎] — 模板解析 → 密钥注入 → 预扣费 → 执行 → 精算差额
    ↓ 海外供应商自动走新加坡代理
[SG-Node] — 常驻 ECS, HTTPS 连接池, SSE 流式
    ↓
[Google / Anthropic / Replicate / ElevenLabs]
```

- 执行引擎支持多步 pipeline，前序步骤输出可供后序步骤引用
- 海外 API (Google, Anthropic, Replicate, ElevenLabs) 自动走新加坡代理
- 国内 API (DashScope, 火山引擎, MiniMax 等) 直连

---

## 常见场景速查

| 我想要... | 推荐方案 | 协议/提示词 |
|-----------|---------|-----------|
| 文字生成图片 | Gemini 3.1 Flash Image | `recipe-google-image-gen-gemini-flash` |
| 图片编辑/修改 | Gemini 3.1 Flash Image | `recipe-google-image-edit-gemini-flash` |
| 风格迁移 | Gemini 3.1 Flash Image | `recipe-google-image-style-transfer` |
| 重复 prompt 降本 | Context Caching | 标准模型支持，图像模型不支持 |
| 图片分析/OCR | Gemini Vision | 协商: "分析图片内容" |
| 中文语音合成 | MiniMax TTS | `tts-minimax-zh-mp3` |
| 文本翻译 | DashScope Qwen | `translate-zh-en` |
| 对话补全 | Gemini/Qwen/GPT | 协商: "对话补全" |
| 结构化数据提取 | Gemini + JSON 模式 | 协商: "从文本提取 JSON" |
| 流式对话 | Gemini SSE | 用 streamGenerateContent 端点 |
| 批量图片处理 | 先上传 OSS 再引用 | 用 /api/files/upload 上传 |
