Spaces:
Runtime error
Runtime error
Upload 8 files
Browse files- .dockerignore +25 -0
- .env +3 -0
- .gitkeep +1 -0
- Dockerfile +26 -0
- README.md +98 -10
- app.py +138 -0
- docker-compose.yml +33 -0
- requirements.txt +11 -0
.dockerignore
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
.gitignore
|
| 3 |
+
.env
|
| 4 |
+
__pycache__
|
| 5 |
+
*.pyc
|
| 6 |
+
*.pyo
|
| 7 |
+
*.pyd
|
| 8 |
+
.Python
|
| 9 |
+
env/
|
| 10 |
+
venv/
|
| 11 |
+
.venv/
|
| 12 |
+
pip-log.txt
|
| 13 |
+
pip-delete-this-directory.txt
|
| 14 |
+
.tox/
|
| 15 |
+
.coverage
|
| 16 |
+
.coverage.*
|
| 17 |
+
.cache
|
| 18 |
+
nosetests.xml
|
| 19 |
+
coverage.xml
|
| 20 |
+
*.cover
|
| 21 |
+
*.log
|
| 22 |
+
.pytest_cache/
|
| 23 |
+
.env
|
| 24 |
+
.venv
|
| 25 |
+
.DS_Store
|
.env
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# API Keys
|
| 2 |
+
GOOGLE_API_KEY=AIzaSyDn_HIQ8bgbzwO2QZrQXVT1iCntRjTfolc
|
| 3 |
+
PINECONE_API_KEY=pcsk_6vr46t_6dHwWDgmQ8vbdG3JGwARyXEHnhyejW276nWZLVDBtrXD4bydfNw3uimdTvyoJLZ
|
.gitkeep
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
Dockerfile
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use Python 3.11 slim image as base
|
| 2 |
+
FROM python:3.11-slim
|
| 3 |
+
|
| 4 |
+
# Set working directory
|
| 5 |
+
WORKDIR /app
|
| 6 |
+
|
| 7 |
+
# Install system dependencies
|
| 8 |
+
RUN apt-get update && apt-get install -y \
|
| 9 |
+
build-essential \
|
| 10 |
+
curl \
|
| 11 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 12 |
+
|
| 13 |
+
# Copy requirements first to leverage Docker cache
|
| 14 |
+
COPY requirements.txt .
|
| 15 |
+
|
| 16 |
+
# Install Python dependencies
|
| 17 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 18 |
+
|
| 19 |
+
# Copy the rest of the application
|
| 20 |
+
COPY . .
|
| 21 |
+
|
| 22 |
+
# Expose port
|
| 23 |
+
EXPOSE 8000
|
| 24 |
+
|
| 25 |
+
# Command to run the application
|
| 26 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
|
README.md
CHANGED
|
@@ -1,10 +1,98 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RAG Model for Solana SuperTeam Chatbot
|
| 2 |
+
|
| 3 |
+
Mô hình RAG (Retrieval Augmented Generation) cho Solana SuperTeam Chatbot sử dụng Gemini-1.5-flash và Pinecone để lưu trữ và truy xuất dữ liệu liên quan đến Solana SuperTeam.
|
| 4 |
+
|
| 5 |
+
## Cấu trúc
|
| 6 |
+
|
| 7 |
+
```
|
| 8 |
+
.
|
| 9 |
+
├── NLP_model/
|
| 10 |
+
│ └── chatbot.py # Chứa logic của mô hình RAG
|
| 11 |
+
├── app.py # FastAPI server
|
| 12 |
+
├── requirements.txt # Thư viện cần thiết
|
| 13 |
+
├── Dockerfile # Docker configuration
|
| 14 |
+
├── docker-compose.yml # Docker Compose configuration
|
| 15 |
+
├── .dockerignore # Docker ignore file
|
| 16 |
+
└── .env # Biến môi trường (API keys)
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
## Cài đặt
|
| 20 |
+
|
| 21 |
+
### Cài đặt trực tiếp
|
| 22 |
+
|
| 23 |
+
1. Cài đặt các thư viện:
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
pip install -r requirements.txt
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
2. Cấu hình API keys trong file `.env`:
|
| 30 |
+
|
| 31 |
+
```
|
| 32 |
+
GOOGLE_API_KEY=your_google_api_key
|
| 33 |
+
PINECONE_API_KEY=your_pinecone_api_key
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
3. Chạy API:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
python app.py
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
### Cài đặt bằng Docker
|
| 43 |
+
|
| 44 |
+
1. Đảm bảo đã cài đặt Docker và Docker Compose
|
| 45 |
+
|
| 46 |
+
2. Cấu hình API keys trong file `.env`:
|
| 47 |
+
|
| 48 |
+
```
|
| 49 |
+
GOOGLE_API_KEY=your_google_api_key
|
| 50 |
+
PINECONE_API_KEY=your_pinecone_api_key
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
3. Build và chạy container:
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
docker-compose up --build
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
API sẽ chạy trên `http://localhost:8000`.
|
| 60 |
+
|
| 61 |
+
## API Endpoints
|
| 62 |
+
|
| 63 |
+
### POST /chat
|
| 64 |
+
|
| 65 |
+
Gửi câu hỏi đến mô hình RAG:
|
| 66 |
+
|
| 67 |
+
```json
|
| 68 |
+
{
|
| 69 |
+
"query": "Câu hỏi của người dùng",
|
| 70 |
+
"user_id": "id_của_người_dùng"
|
| 71 |
+
}
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Response:
|
| 75 |
+
|
| 76 |
+
```json
|
| 77 |
+
{
|
| 78 |
+
"response": "Câu trả lời từ mô hình RAG"
|
| 79 |
+
}
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
### GET /health
|
| 83 |
+
|
| 84 |
+
Kiểm tra trạng thái của API:
|
| 85 |
+
|
| 86 |
+
```json
|
| 87 |
+
{
|
| 88 |
+
"status": "healthy"
|
| 89 |
+
}
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
## Lưu ý
|
| 93 |
+
|
| 94 |
+
- Mô hình sử dụng Pinecone index "testbot768" để lưu trữ và truy xuất thông tin.
|
| 95 |
+
- Nếu Pinecone không khả dụng, mô hình sẽ cố gắng sử dụng FAISS local index nếu có.
|
| 96 |
+
- Mô hình lưu lịch sử trò chuyện cho mỗi người dùng để cung cấp phản hồi phù hợp với ngữ cảnh.
|
| 97 |
+
- Khi sử dụng Docker, các biến môi trường sẽ được tự động load từ file .env.
|
| 98 |
+
- Container sẽ tự động restart nếu gặp lỗi hoặc server được khởi động lại.
|
app.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from fastapi.responses import JSONResponse
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from NLP_model import chatbot
|
| 6 |
+
import uvicorn
|
| 7 |
+
import asyncio
|
| 8 |
+
import time
|
| 9 |
+
import logging
|
| 10 |
+
from contextlib import asynccontextmanager
|
| 11 |
+
|
| 12 |
+
# Configure logging
|
| 13 |
+
logging.basicConfig(
|
| 14 |
+
level=logging.INFO,
|
| 15 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 16 |
+
)
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
# Chuẩn bị RAG model tại lúc khởi động
|
| 20 |
+
@asynccontextmanager
|
| 21 |
+
async def lifespan(app: FastAPI):
|
| 22 |
+
# Khởi tạo retriever sẵn khi server bắt đầu
|
| 23 |
+
logger.info("Initializing RAG model retriever...")
|
| 24 |
+
# Sử dụng asyncio.to_thread để không block event loop
|
| 25 |
+
await asyncio.to_thread(chatbot.get_chain)
|
| 26 |
+
logger.info("RAG model retriever initialized successfully")
|
| 27 |
+
yield
|
| 28 |
+
# Dọn dẹp khi shutdown
|
| 29 |
+
logger.info("Shutting down RAG model...")
|
| 30 |
+
|
| 31 |
+
app = FastAPI(
|
| 32 |
+
title="Solana SuperTeam RAG API",
|
| 33 |
+
description="API cho mô hình RAG của Solana SuperTeam",
|
| 34 |
+
version="1.0.0",
|
| 35 |
+
lifespan=lifespan
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Add CORS middleware
|
| 39 |
+
app.add_middleware(
|
| 40 |
+
CORSMiddleware,
|
| 41 |
+
allow_origins=["*"],
|
| 42 |
+
allow_credentials=True,
|
| 43 |
+
allow_methods=["*"],
|
| 44 |
+
allow_headers=["*"],
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# Request counter để theo dõi số lượng request đang xử lý
|
| 48 |
+
active_requests = 0
|
| 49 |
+
max_concurrent_requests = 5 # Giới hạn số request xử lý đồng thời
|
| 50 |
+
request_lock = asyncio.Lock()
|
| 51 |
+
|
| 52 |
+
class ChatRequest(BaseModel):
|
| 53 |
+
query: str
|
| 54 |
+
user_id: str = "default_user"
|
| 55 |
+
|
| 56 |
+
class ChatResponse(BaseModel):
|
| 57 |
+
response: str
|
| 58 |
+
processing_time: float = None
|
| 59 |
+
|
| 60 |
+
@app.middleware("http")
|
| 61 |
+
async def add_process_time_header(request: Request, call_next):
|
| 62 |
+
"""Middleware để đo thời gian xử lý và kiểm soát số lượng request"""
|
| 63 |
+
global active_requests
|
| 64 |
+
|
| 65 |
+
# Kiểm tra và tăng số request đang xử lý
|
| 66 |
+
async with request_lock:
|
| 67 |
+
# Nếu đã đạt giới hạn, từ chối request mới
|
| 68 |
+
if active_requests >= max_concurrent_requests and request.url.path == "/chat":
|
| 69 |
+
return JSONResponse(
|
| 70 |
+
status_code=429,
|
| 71 |
+
content={"detail": "Too many requests. Please try again later."}
|
| 72 |
+
)
|
| 73 |
+
active_requests += 1
|
| 74 |
+
|
| 75 |
+
try:
|
| 76 |
+
start_time = time.time()
|
| 77 |
+
response = await call_next(request)
|
| 78 |
+
process_time = time.time() - start_time
|
| 79 |
+
|
| 80 |
+
# Thêm thời gian xử lý vào header
|
| 81 |
+
response.headers["X-Process-Time"] = str(process_time)
|
| 82 |
+
logger.info(f"Request processed in {process_time:.2f} seconds: {request.url.path}")
|
| 83 |
+
return response
|
| 84 |
+
finally:
|
| 85 |
+
# Giảm counter khi xử lý xong
|
| 86 |
+
async with request_lock:
|
| 87 |
+
active_requests -= 1
|
| 88 |
+
|
| 89 |
+
@app.post("/chat", response_model=ChatResponse)
|
| 90 |
+
async def chat_endpoint(request: ChatRequest):
|
| 91 |
+
"""
|
| 92 |
+
Xử lý yêu cầu chat từ người dùng
|
| 93 |
+
"""
|
| 94 |
+
start_time = time.time()
|
| 95 |
+
try:
|
| 96 |
+
# Gọi hàm chat với thông tin được cung cấp
|
| 97 |
+
response = await asyncio.to_thread(chatbot.chat, request.query, request.user_id)
|
| 98 |
+
process_time = time.time() - start_time
|
| 99 |
+
return ChatResponse(
|
| 100 |
+
response=response,
|
| 101 |
+
processing_time=process_time
|
| 102 |
+
)
|
| 103 |
+
except Exception as e:
|
| 104 |
+
logger.error(f"Error processing chat request: {e}")
|
| 105 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 106 |
+
|
| 107 |
+
@app.get("/health")
|
| 108 |
+
async def health_check():
|
| 109 |
+
"""
|
| 110 |
+
Kiểm tra trạng thái của API
|
| 111 |
+
"""
|
| 112 |
+
# Kiểm tra xem retriever đã được khởi tạo chưa
|
| 113 |
+
retriever = chatbot.get_chain()
|
| 114 |
+
if retriever:
|
| 115 |
+
status = "healthy"
|
| 116 |
+
else:
|
| 117 |
+
status = "degraded"
|
| 118 |
+
|
| 119 |
+
return {
|
| 120 |
+
"status": status,
|
| 121 |
+
"active_requests": active_requests,
|
| 122 |
+
"cache_size": len(chatbot.response_cache)
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
@app.post("/clear-memory/{user_id}")
|
| 126 |
+
async def clear_user_memory(user_id: str):
|
| 127 |
+
"""
|
| 128 |
+
Xóa lịch sử trò chuyện của một người dùng
|
| 129 |
+
"""
|
| 130 |
+
try:
|
| 131 |
+
result = await asyncio.to_thread(chatbot.clear_memory, user_id)
|
| 132 |
+
return {"status": "success", "message": result}
|
| 133 |
+
except Exception as e:
|
| 134 |
+
logger.error(f"Error clearing memory for user {user_id}: {e}")
|
| 135 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
docker-compose.yml
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version: '3.8'
|
| 2 |
+
|
| 3 |
+
services:
|
| 4 |
+
rag-api:
|
| 5 |
+
build:
|
| 6 |
+
context: .
|
| 7 |
+
dockerfile: Dockerfile
|
| 8 |
+
ports:
|
| 9 |
+
- "8000:8000"
|
| 10 |
+
environment:
|
| 11 |
+
- GOOGLE_API_KEY=${GOOGLE_API_KEY}
|
| 12 |
+
- PINECONE_API_KEY=${PINECONE_API_KEY}
|
| 13 |
+
volumes:
|
| 14 |
+
- .:/app
|
| 15 |
+
restart: unless-stopped
|
| 16 |
+
healthcheck:
|
| 17 |
+
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
|
| 18 |
+
interval: 30s
|
| 19 |
+
timeout: 10s
|
| 20 |
+
retries: 3
|
| 21 |
+
deploy:
|
| 22 |
+
resources:
|
| 23 |
+
limits:
|
| 24 |
+
cpus: '1'
|
| 25 |
+
memory: 2G
|
| 26 |
+
reservations:
|
| 27 |
+
cpus: '0.5'
|
| 28 |
+
memory: 1G
|
| 29 |
+
logging:
|
| 30 |
+
driver: "json-file"
|
| 31 |
+
options:
|
| 32 |
+
max-size: "10m"
|
| 33 |
+
max-file: "3"
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.109.2
|
| 2 |
+
uvicorn==0.27.1
|
| 3 |
+
pydantic==2.6.1
|
| 4 |
+
python-dotenv==1.0.0
|
| 5 |
+
google-generativeai==0.3.2
|
| 6 |
+
langchain==0.1.9
|
| 7 |
+
langchain-google-genai==0.0.10
|
| 8 |
+
langchain-community==0.0.24
|
| 9 |
+
pinecone-client==3.0.2
|
| 10 |
+
sentence-transformers==2.5.1
|
| 11 |
+
requests==2.31.0
|