> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-86180b7b.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`](/ja/reference/settings/session-settings#ai_function_max_input_tokens_per_query), [`ai_function_max_output_tokens_per_query`](/ja/reference/settings/session-settings#ai_function_max_output_tokens_per_query)) および API 呼び出し ([`ai_function_max_api_calls_per_query`](/ja/reference/settings/session-settings#ai_function_max_api_calls_per_query)) に対するクエリ単位の上限。
* **バックオフ付き再試行**: 一時的な障害は、指数バックオフ ([`ai_function_retry_initial_delay_ms`](/ja/reference/settings/session-settings#ai_function_retry_initial_delay_ms)) を使用して再試行 ([`ai_function_max_retries`](/ja/reference/settings/session-settings#ai_function_max_retries)) されます。

<div id="configuration">
  ## 設定
</div>

AI 関数は、プロバイダーの認証情報と設定を格納する **named collection** を参照します。各関数の最初の引数は、この collection の名前です。

プロバイダーの認証情報を含む named collection を作成するステートメントの例:

```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 関連の設定はすべて、`ai_function_` プレフィックスで [Settings](/ja/reference/settings/session-settings) に一覧表示されています。

<div id="restricting-endpoint-hosts">
  ### エンドポイントホストの制限
</div>

AI named collection の `endpoint` URL は、サーバーが自身の identity で接続する送信先であり、リクエストヘッダーに named collection の `api_key` を含めて送信します。デフォルトでは、ClickHouse はすべてのホストへの接続を許可します。関数を特定の provider 群のみに制限するには、サーバー設定で [`remote_url_allow_hosts`](/ja/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` endpoint を使用します。 |

<div id="observability">
  ## オブザーバビリティ
</div>

AI 関数のアクティビティは、ClickHouse の [ProfileEvents](/ja/reference/system-tables/query_log) で追跡できます。

| ProfileEvent      | Description                                                       |
| ----------------- | ----------------------------------------------------------------- |
| `AIAPICalls`      | AI provider に送信された 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プロバイダーを使用して、与えられたカテゴリのいずれか 1 つに分類します。

この関数は、固定の分類プロンプトと、モデルが指定されたラベルのうちちょうど 1 つだけを返すよう制約する JSON スキーマのレスポンスフォーマットとともに、テキストを送信します。レスポンスが `{"category": "..."}` 形式の JSON オブジェクトとして返された場合は、ラベルが取り出され、その文字列が返されます。

最初の引数は、プロバイダー、モデル、エンドポイント、APIキーを指定する named collection です。

**構文**

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

**別名**: `AIClassify`

**引数**

* `collection` — provider credentials と設定を含む named collection の名前。[`String`](/ja/reference/data-types/string)
* `text` — 分類するテキスト。[`String`](/ja/reference/data-types/string)
* `categories` — 候補となるカテゴリラベルの定数リスト。[`Array(String)`](/ja/reference/data-types/array)
* `temperature` — ランダム性を制御するサンプリング温度。デフォルト: `0.0`。[`Float64`](/ja/reference/data-types/float)

**戻り値**

指定されたカテゴリラベルのいずれか、またはリクエストが失敗し、`ai_function_throw_on_error` が無効になっている場合はカラム型のデフォルト値 (空文字列) 。[`String`](/ja/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プロバイダーを使用して、非構造化テキストから構造化情報を抽出します。

3 番目の引数には、自由形式の自然言語による指示 (例: `'主な訴え'`) または
`'{"field_a": "field a の説明", "field_b": "field b の説明"}'` の形式の JSON エンコードされたスキーマを指定できます。

指示モードでは、この関数は抽出した値をプレーンな文字列として返し、何も見つからなかった場合は空文字列を返します。
スキーマモードでは、この関数は要求されたスキーマに対応するキーを持つ JSON オブジェクト文字列を返します。存在しないフィールドは `null` になります。

最初の引数は、provider、model、endpoint、および API key を指定する named collection です。

**構文**

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

**別名**: `AIExtract`

**引数**

* `collection` — provider credentials と設定を含む named collection の名前。[`String`](/ja/reference/data-types/string)
* `text` — 情報を抽出するテキスト。[`String`](/ja/reference/data-types/string)
* `instruction_or_schema` — 自由形式の抽出指示、または抽出するフィールドを記述した定数の JSONオブジェクト。[`const String`](/ja/reference/data-types/string)
* `temperature` — ランダム性を制御するサンプリング温度。デフォルト: `0.0`。[`const Float64`](/ja/reference/data-types/float)

**戻り値**

単一の抽出結果 (指示モード) または JSONオブジェクト文字列 (スキーマモード) 。リクエストが失敗し、`ai_function_throw_on_error` が無効になっている場合は、カラム型のデフォルト値 (空文字列) を返します。[`String`](/ja/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
```

**スキーマ抽出**

```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キーを指定する名前付きコレクションです。

**構文**

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

**別名**: `AIGenerate`

**引数**

* `collection` — provider credentials と configuration を含む named collection の名前。[`String`](/ja/reference/data-types/string)
* `prompt` — モデルに送信するユーザーのプロンプトまたは質問。[`String`](/ja/reference/data-types/string)
* `system_prompt` — モデルの動作を導く任意の固定のシステムレベル命令 (例: ペルソナ、出力フォーマット) 。各プロンプトとともに送信されます。[`String`](/ja/reference/data-types/string)
* `temperature` — ランダム性を制御するサンプリング温度。デフォルト: `0.7`。[`Float64`](/ja/reference/data-types/float)

**戻り値**

生成されたテキスト応答。リクエストが失敗し、`ai_function_throw_on_error` が無効な場合は、カラム型のデフォルト値 (空文字列) が返されます。[`String`](/ja/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プロバイダーを使用して指定した対象言語に翻訳します。

文体や方言に関する追加の指示は、第4引数として渡せます (例: `'keep technical terms untranslated'`) 。

最初の引数は、プロバイダー、モデル、エンドポイント、API key を指定する named collection です。

**構文**

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

**別名**: `AITranslate`

**引数**

* `collection` — provider credentials と configuration を含む名前付きコレクションの名前。[`String`](/ja/reference/data-types/string)
* `text` — 翻訳するテキスト。[`String`](/ja/reference/data-types/string)
* `target_language` — 翻訳先言語の名前または BCP-47 コード (例: `'French'`、`'es-MX'`) 。[`String`](/ja/reference/data-types/string)
* `instructions` — 翻訳者への追加指示 (任意の定数) 。[`String`](/ja/reference/data-types/string)
* `temperature` — ランダム性を制御するサンプリング温度。デフォルト: `0.3`。[`Float64`](/ja/reference/data-types/float)

**戻り値**

翻訳されたテキスト、またはリクエストが失敗し、`ai_function_throw_on_error` が無効な場合はカラム型のデフォルト値 (空文字列) 。[`String`](/ja/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}
```
