pratikshahp commited on
Commit
8d5b4ff
·
verified ·
1 Parent(s): 5f09afc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ import gradio as gr
4
+ from langchain_huggingface import HuggingFaceEndpoint
5
+
6
+ # Load environment variables
7
+ load_dotenv()
8
+ HF_TOKEN = os.getenv("HF_TOKEN")
9
+
10
+ # Initialize the primary chatbot model
11
+ llm = HuggingFaceEndpoint(
12
+ repo_id="mistralai/Mistral-7B-Instruct-v0.3", # Replace with your model repo
13
+ huggingfacehub_api_token=HF_TOKEN.strip(),
14
+ temperature=0.7,
15
+ max_new_tokens=100
16
+ )
17
+
18
+ # Initialize the Meta-Llama Guard model
19
+ guard_llm = HuggingFaceEndpoint(
20
+ repo_id="meta-llama/Meta-Llama-Guard-2-8B",
21
+ huggingfacehub_api_token=HF_TOKEN.strip(),
22
+ temperature=0.7,
23
+ max_new_tokens=100
24
+ )
25
+
26
+ # Function for guarded chatbot response
27
+ def guarded_chatbot_response(message):
28
+ try:
29
+ # Get raw response from primary model
30
+ raw_response = llm(message)
31
+
32
+ # Validate with Meta-Llama Guard
33
+ guard_prompt = f"""
34
+ You are a content safety guard for kids under 16. Analyze the following text and ensure it is friendly and appropriate for children.
35
+ If appropriate, return the text as is. If not, rephrase or respond with "Content not suitable."
36
+ Text: {raw_response}
37
+ """
38
+ guard_response = guard_llm(guard_prompt)
39
+ return guard_response
40
+ except Exception as e:
41
+ return f"Error: {e}"
42
+
43
+
44
+ # Gradio Interface for Chatbot with Guardrails
45
+ with gr.Blocks() as app_with_guardrails:
46
+ gr.Markdown("## Chatbot With Guardrails")
47
+ gr.Markdown("This chatbot ensures all responses are appropriate for kids under 16.")
48
+
49
+ # Input and output
50
+ with gr.Row():
51
+ user_input = gr.Textbox(label="Your Message", placeholder="Type here...")
52
+ response_output = gr.Textbox(label="Guarded Response", placeholder="Bot will respond here...")
53
+ submit_button = gr.Button("Send")
54
+
55
+ # Button click event
56
+ submit_button.click(
57
+ guarded_chatbot_response,
58
+ inputs=[user_input],
59
+ outputs=[response_output]
60
+ )
61
+
62
+ # Launch the app
63
+ if __name__ == "__main__":
64
+ app_with_guardrails.launch()