MikeTerekhov commited on
Commit
6be6272
·
verified ·
1 Parent(s): 6cb0a90

Create demo_rag.py

Browse files
Files changed (1) hide show
  1. demo_rag.py +260 -0
demo_rag.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForCausalLM
2
+ from rag_metadata import SQLMetadataRetriever
3
+ import torch
4
+ import time
5
+
6
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
+
8
+ # Load tokenizer and model
9
+ tokenizer = AutoTokenizer.from_pretrained("./deepseek-coder-1.3b-instruct")
10
+ model = AutoModelForCausalLM.from_pretrained("./deepseek-coder-1.3b-instruct", torch_dtype=torch.bfloat16, device_map=device)
11
+
12
+ # Initialize RAG and add schema docs
13
+ retriever = SQLMetadataRetriever()
14
+ metadata_docs2 = [
15
+ "Table team: columns are id (Unique team identifier), full_name (Full team name, e.g., 'Los Angeles Lakers'), abbreviation (3-letter team code, e.g., 'LAL'), city, state, year_founded.",
16
+ "Table game: columns are game_date (Date of the game), team_id_home, team_id_away (Unique IDs of home and away teams), team_name_home, team_name_away (Full names of the teams), pts_home, pts_away (Points scored), wl_home (W/L result), reb_home, reb_away (Total rebounds), ast_home, ast_away (Total assists), fgm_home, fg_pct_home (Field goals), fg3m_home (Three-pointers), ftm_home (Free throws), tov_home (Turnovers), and other game-related statistics."
17
+ ]
18
+ metadata_docs = [
19
+ '''team Table
20
+ Stores information about NBA teams.
21
+ CREATE TABLE IF NOT EXISTS "team" (
22
+ "id" TEXT PRIMARY KEY, -- Unique identifier for the team
23
+ "full_name" TEXT, -- Full official name of the team (e.g., "Los Angeles Lakers")
24
+ "abbreviation" TEXT, -- Shortened team name (e.g., "LAL")
25
+ "nickname" TEXT, -- Commonly used nickname for the team (e.g., "Lakers")
26
+ "city" TEXT, -- City where the team is based
27
+ "state" TEXT, -- State where the team is located
28
+ "year_founded" REAL -- Year the team was established
29
+ );''',
30
+ '''
31
+ game Table
32
+ Contains detailed statistics for each NBA game, including home and away team performance.
33
+ CREATE TABLE IF NOT EXISTS "game" (
34
+ "season_id" TEXT, -- Season identifier, formatted as "2YYYY" (e.g., "21970" for the 1970 season)
35
+ "team_id_home" TEXT, -- ID of the home team (matches "id" in team table)
36
+ "team_abbreviation_home" TEXT, -- Abbreviation of the home team
37
+ "team_name_home" TEXT, -- Full name of the home team
38
+ "game_id" TEXT PRIMARY KEY, -- Unique identifier for the game
39
+ "game_date" TIMESTAMP, -- Date the game was played (YYYY-MM-DD format)
40
+ "matchup_home" TEXT, -- Matchup details including opponent (e.g., "LAL vs. BOS")
41
+ "wl_home" TEXT, -- "W" if the home team won, "L" if they lost
42
+ "min" INTEGER, -- Total minutes played in the game
43
+ "fgm_home" REAL, -- Field goals made by the home team
44
+ "fga_home" REAL, -- Field goals attempted by the home team
45
+ "fg_pct_home" REAL, -- Field goal percentage of the home team
46
+ "fg3m_home" REAL, -- Three-point field goals made by the home team
47
+ "fg3a_home" REAL, -- Three-point attempts by the home team
48
+ "fg3_pct_home" REAL, -- Three-point field goal percentage of the home team
49
+ "ftm_home" REAL, -- Free throws made by the home team
50
+ "fta_home" REAL, -- Free throws attempted by the home team
51
+ "ft_pct_home" REAL, -- Free throw percentage of the home team
52
+ "oreb_home" REAL, -- Offensive rebounds by the home team
53
+ "dreb_home" REAL, -- Defensive rebounds by the home team
54
+ "reb_home" REAL, -- Total rebounds by the home team
55
+ "ast_home" REAL, -- Assists by the home team
56
+ "stl_home" REAL, -- Steals by the home team
57
+ "blk_home" REAL, -- Blocks by the home team
58
+ "tov_home" REAL, -- Turnovers by the home team
59
+ "pf_home" REAL, -- Personal fouls by the home team
60
+ "pts_home" REAL, -- Total points scored by the home team
61
+ "plus_minus_home" INTEGER, -- Plus/minus rating for the home team
62
+ "video_available_home" INTEGER, -- Indicates whether video is available (1 = Yes, 0 = No)
63
+ "team_id_away" TEXT, -- ID of the away team
64
+ "team_abbreviation_away" TEXT, -- Abbreviation of the away team
65
+ "team_name_away" TEXT, -- Full name of the away team
66
+ "matchup_away" TEXT, -- Matchup details from the away team’s perspective
67
+ "wl_away" TEXT, -- "W" if the away team won, "L" if they lost
68
+ "fgm_away" REAL, -- Field goals made by the away team
69
+ "fga_away" REAL, -- Field goals attempted by the away team
70
+ "fg_pct_away" REAL, -- Field goal percentage of the away team
71
+ "fg3m_away" REAL, -- Three-point field goals made by the away team
72
+ "fg3a_away" REAL, -- Three-point attempts by the away team
73
+ "fg3_pct_away" REAL, -- Three-point field goal percentage of the away team
74
+ "ftm_away" REAL, -- Free throws made by the away team
75
+ "fta_away" REAL, -- Free throws attempted by the away team
76
+ "ft_pct_away" REAL, -- Free throw percentage of the away team
77
+ "oreb_away" REAL, -- Offensive rebounds by the away team
78
+ "dreb_away" REAL, -- Defensive rebounds by the away team
79
+ "reb_away" REAL, -- Total rebounds by the away team
80
+ "ast_away" REAL, -- Assists by the away team
81
+ "stl_away" REAL, -- Steals by the away team
82
+ "blk_away" REAL, -- Blocks by the away team
83
+ "tov_away" REAL, -- Turnovers by the away team
84
+ "pf_away" REAL, -- Personal fouls by the away team
85
+ "pts_away" REAL, -- Total points scored by the away team
86
+ "plus_minus_away" INTEGER, -- Plus/minus rating for the away team
87
+ "video_available_away" INTEGER, -- Indicates whether video is available (1 = Yes, 0 = No)
88
+ "season_type" TEXT -- Regular season or playoffs
89
+ );
90
+ ''',
91
+ '''
92
+ other_stats Table
93
+ Stores additional statistics, linked to the game table via game_id.
94
+ CREATE TABLE IF NOT EXISTS "other_stats" (
95
+ "game_id" TEXT, -- Unique game identifier, matches id column from game table
96
+ "league_id" TEXT, -- League identifier
97
+ "team_id_home" TEXT, -- Home team identifier
98
+ "team_abbreviation_home" TEXT, -- Home team abbreviation
99
+ "team_city_home" TEXT, -- Home team city
100
+ "pts_paint_home" INTEGER, -- Points in the paint by the home team
101
+ "pts_2nd_chance_home" INTEGER, -- Second chance points by the home team
102
+ "pts_fb_home" INTEGER, -- Fast break points by the home team
103
+ "largest_lead_home" INTEGER,-- Largest lead by the home team
104
+ "lead_changes" INTEGER, -- Number of lead changes
105
+ "times_tied" INTEGER, -- Number of times the score was tied
106
+ "team_turnovers_home" INTEGER, -- Home team turnovers
107
+ "total_turnovers_home" INTEGER, -- Total turnovers by the home team
108
+ "team_rebounds_home" INTEGER, -- Home team rebounds
109
+ "pts_off_to_home" INTEGER, -- Points off turnovers by the home team
110
+ "team_id_away" TEXT, -- Away team identifier
111
+ "team_abbreviation_away" TEXT, -- Away team abbreviation
112
+ "pts_paint_away" INTEGER, -- Points in the paint by the away team
113
+ "pts_2nd_chance_away" INTEGER, -- Second chance points by the away team
114
+ "pts_fb_away" INTEGER, -- Fast break points by the away team
115
+ "largest_lead_away" INTEGER,-- Largest lead by the away team
116
+ "team_turnovers_away" INTEGER, -- Away team turnovers
117
+ "total_turnovers_away" INTEGER, -- Total turnovers by the away team
118
+ "team_rebounds_away" INTEGER, -- Away team rebounds
119
+ "pts_off_to_away" INTEGER -- Points off turnovers by the away team
120
+ );
121
+ ''',
122
+ '''
123
+ Team Name Information
124
+ In the plaintext user questions, only the full team names will be used, but in the queries you may use the full team names or the abbreviations.
125
+ The full team names can be used with the game table, while the abbreviations should be used with the other_stats table.
126
+ Notice they are separated by the | character in the following list:
127
+
128
+ Atlanta Hawks|ATL
129
+ Boston Celtics|BOS
130
+ Cleveland Cavaliers|CLE
131
+ New Orleans Pelicans|NOP
132
+ Chicago Bulls|CHI
133
+ Dallas Mavericks|DAL
134
+ Denver Nuggets|DEN
135
+ Golden State Warriors|GSW
136
+ Houston Rockets|HOU
137
+ Los Angeles Clippers|LAC
138
+ Los Angeles Lakers|LAL
139
+ Miami Heat|MIA
140
+ Milwaukee Bucks|MIL
141
+ Minnesota Timberwolves|MIN
142
+ Brooklyn Nets|BKN
143
+ New York Knicks|NYK
144
+ Orlando Magic|ORL
145
+ Indiana Pacers|IND
146
+ Philadelphia 76ers|PHI
147
+ Phoenix Suns|PHX
148
+ Portland Trail Blazers|POR
149
+ Sacramento Kings|SAC
150
+ San Antonio Spurs|SAS
151
+ Oklahoma City Thunder|OKC
152
+ Toronto Raptors|TOR
153
+ Utah Jazz|UTA
154
+ Memphis Grizzlies|MEM
155
+ Washington Wizards|WAS
156
+ Detroit Pistons|DET
157
+ Charlotte Hornets|CHA
158
+ '''
159
+ ]
160
+ retriever.add_documents(metadata_docs)
161
+
162
+ # Define the user question
163
+ user_question = "What is the most points ever scored by the New York Knicks at home?"
164
+
165
+ # Retrieve relevant schema
166
+ relevant_schemas = retriever.retrieve(user_question, top_k=2)
167
+
168
+ print("---------------------------------------------")
169
+ print("INFO: Retrieved relevant documents from RAG:")
170
+ print("")
171
+ for i, doc in enumerate(relevant_schemas):
172
+ print("Relevant doc -> ", i + 1)
173
+ print(doc)
174
+ print("---------------------------------------------")
175
+
176
+ # Concat
177
+ schema_block = "\n\n".join(relevant_schemas)
178
+
179
+ # Construct the prompt with injected schema
180
+ input_text = f"""
181
+ You are an AI assistant that generates SQL queries for an NBA database based on user questions.
182
+
183
+ ### Relevant Schema:
184
+ {schema_block}
185
+
186
+ ### Instructions:
187
+ - Generate a valid SQL query to retrieve relevant data from the database.
188
+ - Use column names correctly based on the provided schema.
189
+ - Output only the SQL query as plain text.
190
+
191
+ ### Example Queries:
192
+ Use team_name_home and team_name_away to match teams to the game table. Use team_abbreviation_home and team_abbreviation away to match teams to the other_stats table.
193
+
194
+ To filter by season, use season_id = '2YYYY'.
195
+
196
+ Example: To get statistics from 2005, use a statement like: season_id = '22005'. To get statistics from 1972, use a statement like: season_id = "21972". To get statistics from 2015, use a statement like: season_id = "22015".
197
+
198
+ Ensure queries return relevant columns and avoid unnecessary joins.
199
+
200
+ Example User Requests and SQLite Queries
201
+ Request:
202
+ "What is the most points the Los Angeles Lakers have ever scored at home?"
203
+ SQLite:
204
+ SELECT MAX(pts_home)
205
+ FROM game
206
+ WHERE team_name_home = 'Los Angeles Lakers';
207
+
208
+ Request:
209
+ "Which teams are located in the state of California?"
210
+ SQLite:
211
+ SELECT full_name FROM team WHERE state = 'California';
212
+
213
+ Request:
214
+ "Which team had the highest number of team turnovers in an away game?"
215
+ SQLite:
216
+ SELECT team_abbreviation_away FROM other_stats ORDER BY team_turnovers_away DESC LIMIT 1;
217
+
218
+ Request:
219
+ "Which teams were founded before 1979?"
220
+ SQLite:
221
+ SELECT full_name FROM team WHERE year_founded < 1979;
222
+
223
+ Request:
224
+ "Find the Boston Celtics largest home victory margin in the 2008 season."
225
+ SQLite:
226
+ SELECT MAX(pts_home - pts_away) AS biggest_win
227
+ FROM game
228
+ WHERE team_name_home = 'Boston Celtics' AND season_id = '22008';
229
+
230
+ Generate only the SQLite query prefaced by SQLite: and no other text, do not output an explanation of the query. Now generate an SQLite query for the following user request. Request:
231
+ {user_question}
232
+ """
233
+
234
+ # Tokenize using chat template
235
+ messages = [{ 'role': 'user', 'content': input_text }]
236
+ prompt_text = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
237
+ inputs = tokenizer(prompt_text, return_tensors="pt", padding=True).to(model.device)
238
+
239
+ # Generate SQL query
240
+ start_time = time.time()
241
+ outputs = model.generate(
242
+ **inputs,
243
+ max_new_tokens=512,
244
+ do_sample=True,
245
+ top_k=50,
246
+ top_p=0.95,
247
+ num_return_sequences=1,
248
+ eos_token_id=tokenizer.eos_token_id,
249
+ pad_token_id=tokenizer.eos_token_id
250
+ )
251
+ end_time = time.time()
252
+
253
+ # Decode and print result
254
+ print("Natural Language Query: ", user_question)
255
+ print("")
256
+
257
+ generated = tokenizer.decode(outputs[0][len(inputs["input_ids"][0]):], skip_special_tokens=True)
258
+ print("Generated SQL Query:\n")
259
+ print(generated)
260
+ print("\nExecution time:", round(end_time - start_time, 2), "seconds")