-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathllm.py
290 lines (251 loc) · 7.84 KB
/
llm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import openai
import os
import os.path
import json
import redshift_connector
import pandas
import geopy
chatCompletionLimit = 20
queryRowLimit = 100
mapEntryLimit = 100
systemMessage = open("system-message.md", "r").read().replace("$queryRowLimit", str(queryRowLimit))
def getDatabases():
# Hardcoded in this prototype
exampleDatabase = {
"name": "example-database",
"description": "A database of our web shop in Brazil"
}
return [ exampleDatabase ]
def getDatabaseSchema(args):
path = 'schemas/{}.sql'.format(args["name"])
if os.path.isfile(path):
f = open(path, "r")
return f.read()
else:
return "Error: not found"
def executeQuery(args):
host = os.getenv("DW_HOST")
user = os.getenv("DW_USER")
password = os.getenv("DW_PASSWORD")
database = os.getenv("DW_DATABASE")
try:
conn = redshift_connector.connect(
host=host,
database=database,
user=user,
password=password
)
if not args["query"].endswith('LIMIT ' + str(queryRowLimit)):
return "Error: Query is not limited by " + str(queryRowLimit) + " (LIMIT " + str(queryRowLimit) + " at the end)"
cursor: redshift_connector.Cursor = conn.cursor()
cursor.execute(args["query"])
return cursor.fetchall()
except Exception as e:
return "Error: " + repr(e) + " " + str(e)
def chart(args):
chartType = args["chart_type"] # bar, area, line, scatter
chartData = args["data"] # csv
return {
"content_type": "chart",
"chart_type": chartType,
"data": chartData,
}
def map(args):
zoomLevel = args["zoomLevel"] # 1-20 (20 = Street, 1 = World)
rows = args["rows"]
if len(rows) > mapEntryLimit:
return "Error: Too many entries. Only " + str(mapEntryLimit) + " are allowed."
# Setup client
API_KEY = os.getenv("BING_MAPS_API_KEY")
geolocator = geopy.geocoders.Bing(API_KEY)
for row in rows:
if not ("lat" in row and "lon" in row):
query = ""
if "street" in row:
query += str(row["street"]) + ", "
if "zip_code" in row:
query += str(row["zip_code"]) + ", "
if "city" in row:
query += str(row["city"]) + ", "
if "state" in row:
query += str(row["state"]) + ", "
query += str(row["country"])
location = geolocator.geocode(query)
if hasattr(location, 'latitude') and hasattr(location, 'longitude'):
row["lat"] = location.latitude
row["lon"] = location.longitude
else:
return "Failed to get location for: " + query
df = pandas.DataFrame(rows)
return {
"content_type": "map",
"data": df.to_csv(index=False),
"zoomLevel": zoomLevel,
}
def chatCompletion(messages):
openai.key = os.getenv("OPENAI_API_KEY")
tools = [
{
"type": "function",
"function": {
"name": "getDatabases",
"description": "Gets all accessible databases as a list",
"parameters": {},
}
},
{
"type": "function",
"function": {
"name": "getDatabaseSchema",
"description": "Gets the schema for a database",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Name of the database you want to receive the schema for",
},
},
"required": ["name"],
},
}
},
{
"type": "function",
"function": {
"name": "executeQuery",
"description": "Executes a SQL query against the data warehouse",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The full SQL query. Always end your SQL query with 'LIMIT " + str(queryRowLimit) + "'",
},
},
"required": ["query"],
},
}
},
{
"type": "function",
"function": {
"name": "chart",
"description": "Shows a chart to the user above",
"parameters": {
"type": "object",
"properties": {
"chart_type": {
"type": "string",
"enum": ["bar", "area", "line", "scatter"],
"description": "The type of the chart",
},
"data": {
"type": "string",
"description": "Data of the chart represented as CSV. Data must be in a format, that it makes sense for the given chart type. The first column is the x-axis, the second one the y-axis. Always include a header.",
}
},
"required": ["chart_type", "data"],
},
}
},
{
"type": "function",
"function": {
"name": "map",
"description": "Shows a map to the user above",
"parameters": {
"type": "object",
"properties": {
"rows": {
"type": "array",
"description": "All entries to show on the map",
"items": {
"type": "object",
"properties": {
"country": {
"type": "string",
"description": "Country of the location displayed on the map"
},
"state": {
"type": "string"
},
"city": {
"type": "string"
},
"zip_code": {
"type": "string"
},
"street": {
"type": "string"
},
"lat": {
"type": "number",
"description": "Latitude of the map entry if known. If empty, the latitude will be retrieved by external API"
},
"lon": {
"type": "number",
"description": "Longitude of the map entry if known, the longitude will be retrieved by external API"
},
"value": {
"description": "Optional value to be shown on the map"
},
},
"required": ["country"]
}
},
"zoomLevel": {
"type": "number",
"description": "Given on the data, choose a zoom level between 1 and 20 where 20 is on street level and 1 on world level.",
},
},
"required": ["data", "zoomLevel"],
}
},
},
]
systemMessages = [ { "role": 'system', "content": systemMessage } ]
chatCompletions = 0
responses = [] # Delta to messages
while True:
if chatCompletions > chatCompletionLimit:
break
completion = openai.ChatCompletion.create(
messages = systemMessages + messages,
model = "gpt-4-1106-preview",
tools = tools,
tool_choice = "auto"
)
message = completion.choices[0].message
messages.append(message)
responses.append(message)
print(message)
if not hasattr(message, "tool_calls") or len(message.tool_calls) <= 0:
break
for call in message.tool_calls:
if call.type == "function":
try:
toolFunction = globals()[call.function.name]
args = json.loads(call.function.arguments)
value = ""
if args is not None and len(args) > 0:
value = str(toolFunction(args))
else:
value = str(toolFunction())
toolMessage = {
"role": "tool",
"tool_call_id": call.id,
"content": value
}
except Exception as e:
toolMessage = {
"role": "tool",
"tool_call_id": call.id,
"content": "Error: Function call failed: " + repr(e) + ": " + str(e)
}
finally:
messages.append(toolMessage)
responses.append(toolMessage)
print(toolMessage)
chatCompletions += 1
return responses