Uhhy commited on
Commit
e3a7b6f
1 Parent(s): 8ea10fb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from llama_cpp import Llama
4
+ from concurrent.futures import ThreadPoolExecutor, as_completed
5
+ import uvicorn
6
+ from dotenv import load_dotenv
7
+ from difflib import SequenceMatcher
8
+ from tqdm import tqdm
9
+
10
+ load_dotenv()
11
+
12
+ app = FastAPI()
13
+
14
+ # Configuración de los modelos
15
+ models = [
16
+ {"repo_id": "Ffftdtd5dtft/gpt2-xl-Q2_K-GGUF", "filename": "gpt2-xl-q2_k.gguf"},
17
+ {"repo_id": "Ffftdtd5dtft/Meta-Llama-3.1-8B-Instruct-Q2_K-GGUF", "filename": "meta-llama-3.1-8b-instruct-q2_k.gguf"},
18
+ {"repo_id": "Ffftdtd5dtft/gemma-2-9b-it-Q2_K-GGUF", "filename": "gemma-2-9b-it-q2_k.gguf"},
19
+ {"repo_id": "Ffftdtd5dtft/gemma-2-27b-Q2_K-GGUF", "filename": "gemma-2-27b-q2_k.gguf"},
20
+ ]
21
+
22
+ # Cargar modelos en RAM solo una vez
23
+ llms = [Llama.from_pretrained(repo_id=model['repo_id'], filename=model['filename']) for model in models]
24
+ print(f"Modelos cargados en RAM: {[model['repo_id'] for model in models]}")
25
+
26
+ class ChatRequest(BaseModel):
27
+ message: str
28
+ top_k: int = 50
29
+ top_p: float = 0.95
30
+ temperature: float = 0.7
31
+
32
+ def generate_chat_response(request, llm):
33
+ try:
34
+ user_input = normalize_input(request.message)
35
+ response = llm.create_chat_completion(
36
+ messages=[{"role": "user", "content": user_input}],
37
+ top_k=request.top_k,
38
+ top_p=request.top_p,
39
+ temperature=request.temperature
40
+ )
41
+ reply = response['choices'][0]['message']['content']
42
+ return {"response": reply, "literal": user_input}
43
+ except Exception as e:
44
+ return {"response": f"Error: {str(e)}", "literal": user_input}
45
+
46
+ def normalize_input(input_text):
47
+ return input_text.strip()
48
+
49
+ def select_best_response(responses):
50
+ # Deduplicar respuestas
51
+ unique_responses = list(set(responses))
52
+ # Filtrar respuestas coherentes
53
+ coherent_responses = filter_by_coherence(unique_responses)
54
+ # Seleccionar la mejor respuesta
55
+ best_response = filter_by_similarity(coherent_responses)
56
+ return best_response
57
+
58
+ def filter_by_coherence(responses):
59
+ # Implementa aquí un filtro de coherencia si es necesario
60
+ return responses
61
+
62
+ def filter_by_similarity(responses):
63
+ responses.sort(key=len, reverse=True)
64
+ best_response = responses[0]
65
+ for i in range(1, len(responses)):
66
+ ratio = SequenceMatcher(None, best_response, responses[i]).ratio()
67
+ if ratio < 0.9:
68
+ best_response = responses[i]
69
+ break
70
+ return best_response
71
+
72
+ @app.post("/generate_chat")
73
+ async def generate_chat(request: ChatRequest):
74
+ if not request.message.strip():
75
+ raise HTTPException(status_code=400, detail="The message cannot be empty.")
76
+
77
+ print(f"Procesando solicitud: {request.message}")
78
+
79
+ # Utilizar un ThreadPoolExecutor para procesar los modelos en paralelo
80
+ with ThreadPoolExecutor() as executor:
81
+ futures = [executor.submit(generate_chat_response, request, llm) for llm in llms]
82
+ responses = []
83
+
84
+ for future in tqdm(as_completed(futures), total=len(futures), desc="Generando respuestas"):
85
+ response = future.result()
86
+ responses.append(response)
87
+ print(f"Modelo procesado: {response['literal'][:30]}...")
88
+
89
+ # Extraer respuestas de los diccionarios
90
+ response_texts = [resp['response'] for resp in responses]
91
+
92
+ # Verificar si hay errores en las respuestas
93
+ error_responses = [resp for resp in responses if "Error" in resp['response']]
94
+ if error_responses:
95
+ error_response = error_responses[0]
96
+ raise HTTPException(status_code=500, detail=error_response['response'])
97
+
98
+ # Seleccionar la mejor respuesta
99
+ best_response = select_best_response(response_texts)
100
+
101
+ print(f"Mejor respuesta seleccionada: {best_response}")
102
+
103
+ return {
104
+ "best_response": best_response,
105
+ "all_responses": response_texts
106
+ }
107
+
108
+ if __name__ == "__main__":
109
+ uvicorn.run(app, host="0.0.0.0", port=7860)