> 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.

# 创建模板运行

POST https://api.elevenlabs.io/v1/flows/templates/{template_id}/runs
Content-Type: application/json

启动 flows 模板运行。传入 `version_id` 以固定快照，或省略它／传入 `latest` 以运行最新发布版本。在 `inputs` 下设置输入值，并以输入端口 id 为键。响应返回初始状态的运行，其中每个输出已在 `outputs` 中列于对应端口 id 下。包含 `webhook` 可在运行 `status` 为 `completed` 或 `failed` 时接收携带已完成运行的 `flows_template_run` 事件；这是推荐的等待方式。若未提供，则以适当间隔获取 `GET /v1/flows/templates/{template_id}/runs/{run_id}`，直到 `status` 为终态。

Reference: https://elevenlabs.io/docs/api-reference/flows/templates/runs/create

## Servers

- `https://api.elevenlabs.io` (Production, default)
- `https://api.us.elevenlabs.io` (Production US)
- `https://api.eu.residency.elevenlabs.io` (Production EU)
- `https://api.in.residency.elevenlabs.io` (Production India)
- `https://api.sg.residency.elevenlabs.io` (Production Singapore)

## Request

### Path parameters

- `template_id` (string, required) — 模板的 ID，如 ElevenLabs 应用中或通过 `GET /v1/flows/templates` 所示。

### Body (application/json)

This endpoint expects a TemplateRunCreateRequest.

- `inputs` (map from string to TemplateRunInput, required) — 以输入端口 ID 为键的输入值。必须提供正在运行版本的每个输入端口；缺少或未知 ID 将被拒绝。对于没有输入的模板，传入 `{}`。
- `version_id` (string, optional, nullable) — 要运行的模板快照。传入特定版本 id 可固定该快照，或传入 `latest`（省略时的默认值）以运行模板最近发布的版本。仅可固定已发布版本；模板所有者也可固定未发布的已保存快照，以便在发布前试用。此 API 永远不会运行实时草稿。
- `webhook` (WebhookTarget, optional, nullable) — 包含此项后，当运行的 `status` 变为 `completed` 或 `failed` 时，会将运行结果发送到工作区配置的 flows webhook。整个运行仅发送一个事件：`flows_template_run` 事件的 `data` 与 `GET /v1/flows/templates/{template_id}/runs/{run_id}` 的最终响应一致。

## Response

### 200

成功响应

- `id` (string, required) — 运行的唯一标识符。
- `template_id` (string, required) — 此次运行执行的模板，使运行多个模板的 webhook 使用方无需维护运行与模板的映射即可区分各次运行。
- `version_id` (string, required) — 此次运行执行的模板版本。创建运行时即会解析，因此使用 `latest` 启动的运行会记录实际执行的具体版本。
- `status` (enum, required) — 运行状态由各输出状态汇总而成：输出开始前为 `pending`，任一输出未完成时为 `generating`，所有输出完成后为 `completed`，所有输出结束且至少一项失败时为 `failed`。`completed` 和 `failed` 为终态：运行达到其中任一状态时，将触发 `flows_template_run` webhook。
  - Allowed values: `pending`, `generating`, `completed`, `failed`
- `outputs` (map from string to TemplateOutput, required) — The run's outputs, keyed by output port id. Each is a `TemplateOutput` discriminated on `type`, the `type` of its port's `content_schema`.

## Errors

### 422 Unprocessable Entity Error

验证错误。

- `detail` (list of ValidationError, optional)

## Types

### TemplateRunInput

绑定到模板输入端口的一个值，其格式由 `content_schema` 指定。`string` 端口接收文本本身；`number`、`integer` 和 `boolean` 端口接收相应类型的 JSON 值。存储在其他位置的内容是按 `type` 区分的引用：之前的 `generation`、已上传的 `asset`、`voice` 或通过 `inline_base64` 传入的媒体。`array` 端口接收 JSON 数组，每个元素对应一个值，并且必须符合架构的 `items`。 `object` 端口暂时无法通过此 API 绑定。 此处除传输格式外没有其他约束：端口可接受的内容（如 `enum`、长度）由其 `content_schema` 说明，运行路径会根据同一架构验证。

- string
- boolean
- integer
- double
- TemplateInputReference: TemplateInputReference
- list of TemplateRunInput

### WebhookTarget

- `type`: `all` (WebhookTargetAll)
- `type`: `ids` (WebhookTargetIds)
  - `ids` (list of string, required) — 用于接收结果的工作区 flows webhook ID。每个 ID 都必须是工作区已配置的 flows webhook。

### TemplateOutput

模板运行的一个输出，按 `type` 区分：即端口 `content_schema` 的 `type`。通过 `status` 查看其所处生命周期阶段。

- `type`: `array` (TemplateArrayOutput)
  - `has_more` (boolean, required) — 列表是否包含 `content` 之外的元素。
  - `id` (string, required) — 此输出对应生成记录的 ID。将其作为 `generation` 引用传入，即可在其他位置将此输出用作输入。
  - `status` (enum, required) — 输出的生命周期状态。当输出的内容字段已设置时，状态为 `completed`；当 `failure_reason` 和 `error_message` 已设置时，状态为 `failed`。
    - Allowed values: `pending`, `generating`, `completed`, `failed`
  - `content` (list of TemplateOutput, optional, nullable) — 列表中按顺序排列的首批元素，每项均遵循架构中 `items` 的结构。仅当 `status` 为 `completed` 时提供。`has_more` 为 true 时，这不是完整列表。保留项：目前尚无模板生成此类输出；发布此项是为了让能生成此类输出的模板可使用相同客户端运行。
  - `error_message` (string, optional, nullable) — 易读的失败说明。仅当 `status` 为 `failed` 时提供。失败的生成不收费。
  - `failure_reason` (enum, optional, nullable) — 失败类别。仅当 `status` 为 `failed` 时提供。
    - Allowed values: `timeout`, `model_error`, `moderated`, `invalid_parameters`, `dependency_failed`, `charging_failed`, `internal_error`
  - `next_cursor` (string, optional, nullable) — 将其作为 `cursor` 传递给后续端点，以获取 `content` 之后的元素。当 `content` 包含完整列表或输出尚未完成时为 `null`。保留字段：目前尚无模板生成此类输出；发布此字段是为了让将来生成此类输出的模板可由同一客户端运行。
- `type`: `audio` (TemplateAudioOutput)
  - `id` (string, required) — 此输出对应生成记录的 ID。将其作为 `generation` 引用传入，即可在其他位置将此输出用作输入。
  - `status` (enum, required) — 输出的生命周期状态。当输出的内容字段已设置时，状态为 `completed`；当 `failure_reason` 和 `error_message` 已设置时，状态为 `failed`。
    - Allowed values: `pending`, `generating`, `completed`, `failed`
  - `content_mime_type` (string, optional, nullable) — 生成媒体的 MIME 类型。仅当 `status` 为 `completed` 时提供。
  - `content_url` (string, optional, nullable) — 用于下载生成媒体的签名 URL。仅当 `status` 为 `completed` 时提供。该 URL 会在返回此响应约 1 小时后过期；请再次获取运行任务以取得新的 URL。
  - `error_message` (string, optional, nullable) — 易读的失败说明。仅当 `status` 为 `failed` 时提供。失败的生成不收费。
  - `failure_reason` (enum, optional, nullable) — 失败类别。仅当 `status` 为 `failed` 时提供。
    - Allowed values: `timeout`, `model_error`, `moderated`, `invalid_parameters`, `dependency_failed`, `charging_failed`, `internal_error`
- `type`: `boolean` (TemplateBooleanOutput)
  - `id` (string, required) — 此输出对应生成记录的 ID。将其作为 `generation` 引用传入，即可在其他位置将此输出用作输入。
  - `status` (enum, required) — 输出的生命周期状态。当输出的内容字段已设置时，状态为 `completed`；当 `failure_reason` 和 `error_message` 已设置时，状态为 `failed`。
    - Allowed values: `pending`, `generating`, `completed`, `failed`
  - `content` (boolean, optional, nullable) — 生成的布尔值。仅当 `status` 为 `completed` 时提供。保留项：目前尚无模板生成此类输出；发布此项是为了让能生成此类输出的模板可使用相同客户端运行。
  - `error_message` (string, optional, nullable) — 易读的失败说明。仅当 `status` 为 `failed` 时提供。失败的生成不收费。
  - `failure_reason` (enum, optional, nullable) — 失败类别。仅当 `status` 为 `failed` 时提供。
    - Allowed values: `timeout`, `model_error`, `moderated`, `invalid_parameters`, `dependency_failed`, `charging_failed`, `internal_error`
- `type`: `image` (TemplateImageOutput)
  - `id` (string, required) — 此输出对应生成记录的 ID。将其作为 `generation` 引用传入，即可在其他位置将此输出用作输入。
  - `status` (enum, required) — 输出的生命周期状态。当输出的内容字段已设置时，状态为 `completed`；当 `failure_reason` 和 `error_message` 已设置时，状态为 `failed`。
    - Allowed values: `pending`, `generating`, `completed`, `failed`
  - `content_mime_type` (string, optional, nullable) — 生成媒体的 MIME 类型。仅当 `status` 为 `completed` 时提供。
  - `content_url` (string, optional, nullable) — 用于下载生成媒体的签名 URL。仅当 `status` 为 `completed` 时提供。该 URL 会在返回此响应约 1 小时后过期；请再次获取运行任务以取得新的 URL。
  - `error_message` (string, optional, nullable) — 易读的失败说明。仅当 `status` 为 `failed` 时提供。失败的生成不收费。
  - `failure_reason` (enum, optional, nullable) — 失败类别。仅当 `status` 为 `failed` 时提供。
    - Allowed values: `timeout`, `model_error`, `moderated`, `invalid_parameters`, `dependency_failed`, `charging_failed`, `internal_error`
- `type`: `integer` (TemplateIntegerOutput)
  - `id` (string, required) — 此输出对应生成记录的 ID。将其作为 `generation` 引用传入，即可在其他位置将此输出用作输入。
  - `status` (enum, required) — 输出的生命周期状态。当输出的内容字段已设置时，状态为 `completed`；当 `failure_reason` 和 `error_message` 已设置时，状态为 `failed`。
    - Allowed values: `pending`, `generating`, `completed`, `failed`
  - `content` (integer, optional, nullable) — 生成的整数。仅当 `status` 为 `completed` 时提供。保留项：目前尚无模板生成此类输出；发布此项是为了让能生成此类输出的模板可使用相同客户端运行。
  - `error_message` (string, optional, nullable) — 易读的失败说明。仅当 `status` 为 `failed` 时提供。失败的生成不收费。
  - `failure_reason` (enum, optional, nullable) — 失败类别。仅当 `status` 为 `failed` 时提供。
    - Allowed values: `timeout`, `model_error`, `moderated`, `invalid_parameters`, `dependency_failed`, `charging_failed`, `internal_error`
- `type`: `number` (TemplateNumberOutput)
  - `id` (string, required) — 此输出对应生成记录的 ID。将其作为 `generation` 引用传入，即可在其他位置将此输出用作输入。
  - `status` (enum, required) — 输出的生命周期状态。当输出的内容字段已设置时，状态为 `completed`；当 `failure_reason` 和 `error_message` 已设置时，状态为 `failed`。
    - Allowed values: `pending`, `generating`, `completed`, `failed`
  - `content` (double, optional, nullable) — 生成的数字。仅当 `status` 为 `completed` 时提供。保留项：目前尚无模板生成此类输出；发布此项是为了让能生成此类输出的模板可使用相同客户端运行。
  - `error_message` (string, optional, nullable) — 易读的失败说明。仅当 `status` 为 `failed` 时提供。失败的生成不收费。
  - `failure_reason` (enum, optional, nullable) — 失败类别。仅当 `status` 为 `failed` 时提供。
    - Allowed values: `timeout`, `model_error`, `moderated`, `invalid_parameters`, `dependency_failed`, `charging_failed`, `internal_error`
- `type`: `object` (TemplateObjectOutput)
  - `id` (string, required) — 此输出对应生成记录的 ID。将其作为 `generation` 引用传入，即可在其他位置将此输出用作输入。
  - `status` (enum, required) — 输出的生命周期状态。当输出的内容字段已设置时，状态为 `completed`；当 `failure_reason` 和 `error_message` 已设置时，状态为 `failed`。
    - Allowed values: `pending`, `generating`, `completed`, `failed`
  - `content` (map from string to TemplateOutput, optional, nullable) — 每个字段一个输出，以字段名为键，且均遵循该字段架构的结构。仅在 `status` 为 `completed` 时提供。保留：目前尚无模板生成此类输出；发布它是为了让能够生成此类输出的模板可通过同一客户端运行。
  - `error_message` (string, optional, nullable) — 易读的失败说明。仅当 `status` 为 `failed` 时提供。失败的生成不收费。
  - `failure_reason` (enum, optional, nullable) — 失败类别。仅当 `status` 为 `failed` 时提供。
    - Allowed values: `timeout`, `model_error`, `moderated`, `invalid_parameters`, `dependency_failed`, `charging_failed`, `internal_error`
- `type`: `string` (TemplateStringOutput)
  - `id` (string, required) — 此输出对应生成记录的 ID。将其作为 `generation` 引用传入，即可在其他位置将此输出用作输入。
  - `status` (enum, required) — 输出的生命周期状态。当输出的内容字段已设置时，状态为 `completed`；当 `failure_reason` 和 `error_message` 已设置时，状态为 `failed`。
    - Allowed values: `pending`, `generating`, `completed`, `failed`
  - `content` (string, optional, nullable) — 生成的文本。仅当 `status` 为 `completed` 时提供。
  - `error_message` (string, optional, nullable) — 易读的失败说明。仅当 `status` 为 `failed` 时提供。失败的生成不收费。
  - `failure_reason` (enum, optional, nullable) — 失败类别。仅当 `status` 为 `failed` 时提供。
    - Allowed values: `timeout`, `model_error`, `moderated`, `invalid_parameters`, `dependency_failed`, `charging_failed`, `internal_error`
- `type`: `video` (TemplateVideoOutput)
  - `id` (string, required) — 此输出对应生成记录的 ID。将其作为 `generation` 引用传入，即可在其他位置将此输出用作输入。
  - `status` (enum, required) — 输出的生命周期状态。当输出的内容字段已设置时，状态为 `completed`；当 `failure_reason` 和 `error_message` 已设置时，状态为 `failed`。
    - Allowed values: `pending`, `generating`, `completed`, `failed`
  - `content_mime_type` (string, optional, nullable) — 生成媒体的 MIME 类型。仅当 `status` 为 `completed` 时提供。
  - `content_url` (string, optional, nullable) — 用于下载生成媒体的签名 URL。仅当 `status` 为 `completed` 时提供。该 URL 会在返回此响应约 1 小时后过期；请再次获取运行任务以取得新的 URL。
  - `error_message` (string, optional, nullable) — 易读的失败说明。仅当 `status` 为 `failed` 时提供。失败的生成不收费。
  - `failure_reason` (enum, optional, nullable) — 失败类别。仅当 `status` 为 `failed` 时提供。
    - Allowed values: `timeout`, `model_error`, `moderated`, `invalid_parameters`, `dependency_failed`, `charging_failed`, `internal_error`

### ValidationError

- `loc` (list of ValidationErrorLocItems, required)
- `msg` (string, required)
- `type` (string, required)

### TemplateInputReference

- `type`: `asset` (StaticAssetReference)
  - `asset_id` (string, required) — 通过 assets API（`POST /v1/assets`）上传的资源 ID，即该响应中返回的 `asset_id`。
- `type`: `generation` (GenerationReference)
  - `generation_id` (string, required) — 要使用其输出的生成记录 ID，在创建生成记录时返回。
- `type`: `inline_base64` (InlineBase64Reference)
  - `content_base64` (string, required) — 媒体文件的字节数据，采用 base64 编码（标准字母表）。解码后最大 25MB。
  - `mime_type` (enum, required) — 编码媒体的 MIME 类型。
    - Allowed values: `image/jpeg`, `image/png`, `image/webp`, `image/heic`, `image/heif`, `audio/mpeg`, `audio/wav`, `video/mp4`, `video/quicktime`, `video/webm`
- `type`: `voice` (VoiceReference)
  - `voice_id` (string, required) — 此工作区中音色的 ID。

### ValidationErrorLocItems

- string
- integer

## Examples

**Request**

```json
{
  "inputs": {
    "prompt": "a corgi on a surfboard",
    "reference": {
      "asset_id": "5xM2KqOnZyce22SPZ9d4",
      "type": "asset"
    }
  },
  "version_id": "latest",
  "webhook": {
    "type": "all"
  }
}
```

**Response**

```json
{
  "id": "sess_JWr5N6X9ZTqf8jD2LmQb",
  "template_id": "tmpl_abc123",
  "version_id": "ver_01hxyz",
  "status": "generating",
  "outputs": {
    "marketing_title": {
      "type": "string",
      "id": "Kx2mP7Y4WVrg9kE3NnRc",
      "status": "completed",
      "content": "Ride the wave."
    },
    "product_demo": {
      "type": "video",
      "id": "QWr5N6X9ZTqf8jD2La3B",
      "status": "generating"
    },
    "product_still": {
      "type": "image",
      "id": "JWr5N6X9ZTqf8jD2LmQb",
      "status": "completed",
      "content_mime_type": "image/png",
      "content_url": "https://storage.googleapis.com/generations/JWr5N6X9ZTqf8jD2LmQb"
    }
  }
}
```

**SDK Code**

```python
import requests

url = "https://api.elevenlabs.io/v1/flows/templates/template_id/runs"

payload = {
    "inputs": {
        "prompt": "a corgi on a surfboard",
        "reference": {
            "asset_id": "5xM2KqOnZyce22SPZ9d4",
            "type": "asset"
        }
    },
    "version_id": "latest",
    "webhook": { "type": "all" }
}
headers = {"Content-Type": "application/json"}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.elevenlabs.io/v1/flows/templates/template_id/runs';
const options = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{"inputs":{"prompt":"a corgi on a surfboard","reference":{"asset_id":"5xM2KqOnZyce22SPZ9d4","type":"asset"}},"version_id":"latest","webhook":{"type":"all"}}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.elevenlabs.io/v1/flows/templates/template_id/runs"

	payload := strings.NewReader("{\n  \"inputs\": {\n    \"prompt\": \"a corgi on a surfboard\",\n    \"reference\": {\n      \"asset_id\": \"5xM2KqOnZyce22SPZ9d4\",\n      \"type\": \"asset\"\n    }\n  },\n  \"version_id\": \"latest\",\n  \"webhook\": {\n    \"type\": \"all\"\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.elevenlabs.io/v1/flows/templates/template_id/runs")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n  \"inputs\": {\n    \"prompt\": \"a corgi on a surfboard\",\n    \"reference\": {\n      \"asset_id\": \"5xM2KqOnZyce22SPZ9d4\",\n      \"type\": \"asset\"\n    }\n  },\n  \"version_id\": \"latest\",\n  \"webhook\": {\n    \"type\": \"all\"\n  }\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.elevenlabs.io/v1/flows/templates/template_id/runs")
  .header("Content-Type", "application/json")
  .body("{\n  \"inputs\": {\n    \"prompt\": \"a corgi on a surfboard\",\n    \"reference\": {\n      \"asset_id\": \"5xM2KqOnZyce22SPZ9d4\",\n      \"type\": \"asset\"\n    }\n  },\n  \"version_id\": \"latest\",\n  \"webhook\": {\n    \"type\": \"all\"\n  }\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.elevenlabs.io/v1/flows/templates/template_id/runs', [
  'body' => '{
  "inputs": {
    "prompt": "a corgi on a surfboard",
    "reference": {
      "asset_id": "5xM2KqOnZyce22SPZ9d4",
      "type": "asset"
    }
  },
  "version_id": "latest",
  "webhook": {
    "type": "all"
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.elevenlabs.io/v1/flows/templates/template_id/runs");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"inputs\": {\n    \"prompt\": \"a corgi on a surfboard\",\n    \"reference\": {\n      \"asset_id\": \"5xM2KqOnZyce22SPZ9d4\",\n      \"type\": \"asset\"\n    }\n  },\n  \"version_id\": \"latest\",\n  \"webhook\": {\n    \"type\": \"all\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = ["Content-Type": "application/json"]
let parameters = [
  "inputs": [
    "prompt": "a corgi on a surfboard",
    "reference": [
      "asset_id": "5xM2KqOnZyce22SPZ9d4",
      "type": "asset"
    ]
  ],
  "version_id": "latest",
  "webhook": ["type": "all"]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.elevenlabs.io/v1/flows/templates/template_id/runs")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```