# @apicity/alibaba 中文文档

规范地址：https://npmcn.com/package/%40apicity/alibaba/

版本：0\.27\.0
npm 元数据更新时间：2026-11-06T09:52:42.496Z
中文译文更新时间：2026-11-06T10:08:32.936Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40apicity/alibaba
原文对照：https://npmcn.com/package/%40apicity/alibaba/?lang=original
项目主页：https://github.com/justintanner/apicity#readme
源码仓库：https://github.com/justintanner/apicity

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：226 kB，39 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=18\.0\.0
- 运行依赖：1 个
- 首次发布：2026-05-10T07:46:00.678Z
- 最新版本发布：2026-11-06T09:52:42.325Z
- 近 30 天下载量：4277（2026-10-06 至 2026-11-04，npm 官方下载统计）
- 已发布版本数：90（近 12 个月 90 个）

## 中文简介

Alibaba Cloud Model Studio提供商,用于聊天完成,图像生成和流出.

## 安装

```sh
npm install @apicity/alibaba
```

也可以使用：`pnpm add @apicity/alibaba`、`yarn add @apicity/alibaba`、`bun add @apicity/alibaba`

## README

# @apicity/ alibaba (英语)

[![npm](https://img.shields.io/npm/v/@apicity/alibaba?color=cb0000)](https://www.npmjs.com/package/@apicity/alibaba) [![dependencies](https://img.shields.io/badge/dependencies-1-blue)](https://npmcn.com/package/%40apicity/alibaba/package.json) [![TypeScript](https://img.shields.io/badge/TypeScript-strict-blue?logo=typescript&logoColor=white)](https://npmcn.com/package/%40apicity/alibaba/tsconfig.json)

Alibaba Cloud Model Studio提供商,用于聊天完成,图像生成和流出.

运行时间依赖性 :

-   `zod@^4.6.6` - 请求在每一个 POST 端点上附加计划 `.schema`

## 安装

```bash
npm install @apicity/alibaba
# or
pnpm add @apicity/alibaba
```

## 快速启动

```typescript
import { createAlibaba } from "@apicity/alibaba";

const alibaba = createAlibaba({ apiKey: process.env.ALIBABA_API_KEY! });
```

## 真实世界的例子:Wan 2.7 图像到视频与同步任务投票

DashScope 软件 `aigc/*` 家庭是逐一违约的:每个视频、图像和 音频生成端点随即返回 `task_id` (单位:千美元) `task_status` 联 合 国 `PENDING`,而实际的艺术品 生活在一个 单独 `GET /api/v1/tasks/{taskId}` 民意调查直到过渡到 `SUCCEEDED`。提供者隐藏 `X-DashScope-Async: enable` 标题 水管,但保持两叫的形状 因为它让你 检查站 `task_id`,走开,以后从任何进程恢复. 下面的例子 `task_id`、时间戳、迅速和解析 从 [`tests/recordings/alibaba_1329897167/wan-i2v_2196817451/`](https://npmcn.com/tests/recordings/alibaba_1329897167/wan-i2v_2196817451/), (中文(简体) ), 这是HAR重播 由 [`tests/integration/alibaba-wan-i2v.test.ts`](https://npmcn.com/tests/integration/alibaba-wan-i2v.test.ts)。 。 。 .

```typescript
import { readFileSync } from "node:fs";
import { createAlibaba, AlibabaError } from "@apicity/alibaba";
import type {
  AlibabaVideoSynthesisSubmitResponse,
  AlibabaTaskStatusResponse,
  AlibabaTaskStatus,
} from "@apicity/alibaba";

const alibaba = createAlibaba({
  apiKey: process.env.DASHSCOPE_API_KEY!,
  // The SUCCEEDED-path round-trip in the recording is ~47s wall-clock;
  // bump the per-request timeout above the default 30s so the submit
  // call doesn't fight a slow scheduling spike.
  timeout: 60_000,
});

// 1. Inline the source frame as a `data:` URL. DashScope also accepts
//    https:// URLs and `oss://` URIs (the latter only when the request
//    carries `X-DashScope-OssResourceResolve: enable`, which the
//    provider sets automatically on every aigc/* call). Inlining is the
//    zero-infra path — no public bucket, no presigned URL — at the cost
//    of paying the upload bytes once per submit.
const frame = readFileSync("./cat.jpg");
const dataUrl = `data:image/jpeg;base64,${frame.toString("base64")}`;

// 2. `media[].type: "first_frame"` is the I2V kick-off — Wan animates
//    forward from the still. Other media types in the same array slot
//    drive different conditioning modes: `last_frame` (animate
//    backward), `first_clip` (continue a video), `reference` (style
//    transfer). The Zod schema enforces that `first_frame` cannot
//    coexist with `first_clip` and that exactly one of each type is
//    present — invalid combinations fail at `.schema.safeParse(...)`
//    before a single byte hits the wire.
//
// 3. `prompt_extend: true` runs the prompt through DashScope's
//    server-side prompt-enhancement model first, which materially
//    improves motion fidelity on terse prompts like the one below.
//    The enhanced prompt is echoed back in the SUCCEEDED response as
//    `actual_prompt` so you can audit what actually got rendered.
//    `watermark: false` removes the corner badge — silently ignored
//    on tiers that don't permit it.
const submit: AlibabaVideoSynthesisSubmitResponse =
  await alibaba.post.api.v1.services.aigc.videoGeneration.videoSynthesis({
    model: "wan2.7-i2v",
    input: {
      prompt:
        "The odd-eyed white cat blinks slowly, whiskers twitching, " +
        "then turns its head toward the camera",
      media: [{ type: "first_frame", url: dataUrl }],
    },
    parameters: {
      resolution: "720P",
      duration: 5,
      prompt_extend: true,
      watermark: false,
    },
  });

console.log(
  `task=${submit.output.task_id} status=${submit.output.task_status}`,
);
// → "task=5a674d6b-6a42-4b07-98bb-147ba79879ea status=PENDING"

// 4. Poll until terminal. The status state machine is
//    PENDING → RUNNING → (SUCCEEDED | FAILED | CANCELED), with
//    SUSPENDED as a transient quota-bound retry state. Treat anything
//    not in TERMINAL as "keep polling." A 5–10s interval matches the
//    server-side scheduling cadence — the recorded run did 8 polls
//    over ~47s, so faster polling just burns rate-limit budget without
//    moving the task forward.
const TERMINAL: ReadonlyArray<AlibabaTaskStatus> = [
  "SUCCEEDED",
  "FAILED",
  "CANCELED",
];
let status: AlibabaTaskStatusResponse = await alibaba.get.api.v1.tasks(
  submit.output.task_id,
);
while (!TERMINAL.includes(status.output.task_status)) {
  await new Promise((r) => setTimeout(r, 5000));
  status = await alibaba.get.api.v1.tasks(submit.output.task_id);
}

// 5. The task-status response shape *grows* as the task progresses —
//    `submit_time` and `scheduled_time` appear once it leaves PENDING;
//    `end_time`, `orig_prompt`, `video_url`, and `usage` only land on
//    SUCCEEDED. `code` and `message` populate on FAILED. Always branch
//    on `task_status` before reading the success-only fields, since
//    they're typed `string | undefined`.
if (status.output.task_status !== "SUCCEEDED") {
  throw new AlibabaError(
    `i2v task ${status.output.task_id} ${status.output.task_status}: ` +
      `${status.output.code ?? "?"}: ${status.output.message ?? "?"}`,
    500,
    status.output,
    status.output.code,
  );
}

console.log(status.output.video_url);
// → "https://dashscope-a717.oss-accelerate.aliyuncs.com/.../70873660-metadata_user_a54afaea6b53dd4e.mp4?Expires=1776489167&..."

const elapsed =
  new Date(status.output.end_time!).getTime() -
  new Date(status.output.submit_time!).getTime();
console.log(
  `model=wan2.7-i2v ${status.usage!.SR}p×${status.usage!.output_video_duration}s ` +
    `elapsed=${(elapsed / 1000).toFixed(1)}s videos=${status.usage!.video_count}`,
);
// → "model=wan2.7-i2v 720p×5s elapsed=47.4s videos=1"
```

**页:1**

-   回来的 `video_url` 是带有短句的预先签名的OSS URL `Expires=` 窗口(以上录入的qq1小时)——下载或 立即重新主持,不要存储URL本身. 这桶是 托管时间 `oss-accelerate.aliyuncs.com`捍卫阿里巴巴CDN a. 与调用器相近 获取.
-   提交电话是 _廉价_ 即使后来的任务是开帐单 仅按任务收取 `usage.duration` (单位:秒) 输出视频)。 内容安全屏幕失败( A)`code: "DataInspectionFailed"`)在输入框上返回一个SUCCEED-形状 HTTP 200 带 `task_status: "FAILED"`而不是4xx,这就是为什么 上面的例子总是读取 `task_status` 而不是依赖 内容相关拒绝的例外流程.
-   一样 `videoSynthesis` 端点遍布整个湾 2.7 通过改变家庭 `model`数字 : `wan2.7-i2v` 为图像-视频, `wan2.7-t2v` 文本-视频(删除 `media` 阵列),以及 `wan2.7-videoedit` 用于视频式传输(使用) `media[].type: "video"`) (中文(简体) ). Zod计划执行每型媒体型 组合- `videoedit` 需要一个 `video` 条目, `i2v` 需求 `first_frame` 或者说 `first_clip`等 (中文(简体) ).
-   对于输入框架超过DashScope 10MB的有效载荷 嵌入式数据- URL 天花板, 互换内线 `data:` 一个 URL `oss://{key}` 通过 `uploadFile(provider, {...})` - 那个 导出助手执行 `getPolicy` + 多部分开放源码软件后台对象 跳起舞来返回URI 准备跳入 `media[].url`编辑 `X-DashScope-OssResourceResolve` 自动设置页眉 每个aigc/\* 调用所以 URI 解决服务器侧.
-   丢出错误 `AlibabaError` 与 `status` 和解析 `body`编辑 本地aigc 错误形状( r)`{code, message, request_id}`已浮出水面 内 `error.code` - 与 `withRetry` 从 `@apicity/alibaba` 页:1 `429` 编号 : `503`但跳过重试 `code === "DataInspectionFailed"` 编号 : `"InvalidParameter"` 因为这些是决定性的拒绝.

## API 参考

7个端点跨出4组. 每个方法都映射出上游的 URL 路径 .

### 兼容模式

`GET` **`alibaba.compatibleMode.v1.models`**

`GET [https://dashscope.aliyuncs.com/compatible-mode/v1/models](https://dashscope.aliyuncs.com/compatible-mode/v1/models)`

成本等级 : `expensive`

[上游区域](https://help.aliyun.com/zh/model-studio)

```typescript
const res = await alibaba.get.compatibleMode.v1.models();
```

资料来源: [`packages/provider/alibaba/src/alibaba.ts`](https://npmcn.com/package/%40apicity/alibaba/src/alibaba.ts)

`POST` **`alibaba.compatibleMode.v1.chat.completions`**

`POST [https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions](https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions)`

成本等级 : `expensive`

[上游区域](https://help.aliyun.com/zh/model-studio)

```typescript
const res = await alibaba.post.compatibleMode.v1.chat.completions({ /* ... */ });
```

资料来源: [`packages/provider/alibaba/src/alibaba.ts`](https://npmcn.com/package/%40apicity/alibaba/src/alibaba.ts)

### 服务

`POST` **`alibaba.api.v1.services.aigc.imageGeneration.generation`**

`POST [https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation](https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation)`

成本等级 : `expensive`

```typescript
const res = await alibaba.post.api.v1.services.aigc.imageGeneration.generation({ /* ... */ });
```

资料来源: [`packages/provider/alibaba/src/alibaba.ts`](https://npmcn.com/package/%40apicity/alibaba/src/alibaba.ts)

`POST` **`alibaba.api.v1.services.aigc.multimodalGeneration.generation`**

`POST [https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation](https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation)`

成本等级 : `expensive`

[上游区域](https://www.alibabacloud.com/help/en/model-studio/qwen-image-edit)

```typescript
const res = await alibaba.post.api.v1.services.aigc.multimodalGeneration.generation({ /* ... */ });
```

资料来源: [`packages/provider/alibaba/src/alibaba.ts`](https://npmcn.com/package/%40apicity/alibaba/src/alibaba.ts)

`POST` **`alibaba.api.v1.services.aigc.videoGeneration.videoSynthesis`**

`POST [https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis](https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis)`

成本等级 : `expensive`

[上游区域](https://help.aliyun.com/zh/model-studio)

```typescript
const res = await alibaba.post.api.v1.services.aigc.videoGeneration.videoSynthesis({ /* ... */ });
```

资料来源: [`packages/provider/alibaba/src/alibaba.ts`](https://npmcn.com/package/%40apicity/alibaba/src/alibaba.ts)

### 任务

`GET` **`alibaba.api.v1.tasks`**

`GET https://dashscope.aliyuncs.com/api/v1/tasks/{taskId}`

成本等级 : `expensive`

[上游区域](https://help.aliyun.com/zh/model-studio)

```typescript
const res = await alibaba.get.api.v1.tasks({ /* ... */ });
```

资料来源: [`packages/provider/alibaba/src/alibaba.ts`](https://npmcn.com/package/%40apicity/alibaba/src/alibaba.ts)

### 上传

`GET` **`alibaba.api.v1.uploads`**

`GET [https://dashscope.aliyuncs.com/api/v1/uploads](https://dashscope.aliyuncs.com/api/v1/uploads)`

成本等级 : `expensive`

[上游区域](https://help.aliyun.com/zh/model-studio)

```typescript
const res = await alibaba.get.api.v1.uploads({ /* ... */ });
```

资料来源: [`packages/provider/alibaba/src/alibaba.ts`](https://npmcn.com/package/%40apicity/alibaba/src/alibaba.ts)

## 中间软件

```typescript
import { createAlibaba, withRetry } from "@apicity/alibaba";

const alibaba = createAlibaba({ apiKey: process.env.ALIBABA_API_KEY! });
const getTask = withRetry(alibaba.get.api.v1.tasks, { retries: 3 });
```

部分 [辣点](https://github.com/justintanner/apicity) 单相机.

## 许可证

麻省理工学院——见 [自由主义](https://npmcn.com/package/%40apicity/alibaba/LICENSE)。 。 。 .

## 常见问题

### @apicity/alibaba 是什么？

Alibaba Cloud Model Studio提供商,用于聊天完成,图像生成和流出\.

### 如何安装 @apicity/alibaba？

在项目目录运行 npm install @apicity/alibaba，或使用 pnpm add / yarn add / bun add。

### @apicity/alibaba 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @apicity/alibaba 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @apicity/alibaba 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=18\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @apicity/alibaba 可以商用吗？

@apicity/alibaba 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @apicity/alibaba 的下载量有多少？

根据 npm 官方下载统计，@apicity/alibaba 在 2026/10/06 – 2026/11/04 这 30 天内被下载 4,277 次，日均约 143 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @apicity/alibaba 还在维护吗？

最新版本 0\.27\.0 发布于 2026/11/06（今天）；至今共发布 90 个版本，其中过去 12 个月发布了 90 个；首次发布于 2026/05/10。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

