> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mountsea.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Compat introduction

# OpenAI 兼容接口

**OpenAI 兼容接口** 是 OpenAI 官方 Images API 的 **直接替代**。完全兼容官方 **`openai`** SDK（Python 与 Node.js）和原生 OpenAI REST 接口 —— 只需修改 `base_url`。

<Tip>
  **无需修改代码** —— 如果您已使用 OpenAI 的 `images.generate` / `images.edit`，只需将 `base_url` 覆盖为 `https://api.mountsea.ai/openai/v1`，使用 Mountsea API Key 即可。
</Tip>

## 为什么使用兼容接口？

<CardGroup cols={2}>
  <Card title="官方 SDK 支持" icon="code">
    完美兼容 OpenAI 官方 `openai` Python 与 Node.js SDK
  </Card>

  <Card title="接口形状一致" icon="equals">
    请求/响应格式与 `https://api.openai.com/v1/images/*` 完全一致
  </Card>

  <Card title="同步返回" icon="bolt">
    直接返回生成的图像，无需轮询
  </Card>

  <Card title="统一计费" icon="wallet">
    一个 API Key，通过 Mountsea 统一跟踪用量
  </Card>
</CardGroup>

## 配置

### Base URL

```
https://api.mountsea.ai/openai/v1
```

### 鉴权

使用您的 **Mountsea API Key**：

* HTTP 头部：`Authorization: Bearer your-api-key`
* 或通过 SDK 的 `api_key` / `apiKey` 参数传入

## 支持的端点

| 端点                              | 方法   | 描述                                        |
| ------------------------------- | ---- | ----------------------------------------- |
| `/openai/v1/images/generations` | POST | 文生图（JSON）—— 与 OpenAI 完全一致                 |
| `/openai/v1/images/edits`       | POST | 图像编辑（multipart/form-data）—— 与 OpenAI 完全一致 |

## 支持的模型

| 模型            | 说明                |
| ------------- | ----------------- |
| `gpt-image-2` | OpenAI 最新图像模型（默认） |

***

## 使用官方 `openai` SDK

### 安装

<CodeGroup>
  ```bash pip theme={null}
  pip install openai
  ```

  ```bash npm theme={null}
  npm install openai
  ```

  ```bash pnpm theme={null}
  pnpm add openai
  ```
</CodeGroup>

### Python

<CodeGroup>
  ```python 文生图 theme={null}
  from openai import OpenAI
  import base64

  client = OpenAI(
      api_key="your-mountsea-api-key",
      base_url="https://api.mountsea.ai/openai/v1",
  )

  response = client.images.generate(
      model="gpt-image-2",
      prompt="A photorealistic cat wearing a space helmet, floating in orbit",
      size="1024x1024",
      quality="high",
      n=1,
  )

  # gpt-image-2 总是返回 b64_json
  image_b64 = response.data[0].b64_json
  with open("output.png", "wb") as f:
      f.write(base64.b64decode(image_b64))
  ```

  ```python 图像编辑 theme={null}
  from openai import OpenAI
  import base64

  client = OpenAI(
      api_key="your-mountsea-api-key",
      base_url="https://api.mountsea.ai/openai/v1",
  )

  with open("source.png", "rb") as img:
      response = client.images.edit(
          model="gpt-image-2",
          image=img,
          prompt="Add a dramatic sunset sky with orange and purple clouds",
          size="1024x1024",
          input_fidelity="high",
      )

  image_b64 = response.data[0].b64_json
  with open("edited.png", "wb") as f:
      f.write(base64.b64decode(image_b64))
  ```

  ```python 局部重绘（mask） theme={null}
  from openai import OpenAI
  import base64

  client = OpenAI(
      api_key="your-mountsea-api-key",
      base_url="https://api.mountsea.ai/openai/v1",
  )

  with open("source.png", "rb") as img, open("mask.png", "rb") as mask:
      response = client.images.edit(
          model="gpt-image-2",
          image=img,
          mask=mask,
          prompt="Replace the masked area with a sunset beach",
          size="1024x1024",
      )

  image_b64 = response.data[0].b64_json
  with open("inpainted.png", "wb") as f:
      f.write(base64.b64decode(image_b64))
  ```
</CodeGroup>

### Node.js / TypeScript

<CodeGroup>
  ```typescript 文生图 theme={null}
  import OpenAI from 'openai';
  import fs from 'fs';

  const client = new OpenAI({
    apiKey: 'your-mountsea-api-key',
    baseURL: 'https://api.mountsea.ai/openai/v1',
  });

  const response = await client.images.generate({
    model: 'gpt-image-2',
    prompt: 'A photorealistic cat wearing a space helmet, floating in orbit',
    size: '1024x1024',
    quality: 'high',
    n: 1,
  });

  const imageB64 = response.data[0].b64_json!;
  fs.writeFileSync('output.png', Buffer.from(imageB64, 'base64'));
  ```

  ```typescript 图像编辑 theme={null}
  import OpenAI, { toFile } from 'openai';
  import fs from 'fs';

  const client = new OpenAI({
    apiKey: 'your-mountsea-api-key',
    baseURL: 'https://api.mountsea.ai/openai/v1',
  });

  const response = await client.images.edit({
    model: 'gpt-image-2',
    image: await toFile(fs.createReadStream('source.png'), 'source.png'),
    prompt: 'Add a dramatic sunset sky with orange and purple clouds',
    size: '1024x1024',
    input_fidelity: 'high',
  });

  const imageB64 = response.data[0].b64_json!;
  fs.writeFileSync('edited.png', Buffer.from(imageB64, 'base64'));
  ```

  ```typescript 局部重绘（mask） theme={null}
  import OpenAI, { toFile } from 'openai';
  import fs from 'fs';

  const client = new OpenAI({
    apiKey: 'your-mountsea-api-key',
    baseURL: 'https://api.mountsea.ai/openai/v1',
  });

  const response = await client.images.edit({
    model: 'gpt-image-2',
    image: await toFile(fs.createReadStream('source.png'), 'source.png'),
    mask: await toFile(fs.createReadStream('mask.png'), 'mask.png'),
    prompt: 'Replace the masked area with a sunset beach',
    size: '1024x1024',
  });

  const imageB64 = response.data[0].b64_json!;
  fs.writeFileSync('inpainted.png', Buffer.from(imageB64, 'base64'));
  ```
</CodeGroup>

***

## 直接调用 REST API

如果不使用 SDK，可直接调用 REST 接口。

### 文生图（JSON）

```bash theme={null}
curl -X POST "https://api.mountsea.ai/openai/v1/images/generations" \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "A photorealistic cat wearing a space helmet, floating in orbit",
    "size": "1024x1024",
    "quality": "high",
    "n": 1
  }'
```

### 图像编辑（multipart/form-data）

```bash theme={null}
curl -X POST "https://api.mountsea.ai/openai/v1/images/edits" \
  -H "Authorization: Bearer your-api-key" \
  -F "model=gpt-image-2" \
  -F "image=@source.png" \
  -F "prompt=Add a dramatic sunset sky" \
  -F "size=1024x1024" \
  -F "input_fidelity=high"
```

### 局部重绘（multipart/form-data）

```bash theme={null}
curl -X POST "https://api.mountsea.ai/openai/v1/images/edits" \
  -H "Authorization: Bearer your-api-key" \
  -F "model=gpt-image-2" \
  -F "image=@source.png" \
  -F "mask=@mask.png" \
  -F "prompt=Replace the masked area with a sunset beach" \
  -F "size=1024x1024"
```

***

## 请求参数

### `images/generations` (JSON)

| 字段                   | 类型         | 说明                                              |
| -------------------- | ---------- | ----------------------------------------------- |
| `prompt`             | string（必填） | 生成提示词                                           |
| `model`              | string     | 默认 `gpt-image-2`                                |
| `size`               | enum       | `auto`、`1024x1024`、`1024x1536`、`1536x1024`      |
| `n`                  | number     | 目前仅支持 1                                         |
| `quality`            | enum       | `auto`、`low`、`medium`、`high`、`standard`         |
| `background`         | enum       | `transparent`、`opaque`、`auto`                   |
| `output_format`      | enum       | `png`、`jpeg`、`webp`                             |
| `output_compression` | number     | JPEG/WebP 压缩等级 0-100                            |
| `moderation`         | enum       | `auto`、`low`                                    |
| `response_format`    | enum       | `url` 或 `b64_json`（gpt-image-2 总是返回 `b64_json`） |
| `user`               | string     | 终端用户标识，用于滥用监控                                   |

### `images/edits` (multipart/form-data)

上述字段再加上：

| 字段               | 类型             | 说明               |
| ---------------- | -------------- | ---------------- |
| `image`          | file（必填）       | 源图像              |
| `mask`           | file           | 可选 mask，透明区域将被重绘 |
| `input_fidelity` | `high` / `low` | 输出与输入图的相似度       |

***

## 响应格式

与 OpenAI 官方响应完全一致：

```json theme={null}
{
  "created": 1712345678,
  "data": [
    {
      "b64_json": "<base64 编码的图像>",
      "revised_prompt": "<模型改写后的 prompt>"
    }
  ],
  "background": "opaque",
  "output_format": "png",
  "quality": "high",
  "size": "1024x1024",
  "usage": {
    "input_tokens": 45,
    "input_tokens_details": { "image_tokens": 0, "text_tokens": 45 },
    "output_tokens": 3200,
    "total_tokens": 3245
  }
}
```

<Info>
  `gpt-image-2` 总是以 `b64_json` 返回图像。`response_format=url` 字段只是为了兼容 DALL·E，对 gpt-image 系列会被忽略。
</Info>

***

## 注意事项与限制

<Warning>
  目前 `n` 仅支持 `1`，暂不支持单次请求生成多张图像。
</Warning>

* 兼容所有 OpenAI 官方参数；未知参数会被优雅忽略。
* 接受 `response_format=url`，但 gpt-image-2 仍会返回 `b64_json`。
* `openai` SDK 调用与直接 REST 调用行为完全一致。

***

## 浏览 API 文档

* [images.generate（兼容）](compat-generate) —— OpenAI 兼容文生图接口
* [images.edit（兼容）](compat-edit) —— OpenAI 兼容图像编辑接口
