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

# 更新文件文档

PATCH https://api.elevenlabs.io/v1/convai/knowledge-base/{documentation_id}/update-file
Content-Type: multipart/form-data

更新文件文档的源文件。文档名称、内容和元数据将更新以反映新文件。所有手动内容编辑都会被覆盖。

Reference: https://elevenlabs.io/docs/eleven-agents/api-reference/knowledge-base/update-file

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

- `documentation_id` (string, required) — 知识库中文档的 ID。添加文档时返回此值。

### Body (multipart/form-data)

This endpoint expects a multipart form containing a file.

- `file` (file, required) — 智能体可访问、用于与用户交互的文档。

## Response

### 200

成功响应

- `DocumentUpdateFileResponse`
  - `type`: `url`
    - `access_info` (ResourceAccessInfo, required)
    - `extracted_inner_html` (string, required)
    - `id` (string, required)
    - `metadata` (KnowledgeBaseDocumentMetadataResponseModel, required)
    - `name` (string, required)
    - `supported_usages` (list of enum, required)
      - Allowed values: `prompt`, `auto`
    - `url` (string, required)
    - `auto_sync_info` (AutoSyncInfo, optional)
    - `content_format` (enum, optional, default: html) — Canonical representation of a knowledge base document's stored content. HTML is the legacy default; documents created before this field existed are interpreted as HTML.
      - Allowed values: `html`, `markdown`
    - `folder_parent_id` (string, optional) — 父文件夹的 ID；如果文档位于根目录，则为 null。
    - `folder_path` (list of KnowledgeBaseFolderPathSegmentResponseModel, optional) — 从根目录到父文件夹、通往此实体的文件夹路径段。
  - `type`: `file`
    - `access_info` (ResourceAccessInfo, required)
    - `extracted_inner_html` (string, required)
    - `filename` (string, required)
    - `id` (string, required)
    - `metadata` (KnowledgeBaseDocumentMetadataResponseModel, required)
    - `name` (string, required)
    - `supported_usages` (list of enum, required)
      - Allowed values: `prompt`, `auto`
    - `auto_sync_info` (AutoSyncInfo, optional)
    - `content_format` (enum, optional, default: html) — Canonical representation of a knowledge base document's stored content. HTML is the legacy default; documents created before this field existed are interpreted as HTML.
      - Allowed values: `html`, `markdown`
    - `external_sync_info` (ExternalFileSyncInfo, optional) — 跟踪返回外部来源原始文件的链接。
    - `folder_parent_id` (string, optional) — 父文件夹的 ID；如果文档位于根目录，则为 null。
    - `folder_path` (list of KnowledgeBaseFolderPathSegmentResponseModel, optional) — 从根目录到父文件夹、通往此实体的文件夹路径段。
    - `is_frozen` (boolean, optional, default: false)
    - `refresh_status` (FileRefreshStatus, optional) — 外部同步文件正在进行或最近一次刷新的状态。客户端可据此显示同步进度，并在刷新排队或处理期间禁用重新同步。
  - `type`: `text`
    - `access_info` (ResourceAccessInfo, required)
    - `extracted_inner_html` (string, required)
    - `id` (string, required)
    - `metadata` (KnowledgeBaseDocumentMetadataResponseModel, required)
    - `name` (string, required)
    - `supported_usages` (list of enum, required)
      - Allowed values: `prompt`, `auto`
    - `content_format` (enum, optional, default: html) — Canonical representation of a knowledge base document's stored content. HTML is the legacy default; documents created before this field existed are interpreted as HTML.
      - Allowed values: `html`, `markdown`
    - `folder_parent_id` (string, optional) — 父文件夹的 ID；如果文档位于根目录，则为 null。
    - `folder_path` (list of KnowledgeBaseFolderPathSegmentResponseModel, optional) — 从根目录到父文件夹、通往此实体的文件夹路径段。
  - `type`: `folder`
    - `access_info` (ResourceAccessInfo, required)
    - `children_count` (integer, required)
    - `document_count` (integer, required) — 此文件夹子树中任意位置的非文件夹文档数量（递归）。计数超过 1000 后停止；
    - `id` (string, required)
    - `metadata` (KnowledgeBaseDocumentMetadataResponseModel, required)
    - `name` (string, required)
    - `supported_usages` (list of enum, required)
      - Allowed values: `prompt`, `auto`
    - `active_sync_job` (KbExternalSyncJob, optional) — 此文件夹最近的外部同步任务（进行中或已结束，如有）。供客户端显示同步进度。
    - `auto_sync_info` (AutoSyncInfo, optional)
    - `external_sync_info` (ExternalFolderSyncInfo, optional) — 镜像外部源文件夹的知识库文件夹元数据。
    - `folder_parent_id` (string, optional) — 父文件夹的 ID；如果文档位于根目录，则为 null。
    - `folder_path` (list of KnowledgeBaseFolderPathSegmentResponseModel, optional) — 从根目录到父文件夹、通往此实体的文件夹路径段。
    - `is_frozen` (boolean, optional, default: false)

## Errors

### 422 Document Update File Request Unprocessable Entity Error

验证错误。

- `detail` (list of ValidationError, optional)

## Types

### ResourceAccessInfo

- `is_creator` (boolean, required) — 发出请求的用户是否为该智能体的创建者
- `creator_name` (string, required) — 智能体创建者名称
- `creator_email` (string, required) — 智能体创建者的邮箱
- `role` (enum, required) — 发出请求的用户角色
  - Allowed values: `admin`, `editor`, `commenter`, `viewer`
- `anonymous_access_level_override` (enum, optional) — 匿名用户的访问级别。若为 None，该资源不会公开共享。
  - Allowed values: `admin`, `editor`, `commenter`, `viewer`
- `access_source` (enum, optional) — 请求用户拥有此资源访问权限的原因。'creator' = 调用者是所有者。'explicit' = 调用者（或其所属的某个工作区群组）列于 role_to_group_ids 中，且不包括工作区范围的所有人群组。'workspace_default' = 工作区范围的所有人群组列于 role_to_group_ids 中（所有非匿名工作区成员，包括管理员，均可查看此资源）。'workspace_admin' = 调用者是工作区管理员，且管理员席位是 *唯一* 的访问路径；此项仅用于其他人均无法查看的文档。这样 UI 可说明管理员绕过权限的查看者为何能看到未明确向其共享的文档。
  - Allowed values: `creator`, `explicit`, `workspace_admin`, `workspace_default`

### KnowledgeBaseDocumentMetadataResponseModel

- `created_at_unix_secs` (integer, required)
- `last_updated_at_unix_secs` (integer, required)
- `size_bytes` (integer, required)

### AutoSyncInfo

- `minimum_frequency_days` (integer, optional, default: 7) — 刷新文档的最低频率（按天计）。实际间隔可能更短，但不会更长。
- `auto_remove` (boolean, optional, default: false) — 当 URL 不可用时是否删除文档
- `consec_failures` (integer, optional, default: 0) — 连续同步失败次数
- `next_refresh_by` (integer, optional) — 下次计划同步的 Unix 时间戳；文件夹时为 None。
- `auto_discover` (boolean, optional, default: false, deprecated) — 已弃用。此字段已不再生效，并将在未来版本中移除。

### KnowledgeBaseFolderPathSegmentResponseModel

- `id` (string, required)
- `name` (string, optional)

### ExternalFileSyncInfo

跟踪返回外部来源原始文件的链接。

- `type` ("google_drive", required) — 提供商标识符
- `source_entity_id` (string, required) — 外部系统中的实体 ID
- `integration_connection_id` (string, required) — 集成连接实例 ID
- `source_parent_entity_id` (string, required) — 此文件同步来源的外部系统文件夹 ID
- `source_mime_type` (string, required) — 外部系统中的原始 MIME 类型
- `source_modified_time` (datetime, required) — 外部系统中的最后修改时间
- `root_folder_id` (string, optional) — 同步根目录的知识库文件夹 ID，用于查询同步树下的所有实体

### FileRefreshStatus

外部同步知识库文件正在进行或最近一次刷新的状态。

- `status` (enum, optional, default: queued)
  - Allowed values: `queued`, `processing`, `succeeded`, `failed`, `skipped`, `cancelled`
- `enqueued_at` (integer, optional)
- `started_at` (integer, optional)
- `completed_at` (integer, optional)
- `last_synced_at` (integer, optional)
- `error_message` (string, optional)

### KbExternalSyncJob

- `type` ("google_drive", required)
- `folder_id` (string, required)
- `integration_connection_id` (string, required)
- `triggered_by` (enum, required)
  - Allowed values: `on_demand`, `on_connect`, `auto`
- `updated_at` (integer, required)
- `id` (string, required)
- `created_at` (integer, required)
- `status` (enum, optional, default: queued)
  - Allowed values: `queued`, `processing`, `succeeded`, `failed`, `skipped`, `cancelled`
- `sync_type` (enum, optional)
  - Allowed values: `full`, `incremental`
- `items_identified` (integer, optional, default: 0)
- `items_processed` (integer, optional, default: 0)
- `error_message` (string, optional)
- `started_at` (integer, optional)
- `completed_at` (integer, optional)

### ExternalFolderSyncInfo

镜像外部源文件夹的知识库文件夹元数据。

- `type` ("google_drive", required) — 提供商标识符
- `source_entity_id` (string, required) — 外部系统中的实体 ID
- `integration_connection_id` (string, required) — 集成连接实例 ID
- `root_folder_id` (string, optional) — 同步根目录的知识库文件夹 ID。None 表示此文件夹为根目录。
- `sync_cursor` (string, optional) — 用于增量同步的不透明游标，由提供商解析
- `last_sync_at` (integer, optional) — 上次完成同步的 Unix 时间戳。

### ValidationError

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

### ValidationErrorLocItem

- string
- integer

## Examples

**Request**

```json
{
  "file": "<file: <file1>>"
}
```

**Response**

```json
{
  "type": "url",
  "access_info": {
    "is_creator": true,
    "creator_name": "John Doe",
    "creator_email": "john.doe@example.com",
    "role": "admin",
    "anonymous_access_level_override": "admin",
    "access_source": "creator"
  },
  "extracted_inner_html": "extracted_inner_html",
  "id": "id",
  "metadata": {
    "created_at_unix_secs": 1,
    "last_updated_at_unix_secs": 1,
    "size_bytes": 1
  },
  "name": "name",
  "supported_usages": [
    "prompt"
  ],
  "url": "url",
  "auto_sync_info": {
    "minimum_frequency_days": 1,
    "auto_remove": true,
    "consec_failures": 1,
    "next_refresh_by": 1
  },
  "content_format": "html",
  "folder_parent_id": "folder_parent_id",
  "folder_path": [
    {
      "id": "id",
      "name": "name"
    }
  ]
}
```

**SDK Code**

```python
import requests

url = "https://api.elevenlabs.io/v1/convai/knowledge-base/21m00Tcm4TlvDq8ikWAM/update-file"

files = { "file": "open('<file1>', 'rb')" }

response = requests.patch(url, files=files)

print(response.json())
```

```javascript
const url = 'https://api.elevenlabs.io/v1/convai/knowledge-base/21m00Tcm4TlvDq8ikWAM/update-file';
const form = new FormData();
form.append('file', '<file1>');

const options = {method: 'PATCH'};

options.body = form;

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/convai/knowledge-base/21m00Tcm4TlvDq8ikWAM/update-file"

	payload := strings.NewReader("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"<file1>\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001--\r\n")

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

	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/convai/knowledge-base/21m00Tcm4TlvDq8ikWAM/update-file")

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

request = Net::HTTP::Patch.new(url)
request.body = "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"<file1>\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001--\r\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.patch("https://api.elevenlabs.io/v1/convai/knowledge-base/21m00Tcm4TlvDq8ikWAM/update-file")
  .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"<file1>\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001--\r\n")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('PATCH', 'https://api.elevenlabs.io/v1/convai/knowledge-base/21m00Tcm4TlvDq8ikWAM/update-file', [
  'multipart' => [
    [
        'name' => 'file',
        'filename' => '<file1>',
        'contents' => null
    ]
  ]
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://api.elevenlabs.io/v1/convai/knowledge-base/21m00Tcm4TlvDq8ikWAM/update-file");
var request = new RestRequest(Method.PATCH);
request.AddParameter("undefined", "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"; filename=\"<file1>\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n-----011000010111000001101001--\r\n", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation
let parameters = [
  [
    "name": "file",
    "fileName": "<file1>"
  ]
]

let boundary = "---011000010111000001101001"

var body = ""
var error: NSError? = nil
for param in parameters {
  let paramName = param["name"]!
  body += "--\(boundary)\r\n"
  body += "Content-Disposition:form-data; name=\"\(paramName)\""
  if let filename = param["fileName"] {
    let contentType = param["content-type"]!
    let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
    if (error != nil) {
      print(error as Any)
    }
    body += "; filename=\"\(filename)\"\r\n"
    body += "Content-Type: \(contentType)\r\n\r\n"
    body += fileContent
  } else if let paramValue = param["value"] {
    body += "\r\n\r\n\(paramValue)"
  }
}

let request = NSMutableURLRequest(url: NSURL(string: "https://api.elevenlabs.io/v1/convai/knowledge-base/21m00Tcm4TlvDq8ikWAM/update-file")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "PATCH"
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()
```