> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-fix-nav-issues.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> AI 函数文档

# AI 函数

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

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

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

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

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

AI 函数会引用一个用于存储提供商凭据和配置信息的**命名集合**。每个函数的第一个参数都是该集合的名称。

创建包含提供商凭据的命名集合的示例语句：

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

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

| 参数            | 类型     | 默认值    | 描述                                                     |
| ------------- | ------ | ------ | ------------------------------------------------------ |
| `provider`    | String | —      | 模型提供商。支持：`'openai'`、`'anthropic'`。请参见下方说明。             |
| `endpoint`    | String | —      | API 端点 URL。                                            |
| `model`       | String | —      | 模型名称 (例如 `'gpt-4o-mini'`、`'text-embedding-3-small'`) 。 |
| `api_key`     | String | —      | 提供商的身份验证密钥。                                            |
| `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="query-level-settings">
  ### 查询级别设置
</div>

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

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

AI 命名集合中的 `endpoint` URL 是服务器以自身身份连接的出站目标端，并会在请求头中携带该命名集合的 `api_key`。默认情况下，ClickHouse 允许连接任意主机。要将函数限制为一组特定的提供商，请在服务器配置中设置 [`remote_url_allow_hosts`](/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="supported-providers">
  ## 支持的提供商
</div>

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

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

可通过 ClickHouse [ProfileEvents](/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 key。

**语法**

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

**别名**: `AIClassify`

**参数**

* `collection` — 包含提供商凭据和配置的命名集合名称。[`String`](/zh/reference/data-types/string)
* `text` — 待分类的文本。[`String`](/zh/reference/data-types/string)
* `categories` — 候选类别标签的常量列表。[`Array(String)`](/zh/reference/data-types/array)
* `temperature` — 用于控制随机性的采样温度。默认值：`0.0`。[`Float64`](/zh/reference/data-types/float)

**返回值**

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

**示例**

**情感分类**

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

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

**对列分类**

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

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

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

引入于：v26.4.0

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

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

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

第一个参数是一个命名集合，用于指定提供商、模型、端点和 API key。

**语法**

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

**别名**: `AIExtract`

**参数**

* `collection` — 包含提供商凭据和配置的命名集合名称。[`String`](/zh/reference/data-types/string)
* `text` — 要从中提取信息的文本。[`String`](/zh/reference/data-types/string)
* `instruction_or_schema` — 自由格式的提取指令，或用于描述待提取字段的常量 JSON 对象。[`const String`](/zh/reference/data-types/string)
* `temperature` — 用于控制随机性的采样温度。默认值：`0.0`。[`const Float64`](/zh/reference/data-types/float)

**返回值**

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

**示例**

**自由格式指令**

```sql title=Query theme={null}
SELECT aiExtract('ai_credentials', '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('ai_credentials', review, '{"sentiment": "positive, negative or neutral", "topic": "main topic of the review"}') FROM reviews LIMIT 5
```

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

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

引入版本：v26.4.0

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

该函数会将提示词发送给已配置的 AI 提供商，并返回生成的文本。
您还可以提供可选的系统提示来引导模型的行为 (例如语气、格式、角色) 。
如果未提供系统提示，则默认系统提示为：`You are a helpful assistant. Provide a clear and concise response.`

第一个参数是一个命名集合，用于指定提供商、模型、端点和 API key。

**语法**

```sql theme={null}
aiGenerate(collection, prompt[, system_prompt[, temperature]])
```

**别名**: `AIGenerate`

**参数**

* `collection` — 包含提供商凭据和配置的命名集合名称。[`String`](/zh/reference/data-types/string)
* `prompt` — 发送给模型的用户提示词或问题。[`String`](/zh/reference/data-types/string)
* `system_prompt` — 可选的固定系统级指令，用于引导模型行为 (例如角色设定、输出格式) ，并会随每次提示词一同发送。[`String`](/zh/reference/data-types/string)
* `temperature` — 控制随机性的采样温度。默认：`0.7`。[`Float64`](/zh/reference/data-types/float)

**返回值**

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

**示例**

**简单问题**

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

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

**使用系统提示**

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

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

**汇总列中的值**

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

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

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

引入版本：v26.4.0

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

还可将额外的风格或方言说明作为第四个参数传入 (例如 `'保留技术术语不翻译'`) 。

第一个参数是一个命名集合，用于指定提供商、模型、端点和 API key。

**语法**

```sql theme={null}
aiTranslate(collection, text, target_language[, instructions[, temperature]])
```

**别名**: `AITranslate`

**参数**

* `collection` — 包含提供商凭据和配置的命名集合名称。[`String`](/zh/reference/data-types/string)
* `text` — 要翻译的文本。[`String`](/zh/reference/data-types/string)
* `target_language` — 目标语言名称或 BCP-47 代码 (例如 `'French'`、`'es-MX'`) 。[`String`](/zh/reference/data-types/string)
* `instructions` — 提供给翻译器的可选固定附加说明。[`String`](/zh/reference/data-types/string)
* `temperature` — 用于控制随机性的采样温度。默认值：`0.3`。[`Float64`](/zh/reference/data-types/float)

**返回值**

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

**示例**

**翻译为法语**

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

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

**翻译成日语，并遵循风格说明**

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

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