-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
470 lines (379 loc) · 13.5 KB
/
app.py
File metadata and controls
470 lines (379 loc) · 13.5 KB
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
from fastapi import FastAPI, APIRouter, HTTPException, status, Depends
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import create_engine, and_, text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
import uvicorn
import os
import uuid
import time
from chat_completion import completion, detect_intention
from models import Base, Message, Product, ParentDocument, DocumentChunk
from openai import AzureOpenAI
from azure.cosmos import CosmosClient
from urllib.parse import quote
from models.all_models import Conversation
app = FastAPI(
title="FastAPI Service",
description="FastAPI service with SQLAlchemy ORM",
version="0.1.0",
)
router = APIRouter()
def make_response(code, msg, result=None) -> JSONResponse:
return JSONResponse(
status_code=code, content={"code": code, "msg": msg, "result": result}
)
AZURE_CONNECTION_STRING = os.getenv("AZURE_CONNECTION_STRING")
CONTAINER_NAME = os.getenv("CONTAINER_NAME")
AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT")
AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY")
OPENAI_API_VERSION = os.getenv("OPENAI_API_VERSION")
AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME = os.getenv(
"AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME"
)
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME = os.getenv("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME")
COSMOSDB_CONNECTION_STRING = os.getenv("COSMOSDB_CONNECTION_STRING")
COSMOSDB_DATABASE_NAME = os.getenv("COSMOSDB_DATABASE_NAME")
COSMOSDB_CONTAINER_NAME = os.getenv("COSMOSDB_CONTAINER_NAME")
PARTITION_KEY_PATH = "/id"
VECTOR_FIELD = "embedding"
CONTENT_FIELD = "chunk_text"
METADATA_FIELD = "group_category"
openai_client = AzureOpenAI(
azure_endpoint=AZURE_OPENAI_ENDPOINT,
api_key=AZURE_OPENAI_API_KEY,
api_version=OPENAI_API_VERSION,
)
cosmos_client = CosmosClient.from_connection_string(COSMOSDB_CONNECTION_STRING)
database = cosmos_client.get_database_client(COSMOSDB_DATABASE_NAME)
container = database.get_container_client(COSMOSDB_CONTAINER_NAME)
DATABASE_URL = f"sqlite:///{db_path}" # TODO: migrate to PostgreSQL
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
Base.metadata.create_all(bind=engine)
# Pydantic Models
class ProductModel(BaseModel):
product_id: str
scheme_code: str
product_description: str
is_active: bool
class Config:
orm_mode = True
class ParentDocumentModel(BaseModel):
id: str
owner_id: str
file_name: str
classification: str
fk_product_id: str
class Config:
orm_mode = True
class ChunkModel(BaseModel):
document_chunk_id: str
parent_document_id: str
page_index: int
content: str
token_count: int
class Config:
orm_mode = True
class TextChunkUploadRequest(BaseModel):
products: Optional[ProductModel] = None
parent_document: ParentDocumentModel
chunks: List[ChunkModel]
class DocumentStatusUpdate(BaseModel):
status: str
class IntentionDetectionRequest(BaseModel):
user_query: str
products: str
# Request Model
class CompletionRequest(BaseModel):
user_id: str
conversation_id: str
content: str
product_name: str
role: Optional[str] = "user"
top_k: Optional[int] = 5 # default value for top_k
class Config:
schema_extra = {
"example": {
"user_id": "user_001",
"conversation_id": "conv_123",
"content": "What is AI?",
"product_name": "E1-BizJamin",
"role": "user",
"top_k": 5,
}
}
# Response Model
class CompletionResponse(BaseModel):
id: str
message_id: str
answer: str
model: str
input_tokens: int
output_tokens: int
cost: float
created_at: datetime
class Config:
orm_mode = True
class UserEmailRequest(BaseModel):
email: str
# Dependency to get DB session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def get_next_sequence(db: Session, conversation_id: str) -> int:
"""Get the sequence number of the next message in the session"""
last_msg = (
db.query(Message)
.filter(Message.conversation_id == conversation_id)
.order_by(Message.sequence.desc())
.first()
)
return (last_msg.sequence + 1) if last_msg else 1
def get_query_embedding(query: str) -> list:
"""Generate embedding for the user query using Azure OpenAI."""
response = openai_client.embeddings.create(
input=query, model=AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME
)
return response.data[0].embedding
def safe_url(url: str) -> str:
if "?" in url:
base, query = url.split("?", 1)
return quote(base, safe="/:") + "?" + query
return quote(url, safe="/:")
@router.get("/")
async def read_root():
return {"message": "Yes to SQLAlchemy!"}
# @router.post("/upload-text-chunks/")
# async def upload_text_chunks(
# request: TextChunkUploadRequest, db: Session = Depends(get_db)
# ):
# try:
# # Process product if exists
# if request.products:
# db_product = Product(
# product_id=request.products.product_id,
# scheme_code=request.products.scheme_code,
# product_description=request.products.product_description,
# is_active=request.products.is_active,
# )
# db.add(db_product)
# db.flush() # Ensure product_id is available for foreign key
# # Create parent document
# db_document = ParentDocument(
# id=request.parent_document.id,
# owner_id=request.parent_document.owner_id,
# file_name=request.parent_document.file_name,
# classification=request.parent_document.classification,
# fk_product_id=request.parent_document.fk_product_id,
# )
# db.add(db_document)
# # Create chunks
# for chunk in request.chunks:
# db_chunk = DocumentChunk(
# document_chunk_id=chunk.document_chunk_id,
# parent_document_id=chunk.parent_document_id,
# page_index=chunk.page_index,
# content=chunk.content,
# token_count=chunk.token_count,
# )
# db.add(db_chunk)
# db.commit()
# return {
# "status": "success",
# "document_id": request.parent_document.id,
# "chunk_count": len(request.chunks),
# "product_processed": request.products is not None,
# }
# except Exception as e:
# db.rollback()
# raise HTTPException(
# status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
# detail=f"Database error: {str(e)}",
# )
# @router.put("/update-document-status/{document_id}")
# async def update_document_status(
# document_id: str, request: DocumentStatusUpdate, db: Session = Depends(get_db)
# ):
# db_document = (
# db.query(ParentDocument).filter(ParentDocument.id == document_id).first()
# )
# if not db_document:
# raise HTTPException(
# status_code=status.HTTP_404_NOT_FOUND, detail="Document not found"
# )
# try:
# db_document.ingest_status = request.status
# db.commit()
# return {
# "status": "success",
# "document_id": document_id,
# "new_status": request.status,
# }
# except Exception as e:
# db.rollback()
# raise HTTPException(
# status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
# )
@router.post("/chat-stream")
async def chat_stream_endpoint(
request: CompletionRequest, db: Session = Depends(get_db)
):
"""Detect user intent to classify the query into one of the predefined categories."""
start_time = time.perf_counter()
user_id = request.user_id
conversation_id = request.conversation_id
user_query = request.content
product_name = request.product_name
top_k = request.top_k or 5
if not user_id or not conversation_id:
return make_response(
400, "Missing required fields: user_id and conversation_id", None
)
if not user_query:
return make_response(400, "Missing required fields: query", None)
if not top_k:
return make_response(400, "Missing required field: top_k", None)
message = Message(
id=str(uuid.uuid4()),
user_id=request.user_id,
conversation_id=request.conversation_id,
content=request.content,
role=request.role,
sequence=get_next_sequence(db, request.conversation_id),
created_at=datetime.now(),
)
product_list = []
if product_name:
scheme_code, product_description = product_name.split("-", 1)
product = (
db.query(Product)
.filter(
and_(
Product.scheme_code == scheme_code,
Product.product_description == product_description,
)
)
.first()
)
product_id = product.product_id if product else None
product_list = [product_id] if product_id else []
# Exception if product_name is invalid
if len(product_list) == 0:
return make_response(400, "Invalid product_name", None)
else:
# query = text(
# """
# SELECT DISTINCT
# a.product_id
# FROM
# users d
# INNER JOIN user_orgs e ON d.id = e.user_id
# INNER JOIN user_roles c ON d.id = c.user_id
# INNER JOIN product_role_permissions b ON c.role_id = b.role_id
# INNER JOIN products a ON b.product_id = a.product_id
# INNER JOIN product_orgs f ON a.product_id = f.fk_product_id AND e.org_id = f.fk_org_id
# WHERE
# d.id = :user_id
# """
# )
with SessionLocal() as db:
result = db.execute(query, {"user_id": user_id}).fetchall()
product_list = [(row.product_id) for row in result]
# Exception if no products found for the user
if len(product_list) == 0:
return make_response(400, "No products found for the user", None)
completion_result = completion(db, product_list, message, request.top_k)
if isinstance(completion_result, str):
return make_response(400, completion_result, None)
message.final_completion_id = completion_result.id
db.add(message)
db.add(completion_result)
db.commit()
end_time = time.perf_counter()
print(f"\n\nTotal tokens used")
print(f"Time taken: {end_time - start_time:.2f} seconds\n\n")
return make_response(200, "Query successfully processed", completion_result.answer)
@router.post("/initiate-conversation")
async def initiate_conversation(
request: UserEmailRequest, db: Session = Depends(get_db)
):
query = text(
"""
SELECT
*
FROM
users a
WHERE
a.email = :email
"""
)
try:
result = db.execute(query, {"email": request.email}).fetchone()
if not result:
raise HTTPException(status_code=404, detail="User not found")
new_conversation = Conversation(
id=str(uuid.uuid4()),
user_id=result.id,
created_at=datetime.now(),
)
db.add(new_conversation)
db.commit()
db.refresh(new_conversation)
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail="Error initiating conversation")
return {"conversation_id": new_conversation.id, "user_id": new_conversation.user_id}
@router.post("/retrieve-products")
async def retrieve_products_by_user_email(
request: UserEmailRequest, db: Session = Depends(get_db)
) -> str:
try:
# query = text(
# """
# SELECT DISTINCT a.product_id, a.scheme_code, a.product_description
# FROM users d
# INNER JOIN user_orgs e ON d.id = e.user_id
# INNER JOIN user_roles c ON d.id = c.user_id
# INNER JOIN product_role_permissions b ON c.role_id = b.role_id
# INNER JOIN products a ON b.product_id = a.product_id
# INNER JOIN product_orgs f ON
# a.product_id = f.fk_product_id
# AND e.org_id = f.fk_org_id
# WHERE d.email = :email
# """
# )
rows = db.execute(query, {"email": request.email}).fetchall()
if not rows:
return "Sorry, you do not have access to any products."
return ", ".join(
f"{(row.scheme_code or '').strip()}-{(row.product_description or '').strip()}"
for row in rows
)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error retrieving products: {str(e)}",
)
@router.post("/intention-detection")
async def intention_detection(
request: IntentionDetectionRequest, db: Session = Depends(get_db)
):
try:
response = detect_intention(request.user_query, request.products, db=db)
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"intent error: {e}",
)
return response
app.include_router(router)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8001)