Uhhy commited on
Commit
b76e293
verified
1 Parent(s): 4178dd1

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +159 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from tqdm import tqdm
6
+ import uvicorn
7
+ from dotenv import load_dotenv
8
+ from difflib import SequenceMatcher
9
+ import re
10
+
11
+ # Cargar variables de entorno
12
+ load_dotenv()
13
+
14
+ # Inicializar aplicaci贸n FastAPI
15
+ app = FastAPI()
16
+
17
+ # Diccionario global para almacenar los modelos
18
+ global_data = {
19
+ 'models': []
20
+ }
21
+
22
+ # Configuraci贸n de los modelos
23
+ model_configs = [
24
+ {"repo_id": "Ffftdtd5dtft/gemma-2-9b-it-Q2_K-GGUF", "filename": "gemma-2-9b-it-q2_k.gguf", "name": "Gemma 2-9B IT"},
25
+
26
+ ]
27
+
28
+ # Clase para gestionar modelos
29
+ class ModelManager:
30
+ def __init__(self):
31
+ self.models = []
32
+
33
+ def load_model(self, model_config):
34
+ print(f"Cargando modelo: {model_config['name']}...")
35
+ return {"model": Llama.from_pretrained(repo_id=model_config['repo_id'], filename=model_config['filename']), "name": model_config['name']}
36
+
37
+ def load_all_models(self):
38
+ print("Iniciando carga de modelos...")
39
+ with ThreadPoolExecutor(max_workers=len(model_configs)) as executor:
40
+ futures = [executor.submit(self.load_model, config) for config in model_configs]
41
+ models = []
42
+ for future in tqdm(as_completed(futures), total=len(model_configs), desc="Cargando modelos", unit="modelo"):
43
+ try:
44
+ model = future.result()
45
+ models.append(model)
46
+ print(f"Modelo cargado exitosamente: {model['name']}")
47
+ except Exception as e:
48
+ print(f"Error al cargar el modelo: {e}")
49
+ print("Todos los modelos han sido cargados.")
50
+ return models
51
+
52
+ # Instanciar ModelManager y cargar modelos
53
+ model_manager = ModelManager()
54
+ global_data['models'] = model_manager.load_all_models()
55
+
56
+ # Modelo global para la solicitud de chat
57
+ class ChatRequest(BaseModel):
58
+ message: str
59
+ top_k: int = 50
60
+ top_p: float = 0.95
61
+ temperature: float = 0.7
62
+
63
+ # Funci贸n para generar respuestas de chat
64
+ def generate_chat_response(request, model_data):
65
+ try:
66
+ user_input = normalize_input(request.message)
67
+ llm = model_data['model']
68
+ response = llm.create_chat_completion(
69
+ messages=[{"role": "user", "content": user_input}],
70
+ top_k=request.top_k,
71
+ top_p=request.top_p,
72
+ temperature=request.temperature
73
+ )
74
+ reply = response['choices'][0]['message']['content']
75
+ return {"response": reply, "literal": user_input, "model_name": model_data['name']}
76
+ except Exception as e:
77
+ return {"response": f"Error: {str(e)}", "literal": user_input, "model_name": model_data['name']}
78
+
79
+ def normalize_input(input_text):
80
+ return input_text.strip()
81
+
82
+ def remove_duplicates(text):
83
+ text = re.sub(r'(Hello there, how are you\? \[/INST\]){2,}', 'Hello there, how are you? [/INST]', text)
84
+ text = re.sub(r'(How are you\? \[/INST\]){2,}', 'How are you? [/INST]', text)
85
+ text = text.replace('[/INST]', '')
86
+ lines = text.split('\n')
87
+ unique_lines = list(dict.fromkeys(lines))
88
+ return '\n'.join(unique_lines).strip()
89
+
90
+ def remove_repetitive_responses(responses):
91
+ seen = set()
92
+ unique_responses = []
93
+ for response in responses:
94
+ normalized_response = remove_duplicates(response['response'])
95
+ if normalized_response not in seen:
96
+ seen.add(normalized_response)
97
+ unique_responses.append(response)
98
+ return unique_responses
99
+
100
+ def select_best_response(responses):
101
+ print("Filtrando respuestas...")
102
+ responses = remove_repetitive_responses(responses)
103
+ responses = [remove_duplicates(response['response']) for response in responses]
104
+ unique_responses = list(set(responses))
105
+ coherent_responses = filter_by_coherence(unique_responses)
106
+ best_response = filter_by_similarity(coherent_responses)
107
+ return best_response
108
+
109
+ def filter_by_coherence(responses):
110
+ print("Ordenando respuestas por coherencia...")
111
+ responses.sort(key=len, reverse=True)
112
+ return responses
113
+
114
+ def filter_by_similarity(responses):
115
+ print("Filtrando respuestas por similitud...")
116
+ responses.sort(key=len, reverse=True)
117
+ best_response = responses[0]
118
+ for i in range(1, len(responses)):
119
+ ratio = SequenceMatcher(None, best_response, responses[i]).ratio()
120
+ if ratio < 0.9:
121
+ best_response = responses[i]
122
+ break
123
+ return best_response
124
+
125
+ def worker_function(model_data, request):
126
+ print(f"Generando respuesta con el modelo: {model_data['name']}...")
127
+ response = generate_chat_response(request, model_data)
128
+ return response
129
+
130
+ @app.post("/generate_chat")
131
+ async def generate_chat(request: ChatRequest):
132
+ if not request.message.strip():
133
+ raise HTTPException(status_code=400, detail="The message cannot be empty.")
134
+
135
+ print(f"Procesando solicitud: {request.message}")
136
+
137
+ responses = []
138
+ num_models = len(global_data['models'])
139
+
140
+ with ThreadPoolExecutor(max_workers=num_models) as executor:
141
+ futures = [executor.submit(worker_function, model_data, request) for model_data in global_data['models']]
142
+ for future in tqdm(as_completed(futures), total=num_models, desc="Generando respuestas", unit="modelo"):
143
+ try:
144
+ response = future.result()
145
+ responses.append(response)
146
+ except Exception as exc:
147
+ print(f"Error en la generaci贸n de respuesta: {exc}")
148
+
149
+ best_response = select_best_response(responses)
150
+
151
+ print(f"Mejor respuesta seleccionada: {best_response}")
152
+
153
+ return {
154
+ "best_response": best_response,
155
+ "all_responses": responses
156
+ }
157
+
158
+ if __name__ == "__main__":
159
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ llama-cpp-python
4
+ python-dotenv
5
+ tqdm