A short and sharp into to running AI workloads on CockroachDB
Required binaries
- The cockroach binary
- A service account API key with
Cluster AdminandCluster Creatorroles
- A service account API key with
Optional binaries
- The docker binary (to install CockroachDB via
docker compose)
Export env vars (specific to Rob's machine, will need changing for yours)
export OPENAI_API_KEY=$(op read "op://Personal/dc32nhj7sjnqs2ggzp4t3tah5u/api key")
export COCKROACH_API_KEY=$(op read "op://Personal/474wdyiiobdurkdhiffzyavtku/API Keys/devrel-demos")
export AWS_PROFILE="rob-sso"Create cluster
cockroach start-single-node \
--insecure \
--listen-addr localhost:26257 \
--http-addr localhost:8080 \
--backgroundCreate cluster
docker compose -f compose.yml up -d
docker exec -it node1 cockroach init --insecureCreate cluster
cockroach demo \
--insecure \
--no-example-database \
--nodes 9 \
--demo-locality=region=aws-eu-west-1,az=a:region=aws-eu-west-1,az=b:region=aws-eu-west-1,az=c:region=aws-eu-west-2,az=a:region=aws-eu-west-2,az=b:region=aws-eu-west-2,az=c:region=aws-eu-central-1,az=a:region=aws-eu-central-1,az=b:region=aws-eu-central-1,az=cCreate cluster
response=$(curl -s https://cockroachlabs.cloud/api/v1/clusters \
-H "Authorization: Bearer ${COCKROACH_API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "crdb-ai-zero-to-hero",
"provider": "AWS",
"plan": "basic",
"spec": {
"serverless": {
"regions": [
"us-east-1",
"eu-central-1",
"ap-southeast-1"
],
"primary_region": "eu-central-1"
}
}
}')
export CLI_CLUSTER_ID=$(echo "$response" | jq -r .id)
pass=$(pa55 --out hex --len 20 --print)
export CLI_CRDB_HOST=$(echo "$response" | jq -r '.sql_dns')
export CLI_CRDB_URL="postgres://rob:${pass}@${CLI_CRDB_HOST}:26257/defaultdb?sslmode=verify-full"Check cluster state (wait for CREATED)
curl -s "https://cockroachlabs.cloud/api/v1/clusters/${CLI_CLUSTER_ID}" \
-H "Authorization: Bearer ${COCKROACH_API_KEY}" | jq .state -rCreate user
curl -s "https://cockroachlabs.cloud/api/v1/clusters/${CLI_CLUSTER_ID}/sql-users" \
-H "Authorization: Bearer ${COCKROACH_API_KEY}" \
--json "{ \"name\": \"rob\", \"password\": \"${pass}\" }"Connect
cockroach sql --url ${CLI_CRDB_URL} --set "prompt1 %/>"Initialise
(cd infra && terraform init)Apply
(cd infra && terraform apply --auto-approve)Connect
export TF_CRDB_URL=$(cd infra && terraform output --raw cockroachdb_url)
cockroach sql --url ${TF_CRDB_URL} --set "prompt1 %/>"Fetch Python dependencies
python3 -m pip install \
langchain \
langchain-core \
langchain-postgres \
langchain-openai \
langgraph \
langgraph-checkpoint-postgres \
"psycopg[binary]"Create table
CREATE TABLE IF NOT EXISTS "chat_history" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"session_id" STRING NOT NULL,
"message" JSONB NOT NULL,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT now()
) WITH (
ttl_expiration_expression = $$("created_at" + '1 day')$$,
ttl_job_cron = '@hourly'
);Run application
python3 -W ignore app/memory/memory.py --db-url ${TF_CRDB_URL}I'm Rob Reid and I'm Cockroach Labs' Technical Evangelist. What's my name and the name of my company? What do you get if you mix red and blue? What do you get if you mix red and yellow? What do you get if you mix blue and yellow? What do you get if you mix red and green? What do you get if you mix blue and orange? What's my name and the name of my company?
View conversation history
SELECT
LEFT(h.session_id, 7) || '...' AS session_id,
LEFT(h.message->'data'->>'content', 50) AS response,
h.message->'data'->>'type' AS participant,
h.message->'data'->'response_metadata'->'token_usage'->>'total_tokens' AS total_tokens
FROM chat_history h
ORDER BY h.created_at, participant DESC;Pick up a past conversation
python3 app/memory/memory.py \
--db-url ${TF_CRDB_URL} \
--session-id 6cd8436d-5cac-422e-a43f-fdc594732d44Create table
CREATE TABLE social_post (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"value" TEXT NOT NULL,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT now(),
"embedding" VECTOR(512) NOT NULL,
VECTOR INDEX ("embedding")
);Run application
export EMBEDDING_API_KEY=$(op read "op://Personal/Takara DS1/embedding api key")
go run app/embeddings/main.go embed \
--db-url "${TF_CRDB_URL}" \
--embed-api-key "${EMBEDDING_API_KEY}" \
--flush-size 32 \
--flush-interval 250msQuery for similar posts
go run app/embeddings/main.go query \
--db-url "${TF_CRDB_URL}" \
--embed-api-key "${EMBEDDING_API_KEY}" \
--top-n 5What's currently happening with Greenland? What happened to Bonnie Tyler? US/Iran military conflict Extreme heatwave Cybersecurity hacking data breach
Reconnect to CLI cluster after closing terminal.
# Set CLUSTER_ID.
export CLUSTER_ID=$(curl -s https://cockroachlabs.cloud/api/v1/clusters \
-H "Authorization: Bearer ${COCKROACH_API_KEY}" \
| jq -r '.clusters[] | select(.name == "crdb-ai-zero-to-hero") | .id')
# Reset password for rob user.
pass=$(pa55 --out hex --len 20 --print)
curl -X PUT \
--url "https://cockroachlabs.cloud/api/v1/clusters/${CLUSTER_ID}/sql-users/rob/password" \
-H "Authorization: Bearer ${COCKROACH_API_KEY}" \
--json "{ \"password\": \"${pass}\" }"
# Set CRDB_HOST and CRDB_URL.
export CRDB_HOST=$(curl -s "https://cockroachlabs.cloud/api/v1/clusters/${CLUSTER_ID}" \
-H "Authorization: Bearer ${COCKROACH_API_KEY}" \
| jq -r '.sql_dns')
export CRDB_URL="postgres://rob:${pass}@${CRDB_HOST}:26257/defaultdb?sslmode=verify-full"Reconnect to Terraform cluster after closing terminal.
export CRDB_URL=$(cd infra && terraform output --raw cockroachdb_url)Read all social posts into a file
cockroach sql --url ${TF_CRDB_URL} -e "SELECT value FROM social_post" --format csv > social_posts.csvReset LangChain tables
cockroach sql --url ${TF_CRDB_URL} -e "DROP TABLE IF EXISTS checkpoint_writes, checkpoints, checkpoint_blobs, checkpoint_migrations;"Reset demo tables
cockroach sql --url ${TF_CRDB_URL} -e "DROP TABLE IF EXISTS chat_history, social_post;"