Skip to content

Adding aiEmbed function - #102922

Merged
george-larionov merged 47 commits into
masterfrom
feature/ai-embeddings
May 27, 2026
Merged

george-larionov merged 47 commits into
masterfrom
feature/ai-embeddings

Conversation

@george-larionov

@george-larionov george-larionov commented Apr 17, 2026 •

Copy link
Copy Markdown
Member

3rd part of #100735.

Adds aiEmbed(collection, text[, dimensions]), an SQL function that returns a text embedding as Array(Float32). Like the existing AI functions it reads its provider, endpoint, model, and API key from a named collection, is gated behind
allow_experimental_ai_functions, and participates in the shared per-query quotas (ai_function_max_input_tokens_per_query, ai_function_max_api_calls_per_query). The optional dimensions argument, when supported by the model (e.g.
OpenAI's text-embedding-3-*), requests a specific output size; otherwise the model's native size is returned. Supported providers are the OpenAI-compatible ones — OpenAI, vLLM, Ollama, HuggingFace TEI; Anthropic has no public embeddings API
and is intentionally unsupported.

Unlike the other AI functions, aiEmbed batches within a single block of rows: up to ai_function_embedding_max_batch_size (default 100) inputs are sent in one HTTP request, then the response is matched back to input rows by index.
This cuts per-row overhead substantially for typical ingestion patterns such as INSERT INTO docs SELECT id, doc, aiEmbed('creds', doc) FROM … or a vector Array(Float32) DEFAULT aiEmbed('creds', doc) column. NULL and empty-string rows are
skipped from batches and produce [] without any HTTP call.

Changelog category (leave one):

  • Experimental Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add aiEmbed function for using LLM APIs to generate embeddings from within ClickHouse.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Note

Cursor Bugbot is generating a summary for commit 075a761. Configure here.

Version info

  • Merged into: 26.6.1.206 (included in 26.6 and later)
  • Backported to: 26.5.5.14, 26.4.5.91

@george-larionov george-larionov changed the title Adding aiEmbeddings function Adding aiGenerateEmbedding function Apr 17, 2026
@george-larionov
george-larionov force-pushed the feature/ai-func-infrastructure branch from 673355f to 49de7bb Compare April 17, 2026 14:34
Base automatically changed from feature/ai-func-infrastructure to master April 17, 2026 19:40
@george-larionov
george-larionov marked this pull request as ready for review April 17, 2026 20:03
@george-larionov
george-larionov marked this pull request as draft April 17, 2026 20:15
@george-larionov george-larionov changed the title Adding aiGenerateEmbedding function Adding aiGenerateEmbedding and aiGenerateSQL functions Apr 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [dfbdcd8]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) DROPPED IGNORED

AI Review

Summary

This PR adds aiEmbed, introduces embedding request/response support in AI providers, and refactors AI-function validation to run before zero-row fast paths. The main remaining issue is quota-contract enforcement under retries: ai_function_max_api_calls_per_query can still be exceeded by multiple retry attempts within a single row/batch. Because this setting is documented as a hard cap on dispatched HTTP requests, this needs to be fixed before merge.

Findings

❌ Blockers

  • [src/Functions/FunctionBaseAI.cpp:242] and [src/Functions/aiEmbed.cpp:224] ai_function_max_api_calls_per_query is checked only once before entering the retry loop, but recordAttempt is called on each retry without an in-loop quota check. A single row/batch can therefore dispatch more HTTP requests than the configured maximum when retries are enabled, violating the setting contract and potentially causing unexpected external API usage/cost.
    Suggested fix: gate each outbound retry attempt with quota enforcement (for example, check quota immediately before each attempt, and stop/throw according to ai_function_throw_on_quota_exceeded once the cap is reached).
Final Verdict
  • Status: ❌ Block
  • Minimum required actions:
  1. Enforce ai_function_max_api_calls_per_query before every retry attempt in FunctionBaseAI::executeImpl.
  2. Enforce the same per-attempt quota check in FunctionAiEmbed::executeImpl.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Apr 17, 2026
Comment thread src/Functions/aiGenerateSQL.cpp Resolved
Comment thread src/Functions/aiGenerateSQL.cpp Resolved
Comment thread src/Functions/aiEmbed.cpp Resolved
Comment thread src/Functions/aiEmbed.cpp Resolved
@george-larionov
george-larionov force-pushed the feature/ai-embeddings branch from 203ea6e to 94c4acf Compare May 6, 2026 11:52
george-larionov and others added 3 commits May 6, 2026 11:53
Port embedding generation onto the reworked `feature/ai-text-functions`
infrastructure:

- Add `AIEmbeddingRequest`/`AIEmbeddingResponse` back to `IAIProvider`
  (with a default `NOT_IMPLEMENTED` `embed` method), and implement it
  in `OpenAIProvider`. This also serves HuggingFace TEI and other
  OpenAI-compatible embedding endpoints, and derives the embedding URL
  from the configured chat endpoint if needed.
- `aiGenerateEmbedding` takes a mandatory named collection followed by
  the text column and an optional constant `dimensions`. Argument
  validation goes through `FunctionArgumentDescriptors`, matching
  the style of the other AI functions.
- Returns non-nullable `Array(Float32)`; empty array for empty/NULL
  input or when the request fails with `ai_function_throw_on_error = 0`
  or a quota is exceeded with `ai_function_throw_on_quota_exceeded = 0`.
- The `OrNull` variant is dropped: `ai_function_throw_on_error` already
  covers the fall-back-to-default behavior for the whole AI family.
- Deduplicates identical texts within a query and batches unique texts
  into `ai_function_embedding_max_batch_size` entries per HTTP request.
  No background thread pool and no result cache, matching the simplified
  execution model of the reworked infrastructure.
Extends the AI function test suite with `aiGenerateEmbedding`-specific
coverage: the function is registered, argument-count validation, rejecting
a non-constant `collection`, rejecting a non-constant `dimensions`, and
rejecting wrong types (signed int, string) for `dimensions`; return type
is `Array(Float32)` both with and without `dimensions`; empty input
returns zero rows without hitting the network; unknown named collection
raises `NAMED_COLLECTION_DOESNT_EXIST`; and the
`ai_function_embedding_max_batch_size` setting default is `100`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Generates a ClickHouse SQL query from a natural-language prompt, limiting
schema introspection to tables/columns the caller has SHOW TABLES / SHOW
COLUMNS grants on so nothing is leaked to the LLM endpoint.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Functions/aiEmbed.cpp Resolved
Comment thread src/Functions/aiEmbed.cpp Resolved
Comment thread src/Functions/aiGenerateEmbedding.cpp Resolved
@george-larionov
george-larionov force-pushed the feature/ai-embeddings branch from 94c4acf to 7c38ca3 Compare May 6, 2026 13:01
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
This reverts commit 7c38ca3.
Comment thread src/Functions/aiGenerateEmbedding.cpp Resolved
Comment thread src/Functions/AI/OpenAIProvider.cpp Resolved
@george-larionov george-larionov changed the title Adding aiGenerateEmbedding and aiGenerateSQL functions Adding aiGenerateEmbedding function May 6, 2026
Comment thread src/Functions/aiEmbed.cpp Resolved
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
Comment thread src/Functions/aiEmbed.cpp Resolved
george-larionov and others added 5 commits May 23, 2026 14:54
Split `AIQuotaTracker::recordResponse` into `recordAttempt` (api_calls)
and `recordTokens` (in/out tokens), and move the `recordAttempt` /
`++total_api_calls` calls to before the provider request. A failing
endpoint with `ai_function_throw_on_error = 0` and retries no longer
bypasses `ai_function_max_api_calls_per_query`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Move `aiEmbed`'s `dimensions` bounds check and `FunctionBaseAI`'s
`buildSystemPrompt` / `buildResponseFormat` calls above the
`input_rows_count == 0` return. Malformed constant arguments
(e.g. `aiEmbed`'s out-of-range `dimensions`, `aiExtract`'s broken
JSON schema) now fail consistently regardless of source cardinality.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…eturn

Add `IAIProvider::supportsEmbeddings()`, defaulting to `false` and
overridden to `true` in `OpenAIProvider`. `aiEmbed` now checks the
capability immediately after `createAIProvider`, and both `aiEmbed` and
`FunctionBaseAI::executeImpl` invoke `createAIProvider` before the
`input_rows_count == 0` fast path so that an unknown provider name or
an `aiEmbed` call against a chat-only provider (e.g. anthropic) fails
the query consistently regardless of source cardinality.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread src/Functions/aiEmbed.cpp Resolved
Comment thread src/Functions/FunctionBaseAI.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented May 26, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.60% 76.60% +0.00%

Changed lines: 76.12% (306/402) | lost baseline coverage: 4 line(s) · Uncovered code

Full report · Diff report

@george-larionov
george-larionov added this pull request to the merge queue May 27, 2026
Merged via the queue into master with commit 01d8f67 May 27, 2026
164 of 166 checks passed
@george-larionov
george-larionov deleted the feature/ai-embeddings branch May 27, 2026 20:29
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 27, 2026
fm4v added a commit that referenced this pull request Jul 1, 2026
Backport #102922 to 26.4: Adding `aiEmbed` function
fm4v added a commit that referenced this pull request Jul 1, 2026
Backport #102922 to 26.5: Adding `aiEmbed` function
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Jul 1, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Jul 1, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
Backport of ClickHouse#102922.
`introduced_in` and the `ai_function_embedding_max_batch_size` settings-history
entry are set to 26.4.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
Backport of ClickHouse#102922.
`introduced_in` and the `ai_function_embedding_max_batch_size` settings-history
entry are set to 26.5.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-experimental Experimental Feature pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.4-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants