How to Build LLM Apps that can See Hear Speak
Notebook
Note
This tutorial is meant for Standard & Premium Clusters. You can't run this with a Free Starter Cluster due to restrictions on Storage. Create a Cluster using +group in the left nav & select Standard for this notebook. Gallery notebooks tagged with "Starter" are suitable to run on a Free Starter Cluster
What you'll build

By the end of this notebook you will have a small application that answers questions about company financials in plain English, and that can see, hear and speak. Three years of quarterly results for Amazon, Tesla and Palantir are loaded from files that ship with this notebook; a LangChain SQL agent turns your questions into MySQL and answers in prose; each question is cached alongside its embedding, so a later question that means the same thing is answered from the cache; the answer is spoken and transcribed back; and a chart drawn from the stored rows is described by a vision model.
All of it lives in one SingleStore database. The rows, the embeddings and the cache sit together, so
the cache lookup is an ordinary SQL query over a VECTOR column — there is no second system to keep in
sync.
Step 1 — one database and three tables, including the
VECTORcolumns the cache needsStep 2 — install LangChain, enter your OpenAI key, open a connection
Step 3 — load quarterly financials for three companies, taken from their SEC filings
Step 4 — ask questions in English, then put a semantic cache in front of the agent
Step 5 — speak the answer, play it, transcribe it back
Step 6 — chart the data and have a vision model describe the chart
Run the cells in order. Every cell is safe to run again. Troubleshooting at the end lists the errors worth knowing about in advance.
Before you start
You need a Standard or Premium cluster, as the alert above says, with a database selected in the drop-down at the top of this notebook — every SQL cell runs against whatever is chosen there.
You need one account: OpenAI, for the models. A full run costs a few cents. The data needs no account at all — it ships with the notebook (see step 3).
Budget about five minutes, most of it the agent thinking in step 4.
First a database named llm_webinar. Expect a one-line success message and nothing else.
Running these cells twice is harmless. The database and the embeddings cache use IF NOT EXISTS, so
the cache step 4 builds survives. The two data tables, companyInfo and financials, are dropped and recreated
instead, because step 3 reloads them from data held in the notebook at no cost. The same cell also drops
stockTable, newsSentiment and earningsCalls, tables left by earlier versions of this notebook.
Every statement names llm_webinar explicitly, so nothing in another database is touched. To start over deliberately, the Reset Demo
cell at the end drops the database outright.
In [1]:
1%%sql2CREATE DATABASE IF NOT EXISTS llm_webinar;
Action Required
Make sure to select a database from the drop-down menu at the top of this notebook. It updates the connection_url to connect to that database.
The three tables
Two tables hold what step 3 loads: companyInfo, one row per company — name, industry, exchange,
fiscal year end — and financials, one row per company per quarter with revenue, operating income
and net income in US dollars. companyInfo is a REFERENCE table because it is tiny — SingleStore
replicates it to every node, so joins against it never move data across the cluster.
The third, embeddings, is the semantic cache: a question, its answer, and an embedding of
each. Those embedding columns are VECTOR(1536, F32), SingleStore's native vector type, sized for
what text-embedding-3-small produces. Using the real type rather than a blob means the dimension
of every value is validated on insert, results print readably, and a vector index can be added
later — which is what NOT NULL is there for.
The money columns are BIGINT rather than FLOAT, because a quarter of Amazon revenue is about
$200 billion, more digits than a FLOAT holds exactly.
The SHOW TABLES cell that follows is your check: expect exactly these three names. If it comes back
empty, the database drop-down at the top of the notebook is pointing somewhere else.
In [2]:
1%%sql2-- Every name is qualified with llm_webinar, so this cell can never drop or create tables in3-- whichever database happens to be selected in the drop-down.4 5-- Tables from earlier versions of this notebook, which loaded data from a stock-data API.6DROP TABLE IF EXISTS llm_webinar.stockTable;7DROP TABLE IF EXISTS llm_webinar.newsSentiment;8DROP TABLE IF EXISTS llm_webinar.earningsCalls;9 10-- The two data tables are rebuilt on every run: step 3 reloads them from the notebook at no11-- cost, and rebuilding means an older copy of either can never be left with stale columns.12DROP TABLE IF EXISTS llm_webinar.companyInfo;13CREATE ROWSTORE REFERENCE TABLE llm_webinar.companyInfo (14 ticker VARCHAR(10) PRIMARY KEY,15 name VARCHAR(200),16 cik CHAR(10), -- the company's SEC identifier17 industry VARCHAR(200), -- SEC's SIC description18 exchange VARCHAR(20),19 fiscal_year_end CHAR(5), -- MM-DD20 state_of_incorporation CHAR(2)21);22 23DROP TABLE IF EXISTS llm_webinar.financials;24CREATE TABLE llm_webinar.financials (25 ticker VARCHAR(10),26 fiscal_year INT,27 fiscal_quarter TINYINT, -- 1 to 428 period_end DATE,29 q4_derived BOOL, -- 1 when Q4 is the full year minus Q1 to Q330 revenue BIGINT, -- US dollars31 operating_income BIGINT,32 net_income BIGINT,33 SORT KEY (ticker, period_end),34 SHARD KEY (ticker)35);36 37CREATE TABLE IF NOT EXISTS `llm_webinar`.`embeddings` (38 `id` bigint(11) NOT NULL AUTO_INCREMENT,39 `category` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,40 `question` longtext CHARACTER SET utf8 COLLATE utf8_general_ci,41 `question_embedding` VECTOR(1536, F32) NOT NULL,42 `answer` longtext CHARACTER SET utf8 COLLATE utf8_general_ci,43 `answer_embedding` VECTOR(1536, F32) NOT NULL,44 `created_at` datetime DEFAULT NULL,45 UNIQUE KEY `PRIMARY` (`id`) USING HASH,46 SHARD KEY `__SHARDKEY` (`id`),47 KEY `category` (`category`) USING HASH,48 SORT KEY `__UNORDERED` (`created_at` DESC)49);
In [3]:
1%%sql2SHOW TABLES;
Step 2: Packages, keys and connections
The hosted image already ships openai, numpy, pandas, requests and singlestoredb, so the
installs are LangChain, for the agent in step 4, and matplotlib, for the chart in step 6. numpy is
pinned to the version already installed, so pip can't replace it under the running kernel. Expect
about thirty seconds of quiet output.
Two warnings you can ignore: langchain-community — the only home for the SQL toolkit step 4 uses
— announces on import that it is being sunset, and pip may mention conflicts among packages this
notebook never imports.
In [4]:
1%pip install --quiet "langchain>=1.3,<2" "langchain-community>=0.4.2,<0.5" "langchain-openai>=1.5,<2"2 3# The hosted image has no matplotlib, which the chart in step 6 needs. numpy is pinned to the4# version already installed, so pip adds matplotlib without swapping numpy under the kernel.5# python-dateutil is capped because 4.x breaks the image's ibis-framework.6from importlib.metadata import version7 8%pip install --quiet "matplotlib<3.11" "numpy=={version('numpy')}" "python-dateutil<3"
Now the imports: standard library, the two SDKs, and the LangChain pieces step 4 needs. Nothing
here touches the network, so this cell returns instantly. A NameError further down usually means
this cell has not run in the current kernel.
In [5]:
1import csv2import getpass3import io4import json5import os6import time7from datetime import datetime, timedelta8 9import numpy as np10import openai11import requests12import singlestoredb as s213 14# LangChain moved these in 1.x: `langchain.sql_database` and15# `langchain.agents.agent_toolkits` no longer exist. These are the current paths.16from langchain_community.utilities import SQLDatabase17from langchain_community.agent_toolkits.sql.toolkit import SQLDatabaseToolkit18from langchain_community.agent_toolkits.sql.base import create_sql_agent19from langchain_openai import ChatOpenAI20 21import langchain22 23print(f'openai {openai.__version__} | langchain {langchain.__version__}')24 25# Report whether this image's brotli is one of the affected ones. This is informational26# only — the OpenAI client cell below sidesteps the decoder either way.27try:28 import brotli29 30 brotli.Decompressor().process(brotli.compress(b'probe'), output_buffer_limit=1 << 20)31 print(f'brotli {brotli.__version__}: accepts output_buffer_limit')32except TypeError:33 print(f'brotli {brotli.__version__}: too old for httpx2 (expected on this image) — '34 f'the OpenAI client below will not request brotli-encoded responses')35except ImportError:36 print('brotli not installed — nothing to work around')
Set your OpenAI key
Run the next cell and paste your OpenAI API key at the prompt.
OpenAI does everything model-shaped here: embeddings, the text-to-SQL agent, speech, transcription and
image description. getpass keeps the key off the screen and out of the saved notebook, which also
means re-entering it after a kernel restart.
In [6]:
1openai_apikey = getpass.getpass('enter openai apikey here')2 3assert openai_apikey, 'An OpenAI key is required for embeddings, the SQL agent, speech and captioning.'4 5os.environ['OPENAI_API_KEY'] = openai_apikey
Build the OpenAI client
One client, used by everything: embeddings, transcription, speech, captioning, and the LangChain
agent in step 4. The models for those jobs are chosen in the next cell. It ends with a deliberately cheap embeddings call, so a wrong or unfunded key fails
here rather than a dozen cells later. Expect two printed lines, the second reading
text-embedding-3-small returned 1536 dimensions — the size the embeddings table was declared
for. If you swap in a different embedding model, read the note on the similarity threshold in step 4
first: the threshold is a property of the model, and carrying one over is a silent failure.
The http_client argument turns off brotli compression, which the version on this image cannot
decode. Without it you get APIConnectionError: Connection error printed under a successful
HTTP/1.1 200 OK — an error that looks like the network or your key and is neither.
In [7]:
1import httpx22from openai import OpenAI3 4# Do not advertise brotli, so the image's brotli 1.1.0 is never asked to decode a response.5http_client = httpx2.Client(headers={'Accept-Encoding': 'gzip, deflate'})6 7client = OpenAI(api_key=openai_apikey, http_client=http_client)8 9print(f"Accept-Encoding: {client._client.headers.get('accept-encoding')}")10 11EMBEDDING_MODEL = 'text-embedding-3-small' # 1536 dimensions, matches the DDL above12 13 14def get_embeddings(inputs: list[str], model: str = EMBEDDING_MODEL) -> list[list[float]]:15 """Return one embedding per input string."""16 return [x.embedding for x in client.embeddings.create(input=inputs, model=model).data]17 18 19# Fail here, on one cheap call, rather than midway through the ingest loops.20_probe = get_embeddings(['connectivity probe'])[0]21print(f'{EMBEDDING_MODEL} returned {len(_probe)} dimensions')22 23assert len(_probe) == 1536, (24 f'{EMBEDDING_MODEL} returned {len(_probe)} dimensions but the embeddings table declares '25 f'VECTOR(1536, F32). Change the DDL to match, or pick a 1536-dimension model.'26)
Choose the models
OpenAI retires older models regularly, usually with at least six months' notice, and its List models endpoint reports each model's planned shutdown date. Rather than trust model names written into this notebook, this cell asks OpenAI which models your key can use right now and skips any that are scheduled to shut down. It picks three: a chat model for the SQL agent and the captions, a speech model, and a transcription model.
For each one it takes the first available entry from its PREFERRED_..._MODELS list. If every
entry has been retired, it falls back to the newest model of the same kind on your account,
preferring the low-cost tiers. Expect four lines naming the models it chose. A retirement then
shows up as a different name in this output rather than an error further down.
In [8]:
1import openai2 3# OpenAI retires models on a schedule. This notebook used to hard-code gpt-4o-mini,4# gpt-4o-mini-tts and whisper-1, and all three are being shut down. So instead of pinning5# names, list the models we'd like for each job, in order of preference. This cell asks6# OpenAI which models your key can use right now and skips any with a shutdown date.7PREFERRED_CHAT_MODELS = ['gpt-6-luna', 'gpt-6.1-terra'] # SQL agent (step 4), captions (step 6)8PREFERRED_SPEECH_MODELS = ['gpt-audio-1.5'] # text to speech (step 5)9PREFERRED_TRANSCRIBE_MODELS = ['gpt-transcribe'] # speech to text (step 5)10 11LOW_COST = ('luna', 'nano', 'mini')12NOT_CHAT = ('audio', 'realtime', 'transcribe', 'tts', 'image', 'search', 'codex', 'cyber',13 'pro', 'chat', 'live', 'oss', 'embedding', 'moderation', 'preview', 'instruct',14 'translate', 'whisper')15 16 17def has_shutdown_date(model) -> bool:18 """True if OpenAI has announced a shutdown date for this model."""19 return bool(getattr(model, 'shutdown_date', None))20 21 22active_models = {m.id: m for m in client.models.list() if not has_shutdown_date(m)}23 24 25def pick_model(preferred: list[str], same_kind) -> str | None:26 """The first preferred model that is active, else the newest active one of the same kind."""27 for name in preferred:28 if name in active_models:29 return name30 31 # Nothing on the list is still active: take the newest model of the same kind,32 # low-cost tiers first.33 fallback = [m for m in active_models.values() if same_kind(m.id)]34 fallback.sort(key=lambda m: (any(word in m.id for word in LOW_COST), m.created), reverse=True)35 return fallback[0].id if fallback else None36 37 38CHAT_MODEL = pick_model(39 PREFERRED_CHAT_MODELS,40 lambda name: name.startswith('gpt-') and not any(word in name for word in NOT_CHAT))41SPEECH_MODEL = pick_model(42 PREFERRED_SPEECH_MODELS,43 lambda name: name.startswith('gpt-audio') and 'preview' not in name)44TRANSCRIBE_MODEL = pick_model(45 PREFERRED_TRANSCRIBE_MODELS,46 lambda name: 'transcribe' in name and not any(w in name for w in ('live', 'realtime', 'diarize')))47 48assert CHAT_MODEL, ('No active GPT chat model is available to this API key. '49 'Check https://developers.openai.com/api/docs/models')50 51# Current models accept "no hidden reasoning step" and the most repeatable output, which keeps52# the agent quick and its answers repeatable. If a future model rejects53# either setting, CHAT_SETTINGS is left empty and the model's defaults are used instead.54CHAT_SETTINGS = {'reasoning_effort': 'none', 'temperature': 0}55try:56 client.chat.completions.create(57 model=CHAT_MODEL, messages=[{'role': 'user', 'content': 'say ok'}], **CHAT_SETTINGS)58except openai.BadRequestError as err:59 # Fall back only if the model objected to the settings; raise any other 400.60 complaint = f"{getattr(err, 'param', '') or ''} {err}"61 if 'reasoning_effort' not in complaint and 'temperature' not in complaint:62 raise63 CHAT_SETTINGS = {}64 65print(f'chat model: {CHAT_MODEL} {CHAT_SETTINGS or "(model defaults)"}')66print(f'speech model: {SPEECH_MODEL or "none available, step 5 cannot speak"}')67print(f'transcription model: {TRANSCRIBE_MODEL or "none available, step 5 cannot transcribe"}')68 69if EMBEDDING_MODEL in active_models:70 print(f'embedding model: {EMBEDDING_MODEL} (no shutdown date announced)')71else:72 print(f'Note: {EMBEDDING_MODEL} has a shutdown date announced, or is not available to this '73 f'key. Pick a 1536-dimension replacement and re-check the similarity threshold in step 4.')
Connect to SingleStore
Expect one line: connected to llm_webinar; all three tables present. If it reports a missing table
or no database selected, the drop-down at the top of the notebook is pointing somewhere other than
where step 1 created things.
The password in a notebook connection URL is a token that expires after about an hour, so the helpers read the URL when they need it and let the driver refresh it. One connection then survives both a token refresh and a change to the database drop-down.
In [9]:
1def current_connection_url() -> str:2 """Return the connection URL as it is now, not as it was at kernel startup.3 4 The password is a JWT that expires after roughly an hour, so a copy taken earlier in the5 session may already be dead. The first two sources are read live.6 """7 url = None8 9 try:10 from singlestoredb.notebook import portal11 url = portal.connection_url12 except Exception:13 pass # not running inside a SingleStore hosted notebook14 15 url = url or os.environ.get('SINGLESTOREDB_URL') or connection_url16 17 # SINGLESTOREDB_URL carries no scheme, and SQLAlchemy needs one to choose a dialect.18 return url if '://' in url else f'singlestoredb://{url}'19 20 21EXPECTED_TABLES = {'companyInfo', 'financials', 'embeddings'}22 23 24def s2_connect():25 """Open a connection that re-reads its credentials rather than pinning them."""26 # track_env=True discards any URL passed to connect() and reads SINGLESTOREDB_URL on every27 # statement, so only ask for it when that variable is actually set.28 if os.environ.get('SINGLESTOREDB_URL'):29 conn = s2.connect(track_env=True)30 else:31 conn = s2.connect(current_connection_url())32 33 try:34 with conn.cursor() as cur:35 # track_env defers connecting, so this statement is what opens the socket.36 cur.execute('SELECT DATABASE()')37 database = cur.fetchone()[0]38 39 cur.execute(40 'SELECT table_name FROM information_schema.tables '41 'WHERE table_schema = DATABASE()'42 )43 tables = {row[0] for row in cur.fetchall()}44 45 except s2.Error as exc:46 if exc.errno == 2628 or 'JWT' in str(exc):47 raise RuntimeError(48 'SingleStore rejected the notebook credentials: the JWT in the connection URL '49 'has expired. It is issued when the kernel starts and lasts about an hour, so a '50 'long session runs past it. Restart the kernel and run the cells again — the '51 'portal issues a fresh token at startup.'52 ) from exc53 raise54 55 assert database, (56 'no database is selected. Pick llm_webinar from the drop-down at the top of the '57 'notebook, then re-run this cell.'58 )59 60 assert database == 'llm_webinar', (61 f'the drop-down points at {database}, not llm_webinar. Select llm_webinar at the top of '62 f'the notebook, then re-run this cell. Step 3 and the cache write to llm_webinar by name, '63 f'and the agent reads whichever database is selected, so the two must match.'64 )65 66 missing = EXPECTED_TABLES - tables67 68 assert not missing, (69 f'connected to {database}, which is missing {sorted(missing)}. Either the DDL cells have '70 f'not been run, or the drop-down points at a different database.'71 )72 73 print(f'connected to {database}; all three tables present')74 75 return conn76 77 78s2_conn = s2_connect()
Step 3: Load the data
The data is part of the notebook itself — the next cell holds it as two short blocks of CSV — so loading it needs no account, no API key and no download. Nothing here can be rate-limited, paywalled or blocked by a firewall.
The figures come from each company's filings with the US Securities and Exchange Commission, through
SEC EDGAR's free XBRL
data: quarterly revenue, operating income and net income (attributable to common stockholders, the
NetIncomeLoss figure in each 10-K and 10-Q) in US dollars, from Q1 2023 to Q3 2026, for
Amazon, Tesla and Palantir — all three on calendar fiscal years. Companies report Q4 only inside the
full year, so each Q4 row is the full year minus the first three quarters, and is marked
q4_derived = 1.
Run the data cell, then the load cell. Expect two lines from the second, companyInfo: 3 rows and
financials: 45 rows. It empties both tables before loading, so running it again leaves the same rows
rather than duplicates.
In [10]:
1# Snapshot of SEC EDGAR XBRL data, taken 2026-11-17. Amounts are US dollars.2COMPANIES_CSV = '''3ticker,name,cik,industry,exchange,fiscal_year_end,state_of_incorporation4AMZN,AMAZON COM INC,0001018724,Retail-Catalog & Mail-Order Houses,Nasdaq,12-31,DE5TSLA,"Tesla, Inc.",0001318605,Motor Vehicles & Passenger Car Bodies,Nasdaq,12-31,TX6PLTR,Palantir Technologies Inc.,0001321655,Services-Prepackaged Software,Nasdaq,12-31,7'''8 9FINANCIALS_CSV = '''10ticker,fiscal_year,fiscal_quarter,period_end,q4_derived,revenue,operating_income,net_income11AMZN,2023,1,2023-03-31,0,127358000000,4774000000,317200000012AMZN,2023,2,2023-06-30,0,134383000000,7681000000,675000000013AMZN,2023,3,2023-09-30,0,143083000000,11188000000,987900000014AMZN,2023,4,2023-12-31,1,169961000000,13209000000,1062400000015AMZN,2024,1,2024-03-31,0,143313000000,15307000000,1043100000016AMZN,2024,2,2024-06-30,0,147977000000,14672000000,1348500000017AMZN,2024,3,2024-09-30,0,158877000000,17411000000,1532800000018AMZN,2024,4,2024-12-31,1,187792000000,21203000000,2000400000019AMZN,2025,1,2025-03-31,0,155667000000,18405000000,1712700000020AMZN,2025,2,2025-06-30,0,167702000000,19171000000,1816400000021AMZN,2025,3,2025-09-30,0,180169000000,17422000000,2118700000022AMZN,2025,4,2025-12-31,1,213386000000,24977000000,2119200000023AMZN,2026,1,2026-03-31,0,181519000000,23852000000,3025500000024AMZN,2026,2,2026-06-30,0,200606000000,27461000000,6264700000025AMZN,2026,3,2026-09-30,0,201944000000,28076000000,2068500000026TSLA,2023,1,2023-03-31,0,23329000000,2664000000,251300000027TSLA,2023,2,2023-06-30,0,24927000000,2399000000,270300000028TSLA,2023,3,2023-09-30,0,23350000000,1764000000,185300000029TSLA,2023,4,2023-12-31,1,25167000000,2064000000,792800000030TSLA,2024,1,2024-03-31,0,21301000000,1171000000,139000000031TSLA,2024,2,2024-06-30,0,25500000000,1605000000,140000000032TSLA,2024,3,2024-09-30,0,25182000000,2717000000,217300000033TSLA,2024,4,2024-12-31,1,25707000000,1583000000,212800000034TSLA,2025,1,2025-03-31,0,19335000000,399000000,40900000035TSLA,2025,2,2025-06-30,0,22496000000,923000000,117200000036TSLA,2025,3,2025-09-30,0,28095000000,1624000000,137300000037TSLA,2025,4,2025-12-31,1,24901000000,1409000000,84000000038TSLA,2026,1,2026-03-31,0,22387000000,941000000,47700000039TSLA,2026,2,2026-06-30,0,28236000000,398000000,111400000040TSLA,2026,3,2026-09-30,0,28046000000,718000000,78700000041PLTR,2023,1,2023-03-31,0,525186000,4115000,1680200042PLTR,2023,2,2023-06-30,0,533317000,10074000,2812700043PLTR,2023,3,2023-09-30,0,558159000,39983000,7150500044PLTR,2023,4,2023-12-31,1,608350000,65794000,9339100045PLTR,2024,1,2024-03-31,0,634338000,80881000,10553000046PLTR,2024,2,2024-06-30,0,678134000,105339000,13412600047PLTR,2024,3,2024-09-30,0,725516000,113140000,14352500048PLTR,2024,4,2024-12-31,1,827519000,11043000,7900900049PLTR,2025,1,2025-03-31,0,883855000,176048000,21403100050PLTR,2025,2,2025-06-30,0,1003697000,269317000,32672700051PLTR,2025,3,2025-09-30,0,1181092000,393256000,47559900052PLTR,2025,4,2025-12-31,1,1406802000,575394000,60867600053PLTR,2026,1,2026-03-31,0,1632583000,753998000,87052700054PLTR,2026,2,2026-06-30,0,1935464000,912004000,106189000055PLTR,2026,3,2026-09-30,0,2313411000,1084845000,112801200056'''
In [11]:
1def read_csv(text: str) -> list[dict]:2 """Parse one of the CSV blocks above into rows, with empty fields as None."""3 rows = list(csv.DictReader(io.StringIO(text.strip())))4 return [{k: (v if v != '' else None) for k, v in row.items()} for row in rows]5 6 7def load_table(table: str, rows: list[dict]) -> None:8 """Replace a table's contents with these rows, always in llm_webinar."""9 qualified = f'llm_webinar.{table}' # named explicitly, so another database is never emptied10 columns = list(rows[0])11 insert = (12 f'INSERT INTO {qualified} (' + ', '.join(columns) + ') VALUES ('13 + ', '.join(f'%({c})s' for c in columns) + ')'14 )15 16 with s2_conn.cursor() as cur:17 cur.execute(f'TRUNCATE TABLE {qualified}')18 cur.executemany(insert, rows)19 20 print(f'{table}: {len(rows)} rows')21 22 23load_table('companyInfo', read_csv(COMPANIES_CSV))24load_table('financials', read_csv(FINANCIALS_CSV))
In [12]:
1%%sql2SELECT ticker, name, industry, exchange FROM companyInfo
The latest quarter for each company
The same rows the agent will query in step 4, so you know the right answers before you ask. Expect three rows; revenue is in billions of dollars, rounded.
In [13]:
1%%sql2SELECT ticker, fiscal_year, fiscal_quarter,3 ROUND(revenue / 1e9, 2) AS revenue_billions,4 ROUND(net_income / 1e9, 2) AS net_income_billions5FROM financials6WHERE period_end = (SELECT MAX(period_end) FROM financials)7ORDER BY revenue DESC
Step 4: Ask questions in English
This is where the notebook stops being a data pipeline. SQLDatabaseToolkit gives the model four tools
— list the tables, read a schema, check a query, run a query — and create_sql_agent wires them into a
loop: the model writes MySQL, runs it against SingleStore, reads the rows back, and answers in prose.
Expect a short confirmation and a deprecation warning from langchain-community; the agent runs in the
cells further down.
A quirk you may hit. Reading a VECTOR column through SQLAlchemy raises AttributeError: 'VECTOR' object has no attribute '_str_impl' on some builds of the SingleStore dialect, and SQLDatabase reads
sample rows from every table. The cell patches that and describes the embeddings table by hand, which
also keeps two 1536-dimension vectors out of the prompt.
In [14]:
1SQL_AGENT_PREFIX = """You are an agent designed to interact with a SQL database called SingleStore.2This sometimes has Shard and Sort keys in the table schemas, which you can ignore.3 4Given an input question, create a syntactically correct {dialect} query to run, then look at the5results of the query and return the answer.6 7If you are asked about similarity questions, you should use the DOT_PRODUCT function.8 9Here are a few examples of how to use the DOT_PRODUCT function:10 11Example 1:12Q: how similar are the questions and answers?13A: select question, answer, dot_product(question_embedding, answer_embedding) as similarity from embeddings;14 15Example 2:16Q: What are the most similar questions in the embeddings table, not including itself?17A: SELECT q1.question as question1, q2.question as question2,18 DOT_PRODUCT(q1.question_embedding, q2.question_embedding) :> float as score19 FROM embeddings q1, embeddings q220 WHERE q1.question != q2.question21 ORDER BY score DESC LIMIT 5;22 23Example 3:24Q: In the embeddings table, which rows are from the chatbot?25A: SELECT category, question, answer FROM embeddings WHERE category = 'chatbot';26 27If you are asked to describe the database, you should run the query SHOW TABLES.28 29Unless the user specifies a specific number of examples they wish to obtain, always limit your30query to at most {top_k} results. You can order the results by a relevant column to return the31most interesting examples in the database.32 33Never SELECT the question_embedding or answer_embedding columns, and never SELECT * from the34embeddings table: those columns hold 1536-dimension vectors. Compare them with35DOT_PRODUCT(a, b), which returns a single float, and select that instead. Never query for all36the columns from any table, only the columns relevant to the question.37 38You have access to tools for interacting with the database. Only use the below tools, and only39use the information returned by them to construct your final answer. You MUST double check your40query before executing it. If you get an error while executing a query, rewrite the query and41try again up to 3 times.42 43DO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the database.44 45If the question does not seem related to the database, just return "I don't know" as the answer.46"""47 48# Older sqlalchemy-singlestoredb builds ship a VECTOR.result_processor that reads49# self._str_impl — an attribute only SQLAlchemy's JSON type defines, while VECTOR subclasses50# BLOB. Reading a VECTOR column through SQLAlchemy therefore raises AttributeError. Current51# builds set it in __init__; this fills it in when they have not, and is a no-op when they have.52try:53 from sqlalchemy import String as _SAString54 from sqlalchemy_singlestoredb.dtypes import VECTOR as _SAVector55 56 if not hasattr(_SAVector, '_str_impl'):57 _SAVector._str_impl = _SAString()58 print('applied the VECTOR._str_impl compatibility shim')59except ImportError:60 pass # not using the SingleStore SQLAlchemy dialect61 62# Describing `embeddings` by hand stops LangChain running SELECT * on it to collect sample63# rows, which is what actually triggered the bug above, and keeps two 1536-dimension vectors64# out of the prompt. The three data tables still get real samples, which is the part that65# helps the agent write good SQL.66EMBEDDINGS_TABLE_INFO = """67CREATE TABLE embeddings (68 id BIGINT, -- auto increment69 category VARCHAR(255), -- 'chatbot' for rows this notebook writes70 question LONGTEXT,71 question_embedding VECTOR(1536, F32), -- never SELECT this column; compare it instead72 answer LONGTEXT,73 answer_embedding VECTOR(1536, F32), -- never SELECT this column; compare it instead74 created_at DATETIME75)76/* Semantic cache. Compare two vectors with DOT_PRODUCT(a, b), which returns a float. */77"""78 79db = SQLDatabase.from_uri(80 current_connection_url(), # read now, not the possibly-expired startup copy81 include_tables=['embeddings', 'companyInfo', 'financials'],82 sample_rows_in_table_info=2,83 custom_table_info={'embeddings': EMBEDDINGS_TABLE_INFO},84)85 86# Reuse the http_client from step 3 so the agent's calls also skip brotli encoding.87# CHAT_SETTINGS comes from "Choose the models" in step 2. The agent's SQL tools go over the88# Responses API, the only endpoint on which some current models (gpt-6.1-terra among them) call89# tools. The answer then arrives as content blocks, which as_text() below flattens.90llm = ChatOpenAI(model=CHAT_MODEL, http_client=http_client, use_responses_api=True, **CHAT_SETTINGS)91 92agent_executor = create_sql_agent(93 llm=llm,94 toolkit=SQLDatabaseToolkit(db=db, llm=llm),95 agent_type='tool-calling',96 prefix=SQL_AGENT_PREFIX,97 top_k=3,98 max_iterations=5,99 verbose=True,100)101 102 103def as_text(output) -> str:104 """Flatten an agent answer to one string.105 106 On the Responses API, which langchain-openai uses for GPT-6 models, the answer comes back107 as a list of content blocks such as [{'type': 'text', 'text': '...'}] rather than a plain108 string. The embeddings endpoint rejects a list, and the cache should store readable text.109 """110 if isinstance(output, str):111 return output112 if isinstance(output, list):113 parts = []114 for block in output:115 if isinstance(block, str):116 parts.append(block)117 elif isinstance(block, dict) and block.get('type') == 'text':118 parts.append(block.get('text', ''))119 return ''.join(parts)120 return str(output)121 122 123def run_agent(question: str) -> str:124 """Ask the SQL agent a question and return just its answer text."""125 return as_text(agent_executor.invoke({'input': question})['output'])126 127 128print(f'agent ready over tables: {db.get_usable_table_names()}')
Put a semantic cache in front of the agent
This is the idea the demo is built around. An agent run costs several seconds and a few thousand tokens,
and many questions users ask are questions somebody already asked, worded differently. So before paying
for a run: embed the question, look for a stored one pointing in nearly the same direction, and if it
scores above a threshold, return its stored answer. Because the vectors live in the same database as the
data, that lookup is a single DOT_PRODUCT query over a VECTOR column.
process_user_question() below is the whole mechanism, and it prints which path it took.
The similarity threshold is a property of the embedding model. 0.85 is right for
text-embedding-3-small; a number borrowed from a different model can mean the cache silently never
hits and you pay for every answer. The next cell measures it rather than trusting it.
In [15]:
1table_name = 'llm_webinar.embeddings' # named explicitly, like every write in this notebook2# Recalibrated for text-embedding-3-small. 0.97 was carried over from text-embedding-ada-002,3# whose cosine scores sit in a narrow band near the top of the range — unrelated text scored4# ~0.7 there, so 0.97 was a reasonable "nearly the same". The 3-small model spreads scores much5# wider, so the same number now means "almost character-for-character identical" and the cache6# never hits. The calibration cell below measures where paraphrases actually land.7similarity_threshold = 0.858 9 10def to_hex(vector: list[float]) -> str:11 """Pack an embedding as the little-endian float32 bytes a VECTOR(1536, F32) expects."""12 return np.array(vector, dtype='<f4').tobytes().hex()13 14 15def process_user_question(question: str, category: str = 'chatbot') -> str:16 print(f'\nQuestion asked: {question}')17 18 start = time.time()19 question_embedding = get_embeddings([question])[0]20 print(f' embedding the question: {(time.time() - start) * 1000:.0f} ms')21 22 lookup = f"""23 SELECT question, answer,24 DOT_PRODUCT(question_embedding, UNHEX(%(qhex)s)) :> float AS score25 FROM {table_name}26 WHERE category = %(category)s27 ORDER BY score DESC28 LIMIT 129 """30 31 with s2_conn.cursor() as cur:32 start = time.time()33 cur.execute(lookup, {'qhex': to_hex(question_embedding), 'category': category})34 row = cur.fetchone()35 print(f' cache lookup: {(time.time() - start) * 1000:.0f} ms')36 37 if row is not None:38 cached_question, cached_answer, score = row39 print(f' closest stored question: "{cached_question}" (score {score:.4f})')40 41 if score > similarity_threshold:42 print(' -> cache hit, returning the stored answer')43 return cached_answer44 else:45 print(' cache is empty')46 47 print(' -> cache miss, running the agent')48 start = time.time()49 answer = run_agent(question)50 print(f' agent run: {(time.time() - start) * 1000:.0f} ms')51 52 if not answer.strip():53 # Nothing to embed, and an empty answer is not worth caching.54 print(' -> the agent returned no answer text, so nothing was cached')55 return 'The agent did not produce an answer. Try rewording the question.'56 57 answer_embedding = get_embeddings([answer])[0]58 59 insert = f"""60 INSERT INTO {table_name}61 (category, question, question_embedding, answer, answer_embedding, created_at)62 VALUES63 (%(category)s, %(question)s, UNHEX(%(qhex)s), %(answer)s, UNHEX(%(ahex)s),64 %(created_at)s)65 """66 67 with s2_conn.cursor() as cur:68 cur.execute(insert, {69 'category': category,70 'question': question,71 'qhex': to_hex(question_embedding),72 'answer': answer,73 'ahex': to_hex(answer_embedding),74 'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),75 })76 77 return answer
Measure the threshold instead of trusting it
A semantic cache has one tuning knob and two ways to get it wrong. Too high and it never hits. Too low and it returns a stored answer to a question that merely sounds similar — which is worse, because a wrong answer arrives looking exactly like a right one.
So this cell scores a few pairs whose relationship you already know: an identical question, two
rewordings, an unrelated question, and one pair that matters more than the rest. It costs a single
embeddings request. Read the gap between the paraphrases and the unrelated pair — your threshold
belongs inside it. With text-embedding-3-small the rewordings land close to 0.9 and the unrelated
pair well below, which is why 0.85 sits where it does. Trust the numbers the cell prints over any
number written in prose, including these.
The first line of output is a check rather than a result: DOT_PRODUCT equals cosine similarity only
for unit-length vectors, so those norms should print as 1.0.
Watch the last row. Bullish and bearish score close together, because an embedding captures what a sentence is about more strongly than which way round it points — the honest limit of caching on similarity alone.
In [16]:
1# Which similarity a paraphrase actually scores is a property of the embedding model, so this2# measures it rather than trusting a threshold inherited from a different one. Costs one3# embeddings request.4CALIBRATION_PAIRS = [5 ('identical but for a stopword', 'describe the database', 'describe database'),6 ('same question, reworded', 'describe the database', 'what tables are in here?'),7 ('same intent, longer', "what is TSLA's average closing price?",8 'give me the mean close for TSLA'),9 ('unrelated', 'describe the database',10 'which tickers have the most bullish news?'),11 ('OPPOSITE meaning', 'which tickers have the most bullish news?',12 'which tickers have the most bearish news?'),13]14 15texts = sorted({text for _, left, right in CALIBRATION_PAIRS for text in (left, right)})16vectors = dict(zip(texts, get_embeddings(texts)))17 18# DOT_PRODUCT equals cosine similarity only for unit-length vectors. OpenAI's embeddings are19# normalised, which is what lets the SQL lookup use the cheaper DOT_PRODUCT — worth confirming20# rather than assuming, since the scores below would mean something else if it were not true.21norms = [float(np.linalg.norm(v)) for v in vectors.values()]22print(f'vector norms: {min(norms):.4f} to {max(norms):.4f} '23 f'(1.0 means DOT_PRODUCT is cosine similarity)\n')24 25print(f'{"relationship":<30} score hit at {similarity_threshold}?')26 27for label, left, right in CALIBRATION_PAIRS:28 score = float(np.dot(vectors[left], vectors[right]))29 print(f'{label:<30} {score:.4f} {"YES" if score > similarity_threshold else "no"}')30 31print(f'\nsimilarity_threshold is {similarity_threshold}. It wants to sit above the unrelated '32 f'pair and below the rewordings;\nif your numbers differ from the commentary above, trust '33 f'these and adjust it.')
See the cache work
Two questions that mean the same thing, worded differently. The first is a miss: it prints the agent's
whole chain of thought — Entering new SQL Agent Executor chain, the queries it writes, the rows it
gets back — and takes around 8 seconds. The second scores above the threshold and comes straight back
from SingleStore in under a second, nearly all of which is the round trip to embed the question. The
absence of that agent chain on the second question is the entire point: that is the latency, the
tokens and the money saved.
The cell clears the cache first so the demonstration still works on a re-run — otherwise both
questions hit and there is nothing to compare. The SELECT after it shows what got stored.
In [17]:
1question_1 = 'describe the database'2question_2 = 'describe database'3 4# Start from an empty cache, or the demo stops demonstrating anything: on a second run the5# stored copy of question_2 would match itself at 1.0 and "hit" for the wrong reason. Only the6# chatbot rows go — anything else in the table is left alone.7with s2_conn.cursor() as cur:8 cur.execute("DELETE FROM llm_webinar.embeddings WHERE category = 'chatbot'")9 10answer = process_user_question(question_1)11print(f'\nThe answer is: {answer}')
In [18]:
1%%sql2SELECT id, category, question, LEFT(answer, 120) AS answer_start FROM embeddings
Now the second question — the same request worded differently. Expect a cache hit with its score, no agent chain, and a total well under a second.
In [19]:
1answer = process_user_question(question_2)2print(f'\nThe answer is: {answer}')
Step 5: Speak and hear
The agent's answer is text. This step turns it into speech, plays it, and transcribes it back — the
"speak" and "hear" of the title. This cell only defines helpers, so expect no output. speak(text)
writes an mp3 using the speech model chosen in step 2 and returns its path. kernel_value(name)
looks up a notebook variable and returns None if the cell that sets it has not run, so re-running
step 5 on its own after a kernel restart gives you a message naming the cell to run rather than a bare
NameError.
OpenAI is shutting down its separate text-to-speech endpoint on January 6, 2027, so the voice comes from an audio model over the same chat endpoint as everything else. The model is told to read the text aloud word for word, and it returns the audio alongside a transcript of what it said.
In [20]:
1import base642 3from IPython.display import Audio, display4 5 6def kernel_value(name: str):7 """A notebook-level value, or None if the cell that sets it has not run.8 9 Step 5 is the section people re-run on its own — after a kernel restart, or to try a10 different voice — and a restart keeps no variables. Looking the keys up this way lets the11 helpers below say which cell to go back and run, instead of raising a bare NameError from12 somewhere inside themselves.13 """14 return globals().get(name)15 16 17def openai_speak(text: str) -> bytes:18 """mp3 bytes from OpenAI's audio model."""19 openai_client = kernel_value('client')20 21 if openai_client is None:22 raise RuntimeError(23 'No OpenAI client in this kernel. Re-run the "Set your OpenAI key" cell and the cell that '24 'builds `client` in step 2 — a restarted kernel keeps none of its variables.')25 26 speech_model = kernel_value('SPEECH_MODEL')27 28 if speech_model is None:29 raise RuntimeError(30 'No OpenAI speech model is available to this key (see "Choose the models" in step 2). '31 'Check https://developers.openai.com/api/docs/models for a current gpt-audio model and '32 'add it to PREFERRED_SPEECH_MODELS.')33 34 # OpenAI's audio models speak through Chat Completions: ask for audio output, and tell the35 # model to read the text rather than reply to it.36 response = openai_client.chat.completions.create(37 model=speech_model,38 modalities=['text', 'audio'],39 audio={'voice': 'alloy', 'format': 'mp3'},40 messages=[41 {'role': 'system', 'content': (42 "You are a text-to-speech voice. Read the user's message aloud exactly as written, "43 'word for word. Do not answer it, comment on it, or add anything.')},44 {'role': 'user', 'content': text},45 ],46 )47 48 audio = response.choices[0].message.audio49 50 if audio is None or not audio.data:51 raise RuntimeError(52 f'{speech_model} returned no audio for this text, so no file was written. Re-run this '53 'cell to try again; if it keeps happening, check the model in "Choose the models".')54 55 return base64.b64decode(audio.data)56 57 58def speak(text: str, path: str = 'output.mp3') -> str:59 """Synthesize `text` to an mp3 at `path` and return the path."""60 audio_bytes = openai_speak(text)61 62 with open(path, 'wb') as f:63 f.write(audio_bytes)64 65 print(f"OpenAI {kernel_value('SPEECH_MODEL')}, voice alloy, wrote {len(audio_bytes):,} bytes to {path}")66 return path
Now speak the answer the agent produced in step 4, and play it back. Expect a line naming the
engine and voice, the number of bytes written, and an audio player that starts on its own. The
file is output.mp3 in the notebook's working directory.
In [21]:
1audio_path = speak(answer)2display(Audio(filename=audio_path, autoplay=True))
Transcribe it back to text
Reading the audio back with the transcription model chosen in step 2 is the "hear" half. Expect a transcript that closely matches the spoken answer — punctuation and capitalisation will differ, and numbers may come back as words, which is a fair illustration of what transcription does and does not preserve. In a real application the input would be a user speaking; round-tripping here means the notebook has an audio file to work with without asking you for a microphone.
In [22]:
1if kernel_value('TRANSCRIBE_MODEL') is None:2 raise RuntimeError(3 'No OpenAI transcription model is available to this key (see "Choose the models" in step 2). '4 'Check https://developers.openai.com/api/docs/models for a current transcription model and '5 'add it to PREFERRED_TRANSCRIBE_MODELS.')6 7with open(audio_path, 'rb') as audio_file:8 transcript = client.audio.transcriptions.create(model=TRANSCRIBE_MODEL, file=audio_file)9 10print(transcript.text)
Step 6: See
The last modality. This step draws a chart straight from the financials rows and hands the picture
to a vision model to describe — the way you would write alt text for a chart in a report. Because the
chart is made from rows you can query, you can check the model's description against the numbers:
the image and the data describing it come from the same table. Three cells: ask the agent a question
about growth, draw the chart, describe it. Then one more to speak the description using step 5's
speak().
No new dependency and no new account: the vision model is the same OpenAI client from step 2, and describing an image is one extra content part in an ordinary chat request.
Ask the agent about growth
A third question for the agent: which company grew revenue fastest over the past year. Expect an agent
run — a cache miss, since the question is new — and an answer with three percentages. The %%sql cell
after it computes the same growth figures directly, so you can check the agent's arithmetic.
In [23]:
1question_3 = (2 'Compare each company\'s revenue in its latest quarter with the same quarter a year earlier. '3 'Which company grew fastest, and by what percentage did each of them grow?'4)5 6answer = process_user_question(question_3)7print(f'\nThe answer is: {answer}')
In [24]:
1%%sql2SELECT latest.ticker,3 latest.fiscal_year, latest.fiscal_quarter,4 ROUND(100 * (latest.revenue - prior.revenue) / prior.revenue, 1) AS revenue_growth_pct5FROM financials latest6JOIN financials prior7 ON prior.ticker = latest.ticker8 AND prior.fiscal_quarter = latest.fiscal_quarter9 AND prior.fiscal_year = latest.fiscal_year - 110WHERE latest.period_end = (SELECT MAX(period_end) FROM financials)11ORDER BY revenue_growth_pct DESC
Draw the chart
Expect a line chart: one line per company, revenue each quarter as a multiple of where it stood in Q1 2023. Indexing them is what makes them comparable — Amazon's revenue is about a hundred times Palantir's, so on a plain dollar axis Palantir would be a flat line along the bottom.
The chart is rendered to PNG bytes in memory and shown from those bytes, the same bytes the next cell sends to the vision model. Nothing is fetched from the internet.
In [25]:
1import base642 3from IPython.display import HTML, display4 5try:6 import matplotlib7 8 matplotlib.use('Agg') # render to memory, not to a window9 import matplotlib.pyplot as plt10except ImportError as exc:11 raise RuntimeError('matplotlib is not installed in this kernel. Re-run the %pip install cell '12 'at the top of the notebook, then re-run this one.') from exc13 14with s2_conn.cursor() as cur:15 cur.execute("""16 SELECT f.ticker, c.name, f.period_end, f.revenue17 FROM financials f JOIN companyInfo c ON c.ticker = f.ticker18 ORDER BY f.ticker, f.period_end19 """)20 chart_rows = cur.fetchall()21 22assert chart_rows, 'financials is empty. Run the load cell in step 3 first.'23 24fig, ax = plt.subplots(figsize=(8, 4.5), dpi=120)25 26for ticker in sorted({row[0] for row in chart_rows}):27 series = [row for row in chart_rows if row[0] == ticker]28 base = series[0][3] # first quarter's revenue, so every line starts at 1.029 ax.plot([row[2] for row in series], [row[3] / base for row in series],30 marker='o', markersize=3, label=f'{ticker} ({series[0][1]})')31 32ax.set_title('Quarterly revenue, as a multiple of Q1 2023')33ax.set_ylabel('Revenue relative to Q1 2023')34ax.axhline(1.0, color='grey', linewidth=0.8, linestyle='--')35ax.legend(loc='upper left')36ax.grid(alpha=0.3)37fig.tight_layout()38 39buffer = io.BytesIO()40fig.savefig(buffer, format='png')41plt.close(fig)42 43chart_png = buffer.getvalue()44chart_data_url = 'data:image/png;base64,' + base64.b64encode(chart_png).decode('ascii')45 46display(HTML(f'<img src="{chart_data_url}" alt="Quarterly revenue chart" style="max-width: 100%">'))47print(f'{len(chart_png):,} bytes of PNG')
Describe the chart
Expect a few sentences describing the chart, in the style of alt text, after a few seconds. Compare it
with the chart above and the growth figures from the %%sql cell: a good description names which line
climbs fastest and roughly how far, and should agree with the rows.
The image goes to the model in the same message as the instruction, as the base64 data: URL the
previous cell built. That is the general pattern for images a kernel holds — there is no public URL for
OpenAI to fetch, and none is needed.
In [26]:
1response = client.chat.completions.create(2 model=CHAT_MODEL,3 messages=[{4 'role': 'user',5 'content': [6 {7 'type': 'text',8 'text': (9 'Describe this chart in three or four sentences, as you would for a screen '10 'reader: what it measures, and the overall trend of each line, with rough '11 'values read from the axis. Describe only what the chart shows.'12 ),13 },14 {'type': 'image_url', 'image_url': {'url': chart_data_url}},15 ],16 }],17 # With CHAT_SETTINGS empty the model may reason first, and reasoning counts against this cap.18 max_completion_tokens=250 if CHAT_SETTINGS else 4000,19 **CHAT_SETTINGS,20)21 22caption = response.choices[0].message.content23print(caption)
Finally, speak the caption with the same speak() helper from step 5, writing caption.mp3 this
time so the answer's audio is still there to compare. All four modalities have now been through one
database: rows in, question in English, answer spoken, image seen and described.
In [27]:
1caption_path = speak(caption, path='caption.mp3')2display(Audio(filename=caption_path, autoplay=True))
Troubleshooting
The errors worth knowing about before you need them. The two marked lies about its cause are the reason this table exists.
| What you see | What it means | What to do |
| --- | --- | --- |
| NameError or ModuleNotFoundError | The cell that defines it has not run in this kernel; a restart keeps no variables | Re-run step 2 from the top |
| OperationalError: 2628: JWT token expired | The connection URL's password is a JWT that lasts about an hour | Restart the kernel, which gets a fresh token |
| no database is selected, or missing tables | The drop-down at the top points somewhere other than llm_webinar | Select the database, re-run step 1, then the connect cell |
| Lies about its cause: APIConnectionError under a successful HTTP/1.1 200 OK | Not the network and not your key — a brotli decoder failed after the response arrived | Re-run the OpenAI client cell in step 2, which turns brotli off |
| Lies about its cause: the cache never hits, and nothing errors | The similarity threshold does not match the embedding model | Run the calibration cell in step 4 and use the measured gap |
| AttributeError: 'VECTOR' object has no attribute '_str_impl' | A SQLAlchemy-only bug in some builds of the SingleStore dialect | Re-run the agent cell in step 4, which patches it in |
What you built
One database, four modalities. Three years of company financials went into SingleStore; a question asked in English came back answered; the answer was spoken and heard again as text; and a chart drawn from those rows was described in a sentence grounded in the row beside it.
None of it needed a second datastore. The cache lookup in step 4 is a SELECT with a DOT_PRODUCT
against the same tables the agent queries — no export, no sync job, and because the cache is just a
table, you can SELECT from it to see why it hit.
Reset the demo
The cell below drops the llm_webinar database — tables, rows, cache and all. Step 1 also drops
and recreates tables, but only inside llm_webinar; this is the cell that removes everything.
Coming back afterwards costs nothing, in this order: run step 1 to recreate the database and its
tables, select llm_webinar in the drop-down, run the connect cell in step 2, then the two load cells
in step 3. To start the demo over without touching the data, re-run the cache test in step 4 instead.
In [28]:
1%%sql2DROP DATABASE IF EXISTS llm_webinar;

Details
About this Template
Using OpenAI to build an app that can take images, audio, and text data to generate output
This Notebook can be run in Standard and Enterprise deployments.
Tags
See Notebook in action
Launch this notebook in SingleStore and start executing queries instantly.
License
This Notebook has been released under the Apache 2.0 open source license.