asasasText / app.py
Uhhy's picture
Create app.py
aa1f0a9 verified
raw
history blame
2.61 kB
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from llama_cpp import Llama
from multiprocessing import Process, Queue
import uvicorn
from dotenv import load_dotenv
from difflib import SequenceMatcher
load_dotenv()
app = FastAPI()
models = [
{"repo_id": "Ffftdtd5dtft/gpt2-xl-Q2_K-GGUF", "filename": "gpt2-xl-q2_k.gguf"},
{"repo_id": "Ffftdtd5dtft/Meta-Llama-3.1-8B-Instruct-Q2_K-GGUF", "filename": "meta-llama-3.1-8b-instruct-q2_k.gguf"},
{"repo_id": "Ffftdtd5dtft/gemma-2-9b-it-Q2_K-GGUF", "filename": "gemma-2-9b-it-q2_k.gguf"},
{"repo_id": "Ffftdtd5dtft/gemma-2-27b-Q2_K-GGUF", "filename": "gemma-2-27b-q2_k.gguf"},
]
llms = []
for model in models:
llm = Llama.from_pretrained(repo_id=model['repo_id'], filename=model['filename'])
llms.append(llm)
class ChatRequest(BaseModel):
message: str
top_k: int = 50
top_p: float = 0.95
temperature: float = 0.7
def generate_chat_response(request, queue):
try:
user_input = request.message
responses = []
for llm in llms:
response = llm.create_chat_completion(
messages=[{"role": "user", "content": user_input}],
top_k=request.top_k,
top_p=request.top_p,
temperature=request.temperature
)
reply = response['choices'][0]['message']['content']
responses.append(reply)
best_response = select_best_response(responses, request)
queue.put(best_response)
except Exception as e:
queue.put(f"Error: {str(e)}")
def select_best_response(responses, request):
coherent_responses = filter_by_coherence(responses, request)
best_response = filter_by_similarity(coherent_responses)
return best_response
def filter_by_coherence(responses, request):
return responses
def filter_by_similarity(responses):
responses.sort(key=len, reverse=True)
best_response = responses[0]
for i in range(1, len(responses)):
ratio = SequenceMatcher(None, best_response, responses[i]).ratio()
if ratio < 0.9:
best_response = responses[i]
break
return best_response
@app.post("/generate_chat")
async def generate_chat(request: ChatRequest):
queue = Queue()
p = Process(target=generate_chat_response, args=(request, queue))
p.start()
p.join()
response = queue.get()
if "Error" in response:
raise HTTPException(status_code=500, detail=response)
return {"response": response}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8001)