Skip to content

Commit 8d6c648

Browse files
authored
Merge pull request #3845 from BrentOzarULTD/3670_AI_starting_point_script
#3670 AI starting point script
2 parents 99ca4c7 + e45cea4 commit 8d6c648

2 files changed

Lines changed: 222 additions & 6 deletions

File tree

Documentation/Using-AI.sql

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
/* You can put the configuration tables in any database, and I personally
2+
prefer using a DBA utility database for this. I usually put the First Responder
3+
Kit stored procs in the master database so that I can refer to 'em from any
4+
database, but these tables will have prompts and configs that you worked hard
5+
to build, and you're probably going to want to restore them if something goes
6+
wrong, plus you may want to replicate them to other servers.
7+
8+
I'm going to use DBAtools, but you can use another name if you want: */
9+
USE DBAtools;
10+
GO
11+
12+
/* Add a list of AI providers: */
13+
CREATE TABLE dbo.Blitz_AI_Providers
14+
(Id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
15+
Model_Nickname NVARCHAR(200),
16+
AI_Model NVARCHAR(100),
17+
AI_URL NVARCHAR(500),
18+
AI_Database_Scoped_Credential_Name NVARCHAR(500),
19+
AI_Parameters NVARCHAR(4000),
20+
Payload_Template NVARCHAR(4000),
21+
Timeout_Seconds TINYINT,
22+
Context INT,
23+
Default_Model BIT DEFAULT 0);
24+
25+
/* OpenAI - fast, cheap model, default: */
26+
INSERT INTO dbo.Blitz_AI_Providers (Model_Nickname, AI_Model, AI_URL, AI_Database_Scoped_Credential_Name, Timeout_Seconds, Default_Model)
27+
VALUES (N'ChatGPT Fast', N'gpt-5-nano', N'https://api.openai.com/v1/chat/completions',
28+
N'https://api.openai.com/', 60, 1);
29+
30+
/* OpenAI - highest quality, slowest, most expensive model: */
31+
INSERT INTO dbo.Blitz_AI_Providers (Model_Nickname, AI_Model, AI_URL, AI_Database_Scoped_Credential_Name, Timeout_Seconds, Default_Model)
32+
VALUES (N'ChatGPT Slow', N'gpt-5.4', N'https://api.openai.com/v1/chat/completions',
33+
N'https://api.openai.com/', 230, 0);
34+
35+
/* Gemini - fast, cheap model: */
36+
INSERT INTO dbo.Blitz_AI_Providers (Model_Nickname, AI_Model, AI_URL, AI_Database_Scoped_Credential_Name, Timeout_Seconds, Default_Model)
37+
VALUES (N'Gemini Fast', N'gemini-3-flash-preview', N'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent',
38+
N'https://generativelanguage.googleapis.com/', 60, 0);
39+
40+
/* Gemini - highest quality, slowest, most expensive model: */
41+
INSERT INTO dbo.Blitz_AI_Providers (Model_Nickname, AI_Model, AI_URL, AI_Database_Scoped_Credential_Name, Timeout_Seconds, Default_Model)
42+
VALUES (N'Gemini Slow', N'gemini-3-1-pro-preview', N'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent',
43+
N'https://generativelanguage.googleapis.com/', 230, 0);
44+
45+
46+
/* Create a default set of prompts: */
47+
CREATE TABLE dbo.Blitz_AI_Prompts
48+
(Id INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
49+
Prompt_Nickname NVARCHAR(200),
50+
AI_System_Prompt NVARCHAR(4000),
51+
Default_Prompt BIT DEFAULT 0);
52+
53+
INSERT INTO dbo.Blitz_AI_Prompts (Prompt_Nickname, Default_Prompt, AI_System_Prompt)
54+
VALUES ('sp_BlitzCache Default', 1, 'You are a very senior database developer working with Microsoft SQL Server and Azure SQL DB. You focus on real-world, actionable advice that will make a big difference, quickly. You value everyone''s time, and while you are friendly and courteous, you do not waste time with pleasantries or emoji because you work in a fast-paced corporate environment.
55+
56+
You have a query that isn''t performing to end user expectations. You have been tasked with making serious improvements to it, quickly. You are not allowed to change server-level settings or make frivolous suggestions like updating statistics. Instead, you need to focus on query changes or index changes.
57+
58+
Do not offer followup options: the customer can only contact you once, so include all necessary information, tasks, and scripts in your initial reply. Render your output in Markdown, as it will be shown in plain text to the customer.');
59+
60+
INSERT INTO dbo.Blitz_AI_Prompts (Prompt_Nickname, Default_Prompt, AI_System_Prompt)
61+
VALUES ('sp_BlitzCache Index Tuning', 0, 'You are a very senior database developer working with Microsoft SQL Server and Azure SQL DB. You focus on real-world, actionable advice that will make a big difference, quickly. You value everyone''s time, and while you are friendly and courteous, you do not waste time with pleasantries or emoji because you work in a fast-paced corporate environment.
62+
63+
You have a query that isn''t performing to end user expectations. You have been tasked with making serious improvements to it, quickly, but you are only allowed to make index changes. You are not allowed to make changes to the query, server-level settings, database settings, etc.
64+
65+
Do not offer followup options: the customer can only contact you once, so include all necessary information, tasks, and scripts in your initial reply. Render your output in Markdown, as it will be shown in plain text to the customer.');
66+
67+
INSERT INTO dbo.Blitz_AI_Prompts (Prompt_Nickname, Default_Prompt, AI_System_Prompt)
68+
VALUES ('sp_BlitzCache Deadlock Tuning', 0, 'You are a very senior database developer working with Microsoft SQL Server and Azure SQL DB. You focus on real-world, actionable advice that will make a big difference, quickly. You value everyone''s time, and while you are friendly and courteous, you do not waste time with pleasantries or emoji because you work in a fast-paced corporate environment.
69+
70+
You have a query that is experiencing deadlocks and blocking. You have been tasked with making serious improvements to it, quickly. You are not allowed to change server-level or database-level settings nor make frivolous suggestions like updating statistics. Instead, you need to focus on query changes or index changes that will reduce blocking and deadlocks.
71+
72+
Do not offer followup options: the customer can only contact you once, so include all necessary information, tasks, and scripts in your initial reply. Render your output in Markdown, as it will be shown in plain text to the customer.');
73+
74+
INSERT INTO dbo.Blitz_AI_Prompts (Prompt_Nickname, Default_Prompt, AI_System_Prompt)
75+
VALUES ('sp_BlitzCache Modernize', 0, 'You are a very senior database developer working with Microsoft SQL Server and Azure SQL DB. You focus on real-world, actionable advice that will make a big difference, quickly. You value everyone''s time, and while you are friendly and courteous, you do not waste time with pleasantries or emoji because you work in a fast-paced corporate environment.
76+
77+
You have been given a legacy query that needs to be modernized. Our goals are to make the query run faster, make it easier to understand, easier to maintain, and to take advantage of new features up to and including SQL Server 2025. You have been tasked with making serious improvements to it, quickly, without touching server-level settings, database-level settings, indexes, or statistics.
78+
79+
Do not offer followup options: the customer can only contact you once, so include all necessary information, tasks, and scripts in your initial reply. Render your output in Markdown, as it will be shown in plain text to the customer.');
80+
GO
81+
82+
83+
84+
85+
/* Now switch over to the user database where you'll be tuning: */
86+
USE StackOverflow;
87+
GO
88+
89+
/* Create a master key for the database to allow for encryption of your AI
90+
provider keys: */
91+
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'SomeStrongPassword!123';
92+
93+
/* If you've already got one, you can just open it instead: */
94+
OPEN MASTER KEY DECRYPTION BY PASSWORD = 'SomeStrongPassword!123';
95+
96+
/* Turn on API calls - remember, this only works in SQL Server 2025 or newer :*/
97+
EXEC sp_configure 'external rest endpoint enabled', 1;
98+
RECONFIGURE WITH OVERRIDE;
99+
GO
100+
101+
102+
/* Go get API keys for OpenAI or Gemini (or both), and then copy/paste them
103+
into the secrets below. */
104+
CREATE DATABASE SCOPED CREDENTIAL [https://api.openai.com/]
105+
WITH IDENTITY = 'HTTPEndpointHeaders',
106+
SECRET = '{"Authorization":"Bearer YourChatGPTKeyGoesHere"}';
107+
GO
108+
/* Note that in the ChatGPT example above, you have to leave the "Bearer "
109+
string, including a space after the word Bearer, then paste your key over
110+
the string "YourChatGPTKeyGoesHere". */
111+
112+
CREATE DATABASE SCOPED CREDENTIAL [https://generativelanguage.googleapis.com/]
113+
WITH IDENTITY = 'HTTPEndpointHeaders',
114+
SECRET = N'{"x-goog-api-key":"YourGeminiKeyGoesHere"}';
115+
GO
116+
117+
118+
119+
/* Grant permissions for that credential to your DBA group,
120+
or developers, or whoever you want to grant it to. I'm going
121+
to create a new database role: */
122+
CREATE ROLE [DBA_AI];
123+
GO
124+
/* Add users to that role if necessary - you're in it already: */
125+
ALTER ROLE [DBA_AI] ADD MEMBER [MyBestFriend];
126+
GO
127+
128+
/* Let the role use the credential, so only our friends
129+
can run up charges on our API keys: */
130+
GRANT REFERENCES ON DATABASE SCOPED CREDENTIAL::[https://api.openai.com/] TO [DBA_AI];
131+
GO
132+
GRANT REFERENCES ON DATABASE SCOPED CREDENTIAL::[https://generativelanguage.googleapis.com/] TO [DBA_AI];
133+
GO
134+
135+
136+
/* Test ChatGPT with an API call using the ChatGPT defaults.
137+
This will take 30-60 seconds: */
138+
sp_BlitzCache @Top = 1, @AI = 1
139+
GO
140+
141+
/* Or if you used Gemini, use this, pointed at your config table: */
142+
sp_BlitzCache @AI = 1, @Top = 1,
143+
@AIConfigTable = 'DBAtools.dbo.Blitz_AI_Providers',
144+
@AIModel = 'gemini-3-flash-preview';
145+
GO
146+
147+
/* Scroll across to the AI Advice column, and make sure you got advice.
148+
149+
If you got an error, read it. If it's a timeout, that's fine, your query was
150+
too complex for the default fast model to digest in the time allowed.
151+
152+
If it's any other error, read it - it's likely a configuration error or a
153+
network connectivity error if your firewall is blocking the SQL Server's access
154+
to the internet, which is fair. No hate there.
155+
*/
156+
157+
158+
159+
160+
/* OPTIONAL: Getting Better Advice
161+
162+
Add a database-level extended property with your company's code standards.
163+
Don't worry too much about formatting - you can copy/paste it straight out of
164+
any standards doc you've got - but keep it to a couple pages or less.
165+
166+
Everything you add in here gets sent to AI with each request, and the more text
167+
in here, the longer it'll take (and the more it'll cost) for each request. */
168+
EXECUTE sp_addextendedproperty
169+
@name = N'CONSTITUTION.md',
170+
@value = N'Any objects and T-SQL in this database must comply with the organizational standards and guidelines outlined in this constitution document.
171+
172+
## Object Naming Standards
173+
174+
Views must always be prefixed with vw_.
175+
Tables should never be prefixed with tbl_.
176+
Table and column names should be in PascalCase with a capitalized first letter, like UserProperties or SalesByMonth.
177+
Index names should be based on the key columns in the index. If the index has include columns, add an _inc suffix to the index name.
178+
Index names should never be prefixed with table names, idx_, ix_, or any variation thereof.
179+
180+
## Query Standards
181+
182+
Queries should be written in a concise, easy-to-understand, performant way.
183+
Queries should prefer CTEs over temp tables unless that presents a performance issue for the query.';
184+
GO
185+
/* You can only have one Constitution per database. You can update it, which
186+
writes over the existing content: */
187+
EXECUTE sp_updateextendedproperty
188+
@name = N'CONSTITUTION.md',
189+
@value = N'These are our new, much better standards...';
190+
GO
191+
192+
/* Or you can drop it: */
193+
EXEC sp_dropextendedproperty
194+
@name = N'CONSTITUTION.md';
195+
GO
196+

Documentation/Using_AI.md

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ sp_BlitzCache and sp_BlitzIndex can build AI prompts with your query and index d
55
- **`@AI = 2`** - Builds the AI prompt and returns it in the result set so you can copy/paste it into ChatGPT, Gemini, or another AI tool. Works on all supported versions of SQL Server and Azure SQL DB, no setup required.
66
- **`@AI = 1`** - Does everything `@AI = 2` does, plus calls the AI API directly from SQL Server and returns advice in the result set. Requires SQL Server 2025 or Azure SQL DB (uses `sp_invoke_external_rest_endpoint`).
77

8+
If you want a single script that will walk you through the setup (which does still require your intervention for stuff like API keys), check out the [Using_AI.sql](Using_AI.sql) file.
9+
810
## Getting Started: Generate Prompts with @AI = 2
911

1012
The fastest way to try the AI features is `@AI = 2`. No credentials, no config tables, no API keys - just run the proc and copy the prompt into your favorite AI tool. (We named this AI = 2 because in the really long term - like a decade from now - we expect everybody to be on SQL Server 2025 or Azure SQL DB, and they'll just use AI = 1.)
@@ -131,13 +133,20 @@ EXECUTE sp_addextendedproperty
131133

132134
To have SQL Server call the AI API directly, you need database-scoped credentials and (optionally) configuration tables.
133135

134-
### Enable External REST Endpoints (SQL Server 2025 only)
136+
**Important Note:** Your database context is about to matter, a LOT. When you use @AI = 1, and we call your AI provider for you, we need access to your API keys. The way Microsoft does database security, those keys have to be set up in whatever database where you'll be running the FRK scripts from. Not where they're *installed*, but your *database context* when you execute them.
135137

136-
```sql
137-
/* Not needed on Azure SQL DB */
138-
EXEC sp_configure 'external rest endpoint enabled', 1;
139-
RECONFIGURE WITH OVERRIDE;
140-
```
138+
For example, if you're not using @AI = 1, you might install the procs in the master database, and then run them from any database. But once you turn on @AI = 1, the context matters:
139+
140+
* If you're in the StackOverflow database, and you run sp_BlitzIndex @AI = 1, then the keys need to be in the StackOverflow Database
141+
* If you're in the DBAtools database, and you run sp_BlitzIndex @DatabaseName = 'StackOverflow', @AI = 1, then the keys need to be in the DBAtools database
142+
* If you're in the DBAtools database, and you run sp_BlitzIndex @GetAllDatabases = 1, @AI = 1, then the keys only need to be in the DBAtools database
143+
144+
So you have to make an executive decision about how you want to run the FRK scripts with @AI = 1. There are two ways you could do this:
145+
146+
* Set up the key, credential, and role in a utility database like DBAtools, and always call the FRK procs from there when you want to call AI providers for advice, or
147+
* Set up the key, credential, and role in every user database, and run the FRK scripts from anywhere without concern.
148+
149+
Either way, follow the next few steps in every database where you want to run @AI = 1.
141150

142151
### Create a Master Key
143152

@@ -175,6 +184,17 @@ GRANT REFERENCES ON DATABASE SCOPED CREDENTIAL::[https://api.openai.com/] TO [DB
175184
GRANT REFERENCES ON DATABASE SCOPED CREDENTIAL::[https://generativelanguage.googleapis.com/] TO [DBA_AI];
176185
```
177186

187+
**Repeat the above key, credential, and access steps for all databases where you'll run the FRK procs from with the @AI = 1 parameter on.**
188+
189+
### Enable External REST Endpoints
190+
191+
You only have to do this once, and it takes effect at the server level. It's required in SQL Server 2025 or newer, but not necessary in some flavors of Azure SQL DB.
192+
193+
```sql
194+
EXEC sp_configure 'external rest endpoint enabled', 1;
195+
RECONFIGURE WITH OVERRIDE;
196+
```
197+
178198
### Configuration Tables (Optional)
179199

180200
You can create configuration tables to store AI provider settings and prompt templates. This avoids passing parameters every time and lets you switch between providers easily. If you don't create these tables, the procs use built-in defaults (OpenAI gpt-5-nano).

0 commit comments

Comments
 (0)