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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
import gradio as gr
|
| 6 |
+
from sentence_transformers import SentenceTransformer
|
| 7 |
+
import numpy as np
|
| 8 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 9 |
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
class MultilingualLlamaAgent:
|
| 12 |
+
"""
|
| 13 |
+
A multilingual chatbot powered by Llama hosted on Hugging Face with RAG capabilities.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def __init__(self):
|
| 17 |
+
"""Initialize the Hugging Face API client for Llama 3.2 and RAG components."""
|
| 18 |
+
print("Initializing Llama 3.2 multilingual agent with RAG...")
|
| 19 |
+
|
| 20 |
+
# Set up the model ID and API token
|
| 21 |
+
self.model_id = os.environ.get('MODEL')
|
| 22 |
+
self.api_token = os.environ.get("HF_TOKEN")
|
| 23 |
+
self.api_url = f"https://api-inference.huggingface.co/models/{self.model_id}"
|
| 24 |
+
|
| 25 |
+
# Parameters for text generation
|
| 26 |
+
self.max_new_tokens = 540
|
| 27 |
+
self.temperature = 0.7
|
| 28 |
+
self.top_p = 0.9
|
| 29 |
+
|
| 30 |
+
# Add greeting message
|
| 31 |
+
self.greeting_message = """Hola, entiendo que estás buscando información y asesoramiento. Estoy aquí para ayudarte.
|
| 32 |
+
Para que esta conversación sea lo más cómoda para ti, ¿cómo prefieres que te llame o cuáles son tus pronombres?. Si prefieres mantener tu anonimato, puedes usar un nombre ficticio.
|
| 33 |
+
|
| 34 |
+
# RAG components
|
| 35 |
+
self.embedding_model = SentenceTransformer(
|
| 36 |
+
"paraphrase-multilingual-MiniLM-L12-v2"
|
| 37 |
+
)
|
| 38 |
+
self.knowledge_base = self.load_knowledge_base(os.environ.get('PROTOCOLO'))
|
| 39 |
+
self.knowledge_embeddings = self.embed_knowledge_base()
|
| 40 |
+
|
| 41 |
+
def load_knowledge_base(self, knowledge_base):
|
| 42 |
+
"""Load the knowledge base from a provided string."""
|
| 43 |
+
try:
|
| 44 |
+
# Split the content into chunks (paragraphs)
|
| 45 |
+
chunks = [
|
| 46 |
+
chunk.strip() for chunk in self.knowledge_base.split("\n\n") if chunk.strip()
|
| 47 |
+
]
|
| 48 |
+
return chunks
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"Error processing knowledge base: {str(e)}")
|
| 51 |
+
return []
|
| 52 |
+
|
| 53 |
+
def embed_knowledge_base(self):
|
| 54 |
+
"""Create embeddings for the knowledge base chunks."""
|
| 55 |
+
if not self.knowledge_base:
|
| 56 |
+
return []
|
| 57 |
+
return self.embedding_model.encode(self.knowledge_base)
|
| 58 |
+
|
| 59 |
+
def retrieve_relevant_info(self, query, top_k=3, threshold=0.5):
|
| 60 |
+
"""Retrieve the most relevant information from the knowledge base."""
|
| 61 |
+
if not self.knowledge_base or not self.knowledge_embeddings.size:
|
| 62 |
+
return ""
|
| 63 |
+
|
| 64 |
+
# Encode the query
|
| 65 |
+
query_embedding = self.embedding_model.encode([query])[0]
|
| 66 |
+
|
| 67 |
+
# Calculate similarity
|
| 68 |
+
similarities = cosine_similarity([query_embedding], self.knowledge_embeddings)[
|
| 69 |
+
0
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
# Get top-k most similar chunks above threshold
|
| 73 |
+
relevant_indices = np.where(similarities > threshold)[0]
|
| 74 |
+
if len(relevant_indices) == 0:
|
| 75 |
+
return ""
|
| 76 |
+
|
| 77 |
+
top_indices = relevant_indices[
|
| 78 |
+
np.argsort(-similarities[relevant_indices])[:top_k]
|
| 79 |
+
]
|
| 80 |
+
|
| 81 |
+
# Combine the relevant information
|
| 82 |
+
relevant_info = "\n\n".join([self.knowledge_base[i] for i in top_indices])
|
| 83 |
+
return relevant_info
|
| 84 |
+
|
| 85 |
+
def extract_answer(self, response_or_json):
|
| 86 |
+
try:
|
| 87 |
+
# Handle different input types
|
| 88 |
+
if hasattr(response_or_json, "json"): # If it's a Response object
|
| 89 |
+
data = response_or_json.json()
|
| 90 |
+
elif isinstance(response_or_json, str): # If it's a JSON string
|
| 91 |
+
data = json.loads(response_or_json)
|
| 92 |
+
else: # If it's already a Python object
|
| 93 |
+
data = response_or_json
|
| 94 |
+
print("data-", data)
|
| 95 |
+
|
| 96 |
+
# Get the generated text from the first item
|
| 97 |
+
generated_text = data[0]["generated_text"]
|
| 98 |
+
pattern = r"<\|start_header_id\|>assistant<\|end_header_id\|>\s*(.*?)(?:<\|eot_id\|>|$)"
|
| 99 |
+
match = re.search(pattern, generated_text, re.DOTALL)
|
| 100 |
+
|
| 101 |
+
if match:
|
| 102 |
+
return match.group(1).strip()
|
| 103 |
+
else:
|
| 104 |
+
return generated_text # Return full text if pattern not found
|
| 105 |
+
|
| 106 |
+
except Exception as e:
|
| 107 |
+
return f"Error processing the input: {str(e)}"
|
| 108 |
+
|
| 109 |
+
def generate_response(self, user_input: str) -> str:
|
| 110 |
+
"""Generate a response using the Hugging Face Inference API and RAG."""
|
| 111 |
+
|
| 112 |
+
# Extract the most recent user query from the full context
|
| 113 |
+
query = user_input.split("Usuario: ")[-1].split("\nAsistente:")[0].strip()
|
| 114 |
+
|
| 115 |
+
# Retrieve relevant information from the knowledge base
|
| 116 |
+
relevant_info = self.retrieve_relevant_info(query)
|
| 117 |
+
|
| 118 |
+
tono = os.environ.get('TONO')
|
| 119 |
+
|
| 120 |
+
tono = f"""
|
| 121 |
+
{tono}
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
# If relevant information is found, include it in the prompt
|
| 125 |
+
if relevant_info:
|
| 126 |
+
system_context = f"""
|
| 127 |
+
Eres un asistente a victimas de violencia laboral que sigue las siguientes instrucciones de tono al reponder las preguntas de los usuarios {tono}
|
| 128 |
+
|
| 129 |
+
Información relevante para responder a la consulta del usuario:
|
| 130 |
+
{relevant_info}
|
| 131 |
+
|
| 132 |
+
Utiliza la información proporcionada para dar una respuesta más precisa y útil, pero siempre manteniendo el tono y enfoque adecuados.
|
| 133 |
+
"""
|
| 134 |
+
else:
|
| 135 |
+
system_context = f"""
|
| 136 |
+
Eres un asistente a victimas de violencia laboral que sigue las siguientes instrucciones de tono al reponder las preguntas de los usuarios {tono}
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
prompt = f"""
|
| 140 |
+
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
|
| 141 |
+
|
| 142 |
+
{system_context}<|eot_id|><|start_header_id|>user<|end_header_id|>
|
| 143 |
+
|
| 144 |
+
{user_input}<|eot_id|><|start_header_id|>assistant<|end_header_id|>
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
try:
|
| 148 |
+
# Prepare the payload for the API request
|
| 149 |
+
payload = {
|
| 150 |
+
"inputs": prompt,
|
| 151 |
+
"parameters": {
|
| 152 |
+
"max_new_tokens": self.max_new_tokens,
|
| 153 |
+
"temperature": self.temperature,
|
| 154 |
+
"top_p": self.top_p,
|
| 155 |
+
},
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
# Set up headers with authorization
|
| 159 |
+
headers = {"Authorization": f"Bearer {self.api_token}"}
|
| 160 |
+
|
| 161 |
+
# Make the API request
|
| 162 |
+
response = requests.post(self.api_url, headers=headers, json=payload)
|
| 163 |
+
|
| 164 |
+
# Check for successful response
|
| 165 |
+
if response.status_code == 200:
|
| 166 |
+
result = response.json()
|
| 167 |
+
print("result-", result)
|
| 168 |
+
return self.extract_answer(result)
|
| 169 |
+
else:
|
| 170 |
+
return f"Error: {response.status_code} - {response.text}"
|
| 171 |
+
|
| 172 |
+
except Exception as e:
|
| 173 |
+
return f"An error occurred: {str(e)}"
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def chat_with_agent(message, history):
|
| 177 |
+
"""Handle user input and generate a response for the Gradio interface."""
|
| 178 |
+
if not agent.api_token:
|
| 179 |
+
return history + [
|
| 180 |
+
[
|
| 181 |
+
message,
|
| 182 |
+
"Error: Hugging Face API token is missing. Please set the HF_TOKEN environment variable.",
|
| 183 |
+
]
|
| 184 |
+
]
|
| 185 |
+
|
| 186 |
+
# Construct full history for context
|
| 187 |
+
full_context = ""
|
| 188 |
+
for h in history:
|
| 189 |
+
full_context += f"Usuario: {h[0]}\nAsistente: {h[1]}\n"
|
| 190 |
+
|
| 191 |
+
full_context += f"Usuario: {message}\nAsistente:"
|
| 192 |
+
|
| 193 |
+
response = agent.generate_response(full_context)
|
| 194 |
+
|
| 195 |
+
# Return updated history with new message pair
|
| 196 |
+
return history + [[message, response]]
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# Initialize the agent
|
| 200 |
+
agent = MultilingualLlamaAgent()
|
| 201 |
+
|
| 202 |
+
# Create the Gradio interface
|
| 203 |
+
with gr.Blocks() as demo:
|
| 204 |
+
gr.Markdown("""
|
| 205 |
+
# 🤖 Chatbot basado en Llama para atencion a victimas de acoso laboral.
|
| 206 |
+
|
| 207 |
+
## ¡Hola!
|
| 208 |
+
|
| 209 |
+
Gracias por contactarnos. Entendemos que has pasado por una situación incómoda y estamos acá para ofrecerte un espacio seguro y confiable para que puedas compartir tu experiencia.
|
| 210 |
+
|
| 211 |
+
Antes de empezar, queremos informarte que estás conversando con un chatbot con inteligencia artificial diseñado para ofrecerte información, recursos, apoyo y acompañamiento. Si en algún momento necesitas hablar con una persona real, te indicaremos cómo hacerlo.
|
| 212 |
+
|
| 213 |
+
Además, queremos asegurarte que toda la información que compartas con nosotros será tratada con la máxima **confidencialidad**. Nadie más tendrá acceso a esta información sin tu consentimiento expreso en esta primera etapa. La información que proporciones se utilizará únicamente para entender mejor lo que te ocurrió y buscar las mejores soluciones para ti. También queremos que sepas que nos guiamos por principios de derechos humanos para que este espacio esté libre de prejuicios, sesgos y estereotipos. Creemos que todas las personas merecen ser tratadas con respeto e igualdad, independientemente de su género, orientación sexual, origen étnico, color de piel, religión o cualquier otra condición. No toleramos ninguna forma de discriminación.
|
| 214 |
+
|
| 215 |
+
Aquí encontrarás información útil sobre la violencia laboral, tus derechos y los recursos disponibles para que puedas tomar las mejores decisiones de manera informada.
|
| 216 |
+
""")
|
| 217 |
+
|
| 218 |
+
with gr.Row():
|
| 219 |
+
with gr.Column(scale=2):
|
| 220 |
+
chatbot = gr.Chatbot(height=500, value=[[None, agent.greeting_message]])
|
| 221 |
+
msg = gr.Textbox(placeholder="Escribe tu mensaje aquí...", show_label=False)
|
| 222 |
+
|
| 223 |
+
with gr.Row():
|
| 224 |
+
submit_btn = gr.Button("Enviar")
|
| 225 |
+
clear_btn = gr.Button("Limpiar chat")
|
| 226 |
+
|
| 227 |
+
with gr.Column(scale=1):
|
| 228 |
+
gr.Markdown("""
|
| 229 |
+
- Este chatbot esta entrenado sobre un modelo Llama.
|
| 230 |
+
- Sigue protocolos creados para atencion a victimas de acoso laboral por expertos en la materia.
|
| 231 |
+
""")
|
| 232 |
+
|
| 233 |
+
# Set up event handlers
|
| 234 |
+
submit_btn.click(chat_with_agent, [msg, chatbot], [chatbot])
|
| 235 |
+
msg.submit(chat_with_agent, [msg, chatbot], [chatbot])
|
| 236 |
+
clear_btn.click(
|
| 237 |
+
lambda: [[None, agent.greeting_message]], None, chatbot, queue=False
|
| 238 |
+
) # Modified to keep greeting
|
| 239 |
+
submit_btn.click(lambda: "", None, msg, queue=False)
|
| 240 |
+
msg.submit(lambda: "", None, msg, queue=False)
|
| 241 |
+
|
| 242 |
+
# Launch the app
|
| 243 |
+
if __name__ == "__main__":
|
| 244 |
+
demo.launch(share=True)
|