-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #92 from Andrewwango/fastapi-backend
Containerised variant of the backend
- Loading branch information
Showing
25 changed files
with
300 additions
and
38 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -347,3 +347,4 @@ __queuestorage__ | |
__azurite_db*__.json | ||
|
||
*.wav | ||
temp/ |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
OPENAI_API_KEY=... | ||
OPENAI_API_URL=... | ||
OPENAI_CHATGPT_DEPLOYMENT=... | ||
OPENAI_GPT_DEPLOYMENT=... | ||
AZURE_SPEECH_KEY=... | ||
AZURE_SPEECH_REGION=... | ||
AZURE_LANGUAGE_KEY=... | ||
AZURE_LANGUAGE_ENDPOINT=... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
azure-ai-textanalytics | ||
azure-cognitiveservices-speech | ||
fastapi | ||
openai | ||
pydantic | ||
python-dotenv | ||
python-multipart | ||
uvicorn |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
if __name__ == "__main__": | ||
from dotenv import load_dotenv | ||
load_dotenv() | ||
|
||
import asyncio | ||
from collections import defaultdict | ||
from datetime import datetime, timedelta | ||
from typing import Annotated | ||
|
||
import fastapi | ||
from fastapi.responses import StreamingResponse | ||
import uvicorn | ||
|
||
from accessible_search import handlers, protocol, services | ||
|
||
app = fastapi.FastAPI() | ||
|
||
rate_limit_lock = asyncio.Lock() | ||
rate_limit_data = defaultdict(list) | ||
rate_limit_times = 10 | ||
rate_limit_window = timedelta(seconds=60) | ||
|
||
|
||
@app.middleware("http") | ||
async def rate_limit_middleware(request: fastapi.Request, call_next): | ||
"""Rudimentary in-memory rate limiting solution.""" | ||
global rate_limit_data | ||
|
||
client_ip = request.client.host | ||
current_time = datetime.now() | ||
|
||
async with rate_limit_lock: | ||
rate_limit_data[client_ip] = [ | ||
time for time in rate_limit_data[client_ip] | ||
if current_time - time < rate_limit_window | ||
] | ||
|
||
if len(rate_limit_data[client_ip]) >= rate_limit_times: | ||
raise fastapi.HTTPException(status_code=429, detail="Too Many Requests") | ||
|
||
rate_limit_data[client_ip].append(current_time) | ||
|
||
return await call_next(request) | ||
|
||
|
||
@app.post("/api/chatgpt", response_model=protocol.TextOutputResponse) | ||
async def query_chatgpt(parameters: protocol.ChatGPTRequest): | ||
response_dict = await handlers.handle_query_chatgpt_async(parameters) | ||
return protocol.TextOutputResponse(**response_dict) | ||
|
||
|
||
@app.post("/api/chatgpt-stream") | ||
async def query_chatgpt_stream(parameters: protocol.ChatGPTRequest): | ||
event_stream = handlers.handle_query_chatgpt_stream(parameters) | ||
return StreamingResponse(event_stream, media_type="text/event-stream") | ||
|
||
|
||
@app.post("/api/select-relevant-section") | ||
async def select_relevant_section(parameters: protocol.SelectRelevantSectionRequest): | ||
response_dict = await handlers.handle_select_relevant_section_async(parameters) | ||
return protocol.TextOutputResponse(**response_dict) | ||
|
||
|
||
@app.post("/api/speech-to-text") | ||
async def speech_to_text(file: Annotated[bytes, fastapi.File()]): | ||
response_dict = services.perform_speech_to_text(content=file) | ||
return protocol.TextOutputResponse(**response_dict) | ||
|
||
|
||
@app.post("/api/text-to-speech") | ||
async def text_to_speech(parameters: protocol.TextToSpeechRequest): | ||
response_dict = services.perform_text_to_speech(parameters.text) | ||
return protocol.TextOutputResponse(**response_dict) | ||
|
||
|
||
if __name__ == "__main__": | ||
# For local testing only | ||
uvicorn.run("server:app", port=8000) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,3 +6,4 @@ azure-ai-textanalytics | |
azure-cognitiveservices-speech | ||
azure-functions | ||
openai | ||
pydantic |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Shared code across backends (Azure Functions, FastAPI). |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
"""Request handlers.""" | ||
|
||
import json | ||
from typing import AsyncIterable | ||
|
||
from accessible_search import preprocessing, prompts, protocol, services | ||
|
||
|
||
def _prepare_query(parameters: protocol.ChatGPTRequest) -> tuple[list[dict], str, float]: | ||
history = preprocessing.preprocess_history(parameters.history) | ||
query = preprocessing.preprocess_query(parameters.query) | ||
context = preprocessing.preprocess_context(parameters.context) | ||
prompt = prompts.construct_query_prompt(context, query) | ||
return history, prompt, parameters.temperature | ||
|
||
|
||
def handle_query_chatgpt(parameters: protocol.ChatGPTRequest) -> protocol.TextOutputResponse: | ||
history, prompt, temperature = _prepare_query(parameters) | ||
return services.perform_chat_completion(history, prompt, temperature=temperature) | ||
|
||
|
||
async def handle_query_chatgpt_async(parameters: protocol.ChatGPTRequest) -> protocol.TextOutputResponse: | ||
history, prompt, temperature = _prepare_query(parameters) | ||
return await services.perform_chat_completion_async(history, prompt, temperature=temperature) | ||
|
||
|
||
async def handle_query_chatgpt_stream(parameters: protocol.ChatGPTRequest) -> AsyncIterable[str]: | ||
history, prompt, temperature = _prepare_query(parameters) | ||
async for result in services.perform_chat_completion_streaming(history, prompt, temperature=temperature): | ||
yield json.dumps({"data": result}) + "\n" | ||
|
||
|
||
def _prepare_select(parameters: protocol.SelectRelevantSectionRequest) -> tuple[list[dict], str]: | ||
history = preprocessing.preprocess_history(parameters.history) | ||
query = preprocessing.preprocess_query(parameters.query) | ||
context = preprocessing.preprocess_context(parameters.context) | ||
prompt = prompts.construct_select_prompt(parameters.options, context, query) | ||
return history, prompt | ||
|
||
|
||
def handle_select_relevant_section(parameters: protocol.SelectRelevantSectionRequest) -> protocol.TextOutputResponse: | ||
history, prompt = _prepare_select(parameters) | ||
return services.perform_chat_completion(history, prompt, max_tokens=16) | ||
|
||
|
||
async def handle_select_relevant_section_async(parameters: protocol.SelectRelevantSectionRequest) -> protocol.TextOutputResponse: | ||
history, prompt = _prepare_select(parameters) | ||
return await services.perform_chat_completion_async(history, prompt, max_tokens=16) |
File renamed without changes.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import pydantic | ||
|
||
|
||
class ChatGPTRequest(pydantic.BaseModel): | ||
query: str | ||
context: str | ||
history: list[dict] = [] | ||
temperature: float = 0.0 | ||
|
||
|
||
class SelectRelevantSectionRequest(pydantic.BaseModel): | ||
query: str | ||
context: str = "" | ||
options: list[str] | ||
history: list[dict] = [] | ||
|
||
|
||
class TextToSpeechRequest(pydantic.BaseModel): | ||
text: str | ||
|
||
|
||
class TextOutputResponse(pydantic.BaseModel): | ||
output: str |
Oops, something went wrong.