Spaces:
Sleeping
Sleeping
import gradio as gr | |
from llama_cpp import Llama | |
# Ruta al modelo GGUF descargado | |
MODEL_PATH = "./shieldgemma-9b.Q4_K_M.gguf" | |
# Inicializa el modelo con llama-cpp-python | |
llm = Llama(model_path=MODEL_PATH, n_ctx=2048, n_threads=2, chat_format="chatml") | |
def generar_prompt(user_prompt, policy): | |
prompt = f"""You are a policy expert trying to help determine whether a user prompt is in violation of the following safety policy: | |
{policy} | |
<start_of_turn> | |
Human Question: {user_prompt.strip()} | |
<end_of_turn> | |
Does the human question violate the above policy? Your answer must start with 'Yes' or 'No'. And then walk through step by step to be sure we answer correctly. | |
""" | |
return prompt | |
def verificar_politica(message): | |
policies = { | |
"No Dangerous Content": "The prompt shall not contain or seek generation of content that harms oneself and/or others (e.g., accessing or building firearms and explosive devices, promotion of terrorism, instructions for suicide).", | |
"No Harassment": "The prompt shall not contain or seek generation of content that is malicious, intimidating, bullying, or abusive content targeting another individual (e.g., physical threats, denial of tragic events, disparaging victims of violence).", | |
"No Hate Speech": "The prompt shall not contain or seek generation of content that targets identity and/or protected attributes (e.g., racial slurs, promotion of discrimination, calls to violence against protected groups) or dehumanizing/belittling/vilifying based on race, ethnicity, religion, disability, age, nationality, veteran status, sexual orientation, gender, gender identity, caste, or any other protected status.", | |
"No Sexually Explicit Information": "The prompt shall not contain or seek generation of content that contains references to sexual acts or other lewd content (e.g., sexually graphic descriptions, content aimed at causing arousal). Medical or scientific terms related to human anatomy or sex education are permitted." | |
} | |
scores = {} | |
for policy_name, policy_text in policies.items(): | |
prompt = generar_prompt(message, policy_text) | |
response = llm.create_chat_completion( | |
messages=[{"role": "system", "content": prompt}], | |
stream=False | |
) | |
answer = response['choices'][0]['message']['content'] | |
# Calcula las probabilidades de "Yes" y "No" bas谩ndote en la respuesta generada | |
yes_count = answer.lower().count("yes") | |
no_count = answer.lower().count("no") | |
total_count = yes_count + no_count | |
if total_count == 0: | |
yes_probability = 0 | |
else: | |
yes_probability = yes_count / total_count | |
scores[policy_name] = yes_probability | |
print(f"Policy: {policy_name}") | |
print(f"Score: {yes_probability:.2f}") | |
# Determina si alguna pol铆tica tiene una puntuaci贸n alta | |
for policy_name, score in scores.items(): | |
if score > 0.5: | |
return f"Your question violates the following policy: {policy_name} with a score of {score:.2f}" | |
return None | |
def respond(message, history, system_prompt): | |
policy_violation = verificar_politica(message) | |
if policy_violation: | |
return policy_violation | |
messages_prompts = [{"role": "system", "content": system_prompt}] | |
for human, assistant in history: | |
messages_prompts.append({"role": "user", "content": human}) | |
messages_prompts.append({"role": "assistant", "content": assistant}) | |
messages_prompts.append({"role": "user", "content": message}) | |
response = llm.create_chat_completion( | |
messages=messages_prompts, | |
stream=False | |
) | |
return response['choices'][0]['message']['content'] | |
def chat_stream_completion(message, history, system_prompt): | |
messages_prompts = [{"role": "system", "content": system_prompt}] | |
for human, assistant in history: | |
messages_prompts.append({"role": "user", "content": human}) | |
messages_prompts.append({"role": "assistant", "content": assistant}) | |
messages_prompts.append({"role": "user", "content": message}) | |
response = llm.create_chat_completion( | |
messages=messages_prompts, | |
stream=True | |
) | |
message_repl = "" | |
for chunk in response: | |
if len(chunk['choices'][0]["delta"]) != 0 and "content" in chunk['choices'][0]["delta"]: | |
message_repl += chunk['choices'][0]["delta"]["content"] | |
yield message_repl | |
# Interfaz de Gradio con la descripci贸n y configuraci贸n adicional | |
with gr.Blocks() as demo: | |
gr.Markdown("# Child-Safe-Chatbot-for-CPU (Experimental)") | |
gr.Markdown(""" | |
### Description | |
This chatbot is designed to assist users while ensuring that all interactions comply with defined safety policies. It checks whether user inputs violate any of the following categories: | |
- Dangerous Content | |
- Harassment | |
- Hate Speech | |
- Sexually Explicit Information | |
The chatbot will inform the user if any violation occurs and, if not, will proceed to respond to the user's message in a friendly manner. | |
I'm Norberto Mart铆n Afonso. Follow me on [Twitter](https://twitter.com/norbertomartnaf) and [GitHub](https://github.com/nmarafo) for more updates and projects! | |
""") | |
# A帽ade el ChatInterface al bloque | |
chatbot = gr.ChatInterface( | |
fn=chat_stream_completion, | |
#additional_inputs=[gr.Textbox("You are a helpful AI.", label="System Prompt")] | |
) | |
demo.launch(server_name="0.0.0.0", debug=True) |