Tan Phat commited on
Commit ·
2ea1d2a
1
Parent(s): a126f1c
Create get vector embedding API
Browse files- api_main.py +48 -3
- requirements.txt +5 -2
- src/embedding.py +30 -0
api_main.py
CHANGED
|
@@ -3,13 +3,14 @@ import sys
|
|
| 3 |
from fastapi import FastAPI, HTTPException, Depends, status
|
| 4 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 5 |
from pydantic import BaseModel, Field
|
| 6 |
-
from typing import Optional, List, Dict, Any
|
| 7 |
from datetime import datetime, timezone, timedelta
|
| 8 |
import psycopg2
|
| 9 |
from psycopg2 import pool as psycopg2_pool
|
| 10 |
from jose import JWTError, jwt
|
| 11 |
import uvicorn
|
| 12 |
from dotenv import load_dotenv
|
|
|
|
| 13 |
|
| 14 |
load_dotenv()
|
| 15 |
|
|
@@ -17,12 +18,14 @@ try:
|
|
| 17 |
from src.config import DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME, DB_ENDPOINT_ID, GOOGLE_API_KEY
|
| 18 |
from src.database import conn_pool
|
| 19 |
from src.graph_builder import graph_app
|
|
|
|
| 20 |
from langchain_core.messages import HumanMessage, AIMessage, BaseMessage
|
| 21 |
except ImportError as e:
|
| 22 |
print(f"Error importing from src: {e}. Using placeholders. API will likely fail at runtime until this is fixed.")
|
| 23 |
DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME, DB_ENDPOINT_ID, GOOGLE_API_KEY = [None]*7
|
| 24 |
conn_pool = None
|
| 25 |
graph_app = None
|
|
|
|
| 26 |
class HumanMessage:
|
| 27 |
def __init__(self, content):
|
| 28 |
self.content = content
|
|
@@ -43,6 +46,14 @@ reusable_oauth2 = HTTPBearer(
|
|
| 43 |
scheme_name="Bearer"
|
| 44 |
)
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
class TokenData(BaseModel):
|
| 47 |
user_id: Optional[int] = None
|
| 48 |
|
|
@@ -122,7 +133,7 @@ def save_interaction_to_history(db_conn, user_id: int, user_message: str, chatbo
|
|
| 122 |
print(f"Error saving interaction to history for user_id {user_id}: {e}")
|
| 123 |
db_conn.rollback()
|
| 124 |
|
| 125 |
-
@app.post("/api/
|
| 126 |
async def chat_endpoint(payload: ChatMessageInput, current_user_id: int = Depends(get_current_user), db_conn = Depends(get_db_connection)):
|
| 127 |
if graph_app is None:
|
| 128 |
print("graph_app is None in chat_endpoint. Graph_builder module likely not initialized.")
|
|
@@ -173,4 +184,38 @@ async def chat_endpoint(payload: ChatMessageInput, current_user_id: int = Depend
|
|
| 173 |
response=full_response_content,
|
| 174 |
session_id=payload.session_id,
|
| 175 |
timestamp=datetime.now(timezone.utc)
|
| 176 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from fastapi import FastAPI, HTTPException, Depends, status
|
| 4 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 5 |
from pydantic import BaseModel, Field
|
| 6 |
+
from typing import Optional, List, Dict, Any, Union
|
| 7 |
from datetime import datetime, timezone, timedelta
|
| 8 |
import psycopg2
|
| 9 |
from psycopg2 import pool as psycopg2_pool
|
| 10 |
from jose import JWTError, jwt
|
| 11 |
import uvicorn
|
| 12 |
from dotenv import load_dotenv
|
| 13 |
+
import time
|
| 14 |
|
| 15 |
load_dotenv()
|
| 16 |
|
|
|
|
| 18 |
from src.config import DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME, DB_ENDPOINT_ID, GOOGLE_API_KEY
|
| 19 |
from src.database import conn_pool
|
| 20 |
from src.graph_builder import graph_app
|
| 21 |
+
from src.embedding import embedding_model
|
| 22 |
from langchain_core.messages import HumanMessage, AIMessage, BaseMessage
|
| 23 |
except ImportError as e:
|
| 24 |
print(f"Error importing from src: {e}. Using placeholders. API will likely fail at runtime until this is fixed.")
|
| 25 |
DB_USER, DB_PASSWORD, DB_HOST, DB_PORT, DB_NAME, DB_ENDPOINT_ID, GOOGLE_API_KEY = [None]*7
|
| 26 |
conn_pool = None
|
| 27 |
graph_app = None
|
| 28 |
+
embedding_model = None
|
| 29 |
class HumanMessage:
|
| 30 |
def __init__(self, content):
|
| 31 |
self.content = content
|
|
|
|
| 46 |
scheme_name="Bearer"
|
| 47 |
)
|
| 48 |
|
| 49 |
+
class EmbeddingRequest(BaseModel):
|
| 50 |
+
text: Union[str, List[str]]
|
| 51 |
+
|
| 52 |
+
class EmbeddingResponse(BaseModel):
|
| 53 |
+
embeddings: List[List[float]]
|
| 54 |
+
model: str
|
| 55 |
+
dimensions: int
|
| 56 |
+
|
| 57 |
class TokenData(BaseModel):
|
| 58 |
user_id: Optional[int] = None
|
| 59 |
|
|
|
|
| 133 |
print(f"Error saving interaction to history for user_id {user_id}: {e}")
|
| 134 |
db_conn.rollback()
|
| 135 |
|
| 136 |
+
@app.post("/api/chat/", response_model=ChatResponseOutput)
|
| 137 |
async def chat_endpoint(payload: ChatMessageInput, current_user_id: int = Depends(get_current_user), db_conn = Depends(get_db_connection)):
|
| 138 |
if graph_app is None:
|
| 139 |
print("graph_app is None in chat_endpoint. Graph_builder module likely not initialized.")
|
|
|
|
| 184 |
response=full_response_content,
|
| 185 |
session_id=payload.session_id,
|
| 186 |
timestamp=datetime.now(timezone.utc)
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
@app.get("/api/health")
|
| 190 |
+
async def health_check():
|
| 191 |
+
return {"status": "ok", "message": "API is running"}
|
| 192 |
+
|
| 193 |
+
@app.post("/api/embed", response_model=EmbeddingResponse)
|
| 194 |
+
async def get_embedding(request: EmbeddingRequest):
|
| 195 |
+
if embedding_model is None:
|
| 196 |
+
raise HTTPException(
|
| 197 |
+
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
| 198 |
+
detail="Embedding service not initialized. Check src.embedding module."
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
try:
|
| 202 |
+
embeddings = embedding_model.get_embedding(request.text)
|
| 203 |
+
|
| 204 |
+
return {
|
| 205 |
+
"embeddings": embeddings,
|
| 206 |
+
"model": embedding_model.model_name,
|
| 207 |
+
"dimensions": len(embeddings[0])
|
| 208 |
+
}
|
| 209 |
+
except Exception as e:
|
| 210 |
+
raise HTTPException(
|
| 211 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
| 212 |
+
detail=f"Error generating embeddings: {str(e)}"
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
@app.on_event("startup")
|
| 216 |
+
async def startup_event():
|
| 217 |
+
try:
|
| 218 |
+
if embedding_model:
|
| 219 |
+
embedding_model.load_model()
|
| 220 |
+
except Exception as e:
|
| 221 |
+
print(f"Failed to load embedding model on startup: {str(e)}")
|
requirements.txt
CHANGED
|
@@ -10,6 +10,9 @@ dateparser==1.2.1
|
|
| 10 |
pandas==2.2.3
|
| 11 |
beautifulsoup4==4.13.4
|
| 12 |
fastapi==0.115.12
|
| 13 |
-
uvicorn
|
| 14 |
python-jose[cryptography]==3.4.0
|
| 15 |
-
passlib[bcrypt]==1.7.4
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
pandas==2.2.3
|
| 11 |
beautifulsoup4==4.13.4
|
| 12 |
fastapi==0.115.12
|
| 13 |
+
uvicorn==0.34.0
|
| 14 |
python-jose[cryptography]==3.4.0
|
| 15 |
+
passlib[bcrypt]==1.7.4
|
| 16 |
+
sentence-transformers==4.0.2
|
| 17 |
+
python-multipart==0.0.20
|
| 18 |
+
pydantic==2.11.3
|
src/embedding.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sentence_transformers import SentenceTransformer
|
| 2 |
+
import numpy as np
|
| 3 |
+
from typing import List, Union
|
| 4 |
+
|
| 5 |
+
class EmbeddingModel:
|
| 6 |
+
def __init__(self):
|
| 7 |
+
self.model = None
|
| 8 |
+
self.model_name = 'keepitreal/vietnamese-sbert'
|
| 9 |
+
|
| 10 |
+
def load_model(self):
|
| 11 |
+
if self.model is None:
|
| 12 |
+
try:
|
| 13 |
+
self.model = SentenceTransformer(self.model_name)
|
| 14 |
+
except Exception as e:
|
| 15 |
+
raise RuntimeError(f"Failed to load model: {str(e)}")
|
| 16 |
+
|
| 17 |
+
def get_embedding(self, text: Union[str, List[str]]) -> List[List[float]]:
|
| 18 |
+
if self.model is None:
|
| 19 |
+
self.load_model()
|
| 20 |
+
|
| 21 |
+
if isinstance(text, str):
|
| 22 |
+
text = [text]
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
embeddings = self.model.encode(text)
|
| 26 |
+
return [embedding.tolist() for embedding in embeddings]
|
| 27 |
+
except Exception as e:
|
| 28 |
+
raise RuntimeError(f"Failed to generate embeddings: {str(e)}")
|
| 29 |
+
|
| 30 |
+
embedding_model = EmbeddingModel()
|