0-Parth-D commited on
Commit
55bac67
·
1 Parent(s): 8ab380e

Secured the API endpoint

Browse files
Files changed (1) hide show
  1. src/rag_code_assistant/agent.py +19 -3
src/rag_code_assistant/agent.py CHANGED
@@ -3,7 +3,9 @@ import uvicorn
3
  from dotenv import load_dotenv
4
 
5
  load_dotenv()
6
- from fastapi import FastAPI, UploadFile, File
 
 
7
  from fastapi.middleware.cors import CORSMiddleware
8
  from fastapi.responses import StreamingResponse
9
  from pydantic import BaseModel
@@ -78,6 +80,20 @@ def load_agent(tools, llm):
78
 
79
  app = FastAPI(title="Python RAG Agent API")
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  app.add_middleware(
82
  CORSMiddleware,
83
  allow_origins=["*"],
@@ -101,7 +117,7 @@ class ChatRequest(BaseModel):
101
  message: str
102
  history: list[dict] = [] # Allows UI to send previous messages
103
 
104
- @app.post("/chat")
105
  async def chat_endpoint(request: ChatRequest):
106
  # 1. Build the chat history array from the UI's request
107
  chat_history = []
@@ -134,7 +150,7 @@ def custom_token_length(text):
134
  tokens = fast_tokenizer.tokenize(text)
135
  return len(tokens)
136
 
137
- @app.post("/upload")
138
  async def upload_document(file: UploadFile = File(...)):
139
  """Accepts PDF, HTML, MD, and TXT files and uploads them to Pinecone using fast_tokenizer."""
140
 
 
3
  from dotenv import load_dotenv
4
 
5
  load_dotenv()
6
+
7
+ from fastapi.security import APIKeyHeader
8
+ from fastapi import FastAPI, UploadFile, File, Security, HTTPException, status, Depends
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from fastapi.responses import StreamingResponse
11
  from pydantic import BaseModel
 
80
 
81
  app = FastAPI(title="Python RAG Agent API")
82
 
83
+ # 1. Define the name of the header we expect
84
+ api_key_header = APIKeyHeader(name="X-API-Key")
85
+
86
+ # 2. Get your secret password from environment variables
87
+ SECRET_APP_KEY = os.environ["APP_API_KEY"]
88
+
89
+ # 3. Create the security function
90
+ def verify_api_key(api_key: str = Security(api_key_header)):
91
+ if api_key != SECRET_APP_KEY:
92
+ raise HTTPException(
93
+ status_code=status.HTTP_401_UNAUTHORIZED,
94
+ detail="Invalid or missing API Key"
95
+ )
96
+
97
  app.add_middleware(
98
  CORSMiddleware,
99
  allow_origins=["*"],
 
117
  message: str
118
  history: list[dict] = [] # Allows UI to send previous messages
119
 
120
+ @app.post("/chat", dependencies=[Depends(verify_api_key)])
121
  async def chat_endpoint(request: ChatRequest):
122
  # 1. Build the chat history array from the UI's request
123
  chat_history = []
 
150
  tokens = fast_tokenizer.tokenize(text)
151
  return len(tokens)
152
 
153
+ @app.post("/upload", dependencies=[Depends(verify_api_key)])
154
  async def upload_document(file: UploadFile = File(...)):
155
  """Accepts PDF, HTML, MD, and TXT files and uploads them to Pinecone using fast_tokenizer."""
156