# 阿威云试炼 · API 调用示例

本平台所有接口均由本地 `server.js` 提供，**基础地址为 `https://awgzs.cn`**（可用 `PORT` 环境变量修改端口）。

> 当前本地部署**未启用密钥校验**，请求头里的 `Authorization` 可任意填写；上线正式域名后将启用真实密钥。
> 调用方传入的 `model` 既可以是类型简写（`llm` / `code` / `master` / `think` / `draw`），也可以是展示名（`Awei AI 1.0` 等），平台会统一映射并注入身份提示词。

---

## 1. 对话（文本生成）

接口：`POST /api/chat`（原生流式 SSE）或 `POST /v1/chat/completions`（OpenAI 兼容别名）

### 请求头
```
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY   # 本地部署可任意填写
```

### 请求体（Body）
```json
{
  "model": "Awei AI 1.0",
      "messages": [
        { "role": "system", "content": "你是一个简洁的助手" },
        { "role": "user",   "content": "用一句话介绍你自己" }
      ]
    }
    ```

    > **流式开关 `stream`**：请求体可加 `"stream": true`（默认，返回 SSE 流，需逐行拼 `delta.content`）或 `"stream": false`（返回一次性完整 JSON，OpenAI 格式，字段 `choices[0].message.content`）。无论哪种，返回里的 `model` 字段始终显示为阿威模型名（如 `Awei AI 1.0`），**不会暴露底层模型**。

    **非流式示例（`stream: false`，一次拿到完整回答）**
    ```bash
    curl -X POST https://awgzs.cn/v1/chat/completions \
      -H "Content-Type: application/json" -H "Authorization: Bearer sk-demo" \
      -d '{"model":"Awei AI 1.0","stream":false,"messages":[{"role":"user","content":"用一句话介绍你自己"}]}'
    # 返回：{"id":"...","model":"Awei AI 1.0","choices":[{"message":{"role":"assistant","content":"..."}}],"usage":{...}}
    ```

    ### cURL（流式，可正常返回）
```bash
curl -N -X POST https://awgzs.cn/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-demo" \
  -d '{
    "model": "Awei AI 1.0",
    "messages": [{"role":"user","content":"用一句话介绍你自己"}]
  }'
```
> 返回为 SSE 流，每行 `data: {"choices":[{"delta":{"content":"..."}}]}`；客户端按 `delta.content` 拼接即可。

### Python（requests，拼出完整回复）
```python
import requests, json

resp = requests.post(
    "https://awgzs.cn/v1/chat/completions",
    headers={"Content-Type": "application/json", "Authorization": "Bearer sk-demo"},
    json={"model": "Awei AI 1.0",
          "messages": [{"role": "user", "content": "用一句话介绍你自己"}]},
    stream=True,
)
text = ""
for line in resp.iter_lines(decode_unicode=True):
    if line and line.startswith("data:") and line[5:].strip() != "[DONE]":
        try:
            d = json.loads(line[5:].strip())
            text += d["choices"][0]["delta"].get("content", "") or ""
        except Exception:
            pass
print(text)
```

### JavaScript（浏览器 / Node fetch）
```javascript
const res = await fetch("https://awgzs.cn/v1/chat/completions", {
  method: "POST",
  headers: { "Content-Type": "application/json", "Authorization": "Bearer sk-demo" },
  body: JSON.stringify({
    model: "Awei AI 1.0",
    messages: [{ role: "user", content: "用一句话介绍你自己" }]
  })
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "", full = "";
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buf += decoder.decode(value, { stream: true });
  let i;
  while ((i = buf.indexOf("\n")) >= 0) {
    const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1);
    if (line.startsWith("data:")) {
      const data = line.slice(5).trim();
      if (data && data !== "[DONE]") {
        try { full += JSON.parse(data).choices[0].delta.content || ""; } catch (e) {}
      }
    }
  }
}
console.log(full);
```

---

## 2. 图像生成（Awei Draw）

接口：`POST /api/image` 或 `POST /v1/images/generations`

### 请求头
```
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY
```

### 请求体（Body）
```json
{
  "model": "Awei Draw 1.0",
  "prompt": "雪山下的湖泊，写实风格",
  "size": "1024x1024",
  "username": "your_username",
  "AI-platform": "发送请求的 AI / 应用名称（由调用方填写）"
}
```

### cURL
```bash
curl -X POST https://awgzs.cn/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-demo" \
  -d '{
    "model": "Awei Draw 1.0",
    "prompt": "雪山下的湖泊，写实风格",
    "size": "1024x1024",
    "username": "your_username",
    "AI-platform": "Awei AI 2.5"
  }'
```

> **`AI-platform` 字段（推荐填写）**：标识「是谁/哪个 AI 发起了这次生图请求」。
> - 任何调用方都可在请求体里带上 `"AI-platform": "<名称>"`（如 `Awei AI 2.5`、`Awei Chat`、`我的智能体` 等），名称由调用方自己定义，最长 64 字符。
> - 该字段会随作品一起记入「我的作品」，并在返回结果里原样回传（`platform` 字段），方便你追溯每张图具体由哪个 AI / 应用生成。
> - 不填则留空，不影响生图；本接口为一次性 JSON 返回，**不使用流式输出**。
> - 若是 AI 助手 / Agent 通过本接口生图，规范做法是**在 skill / 调用代码里把自己的名称写进 `AI-platform`**，而不是留空。

> 返回 JSON：`{ "images": [ { "url": "..." } ], "model": "...", "platform": "Awei AI 2.5", "created": 1234567890, "cost": 5000 }`，`url` 即为生成图片地址，`platform` 即本次调用方标识。
> **链接说明**：接口会把生成的图片下载到本平台并托管，返回的 `url` 形如 `http://<你的域名>/files/<id>.png`（**不再是硅基流动的 s3 链接**），直接用浏览器或 `<img>` 打开即可，有效期由本平台控制。

---

## 3. 模型微调（创建训练任务）

接口：`POST /api/finetune`

### 请求头
```
Content-Type: application/json
```

### 请求体（Body）
```json
{
  "model": "Awei AI 1.0",
  "taskName": "客服助手-v1",
  "dataset": "{\"messages\":[{\"role\":\"system\",\"content\":\"你是客服\"},{\"role\":\"user\",\"content\":\"如何退货\"},{\"role\":\"assistant\",\"content\":\"进入订单点退货\"}]}\n{\"messages\":[{\"role\":\"system\",\"content\":\"你是客服\"},{\"role\":\"user\",\"content\":\"运费谁出\"},{\"role\":\"assistant\",\"content\":\"七天内包邮\"}]}",
  "epochs": 3,
  "batchSize": 8,
  "learningRate": 0.0001,
  "loraRank": 8,
  "loraAlpha": 32,
  "loraDropout": 0.05
}
```
> `dataset` 为 **JSONL 文本**：每行一个 `{"messages":[...]}`，以 `\n` 换行。

### cURL
```bash
curl -X POST https://awgzs.cn/api/finetune \
  -H "Content-Type: application/json" \
  -d @payload.json
```

### 查询任务列表
```bash
curl https://awgzs.cn/api/finetune
```

### 取消任务
```bash
curl -X POST https://awgzs.cn/api/finetune/<任务ID>/cancel
```

---

## 4. 健康检查

```bash
curl https://awgzs.cn/health
# => {"ok":true}
```

---

## 模型名称对照

| 类型简写 | 展示名 | 能力 |
|---------|--------|------|
| `llm`    | Awei AI 1.0    | 通用对话 |
| `code`   | Awei Code 1.0  | 代码生成 |
| `master` | Awei AI Master | 长文 / 复杂推理 |
| `think`  | Awei Think     | 轻量思考 |
| `draw`   | Awei Draw 1.0  | 图像生成 |

启动服务：`node server.js`（默认 1245 端口，可用 `PORT=1245 node server.js` 指定）。
