forked from openai/chatgpt-retrieval-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.py
357 lines (315 loc) · 13.1 KB
/
main.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import os
from typing import Optional
import uvicorn
import uuid
from fastapi import FastAPI, File, Form, HTTPException, Depends, Body, UploadFile, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi.staticfiles import StaticFiles
from datastore.factory import get_datastore
from services.file import get_document_from_file
from fastapi.middleware.cors import CORSMiddleware
from models.models import DocumentMetadata, Source
from transformers import AutoTokenizer, AutoModel
from db import *
from models.api import *
bearer_scheme = HTTPBearer(auto_error=False)
def validate_api_key(credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer(auto_error=False)), db = Depends(get_db)):
api_key = credentials.credentials
if credentials.scheme != "Bearer" or not authenticate_user(api_key, db=db):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or missing API key")
return api_key
app = FastAPI()
app.mount("/.well-known", StaticFiles(directory=".well-known"), name="static")
# Create a sub-application, in order to access just the query endpoint in an OpenAPI schema, found at http://0.0.0.0:8000/sub/openapi.json when the app is running locally
sub_app = FastAPI(
title="SERP AI Retrieval Plugin",
description="A retrieval API for querying and filtering documents based on natural language queries and metadata",
version="1.0.0",
servers=[{"url": "https://v3ctron.serp.ai"}]
)
app.mount("/sub", sub_app)
@app.post(
"/create-collection",
response_model=CreateCollectionResponse,
)
async def create_collection(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
request: CreateCollectionRequest = Body(...),
):
try:
assert request.embedding_method in ["mpnet", "openai"], "Invalid embedding method"
_uuid = uuid.uuid4()
collection_name = request.collection_name + "_" + str(_uuid)
collection_name = collection_name.replace(" ", "_").replace("-", "_")
response = await datastore.create_collection(collection_name, request.embedding_method)
if response == True:
response = await add_collection_to_db(api_key, request.collection_name, collection_name, request.embedding_method, request.overview, request.description, request.is_active, db=db)
return CreateCollectionResponse(success=response)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@app.post(
"/update-collection",
response_model=UpdateCollectionResponse,
)
async def update_collection(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
collection_name: str = Form(...),
new_collection_name: Optional[str] = Form(None),
overview: Optional[str] = Form(None),
description: Optional[str] = Form(None),
is_active: Optional[bool] = Form(None),
):
try:
response = await update_collection_in_db(api_key, collection_name, new_collection_name, overview, description, is_active, db=db)
return UpdateCollectionResponse(success=response)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@app.get(
"/get-active-collections",
response_model=GetActiveCollectionsResponse,
)
async def get_active_collections(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
):
try:
collections = await get_collections_from_db(api_key, db=db)
for collection in collections:
collection['collection_name'] = collection.pop('name')
return GetActiveCollectionsResponse(collections=collections)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@sub_app.get(
"/get-active-collections",
response_model=GetActiveCollectionsResponse,
# NOTE: We are describing the shape of the API endpoint input due to a current limitation in parsing arrays of objects from OpenAPI schemas. This will not be necessary in the future.
description="Returns a list of active collections and overviews of what they are used for and/or what they contain.",
)
async def get_active_collections(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
):
try:
collections = await get_collections_from_db(api_key, db=db)
return GetActiveCollectionsResponse(collections=collections)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@app.get(
"/get-all-collections",
response_model=GetAllCollectionsResponse,
)
async def get_all_collections_from_db(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
):
try:
collections = await get_collections_from_db(api_key, db=db, return_only_names_and_overviews=False)
for collection in collections:
collection['collection_name'] = collection.pop('name')
return GetAllCollectionsResponse(collections=collections)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@app.post(
"/upsert-file",
response_model=UpsertResponse,
)
async def upsert_file(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
file: UploadFile = File(...),
metadata: Optional[str] = Form(None),
collection_name: str = Form(None),
):
try:
metadata_obj = (
DocumentMetadata.parse_raw(metadata)
if metadata
else DocumentMetadata(source=Source.file)
)
except:
metadata_obj = DocumentMetadata(source=Source.file)
document = await get_document_from_file(file, metadata_obj)
try:
collection = await get_collection_from_db(api_key, collection_name, db=db)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
if collection is None:
raise HTTPException(status_code=500, detail="Invalid collection name")
try:
collection_name, mode = collection
ids = await datastore.upsert([document], mode=mode, model=model, tokenizer=tokenizer, collection_name=collection_name)
return UpsertResponse(ids=ids)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail=f"str({e})")
@app.post(
"/upsert",
response_model=UpsertResponse,
)
async def upsert_main(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
request: UpsertRequest = Body(...),
):
try:
collection = await get_collection_from_db(api_key, request.collection_name, db=db)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
if collection is None:
raise HTTPException(status_code=500, detail="Invalid collection name")
try:
collection_name, mode = collection
ids = await datastore.upsert(request.documents, mode=mode, model=model, tokenizer=tokenizer, collection_name=collection_name)
return UpsertResponse(ids=ids)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@sub_app.post(
"/upsert",
response_model=UpsertResponse,
# NOTE: We are describing the shape of the API endpoint input due to a current limitation in parsing arrays of objects from OpenAPI schemas. This will not be necessary in the future.
description="Save chat information. Accepts a collection name and an array of documents with text (potential questions + conversation text), metadata (source 'chat' and timestamp, no ID as this will be generated). Confirm with the user before saving, ask for more details/context.",
)
async def upsert(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
request: UpsertRequest = Body(...),
):
try:
collection = await get_collection_from_db(api_key, request.collection_name, db=db)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
if collection is None:
raise HTTPException(status_code=500, detail="Invalid collection name")
try:
collection_name, mode = collection
ids = await datastore.upsert(request.documents, mode=mode, model=model, tokenizer=tokenizer, collection_name=collection_name)
return UpsertResponse(ids=ids)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@app.post(
"/query",
response_model=QueryResponse,
)
async def query_main(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
request: QueryRequest = Body(...),
):
try:
collection = await get_collection_from_db(api_key, request.collection_name, db=db)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
if collection is None:
raise HTTPException(status_code=500, detail="Invalid collection name")
try:
collection_name, mode = collection
results = await datastore.query(
request.queries,
mode=mode,
model=model,
tokenizer=tokenizer,
collection_name=collection_name,
)
return QueryResponse(results=results)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@sub_app.post(
"/query",
response_model=QueryResponse,
# NOTE: We are describing the shape of the API endpoint input due to a current limitation in parsing arrays of objects from OpenAPI schemas. This will not be necessary in the future.
description="Accepts a collection name and an objects array with each item having a query and an optional filter. Break down complex queries into sub-queries. Refine results by criteria, e.g. time / source, don't do this often. Split queries if ResponseTooLargeError occurs.",
)
async def query(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
request: QueryRequest = Body(...),
):
try:
collection = await get_collection_from_db(api_key, request.collection_name, db=db)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
if collection is None:
raise HTTPException(status_code=500, detail="Invalid collection name")
try:
collection_name, mode = collection
results = await datastore.query(
request.queries,
mode=mode,
model=model,
tokenizer=tokenizer,
collection_name=collection_name,
)
return QueryResponse(results=results)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@app.delete(
"/delete",
response_model=DeleteResponse,
)
async def delete(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
request: DeleteRequest = Body(...),
):
if not (request.ids or request.filter or request.delete_all):
raise HTTPException(
status_code=400,
detail="One of ids, filter, or delete_all is required",
)
try:
collection_name, mode = await get_collection_from_db(api_key, request.collection_name, db=db)
success = await datastore.delete(
ids=request.ids,
filter=request.filter,
delete_all=request.delete_all,
collection_name=collection_name,
)
return DeleteResponse(success=success)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@app.delete(
"/delete-collection",
response_model=DeleteResponse,
description="Delete a collection and all its data. This is irreversible.",
)
async def delete_collection(
api_key: str = Depends(validate_api_key),
db = Depends(get_db),
request: DeleteCollectionRequest = Body(...),
):
try:
collection_name, _ = await get_collection_from_db(api_key, request.collection_name, db=db)
success = await datastore.delete_collection(collection_name)
if success:
success = await delete_collection_from_db(api_key, request.collection_name, db=db)
return DeleteResponse(success=success)
except Exception as e:
print("Error:", e)
raise HTTPException(status_code=500, detail="Internal Service Error")
@app.on_event("startup")
async def startup():
global datastore
global model
global tokenizer
datastore = await get_datastore()
tokenizer = AutoTokenizer.from_pretrained('sentence-transformers/all-mpnet-base-v2')
model = AutoModel.from_pretrained('sentence-transformers/all-mpnet-base-v2')
def start():
uvicorn.run("server.main:app", host="0.0.0.0", port=8000, reload=True)