> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# 模板快速入门

本教程将通过 Python 或 TypeScript 脚本运行一个公开模板。该模板可将随手拍摄的服装手机照片转换为干净的产品图，脚本会将结果保存到原图旁边。教程约需 5 分钟，其中实际运行不到 1 分钟。

![手机照片和产品图](/docs/_fern-img/6afed41d4d791df68c87f183bd8db1d4aca8b4be3e946cc518534bda902f9528.webp)

**模板**是已发布的 [ElevenCreative Flow](/docs/zh/eleven-creative/products/flows)：由一系列模型组成，接收固定的一组**输入**并生成固定的一组**输出**。即将运行的 [Phone Photo to Packshot](https://elevenlabs.io/app/templates/Yz4DETxRv4uXyIo5PnEy) 接收 1 张图片并返回 1 张图片。其作者已选好模型和提示词，因此代码只需传入照片。

> **Warning**
>
> 运行模板需要 Pro 或更高套餐。

## 设置

#### 创建 API 密钥

[在控制台创建 API 密钥](https://elevenlabs.io/app/settings/api-keys)，用于安全地[访问 API](/docs/zh/api-reference/authentication)。

将密钥存储为托管密钥，并根据需要通过 `.env` 文件将其作为环境变量传递给 SDK，或直接在应用配置中设置。

**`.env`**

```js title=".env"
ELEVENLABS_API_KEY=<your_api_key_here>
```

为密钥授予 **Image & Video** 权限。

#### 安装 SDK

#### SDK

我们还会使用 `dotenv` 库从环境变量加载 API 密钥。

```python
pip install elevenlabs
pip install python-dotenv
```

```typescript
npm install @elevenlabs/elevenlabs-js
npm install dotenv
```

#### CLI

安装 ElevenLabs CLI。推荐使用 Homebrew（macOS）和 Scoop（Windows）。

**`Homebrew（macOS）`**

```bash title="Homebrew（macOS）"
brew install elevenlabs/tap/elevenlabs
```

**`Scoop（Windows）`**

```powershell title="Scoop（Windows）"
scoop bucket add elevenlabs https://github.com/elevenlabs/scoop-bucket
scoop install elevenlabs
```

**`npm`**

```bash title="npm"
npm install -g @elevenlabs/cli
```

**`curl`**

```bash title="curl"
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/elevenlabs/cli/releases/latest/download/elevenlabs-cli-installer.sh | sh
```

> **Tip**
>
> 正在使用 AI 编程助手？在项目中运行 `elevenlabs generate-skills`，即可将每个命令组的
> `SKILL.md` 写入 `skills/`，无需粘贴文档，助手就能了解 CLI 的完整功能。使用 `--output-dir`
> 可将其放到其他位置。该命令会读取 CLI 内置的 API 定义，因此无需 API 密钥且可离线运行——还能始终与已安装的 CLI 版本保持同步。

然后进行身份验证——这会打开浏览器以授权 CLI：

```bash
elevenlabs auth login
```

#### 获取照片

将示例照片下载到准备创建脚本的文件夹中：

```bash
curl -o garment.jpg https://storage.googleapis.com/eleven-public-cdn/documentation_assets/templates/garment.jpg
```

## 查找模板代码

在 ElevenLabs 应用中打开 [Phone Photo to Packshot](https://elevenlabs.io/app/templates/Yz4DETxRv4uXyIo5PnEy)，然后选择 **API** 标签。每个模板都有该标签，其中提供以 cURL、Python 和 TypeScript 运行模板的代码。

![模板 API 标签](/docs/_fern-img/801c9d2e2736964b35f5bad954092c973b21eedc03801128f1ed8bf31ea095b1.webp)

该标签将引导你完成 3 个步骤：获取 API 密钥、选择获取结果的方式，以及运行模板。在 **Choose how to get the result** 下，默认选择 **Wait for the result**。第 3 步的代码默认显示 cURL；选择 **Python** 或 **TypeScript** 后，该步骤会变为 **Run and wait for the result**。其中的代码片段会启动运行、等待完成，并打印每项输出。它会在 `inputs` 下为模板的每个输入传入一个值，以输入的 id 为键；并通过输出的 id 从 `outputs` 读取每项结果。此模板有 1 个输入 `garment_photo` 和 1 个输出 `packshot`。代码只需要这两个 id。

## 运行模板

创建 `packshot.py` 或 `packshot.mts`。它基于 API 标签中的代码片段，并进行以下修改：

* 从 `.env` 文件加载 API 密钥。
* 用 base64 格式的照片替换 `YOUR_ASSET_ID`，后者是已上传至 ElevenLabs 的文件 ID。
* 脚本会在运行过程中打印一行提示，并将产品图保存为 `packshot.jpg`，而不是打印其 URL。

**`packshot.py`**

```python title="packshot.py" maxLines=0
import base64
import os
import urllib.request

from dotenv import load_dotenv
from elevenlabs import ElevenLabs, TemplateInputReference_InlineBase64

load_dotenv()

client = ElevenLabs(api_key=os.environ["ELEVENLABS_API_KEY"])

with open("garment.jpg", "rb") as f:
    photo = base64.b64encode(f.read()).decode()

print("Running the template, this takes up to a minute...")

# Starts a run and waits for it to finish, checking back as often as the API
# asks. In production, receive the result by webhook instead.
run = client.flows.templates.runs.create_and_wait(
    template_id="Yz4DETxRv4uXyIo5PnEy",
    # Pins the version this tutorial was written against.
    version_id="Kqs4nRrpndEjQ54BhbwE",
    inputs={
        "garment_photo": TemplateInputReference_InlineBase64(
            content_base_64=photo,
            mime_type="image/jpeg",
        ),
    },
)

packshot = run.outputs["packshot"]
# Checking `type` tells your editor this output is an image, which has a content_url.
if packshot.type == "image" and packshot.status == "completed" and packshot.content_url:
    urllib.request.urlretrieve(packshot.content_url, "packshot.jpg")
    print("Saved packshot.jpg")
else:
    print("The run failed:", packshot.failure_reason)

```

**`packshot.mts`**

```typescript title="packshot.mts" maxLines=0
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
import "dotenv/config";
import { readFile, writeFile } from "fs/promises";

const client = new ElevenLabsClient({
  apiKey: process.env.ELEVENLABS_API_KEY,
});

const photo = await readFile("garment.jpg");

console.log("Running the template, this takes up to a minute...");

// Starts a run and waits for it to finish, checking back as often as the API
// asks. In production, receive the result by webhook instead.
const run = await client.flows.templates.runs.createAndWait("Yz4DETxRv4uXyIo5PnEy", {
  // Pins the version this tutorial was written against.
  versionId: "Kqs4nRrpndEjQ54BhbwE",
  inputs: {
    garment_photo: {
      type: "inline_base64",
      contentBase64: photo.toString("base64"),
      mimeType: "image/jpeg",
    },
  },
});

const packshot = run.outputs["packshot"];
// Checking `type` tells TypeScript this output is an image, which has a contentUrl.
if (packshot.type === "image" && packshot.status === "completed" && packshot.contentUrl) {
  const response = await fetch(packshot.contentUrl);
  await writeFile("packshot.jpg", Buffer.from(await response.arrayBuffer()));
  console.log("Saved packshot.jpg");
} else {
  console.error("The run failed:", packshot.failureReason);
}

```

`create_and_wait`（TypeScript 中为 `createAndWait`）会启动运行，然后按 API 建议的间隔检查状态，直至所有输出完成。运行失败时会返回结果而非抛出异常，因此脚本会在读取输出前检查其 `status`。`version_id` 会固定本教程所基于的模板版本，因此之后对模板的编辑不会导致脚本失效。

运行脚本。运行此模板约消耗 1,020 credits，与在应用中运行相同。

```python
python packshot.py
```

```typescript
npx tsx packshot.mts
```

30 秒至 1 分钟后，脚本会打印：

```text
Running the template, this takes up to a minute...
Saved packshot.jpg
```

打开 `packshot.jpg`。照片中的服装现在会展示在纯色摄影棚背景前的人体模型上，床和原有光线都已消失。

> **Note**
>
> `create_and_wait` 适用于脚本和试用模板。在生产环境中，应通过 [webhook](/docs/zh/eleven-api/guides/how-to/image-and-video/webhooks) 接收完成的运行结果，以免应用在运行过程中一直保持请求开启。[运行团队的 模板](/docs/zh/eleven-api/guides/how-to/templates/run-a-template)介绍了具体方法。

## 使用自己的照片运行

用手机拍摄任意一件服装。无需拍得很好：床上的 T 恤或搭在椅背上的夹克都可以。将其保存为 JPEG 格式的 `garment.jpg`，然后再次运行脚本。

你会获得同样摄影棚风格的服装产品图，因为模板的每次运行都会经过相同的模型和设置。即使使用同一张照片，细节仍可能因每次运行而有所不同。

## 你学到了什么

* 模板接收具名**输入**并生成具名**输出**，其 **API** 标签会显示运行模板的代码。
* `flows.templates.runs.create_and_wait` 会以每个输入 id 对应的一个值启动一次**运行**，并在完成后返回。通过 id 读取每项输出，并检查其 `status`。
* 在生产环境中，**webhook** 会交付每次完成的运行结果，因此无需等待。

## 后续步骤

#### [运行团队的模板](/docs/zh/eleven-api/guides/how-to/templates/run-a-template)

从模板的 API 标签复制代码，填入各类输入，通过 webhook 接收结果，并固定版本。

#### [Webhooks](/docs/zh/eleven-api/guides/how-to/image-and-video/webhooks)

设置生产环境 webhook，手动验证签名，并处理重试和重复事件。

#### [创建模板](/docs/zh/eleven-creative/products/flows#creating-a-template)

了解团队如何将 Flow 转换为模板：选择输入和输出，并进行共享。

#### [API 参考文档](/docs/zh/api-reference/flows/templates/runs/create)

模板运行的所有参数。