Using ClickHouse UDFs to integrate with OpenAI models
ClickHouse executable user-defined functions can call the OpenAI chat completions API from SQL, adding sentiment labels or extracted entities to rows at insert or query time. The walkthrough starts with a Bash script and then moves to a Python script with retries and exponential backoff, configured as an executable_pool with chunk headers for parallel, batched invocation. Applying the UDF only to final result rows keeps API calls few, since OpenAI latency far exceeds ClickHouse query time. Aggregating sentiment across many rows means thousands of API calls, so rate limits and latency become the main constraints.
Related posts
- AI Functions in ClickHouse: Upgrade your SQL to the AI age
ClickHouse mediumAdept
ClickHouse's beta AI Functions call LLM and embedding providers directly from SQL. They include aiClassify, aiExtract, aiGenerate, aiTranslate, aiFilter, aiRedact, aiEmbed and aiSimilarity, added across releases 26.4 to 26.8, and they make one HTTP request per row (batched for embeddings) and return native ClickHouse values. Setup on OSS uses named collections for credentials and works with any OpenAI-compatible endpoint, including local models via Ollama. Examples on the Hacker News dataset show classification, LLM predicates in WHERE, summarization, translation and an in-database RAG pipeline built on materialized-view embeddings and vector indexes. Per-query quotas on API calls and input/output tokens cap spend: call limits are exact, token limits can overshoot by one in-flight request per thread, a soft-stop mode returns partial results, and actual usage is visible in system.query_log ProfileEvents.
- Executable UDFs are now generally available on ClickHouse Cloud
ClickHouse mediumAdept
Executable UDFs are now generally available on ClickHouse Cloud across AWS, GCP and Azure, adding a Native runtime for statically linked Rust/Go/C++/JavaScript binaries, outbound network access, per-process memory limits, a deterministic flag that enables the query cache, Cloud API and Terraform support, and per-query UDF metrics in 26.6+. The worked example is a Rust tokenizer UDF built on tiktoken-rs that speaks RowBinary with chunk headers and is called from a materialized view at insert time to count LLM tokens per span. Its token counts are joined against a daily-refreshed LiteLLM price dictionary for cost attribution, and a Python UDF calls Claude to grade a sample of completions. Practical lessons include RowBinary being ~20% faster than TabSeparatedRaw and binary-safe, sizing memory limits for virtual address space (Go reserves ~1.2 GiB), and throughput of ~13M tokens/sec on 4 vCPUs.
- Tracing OpenAI agents with ClickStack
ClickHouse mediumAdept
OpenAI's agents SDK has built-in tracing that can be redirected from OpenAI's hosted product to a custom TracingExporter. Spans can then be written into ClickHouse and explored in HyperDX as part of ClickStack. The worked example uses a gpt-5-mini agent that queries the ClickHouse SQL Playground through the ClickHouse MCP Server. The exporter is attached via a BatchTraceProcessor, adds the missing model name to response spans, and inserts rows into a JSON-typed ClickHouse table. The traces show tool calls, failed SQL attempts and LLM responses, which helps when comparing how different models handle ambiguous instructions.
- How Fetch built its flexible agentic analytics tool on ClickHouse Cloud
ClickHouse easyNovice
Fetch built FAST, a conversational BI agent that lets non-technical sales teams query receipt purchase data in plain language, on ClickHouse Cloud ingesting 150 billion rows (6.5 TB compressed) a day. Ad hoc queries such as same-receipt basket intersections scan hundreds of millions of rows in under a second, and median agent response time is 1.9 seconds across about 500 daily queries. The team picked ClickHouse for its ad hoc query speed, compute isolation between concurrent queries and simple scaling. A nightly pipeline copies data from Snowflake to S3, loads it via ClickPipes into a new versioned wide table, then repoints a view at it. That keeps LLM-generated queries stable and makes rollback trivial, at the cost of skipping incremental loads.
- Executable UDFs are now in public beta on ClickHouse Cloud
ClickHouse mediumAdept
Executable UDFs are in public beta on ClickHouse Cloud: you upload a zipped Python function with its model files, and ClickHouse runs it in a pool of long-lived sandboxed processes that can be called from SQL, including inside materialized views. The demo trains a ~270K-parameter PyTorch autoencoder on trade ticks and scores each insert inline through a materialized view, producing a 32-dim embedding and a reconstruction error. A backfill of ~6B rows ran at ~35K rows/sec on a 3-replica cluster. A raw global anomaly threshold proved misleading for high-priced symbols, so anomalies are defined against per-symbol p95 baselines kept in an hourly refreshable materialized view, which cut leaderboard query time from ~1.7s to ~0.27s. Network-access UDFs that can make outbound HTTPS calls are in private beta.