DEV Community

Sagara
Sagara

Posted on

Trying dbt_context_engineering on dbt Projects on Snowflake: Chunking, Embedding, and Searching Japanese Text

This article is an English translation of the following Japanese article:

https://dev.classmethod.jp/articles/dbt-context-engineering-package-try/


Hi, I'm Sagara.

dbt Labs has released dbt_context_engineering, an open-source package for using dbt to model the text data that AI agents read. Its main feature is that you can write chunking, embedding, classification, and vector search as dbt macros and models.

https://docs.getdbt.com/blog/dbt-context-engineering

https://github.com/dbt-labs/dbt-context-engineering

This package isn't an agent or a search service. It's for using dbt to prepare the context that agents and search services read. It brings dbt practices like version control, testing, and lineage to text processing and search.

In this article, I'll use dbt Projects on Snowflake to chunk, embed, and search Japanese "order inquiries and reviews." Then I'll show how to narrow down the search targets with classification labels.

Feature Overview

dbt_context_engineering is a dbt package that turns unstructured text, such as inquiries, reviews, and call transcripts, into a form AI agents can search and cite. According to the README, it supports Snowflake (Cortex), Databricks, BigQuery, and Redshift (Amazon Bedrock).

Here are the main macros used in this article and what each one does on Snowflake:

Macro Role Main processing on Snowflake
chunk Groups text rows into chunks Estimates token counts with LENGTH and CEIL, and groups rows with SUM ... OVER and similar functions
embed Converts text into vectors AI_EMBED
vector_search Searches by vector similarity VECTOR_COSINE_SIMILARITY with ORDER BY and LIMIT
classify Assigns classification labels to text AI_CLASSIFY, plus extracting the label from the returned object
guard_batch Checks processing volume before running AI Aggregates with COUNT and SUM, then checks limits on the dbt side

The package doesn't come with its own AI engine. Its macros generate SQL that calls Snowflake functions and similar features. I've linked to each macro's source code where it's used.

The basic flow has three steps:

  1. chunk: Group multiple text rows into chunks, using the estimated token count as a guide
  2. embed: Convert each chunk into a vector
  3. vector_search: Calculate the similarity to the search query and return the top chunks

You can also use classify to assign classification labels and narrow down the search targets. The official blog shows a case where vector similarity alone doesn't judge relevance to the question well enough, and it uses classification labels to fix that.

How It Relates to Cortex Search on Snowflake

When you hear "a package for Snowflake," you might wonder whether it creates Cortex Search services through dbt.

The short answer: the package can create a Cortex Search service, but that's optional. The standard search flow doesn't use Cortex Search.

In the standard setup, the vectors generated by embed are stored as a column in a regular table. vector_search then calculates the similarity between that vector column and the query vector using VECTOR_COSINE_SIMILARITY.

The optional piece is the create_vector_index macro. Here's the source code:

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/operations/create_vector_index.sql

On Snowflake, it doesn't call an AI function. Instead, it generates and runs a CREATE OR REPLACE CORTEX SEARCH SERVICE DDL statement. You run it explicitly with dbt run-operation, separately from your normal model builds.

However, when I checked, this was a Beta feature, and the full "create → search → drop" flow hadn't been verified in a real environment yet. A service you create is billed separately and has a different lifecycle from a regular table, so you need to drop it explicitly when you no longer need it.

Also, creating the service doesn't automatically make the vector_search used in this article go through Cortex Search.

Cost

chunk doesn't use AI, so it doesn't incur AI function charges. That said, the Snowflake compute used to run the SQL and the storage for the created tables aren't free.

embed and classify call Snowflake's AI_EMBED and AI_CLASSIFY. In this article, I also use embed to vectorize the search query, so rebuilding a search result model calls an AI function too.

The package offers these mechanisms for managing processing volume:

  • ai_functions_enabled: A setting that enables AI function execution
  • guard_batch: Checks row counts and estimated token counts against limits
  • dev_sample_filter: Samples the data to process during development
  • log_ai_run and related macros: Record execution logs

You have to add sampling and logging to your own models or hooks. Also, guard_batch doesn't stop processing based on the actual billed amount.

For reference, here's the source code for the sampling macro:

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/cost/dev_sample_filter.sql

On Snowflake, it generates SQL that creates a random order with RANDOM() and limits the row count with ROW_NUMBER() and QUALIFY. This article processes all 24 records, so I don't use this macro.

Prerequisites

I'm using dbt Projects on Snowflake (dbt 1.12.3).

In this walkthrough, I run all Snowflake operations and dbt commands with the ACCOUNTADMIN role, so I don't create a dedicated role or grant any privileges.

dbt_context_engineering is an external package. To use external packages in dbt Projects on Snowflake, you need an EXTERNAL ACCESS INTEGRATION. I recommend allowing only the minimum necessary hosts. For detailed steps, see this blog post (in Japanese):

https://dev.classmethod.jp/articles/dbt-project-on-snowflake-dbt-dbt_external_tables/

Setup

About the Data

dbt's Snowflake quickstart uses data from a fictional shop called "Jaffle Shop." This article uses a similar data structure.

https://docs.getdbt.com/guides/snowflake

To make this easy to try using only the CSVs in this article, I've prepared small customer and order datasets. I've also added a custom seed of order-related inquiries and reviews, plus support replies.

seed Contents Rows
raw_customers Customers 12
raw_orders Orders 20
raw_order_feedback Japanese inquiries, reviews, and support replies 24

raw_order_feedback contains fictional texts of about 200 Japanese characters each. They cover the following topics:

  • Delivery delays caused by sorting mistakes at a distribution center or by traffic congestion
  • Delivery impacts from snow or storms
  • Wrong items or incorrect shipping labels
  • Complaints about product or packaging quality
  • Praise for products or service
  • Delivery status checks and resolution notices

The key point is that the data also includes texts that relate to delivery but don't explain the cause of a delay.

This data isn't a direct Japanese translation of the short sample texts in the official blog, so don't expect the same search rankings or scores.

1. Prepare Snowflake Objects

This walkthrough uses the following objects. If you already have your own, substitute them as needed.

Type Name
Warehouse DBT_CE_DEMO_WH
Database DBT_CE_DEMO_DB
Output schema DBT_CE_DEMO

Create the warehouse, database, and schema as ACCOUNTADMIN.

USE ROLE ACCOUNTADMIN;

CREATE OR REPLACE WAREHOUSE DBT_CE_DEMO_WH
  WAREHOUSE_SIZE = XSMALL
  AUTO_SUSPEND = 60
  AUTO_RESUME = TRUE;

CREATE OR REPLACE DATABASE DBT_CE_DEMO_DB;

CREATE SCHEMA IF NOT EXISTS DBT_CE_DEMO_DB.DBT_CE_DEMO;
Enter fullscreen mode Exit fullscreen mode

All later operations also use the ACCOUNTADMIN role, so you don't need to create roles or grant privileges for Cortex AI functions or any objects.

2. Prepare the EXTERNAL ACCESS INTEGRATION

Create an EXTERNAL ACCESS INTEGRATION so dbt deps can fetch external packages. Only allow the minimum hosts that the official docs list for dbt deps: hub.getdbt.com and codeload.github.com.

SQL to create the EXTERNAL ACCESS INTEGRATION (click to expand)
USE ROLE ACCOUNTADMIN;

-- Network rule allowing only the minimum hosts required for dbt deps
CREATE OR REPLACE NETWORK RULE dbt_network_rule
  MODE = EGRESS
  TYPE = HOST_PORT
  VALUE_LIST = ('hub.getdbt.com', 'codeload.github.com');

-- Create the external access integration
CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION dbt_external_access_integration
  ALLOWED_NETWORK_RULES = (dbt_network_rule)
  ENABLED = TRUE;
Enter fullscreen mode Exit fullscreen mode

3. Create a dbt Project in Workspaces

In Snowsight, go to Projects → Workspaces and create a Workspace for a dbt project.

Use the objects you just created, as shown below. After creating the Workspace, delete the sample my_first_dbt_model.sql and my_second_dbt_model.sql files in the models folder.

4. Load the Seeds

Put the following three CSV files in the seeds folder.

seeds/raw_customers.csv (click to expand)
id,first_name,last_name
1,Michael,Perez
2,Shawn,Mitchell
3,Kathleen,Payne
4,Jimmy,Cole
5,Katherine,Reed
6,Sarah,Robinson
7,Martin,Meyer
8,Frank,Rose
9,Jennifer,Fox
10,Henry,Watts
11,Diana,Lopez
12,Tom,Kim
Enter fullscreen mode Exit fullscreen mode

seeds/raw_orders.csv (click to expand)
id,user_id,order_date,status
1,1,2026-10-01,completed
2,2,2026-10-01,completed
3,3,2026-10-02,completed
4,4,2026-10-03,returned
5,5,2026-10-03,completed
6,6,2026-10-04,shipped
7,7,2026-10-05,completed
8,8,2026-10-06,completed
9,9,2026-10-07,return_pending
10,10,2026-10-08,completed
11,1,2026-10-09,completed
12,2,2026-10-10,shipped
13,3,2026-10-11,completed
14,4,2026-10-12,placed
15,5,2026-10-13,completed
16,6,2026-10-14,completed
17,11,2026-10-15,completed
18,12,2026-10-16,returned
19,7,2026-10-17,completed
20,8,2026-10-18,completed
Enter fullscreen mode Exit fullscreen mode

seeds/raw_order_feedback.csv (click to expand)
feedback_id,order_id,channel,created_at,feedback_text
1,3,email,2026-10-02 18:10:00,"注文した商品が、案内されていた配達予定日を二日過ぎてようやく届きました。追跡画面の表示が長い時間変わらず、問い合わせても到着の見通しが分からなかったため、予定を何度も変更することになりました。さらに、配達員が隣の建物に商品を置いてしまい、受け取りにも時間がかかりました。配送が遅れた理由と、届け先の確認が適切に行われなかった理由を調べてください。今後は予定に変更がある時点で、早めに連絡していただきたいです。"
2,3,chat,2026-10-03 09:05:00,"昨日問い合わせた配送遅延について、配送会社から追加の説明がありました。地域の配送拠点で仕分け先を間違え、別の営業所へ商品を送ってしまったことが原因だったそうです。正しい拠点へ戻す作業に時間がかかり、当初の配達予定に間に合わなかったとのことでした。天候や注文の集中ではなく、拠点内の仕分け作業に問題があったと理解しています。同じことが繰り返されないよう、物流の担当部署にも今回の経緯を共有していただけると助かります。"
3,4,review,2026-10-05 12:30:00,"届いたホットサンドを開けたところ、全体がすっかり冷めていて、パンも水分を吸って柔らかくなっていました。写真では表面が香ばしく焼けているように見えたので、実物との違いが残念でした。具材の温かさもほとんど感じられず、家族と相談して今回は注文した商品を返品することにしました。包装の中に蒸気がこもっていたようにも見えるため、調理後の保管方法や容器の仕様を確認してほしいです。次回は説明どおりの品質で受け取りたいです。"
4,1,review,2026-10-02 20:00:00,"今回初めて注文しましたが、パンの表面が香ばしく、中のチーズも程よく溶けていて、とてもおいしくいただきました。ハムと具材のバランスがよく、最後まで飽きずに食べられたのもよかったです。家族にも好評で、別の味も試してみたいという話になりました。注文画面が分かりやすく、商品の説明から受け取りまで安心して利用できました。忙しい日の昼食として使いやすいので、次回は人数分をまとめて注文したいと思っています。ごちそうさまでした。"
5,2,chat,2026-10-02 11:15:00,"先ほどはお問い合わせへのご対応ありがとうございました。ご案内いただいた内容を確認し、こちらで必要な手続きが済んだことをご連絡します。現時点で追加の質問やお願いはありませんので、この問い合わせは対応完了として扱っていただいて大丈夫です。注文に関する連絡は登録済みのメールアドレスで受け取れますので、今後確認が必要になった場合はそちらへお願いします。今回は状況の共有のみで、商品の品質や配送について新たに申告したい事項はありません。"
6,5,chat,2026-10-04 08:40:00,"配送担当への確認が済みましたので、取り急ぎ状況をご連絡します。今回の注文については、担当者と管理画面の内容を照合し、現在表示されている情報を確認しています。お客様に新しくお願いする手続きや、追加で提出していただく情報はありません。現時点では詳細な調査結果や配送予定の変更についてお知らせする内容はなく、確認を実施したことのご報告となります。今後ご案内が必要になりましたら、このチャットまたは登録メールアドレスへご連絡します。"
7,6,email,2026-10-06 10:00:00,"商品の追跡情報が四日間ずっと輸送中のままで、いつ受け取れるのか分からず困っています。配送会社のお知らせでは、輸送経路の山間部で大雪が降り、一部の道路が通行止めになっていると案内されていました。今回の注文も、その影響で配送が止まっているのでしょうか。天候による遅れであれば事情は理解できますが、到着の見込みだけでも知りたいです。商品の保管状態も気になりますので、現在地と今後の配送予定を確認して連絡していただけると助かります。"
8,7,email,2026-10-06 15:20:00,"ハムとチーズのホットサンドを注文しましたが、届いた袋には野菜だけの商品が入っていました。注文確認メールと伝票には正しい商品名が記載されているため、注文時ではなく、商品を取りそろえる作業で間違いが起きたように見えます。一緒に注文した家族の分は合っていたので、一部の商品だけ取り違えたのだと思います。食事の予定があるため、正しい商品を届けてもらえるか確認したいです。出荷前に商品と伝票を照合する手順も見直していただきたいです。"
9,7,chat,2026-10-06 15:45:00,"このたびはご連絡いただきありがとうございます。ご申告いただいた注文内容を担当部署へ共有し、正しい商品を本日中にお届けする手配を進めています。お届け先は今回の注文に登録されているご住所で承っていますので、変更がある場合のみお知らせください。詳しいお届け時間は、担当者からの連絡をご確認いただければと思います。こちらのメッセージは再手配の受付状況をお知らせするもので、追加の原因調査結果については現時点でご案内できる情報はありません。"
10,7,email,2026-10-07 09:10:00,"再手配していただいた商品を受け取り、注文内容と一致していることを確認しました。今回の問い合わせについて、こちらから追加でお願いすることはありません。受け取りが完了したことをお伝えしたかったため、ご連絡しました。担当の方にも確認済みと共有していただければと思います。今後こちらで確認する必要がある書類や手続きがありましたら、登録済みのメールアドレスへお知らせください。この連絡への返信は不要ですので、対応完了として扱っていただいて構いません。"
11,8,chat,2026-10-07 13:00:00,"本日の注文について、受け取り可能な時間帯を確認したくご連絡しました。注文画面に表示されている案内は確認していますが、外出の予定を調整したいため、現在の配送予定をもう一度教えていただけますか。現時点で配達が遅れているという問い合わせではなく、あくまで受け取りの準備のための確認です。住所や電話番号に変更はありません。時間帯の指定ができない場合は、その旨をご案内いただければ大丈夫です。必要であれば注文番号も改めてお送りします。"
12,9,email,2026-10-09 17:30:00,"受け取った商品の外箱が大きくつぶれており、中を確認すると容器のふたがずれて、具材とソースが袋の中に漏れていました。食べ物に触れる部分まで汚れていたため、そのまま食べることには不安があります。受け取り直後の写真を撮影しましたので、必要であればお送りします。今回は返品または返金をお願いしたいです。商品を重ねたときに容器が変形しないか、箱の強度や緩衝材の入れ方も確認してください。注文した商品自体は楽しみにしていたので、とても残念です。"
13,10,review,2026-10-09 19:00:00,"価格に対して十分なボリュームがあり、昼食としてとても満足できました。注文時に商品の違いを問い合わせたところ、スタッフの方が具材や味付けを分かりやすく説明してくれたので、安心して選べました。届いた商品も案内されていた内容どおりで、家族と分けておいしくいただきました。予定していた時間に受け取れたため、その後の用事にも余裕を持って出かけられました。味だけでなく接客もよかったので、初めて利用する知人にも紹介したいと思います。"
14,11,chat,2026-10-10 10:30:00,"ご案内いただいた内容を確認しました。こちらで確認したかった点は解消しましたので、追加の調査や折り返しの連絡は不要です。注文情報についても手元の控えと一致しており、現時点で変更をお願いする予定はありません。このメッセージは問い合わせを終了してよいことをお伝えするために送っています。担当部署への引き継ぎが残っている場合は、確認済みであることだけ共有してください。今後別の確認事項が生じた際には、改めてこちらからご連絡します。"
15,12,email,2026-10-12 08:15:00,"指定していた配達時間を過ぎても商品が届かず、問い合わせたところ、配送車が渋滞にはまっているとの説明でした。同じ地域への注文で時間帯に間に合わなかったのは、今月に入ってこれで三回目です。毎回同じ道路の混雑が理由であれば、配送ルートや一台あたりの配達件数を見直す必要があるのではないでしょうか。予定に合わせて在宅しているため、遅れる場合は事前に知らせてほしいです。今回の到着見込みと、繰り返し遅延している原因への対応を教えてください。"
16,13,review,2026-10-12 21:00:00,"味付けは好みでしたが、届いた商品の大きさが掲載写真から想像していたものより小さく、食事としては少し物足りなく感じました。写真では具材がたっぷり入っているように見えたものの、実際には端の部分に具がほとんどなく、パンだけを食べているような箇所もありました。個体差があることは理解していますが、価格を考えるともう少し内容をそろえてほしいです。商品の重量や具材の量を案内に記載してもらえると、次回注文するときの参考になると思います。"
17,15,chat,2026-10-14 12:00:00,"ご連絡いただいた注文について、配送担当と確認を行いました。担当者が現在の登録内容を確認したことを、このチャットで共有します。現時点でお客様に対応いただく追加作業はありませんので、こちらからの次のご案内をお待ちください。配送予定の変更や、確認済みの問題について新しい詳細をお知らせする連絡ではありません。今後必要な情報がそろい次第、登録されている連絡先へご案内します。このメッセージに対して、受領確認の返信をしていただく必要はありません。"
18,16,email,2026-10-15 09:45:00,"今回の注文は予定より一日遅れて届きました。配送会社からは、暴風雨の影響で高速道路が通行止めになり、配送車が通常の経路を使えなくなったと説明を受けています。迂回路も混雑していたため、当日中の配達が難しかったそうです。遅れは残念でしたが、担当の運転手さんが早めに電話で状況を知らせてくれたので、受け取り予定を調整できました。天候が原因であれば仕方ないと思いますが、注文画面の到着予定にも変更が反映されると、さらに分かりやすいです。"
19,17,review,2026-10-16 18:20:00,"新しく追加されたメニューを昼食用に注文しました。香ばしいパンと具材の組み合わせがよく、普段頼んでいる商品とは違ったおいしさを楽しめました。味が濃すぎないので最後まで食べやすく、職場の同僚からも好評でした。個別に包装されていて配りやすかった点も、まとめて注文する立場として助かりました。商品の説明や写真から想像したとおりの内容で、満足しています。期間限定であれば販売期間を知りたいですし、できれば今後も定番として残してほしいです。"
20,18,email,2026-10-17 14:05:00,"配達完了の通知が来たのに商品が見当たらず、確認したところ隣の家に届いていました。注文確認メールの住所は正しかったのですが、商品の配送ラベルには別の番地が印字されていました。配送員の見間違いというより、出荷前のラベル作成や貼り付けの段階で誤りがあったように思います。近所の方から連絡をいただいて気付きましたが、食品なので受け取りまでの保管状態も心配です。倉庫で住所情報とラベルを照合する手順を確認し、今後の対応を教えてください。"
21,18,chat,2026-10-17 14:30:00,"ご連絡いただいた注文について、明日の再配達を受け付けました。お届け先は登録済みの住所を利用する予定ですので、変更が必要な場合は本日中にお知らせください。具体的な配達時間のご案内は、配送担当からの連絡をお待ちいただければと思います。このメッセージは再配達の受付が完了したことをお伝えするためのものです。調査内容や原因について新たに確定した情報は含まれていません。受け取り方法について追加のご希望がある場合は、このチャットからご連絡ください。"
22,19,chat,2026-10-18 11:00:00,"注文した商品の受け取りについて、配達予定の時間帯を教えていただけますか。午後に短時間だけ外出する可能性があるため、在宅する時間を調整したいと考えています。現在のところ配達予定日を過ぎているわけではなく、配送上のトラブルを報告する問い合わせでもありません。注文時の住所や連絡先はそのままで問題ありません。細かい時刻が分からない場合は、午前か午後かといった目安だけでも助かります。追加で必要な情報があれば、確認して返信します。"
23,20,review,2026-10-19 20:30:00,"注文から受け取りまでがスムーズで、届いたホットサンドも温かいまま食べられました。パンの表面がべたつかず、具材もしっかり入っていて、家で手軽に外食気分を楽しめたのがよかったです。包装が開けやすく、食卓に出すまでに手間がかからなかった点も助かりました。配達の方も丁寧に声をかけてくれたので、最後まで気持ちよく利用できました。忙しくて食事の準備が難しい日に頼れるお店が見つかってうれしいです。また別の商品も注文してみたいと思います。"
24,14,chat,2026-10-13 16:00:00,"お問い合わせへのご回答を確認しました。説明いただいた内容で理解できましたので、この件について追加の対応をお願いする必要はありません。注文の状況についても、こちらで確認したかった内容は把握できています。今回のメッセージは対応完了のご連絡であり、新しい不具合や配送の問題をお伝えするものではありません。確認のために別の担当者からご連絡いただく予定がある場合は、すでに解決している旨を共有してください。今後必要になった際には、改めてお問い合わせします。"
Enter fullscreen mode Exit fullscreen mode

The channel values (email, chat, and review) stay in English because they're only used for management. All of the feedback_text values, which are the targets of search and classification, are in Japanese.

Add the seed configuration to the end of dbt_project.yml. If you already have a seeds: section, merge this into it.

seeds:
  jaffle_shop:
    +quote_columns: false
    raw_order_feedback:
      +column_types:
        feedback_text: varchar
        created_at: timestamp
Enter fullscreen mode Exit fullscreen mode

Run dbt seed in the Workspace. To reload the data, also add --full-refresh to Additional Flags. If all three seeds succeed (for example, PASS=3 ERROR=0), you're good.

As a sample check, look at one of the loaded tables. You should see 24 Japanese texts. The character_count column also shows the number of characters in each text.

SELECT
    feedback_id,
    order_id,
    channel,
    created_at,
    LENGTH(feedback_text) AS character_count,
    feedback_text
FROM DBT_CE_DEMO_DB.DBT_CE_DEMO.raw_order_feedback
ORDER BY order_id, created_at;
Enter fullscreen mode Exit fullscreen mode

5. Create Staging Models

Since we're using seeds, we reference them with ref(). Create three staging models for customers, orders, and feedback.

-- models/staging/stg_customers.sql
select
    id as customer_id,
    first_name,
    last_name
from {{ ref('raw_customers') }}
Enter fullscreen mode Exit fullscreen mode
-- models/staging/stg_orders.sql
select
    id as order_id,
    user_id as customer_id,
    order_date,
    status
from {{ ref('raw_orders') }}
Enter fullscreen mode Exit fullscreen mode
-- models/staging/stg_order_feedback.sql
select
    feedback_id,
    order_id,
    channel,
    created_at,
    feedback_text
from {{ ref('raw_order_feedback') }}
Enter fullscreen mode Exit fullscreen mode

The search process in this article uses only stg_order_feedback directly. The customer and order models are a foundation for adding order and customer information to search results later.

6. Install dbt_context_engineering

Put a packages.yml file in the project root. This example pins version 0.2.0.

packages:
  - package: dbt-labs/dbt_context_engineering
    version: "0.2.0"
Enter fullscreen mode Exit fullscreen mode

After you save packages.yml, run Deps in the Workspace. Specify the EXTERNAL ACCESS INTEGRATION created during setup (dbt_external_access_integration).

The install worked if dbt_context_engineering installs successfully and a dbt_packages folder appears in the Workspace.

7. Configure vars and Run the Staging Models

Add vars to dbt_project.yml.

vars:
  # Explicitly enable AI functions via the run command
  ai_functions_enabled: false

  # Multilingual embedding model
  embedding_model: 'snowflake-arctic-embed-l-v2.0'

  # Set smaller values for this Japanese sample
  chunk_target_tokens: 64
  chunk_overlap_tokens: 0

  # guard_batch limits
  max_batch_rows: 10000
  max_est_tokens: 5000000
Enter fullscreen mode Exit fullscreen mode

Here's why chunk_target_tokens is set to a small value.

The chunk implementation I checked estimates token counts with CEIL(LENGTH(text) / 4.0). It doesn't measure the actual token count of Japanese text. Each comment here is about 200 characters, so I set the target to 64 to avoid packing too many comments into one chunk.

However, this setting alone doesn't guarantee one comment per chunk, and it doesn't guarantee that you stay within the model's input limit. We'll look at the actual chunks later.

For commands that use AI functions, enable them by adding the following option to Additional Flags in the Workspace. Leave the default in dbt_project.yml disabled.

--vars '{"ai_functions_enabled": true}'
Enter fullscreen mode Exit fullscreen mode

Next, build the staging models. Run dbt run in the Workspace with --select stg_customers stg_orders stg_order_feedback in Additional Flags.

You're good if all three models build successfully.

Trying It Out

1. chunk: Group Texts into Chunks

First, group the texts with chunk. Here's the source code:

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/chunking/chunk.sql

On Snowflake, it builds chunks with SQL such as window functions, without using AI functions.

Roughly, it works like this:

  1. Calculate each row's estimated token count with LENGTH and CEIL
  2. Calculate running totals within the same order with SUM(...) OVER (...)
  3. Assign chunk groups with FLOOR and DENSE_RANK
  4. Concatenate the texts in each group and keep the original row IDs in source_rows

It doesn't call a Snowflake-specific AI for splitting text. It simply groups the input rows in order.

Here, we partition by order and sort the texts for each order by posting time.

-- models/context/feedback_chunks.sql
{{ config(materialized='table') }}

{{ dbt_context_engineering.chunk(
    relation = ref('stg_order_feedback'),
    id_column = 'feedback_id',
    order_column = 'created_at',
    text_column = 'feedback_text',
    partition_column = 'order_id',
    label_column = 'channel'
) }}
Enter fullscreen mode Exit fullscreen mode

partition_column = 'order_id' keeps texts from different orders out of the same chunk.

With label_column = 'channel', each text gets a channel name prefix such as email:. This label is separate from the classification labels we'll add later with classify.

Run dbt run in the Workspace with the following in Additional Flags:

--select feedback_chunks
Enter fullscreen mode Exit fullscreen mode

Check the results:

SELECT
    chunk_id,
    partition_key,
    chunk_seq,
    source_rows,
    n_source_rows,
    token_estimate,
    exceeds_target,
    LENGTH(chunk_text) AS character_count,
    chunk_text
FROM DBT_CE_DEMO_DB.DBT_CE_DEMO.feedback_chunks
ORDER BY partition_key, chunk_seq;
Enter fullscreen mode Exit fullscreen mode

The results are shown below. In this example, no single comment was split, and comments for the same order were grouped into one chunk.

2. embed: Vectorize the Chunks

Next, vectorize the chunks with embed. Here's the source code:

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/functions/embed.sql

The Snowflake implementation, snowflake__embed, calls AI_EMBED. With our settings, it generates this SQL expression:

AI_EMBED('snowflake-arctic-embed-l-v2.0', chunk_text)
Enter fullscreen mode Exit fullscreen mode

AI_EMBED converts text into a numeric vector and returns it as the VECTOR type. With this model, the vectors have 1024 dimensions.

We also configure guard_batch on the model to check processing volume. Here's the source code for it and for the token estimate calculation:

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/cost/guard_batch.sql

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/cost/estimate_tokens.sql

On Snowflake, it runs COUNT(*) and a SUM of estimated tokens on the input table. dbt compares the results against the limits and stops with a compilation error if they're exceeded.

-- models/context/feedback_embeddings.sql
{{ config(
    materialized='table',
    pre_hook=[
        "{{ dbt_context_engineering.guard_batch(ref('feedback_chunks'), 'chunk_text') }}"
    ]
) }}

select
    chunk_id,
    partition_key as order_id,
    source_rows,
    chunk_text,
    {{ dbt_context_engineering.embed('chunk_text') }} as embedding
from {{ ref('feedback_chunks') }}
Enter fullscreen mode Exit fullscreen mode

We also carry over source_rows so search results can be traced back to the original posts.

Run dbt run in the Workspace with the following in Additional Flags. Because this uses AI functions, enable ai_functions_enabled.

--select feedback_embeddings --vars '{"ai_functions_enabled": true}'
Enter fullscreen mode Exit fullscreen mode

Check the results:

SELECT
    chunk_id,
    order_id,
    source_rows,
    chunk_text,
    embedding
FROM DBT_CE_DEMO_DB.DBT_CE_DEMO.feedback_embeddings
ORDER BY order_id, chunk_id;
Enter fullscreen mode Exit fullscreen mode

You're good if each chunk's embedding column contains a vector.

Note that the configuration so far doesn't write anything to ai_run_log.

To record logs, you'd use log_ai_run for the start log and complete_ai_run for the successful-completion log.

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/cost/log_ai_run.sql

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/cost/complete_ai_run.sql

On Snowflake, both macros simply INSERT into a log table. They append records at the start and at successful completion. They don't automatically fetch your actual Snowflake charges. To use them, you need to prepare the log table and add the macros to your hooks. This article skips logging.

3. vector_search: Semantic Search in Japanese

We'll use the following Japanese search query:

配送が遅れた注文について、遅延の原因を知りたい
(For orders whose delivery was delayed, I want to know the cause of the delay.)

The goal isn't to collect every text about delivery. It's to retrieve texts that explain the cause of a delay, such as sorting mistakes, traffic congestion, or bad weather.

The macro here is vector_search. Here's the source code:

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/retrieval/vector_search.sql

On Snowflake, VECTOR_COSINE_SIMILARITY calculates the similarity between the stored vectors and the query vector. It returns the result as score and gets the top results with ORDER BY score DESC and LIMIT.

vector_search doesn't vectorize the search string automatically. You have to pass a SQL expression that returns a vector to query_embedding.

So we use embed for the query too, which is also AI_EMBED on Snowflake. The documents and the query use the same embedding model.

-- models/context/search_raw.sql
{{ config(materialized='table') }}

{{ dbt_context_engineering.vector_search(
    relation = ref('feedback_embeddings'),
    embedding_column = 'embedding',
    query_embedding = dbt_context_engineering.embed(
        "'配送が遅れた注文について、遅延の原因を知りたい'"
    ),
    top_k = 10,
    id_column = 'chunk_id',
    select_columns = [
        'order_id',
        'source_rows',
        'chunk_text'
    ]
) }}
Enter fullscreen mode Exit fullscreen mode

The inner single quotes in the embed argument are there so the text is passed as a SQL string literal.

The core of the generated SQL looks like this:

SELECT
    chunk_id,
    order_id,
    source_rows,
    chunk_text,
    VECTOR_COSINE_SIMILARITY(
        embedding,
        AI_EMBED(
            'snowflake-arctic-embed-l-v2.0',
            '配送が遅れた注文について、遅延の原因を知りたい'
        )
    ) AS score
FROM DBT_CE_DEMO_DB.DBT_CE_DEMO.feedback_embeddings
ORDER BY score DESC, chunk_id
LIMIT 10;
Enter fullscreen mode Exit fullscreen mode

As you can see, this is plain SQL against a regular table, not a query to a Cortex Search service.

To build it as a table, run dbt run in the Workspace with the following in Additional Flags:

--select search_raw --vars '{"ai_functions_enabled": true}'
Enter fullscreen mode Exit fullscreen mode

Check the results in score order:

SELECT *
FROM DBT_CE_DEMO_DB.DBT_CE_DEMO.search_raw
ORDER BY score DESC, chunk_id;
Enter fullscreen mode Exit fullscreen mode

score is the cosine similarity. A higher value ranks a vector as closer to the query, but the score isn't a measure of answer correctness or a probability of relevance.

The top three results matched the question "For orders whose delivery was delayed, I want to know the cause of the delay." They were about "sorting to the wrong destination," "traffic congestion," and "road closures due to a storm."

On the other hand, the 4th to 6th results were mostly about "delivery status checks." They didn't really answer the question "For orders whose delivery was delayed, I want to know the cause of the delay."

Note that this example uses dbt to build a table of results for a fixed search query. To offer search to end users, you'd need to build an interactive search UI or an API that accepts arbitrary questions separately.

4. classify: Improve Relevance by Filtering with Labels

Next, we assign classification labels to each chunk and use them to narrow down the search targets.

We define the following six labels:

Label Description
delivery_delay Delivery delays caused by something other than weather
weather_disruption Delivery impacts from snow, storms, and similar weather
handling_error Wrong items, incorrect shipping labels, or misdelivery
product_quality Complaints about product or packaging quality
praise Specific praise for products or service
routine_status Status checks, procedural notices, resolution notices, and similar messages

The label identifiers are in English so they're easy to handle in SQL, and the classification instructions are written in Japanese.

First, define the prompt and classification schema as macros in your own project.

macros/prompts/feedback_topic.sql (click to expand)
-- macros/prompts/feedback_topic.sql
{% macro prompt__feedback_topic__v1() -%}
{%- raw -%}
以下の注文に関する文章を読み、最も適切なトピックラベルを1つ選んでください。

入力には、お客様からの問い合わせやレビューだけでなく、
サポート担当者からの返信が含まれる場合もあります。
また、同じ注文に関する複数のメッセージが含まれる場合もあります。

ラベルの定義:
- delivery_delay:
  渋滞、配送拠点の仕分けミス、配送ルートなど、
  天候以外の理由による配送の遅れが主な話題である文章。
- weather_disruption:
  大雪、暴風雨、悪天候による通行止めなど、
  天候が配送に影響したことが主な話題である文章。
- handling_error:
  商品の取り違え、配送ラベルの誤り、
  届け先の間違いなどが主な話題である文章。
- product_quality:
  商品の温度、食感、量、包装の破損、
  中身の漏れなど、品質への不満が主な話題である文章。
- praise:
  商品のおいしさ、接客、包装などに対する
  具体的な称賛が主な話題である文章。
- routine_status:
  状況確認、配達時間の問い合わせ、受付完了、
  再配達の手配、対応完了などの定型的な連絡。
  原因や具体的な問題について、新しい説明がない文章。

判断ルール:
- 文章の長さではなく、内容に基づいて分類してください。
- 「配送」「確認」「再配達」という言葉だけで
  delivery_delayに分類しないでください。
- 単に配達予定を尋ねている文章や、
  配送担当に確認したことだけを伝える文章はroutine_statusです。
- 天候が配送遅延の原因として明記されている場合は、
  weather_disruptionを優先してください。
- 配送遅延の原因が主な話題で、誤配送にも触れている場合は、
  主題に応じてdelivery_delayまたはweather_disruptionを選んでください。
- 問題が解決したことだけを伝えるお礼はroutine_statusです。
- 複数のメッセージがある場合、定型的な返信よりも、
  具体的な問題や原因の説明を重視してください。
- 複数の具体的な問題がある場合は、中心となる話題を1つ選んでください。

対象の文章:
{{ input }}
{%- endraw -%}
{%- endmacro %}

{% macro schema__feedback_topic__v1() -%}
{%- raw -%}
{
  "type": "object",
  "properties": {
    "topic": {
      "type": "string",
      "enum": [
        "delivery_delay",
        "weather_disruption",
        "handling_error",
        "product_quality",
        "praise",
        "routine_status"
      ]
    }
  },
  "required": ["topic"],
  "additionalProperties": false
}
{%- endraw -%}
{%- endmacro %}
Enter fullscreen mode Exit fullscreen mode

To load these, use prompt and schema_def. Here's the source code:

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/prompts/prompt.sql

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/prompts/schema_def.sql

These two macros don't call Snowflake AI functions. At dbt compile time, they look up the macros that match the given name and version, then return the prompt string and the JSON schema string. Here, they call prompt__feedback_topic__v1 and schema__feedback_topic__v1.

Here's the macro that does the classification and the macro that combines the prompt with the input column:

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/functions/classify.sql

https://github.com/dbt-labs/dbt-context-engineering/blob/main/macros/prompts/render_prompt.sql

On Snowflake, the flow is:

  1. Get the candidate labels from the schema's enum
  2. Use render_prompt to generate a SQL expression that inserts the input column into the prompt's {{ input }} placeholder
  3. Build an array of candidate labels with ARRAY_CONSTRUCT and pass it to AI_CLASSIFY
  4. Extract :labels[0] from the return value and convert it to a string

Next, create the classification model, again with guard_batch. This time we set meta.ai_prompt so the estimate includes the prompt and schema in addition to the input text. This still isn't a measurement of the actual billed tokens.

-- models/context/feedback_classified.sql
{{ config(
    materialized='table',
    meta={
        'ai_prompt': {
            'name': 'feedback_topic',
            'version': 'v1'
        }
    },
    pre_hook=[
        "{{ dbt_context_engineering.guard_batch(ref('feedback_chunks'), 'chunk_text') }}"
    ]
) }}

select
    chunk_id,
    {{ dbt_context_engineering.classify(
        'chunk_text',
        dbt_context_engineering.prompt('feedback_topic', 'v1'),
        dbt_context_engineering.schema_def('feedback_topic', 'v1')
    ) }} as classification
from {{ ref('feedback_chunks') }}
Enter fullscreen mode Exit fullscreen mode

Run dbt run in the Workspace with the following in Additional Flags:

--select feedback_classified --vars '{"ai_functions_enabled": true}'
Enter fullscreen mode Exit fullscreen mode

Check the classification results:

SELECT
    c.chunk_id,
    c.classification,
    k.source_rows,
    k.chunk_text
FROM DBT_CE_DEMO_DB.DBT_CE_DEMO.feedback_classified c
JOIN DBT_CE_DEMO_DB.DBT_CE_DEMO.feedback_chunks k
    USING (chunk_id)
ORDER BY c.chunk_id;
Enter fullscreen mode Exit fullscreen mode

The package's classify returns a label string. In later SQL, compare classification directly as a string instead of using something like classification:topic.

None of the records had a NULL CLASSIFICATION, and the texts were classified correctly.

Next, join the embeddings with the classification labels. This model doesn't call any AI functions. It's a view that joins the stored results.

-- models/context/feedback_embeddings_labeled.sql
{{ config(materialized='view') }}

select
    e.chunk_id,
    e.order_id,
    e.source_rows,
    e.chunk_text,
    e.embedding,
    c.classification
from {{ ref('feedback_embeddings') }} e
join {{ ref('feedback_classified') }} c
    using (chunk_id)
Enter fullscreen mode Exit fullscreen mode

Finally, narrow the search targets to three labels: delivery_delay, weather_disruption, and handling_error. For comparison, we use the same search query as before.

Again, we use vector_search and embed to vectorize the query. On Snowflake, the condition passed to filter becomes the SQL WHERE clause. The search first filters to rows with the target labels, then returns the top results by VECTOR_COSINE_SIMILARITY score.

-- models/context/search_classified.sql
{{ config(materialized='table') }}

{{ dbt_context_engineering.vector_search(
    relation = ref('feedback_embeddings_labeled'),
    embedding_column = 'embedding',
    query_embedding = dbt_context_engineering.embed(
        "'配送が遅れた注文について、遅延の原因を知りたい'"
    ),
    top_k = 10,
    id_column = 'chunk_id',
    select_columns = [
        'order_id',
        'source_rows',
        'chunk_text',
        'classification'
    ],
    filter = "classification in ('delivery_delay', 'weather_disruption', 'handling_error')"
) }}
Enter fullscreen mode Exit fullscreen mode

Run dbt run in the Workspace with the following in Additional Flags:

--select feedback_embeddings_labeled search_classified --vars '{"ai_functions_enabled": true}'
Enter fullscreen mode Exit fullscreen mode

Check the results:

SELECT *
FROM DBT_CE_DEMO_DB.DBT_CE_DEMO.search_classified
ORDER BY score DESC, chunk_id;
Enter fullscreen mode Exit fullscreen mode

As shown below, the output now has fewer records. If you want to narrow down the records that VECTOR_COSINE_SIMILARITY scores, good labeling seems to be an effective approach.

Wrapping Up

I used dbt_context_engineering on dbt Projects on Snowflake to search Japanese inquiries and reviews with "chunk → embed → vector_search," then narrowed the search targets with classify labels.

Chunking, embedding, search, and classification can all be written as regular dbt models linked by ref(). That means you can manage processing that uses Snowflake's AI_EMBED and AI_CLASSIFY in dbt too, which I found really convenient!

That said, as of November 16, 2026, the package is still at version 0.x and includes Beta features, so use it with care. I recommend trying it on a small dataset first.

Top comments (0)