> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> AI 函数文档

# AI 函数

AI 函数是 ClickHouse 中的内置函数，可用于调用 AI 或生成嵌入向量，以处理数据、提取信息、对数据进行分类等……

<Note>
  AI 函数处于 Experimental 阶段。设置 [`allow_experimental_ai_functions`](/docs/zh/reference/settings/session-settings#allow_experimental_ai_functions) 以启用它们。
</Note>

<Note>
  AI 函数可能会返回不可预测的输出。结果在很大程度上取决于提示词的质量和所使用的模型。
</Note>

所有函数共用一套通用基础设施，提供：

* **配额限制**：每次查询的标记数限制 ([`ai_function_max_input_tokens_per_query`](/docs/zh/reference/settings/session-settings#ai_function_max_input_tokens_per_query)、[`ai_function_max_output_tokens_per_query`](/docs/zh/reference/settings/session-settings#ai_function_max_output_tokens_per_query)) 以及 API 调用次数限制 ([`ai_function_max_api_calls_per_query`](/docs/zh/reference/settings/session-settings#ai_function_max_api_calls_per_query)) 。
* **退避重试**：遇到临时性故障时会自动重试 ([`ai_function_max_retries`](/docs/zh/reference/settings/session-settings#ai_function_max_retries)) ，并采用指数退避 ([`ai_function_retry_initial_delay_ms`](/docs/zh/reference/settings/session-settings#ai_function_retry_initial_delay_ms)) 。

<div id="configuration">
  ## 配置
</div>

AI 函数会引用一个**命名集合**，其中存储了提供商凭据和配置信息。可以针对不同的函数或函数调用创建并使用不同的命名集合。例如，你可能希望为文本函数 (`aiGenerate`、`aiClassify`、`aiExtract`、`aiTranslate`) 定义一个命名集合，而为 `aiEmbed` 函数定义另一个，因为它们需要不同的端点，通常也会使用不同的模型。

以下是创建包含提供商凭据的命名集合的示例语句：一个用于聊天端点，另一个用于 embedding 端点：

```sql theme={null}
CREATE NAMED COLLECTION ai_text_credentials AS
    provider = 'openai',
    endpoint = 'https://api.openai.com/v1/chat/completions',
    model = 'gpt-4o-mini',
    api_key = 'sk-...';

-- `aiEmbed` does not read `model` from the named collection; pass it as a positional argument instead.
-- Defining `model` in an `aiEmbed` collection is an error, not silently ignored.
CREATE NAMED COLLECTION ai_embedding_credentials AS
    provider = 'openai',
    endpoint = 'https://api.openai.com/v1/embeddings',
    api_key = 'sk-...';
```

<div id="named-collection-parameters">
  ### 命名集合参数
</div>

| 参数            | 类型     | 默认值    | 描述                                                                                      |
| ------------- | ------ | ------ | --------------------------------------------------------------------------------------- |
| `provider`    | String | —      | 模型提供商。支持：`'openai'`、`'anthropic'`。请参见下方说明。                                              |
| `endpoint`    | String | —      | API 端点 URL。                                                                             |
| `model`       | String | —      | 模型名称 (例如 `'gpt-4o-mini'`)。由文本函数使用；`aiEmbed` 要求将 `model` 作为位置参数，如果在命名集合中指定 `model`，则会报错。 |
| `api_key`     | String | —      | 提供商的身份验证密钥。可选：省略时不会发送身份验证请求头，因此可以将目标指向不需要身份验证的 OpenAI 兼容服务器。                            |
| `max_tokens`  | UInt64 | `1024` | 每次 API 调用可输出的最大标记数。                                                                     |
| `api_version` | String | —      | API 版本字符串。Anthropic 使用此参数 (`'2023-06-01'`) 。                                            |

<Note>
  将 `provider` 设为 `'openai'`，并把 `endpoint` 指向你的服务，即可使用任何与 OpenAI 兼容的 API (例如 vLLM、Ollama、LiteLLM) 。
</Note>

<div id="selecting-credentials">
  ### 选择凭据
</div>

函数会按以下顺序确定要使用的命名集合：

1. 参数映射中的 `credentials` 键 (如果存在) ；
2. 否则，使用适用的默认凭据设置：
   * 文本函数 (`aiGenerate`、`aiClassify`、`aiExtract`、`aiTranslate`) 使用 [`ai_function_text_default_credentials`](/docs/zh/reference/settings/session-settings#ai_function_text_default_credentials)；
   * `aiEmbed` 使用 [`ai_function_embedding_default_credentials`](/docs/zh/reference/settings/session-settings#ai_function_embedding_default_credentials)。

如果两者都未设置，调用就会失败。文本函数和嵌入向量函数分别使用不同的默认设置，因为聊天补全所用的端点与嵌入向量所用的端点不同。

```sql theme={null}
SET ai_function_text_default_credentials = 'ai_text_credentials';

-- Uses ai_text_credentials from the setting:
SELECT aiGenerate('What is 2 + 2? Reply with just the number.');

-- Overrides the default for this call:
SELECT aiGenerate('Bonjour', map('credentials', 'other_credentials'));
```

<div id="parameter-map">
  ### 参数映射
</div>

每个函数都接受一个可选的末尾 `Map(String, String)` 参数映射。所有值都必须是字符串 (数字也要加引号，例如 `'0.2'`) 。未知键会被拒绝。已提供的键会覆盖对应的命名集合值；未提供的键则回退到命名集合 (对于 `model`/`max_tokens`) 或内置默认值。例外情况是 `aiEmbed`，它将 `model` 作为必需的位置参数 (`aiEmbed(text, model[, params])`) 传入；如果改为在参数映射或命名集合中设置，则会报错。

以下参数是所有 AI 函数通用的：

| 键             | 描述                                                               |
| ------------- | ---------------------------------------------------------------- |
| `credentials` | 要使用的命名集合 (见上文) 。                                                 |
| `model`       | 覆盖该集合中的 `model` (仅限文本函数；`aiEmbed` 将 `model` 作为必需的位置参数传入，而不是映射键)。 |

各个函数还接受额外的函数专用参数 (例如 `max_tokens`、`temperature`、`system_prompt`、`instructions` 和 `dimensions`) 。有关每个函数支持的参数及其默认值，请参阅下方各函数的参考说明。

```sql theme={null}
SELECT aiGenerate(body, map('temperature', '0.2', 'system_prompt', 'You are terse.')) FROM articles;
```

<div id="query-level-settings">
  ### 查询级别设置
</div>

所有与 AI 相关的设置均列在 [设置](/docs/zh/reference/settings/session-settings) 中，前缀为 `ai_function_`。

<div id="restricting-endpoint-hosts">
  ### 限制端点主机
</div>

AI 命名集合中的 `endpoint` URL 是服务器以自身身份连接的出站目标端，并可能 (如果已指定) 在请求头中携带该命名集合的 `api_key`。默认情况下，ClickHouse 允许连接任意主机。要将函数限制为一组特定的提供商，请在服务器配置中设置 [`remote_url_allow_hosts`](/docs/zh/reference/settings/server-settings/settings#remote_url_allow_hosts)，例如：

```xml theme={null}
<remote_url_allow_hosts>
    <host>api.openai.com</host>
    <host>api.anthropic.com</host>
</remote_url_allow_hosts>
```

请注意，此设置对整个服务器生效，并适用于所有使用 HTTP 的功能。

<div id="transport-security">
  ### 传输安全 (HTTP 与 HTTPS)
</div>

传输方式完全由 `endpoint` URL 的 scheme 决定。请求载荷本身没有应用层加密；传输中数据的保护完全取决于所使用的 scheme：

* `https://` — 连接使用 TLS。请求体 (输入文本、提示词) 以及请求头中的 `api_key` 都会在传输过程中加密，并且会验证提供商的证书。对于任何远程提供商，都应使用此方式。
* `http://` — 连接**不加密**。请求体和 `api_key` 会以明文发送。仅应在私网中的可信提供商上使用此方式 (例如本地的 `vLLM` 或 `Ollama` 实例) 。

AI 函数不会强制使用 HTTPS：`http://` 端点会被接受，并以未加密方式发送数据。目前还没有会拒绝明文 AI 端点的服务端设置——[`remote_url_allow_hosts`](/docs/zh/reference/settings/server-settings/settings#remote_url_allow_hosts) 仅限制目标 host，不会检查 URL scheme，因此指向允许 host 的 `http://` 端点仍然可以通过。要确保传输加密，请将 命名集合 配置为使用 `https://` 端点。

请注意，无论哪种情况，TLS 终止后提供商都会以明文接收输入数据；TLS 仅保护 服务器 与提供商之间网络路径上的数据。

<div id="supported-providers">
  ## 支持的提供商
</div>

| 提供商       | `provider` 值  | 聊天功能 | 说明                    |
| --------- | ------------- | ---- | --------------------- |
| OpenAI    | `'openai'`    | 是    | 默认提供商。                |
| Anthropic | `'anthropic'` | 是    | 使用 `/v1/messages` 端点。 |

<div id="observability">
  ## 可观测性
</div>

可通过 ClickHouse [ProfileEvents](/docs/zh/reference/system-tables/query_log) 跟踪 AI 函数活动：

| ProfileEvent      | Description                                               |
| ----------------- | --------------------------------------------------------- |
| `AIAPICalls`      | 向 AI 提供商发出的 HTTP 请求数。                                     |
| `AIInputTokens`   | 消耗的输入标记总数。                                                |
| `AIOutputTokens`  | 消耗的输出标记总数。                                                |
| `AIRowsProcessed` | 获得结果的行数。                                                  |
| `AIRowsSkipped`   | 被跳过的行数 (超出配额，或在 `ai_function_throw_on_error = 0` 时发生错误) 。 |

查询这些事件：

```sql theme={null}
SELECT
    ProfileEvents['AIAPICalls'] AS api_calls,
    ProfileEvents['AIInputTokens'] AS input_tokens,
    ProfileEvents['AIOutputTokens'] AS output_tokens
FROM system.query_log
WHERE query_id = 'query_id'
AND type = 'QueryFinish'
ORDER BY event_time DESC;
```

{/*AUTOGENERATED_START*/}

<div id="aiClassify">
  ## aiClassify
</div>

引入版本：v26.4.0

使用 LLM 提供商将给定文本归类到所提供类别中的某一类。

该函数会将文本与固定的分类提示词以及 JSON schema 响应格式一并发送，
以约束模型必须精确返回所提供标签中的一个。当响应以 `{"category": "..."}` 形式的 JSON
对象返回时，会提取其中的标签并返回该标签字符串。

凭据 (一个用于指定提供商、模型、端点，以及可选的 API 密钥的命名集合)
取自可选参数映射中的 `credentials` 键，或者在该映射省略此项时，
取自 `ai_function_text_default_credentials` 设置。

**语法**

```sql theme={null}
aiClassify(text, categories[, params])
```

**别名**: `AIClassify`

**参数**

* `text` — 待分类的文本。[`String`](/docs/zh/reference/data-types/string)
* `categories` — 候选类别标签的常量列表。[`Array(String)`](/docs/zh/reference/data-types/array)
* `params` — 可选的常量 `Map(String, String)` 参数映射。函数特定键包括：`temperature` (用于控制随机性的采样温度；默认值 `0.0`) 、`max_tokens` (每次调用的最大输出标记数；默认值 `1024`) 。通用参数 `credentials` 和 `model` 同样适用 (参见 [AI 函数](/docs/zh/reference/functions/regular-functions/ai-functions)) 。[`Map(String, String)`](/docs/zh/reference/data-types/map)

**返回值**

返回提供的类别标签之一；如果请求失败且禁用了 `ai_function_throw_on_error`，则返回该列类型的默认值 (空字符串) 。[`String`](/docs/zh/reference/data-types/string)

**示例**

**情感分类**

```sql title=Query theme={null}
SELECT aiClassify('I love this product!', ['positive', 'negative', 'neutral'])
```

```response title=Response theme={null}
positive
```

**使用显式凭据对列进行分类**

```sql title=Query theme={null}
SELECT body, aiClassify(body, ['bug', 'question', 'feature'], map('credentials', 'ai_text_credentials')) AS kind FROM issues LIMIT 5
```

<div id="aiEmbed">
  ## aiEmbed
</div>

引入于：v26.6.0

使用已配置的 AI 提供商为给定文本生成嵌入向量。

该函数会将文本发送到已配置的嵌入端点，并以 `Array(Float32)` 形式返回结果向量。
在单个数据块内，输入会按批次分组，每个 HTTP 请求最多包含
[`ai_function_embedding_max_batch_size`](/docs/zh/reference/settings/session-settings#ai_function_embedding_max_batch_size)
个条目，以减少每次调用的额外开销。

凭据 (一个指定提供商、端点以及可选 API key 的命名集合)
取自参数映射中的 `credentials` 键；如果映射中省略了该键，则使用
`ai_function_embedding_default_credentials` 设置。请注意，`aiEmbed` 使用的是一个
独立于文本函数的默认凭据设置，因为嵌入端点与聊天端点不同。

`model` 是必需的位置参数 (一个常量 `String`) 。与文本函数不同，
`aiEmbed` 不会从命名集合或参数映射中读取 `model`。如果某个命名集合
定义了 `model`，则会被拒绝，而不会被静默忽略。

可选的 `dimensions` 参数在模型支持时 (例如 OpenAI's `text-embedding-3-*`)
会请求返回指定大小的向量；否则将返回该模型的原生大小。

**语法**

```sql theme={null}
aiEmbed(text, model[, params])
```

**参数**

* `text` — 要嵌入的文本。[`String`](/docs/zh/reference/data-types/string)
* `model` — 嵌入模型名称。[`const String`](/docs/zh/reference/data-types/string)
* `params` — 可选的常量 `Map(String, String)` 参数。此函数特有的键为：`dimensions` (输出向量的目标维数；`0` 或省略表示使用模型的原生维数) 。通用参数 `credentials` 也适用 (请参见 [AI 函数](/docs/zh/reference/functions/regular-functions/ai-functions)) 。[`Map(String, String)`](/docs/zh/reference/data-types/map)

**返回值**

嵌入向量；如果输入为 NULL 或空值、请求失败且禁用了 `ai_function_throw_on_error`，或者超出配额且禁用了 `ai_function_throw_on_quota_exceeded`，则返回空数组。[`Array(Float32)`](/docs/zh/reference/data-types/array)

**示例**

**嵌入单个字符串 (如果已设置 `ai_function_embedding_default_credentials`，则可省略 `credentials`) **

```sql title=Query theme={null}
SELECT aiEmbed('Hello world', 'text-embedding-3-small', map('credentials', 'ai_embedding_credentials'))
```

**显式指定维度**

```sql title=Query theme={null}
SELECT aiEmbed('Hello world', 'text-embedding-3-small', map('credentials', 'ai_embedding_credentials', 'dimensions', '256'))
```

**嵌入文本列**

```sql title=Query theme={null}
SELECT aiEmbed(title, 'text-embedding-3-small', map('credentials', 'ai_embedding_credentials', 'dimensions', '256')) FROM articles LIMIT 10
```

<div id="aiExtract">
  ## aiExtract
</div>

引入于：v26.4.0

使用 LLM 提供商从非结构化文本中提取结构化信息。

第三个参数既可以是自由形式的自然语言指令 (例如 `'主要诉求'`) ，也可以是如下形式的 JSON 编码 schema：`'{"field_a": "字段 a 的描述", "field_b": "字段 b 的描述"}'`。

在指令模式下，该函数会将提取出的值作为普通字符串返回；如果未找到任何内容，则返回空字符串。
在 schema 模式下，该函数返回一个 JSON 对象字符串，其键与所请求的 schema 一致；缺失字段为 `null`。

凭据 (用于指定提供商、模型、端点以及可选 API 密钥的命名集合)
取自可选参数映射中的 `credentials` 键；如果映射中未提供，
则取自 `ai_function_text_default_credentials` 设置。

**语法**

```sql theme={null}
aiExtract(text, instruction_or_schema[, params])
```

**别名**: `AIExtract`

**参数**

* `text` — 要从中提取信息的文本。[`String`](/docs/zh/reference/data-types/string)
* `instruction_or_schema` — 自由格式的提取指令，或用于描述待提取字段的常量 JSON 对象。[`const String`](/docs/zh/reference/data-types/string)
* `params` — 可选的常量 `Map(String, String)` 参数映射。函数特定键包括：`temperature` (用于控制随机性的采样温度；默认值 `0.0`) ，`max_tokens` (每次调用的最大输出标记数；默认值 `1024`) 。通用参数 `credentials` 和 `model` 也适用 (参见 [AI Functions](/docs/zh/reference/functions/regular-functions/ai-functions)) 。[`Map(String, String)`](/docs/zh/reference/data-types/map)

**返回值**

单个提取值 (指令模式) ，或 JSON 对象字符串 (schema 模式) 。如果请求失败且禁用了 `ai_function_throw_on_error`，则返回该列类型的默认值 (空字符串) 。[`String`](/docs/zh/reference/data-types/string)

**示例**

**自由格式指令**

```sql title=Query theme={null}
SELECT aiExtract('The package arrived late and was damaged.', 'the main complaint')
```

```response title=Response theme={null}
late and damaged package
```

**Schema 提取**

```sql title=Query theme={null}
SELECT aiExtract(review, '{"sentiment": "positive, negative or neutral", "topic": "main topic of the review"}') FROM reviews LIMIT 5
```

<div id="aiGenerate">
  ## aiGenerate
</div>

引入版本：v26.4.0

使用 LLM 提供商根据提示生成自由形式的文本内容。

该函数会将提示发送给已配置的 AI 提供商，并返回生成的文本。

凭据 (一个 命名集合，用于指定提供商、模型、端点，以及可选的 API 密钥)
取自可选参数映射中的 `credentials` 键；如果该映射中未提供，则取自
`ai_function_text_default_credentials` 设置。

可选参数映射还可设置 `system_prompt` (用于引导模型行为的指令，
例如语气、格式、角色) 、`temperature`、`max_tokens` 和 `model`。如果未设置 `system_prompt`，
默认值为：`You are a helpful assistant. Provide a clear and concise response.`

**语法**

```sql theme={null}
aiGenerate(prompt[, params])
```

**别名**: `AIGenerate`

**参数**

* `prompt` — 发送给模型的用户提示词或问题。[`String`](/docs/zh/reference/data-types/string)
* `params` — 可选的常量 `Map(String, String)` 参数映射。此函数特有的键包括：`temperature` (控制随机性的采样温度；默认值为 `0.7`) 、`max_tokens` (每次调用可生成的最大输出标记数；默认值为 `1024`) 、`system_prompt` (用于引导模型行为的常量系统级指令；默认值为通用助手提示词) 。通用参数 `credentials` 和 `model` 也同样适用 (参见 [AI 函数](/docs/zh/reference/functions/regular-functions/ai-functions)) 。[`Map(String, String)`](/docs/zh/reference/data-types/map)

**返回值**

生成的文本响应；如果请求失败且 `ai_function_throw_on_error` 被禁用，则返回该列类型的默认值 (空字符串) 。[`String`](/docs/zh/reference/data-types/string)

**示例**

**简单问题**

```sql title=Query theme={null}
SELECT aiGenerate('What is 2 + 2? Reply with just the number.')
```

```response title=Response theme={null}
4
```

**使用明确指定的凭据和系统提示**

```sql title=Query theme={null}
SELECT aiGenerate('Explain ClickHouse', map('credentials', 'ai_text_credentials', 'system_prompt', 'You are a database expert. Be concise.'))
```

**汇总列中的值**

```sql title=Query theme={null}
SELECT article_title, aiGenerate(concat('Summarize in one sentence: ', article_body)) AS summary FROM articles LIMIT 5
```

<div id="aiTranslate">
  ## aiTranslate
</div>

引入版本：v26.4.0

使用 LLM 提供商将给定文本翻译成指定的目标语言。

还可以通过参数映射中的 `instructions` 键传入额外的风格或语言变体说明 (例如：`'保留技术术语不翻译'`) 。

凭据 (一个命名集合，用于指定提供商、模型、端点，以及可选的 API 密钥)
取自可选参数映射中的 `credentials` 键；如果该映射中未提供此项，
则取自 `ai_function_text_default_credentials` 设置。

**语法**

```sql theme={null}
aiTranslate(text, target_language[, params])
```

**别名**: `AITranslate`

**参数**

* `text` — 要翻译的文本。[`String`](/docs/zh/reference/data-types/string)
* `target_language` — 目标语言名称或 BCP-47 代码 (例如 `'French'`、`'es-MX'`) 。[`String`](/docs/zh/reference/data-types/string)
* `params` — 可选的常量 `Map(String, String)` 参数映射。此函数特有的键包括：`temperature` (控制随机性的采样温度；默认值为 `0.3`) 、`max_tokens` (每次调用可生成的最大输出标记数；默认值为 `1024`) 、`instructions` (给翻译器的附加风格或方言说明) 。通用参数 `credentials` 和 `model` 同样适用 (参见 [AI 函数](/docs/zh/reference/functions/regular-functions/ai-functions)) 。[`Map(String, String)`](/docs/zh/reference/data-types/map)

**返回值**

翻译后的文本；如果请求失败且 `ai_function_throw_on_error` 被禁用，则返回列类型的默认值 (空字符串) 。[`String`](/docs/zh/reference/data-types/string)

**示例**

**翻译成法语**

```sql title=Query theme={null}
SELECT aiTranslate('Hello, world!', 'French')
```

```response title=Response theme={null}
Bonjour le monde!
```

**根据风格说明翻译成日语**

```sql title=Query theme={null}
SELECT aiTranslate(body, 'Japanese', map('instructions', 'Use polite form (desu/masu)')) FROM articles LIMIT 5
```
