Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,63 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
def respond(
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
)
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
-
|
20 |
-
for val in history:
|
21 |
-
if val[0]:
|
22 |
-
messages.append({"role": "user", "content": val[0]})
|
23 |
-
if val[1]:
|
24 |
-
messages.append({"role": "assistant", "content": val[1]})
|
25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
messages.append({"role": "user", "content": message})
|
|
|
27 |
|
28 |
response = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
-
|
39 |
-
response += token
|
40 |
-
yield response
|
41 |
-
|
42 |
-
"""
|
43 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
44 |
-
"""
|
45 |
demo = gr.ChatInterface(
|
46 |
-
respond,
|
47 |
additional_inputs=[
|
48 |
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
49 |
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
50 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
51 |
-
gr.Slider(
|
52 |
-
minimum=0.1,
|
53 |
-
maximum=1.0,
|
54 |
-
value=0.95,
|
55 |
-
step=0.05,
|
56 |
-
label="Top-p (nucleus sampling)",
|
57 |
-
),
|
58 |
],
|
|
|
|
|
59 |
)
|
60 |
|
61 |
-
|
62 |
if __name__ == "__main__":
|
63 |
demo.launch()
|
|
|
1 |
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
2 |
+
|
3 |
+
def load_llm():
|
4 |
+
"""
|
5 |
+
Loads the GPT-2 model and tokenizer using the Hugging Face `transformers` library.
|
6 |
+
"""
|
7 |
+
try:
|
8 |
+
# Load pre-trained model and tokenizer from Hugging Face
|
9 |
+
print("Downloading or loading the GPT-2 model and tokenizer...")
|
10 |
+
model_name = 'gpt2'
|
11 |
+
model = GPT2LMHeadModel.from_pretrained(model_name)
|
12 |
+
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
|
13 |
+
print("Model and tokenizer successfully loaded!")
|
14 |
+
return model, tokenizer
|
15 |
+
|
16 |
+
except Exception as e:
|
17 |
+
print(f"An error occurred while loading the model: {e}")
|
18 |
+
return None, None
|
19 |
+
|
20 |
+
def generate_response(model, tokenizer, user_input):
|
21 |
+
"""
|
22 |
+
Generates a response using the GPT-2 model and tokenizer.
|
23 |
+
|
24 |
+
Args:
|
25 |
+
- model: The loaded GPT-2 model.
|
26 |
+
- tokenizer: The tokenizer corresponding to the GPT-2 model.
|
27 |
+
- user_input (str): The input question from the user.
|
28 |
+
|
29 |
+
Returns:
|
30 |
+
- response (str): The generated response.
|
31 |
+
"""
|
32 |
+
try:
|
33 |
+
inputs = tokenizer.encode(user_input, return_tensors='pt')
|
34 |
+
outputs = model.generate(inputs, max_length=512, num_return_sequences=1)
|
35 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
36 |
+
return response
|
37 |
+
|
38 |
+
except Exception as e:
|
39 |
+
return f"An error occurred during response generation: {e}"
|
40 |
+
|
41 |
+
# Load the model and tokenizer
|
42 |
+
model, tokenizer = load_llm()
|
43 |
+
|
44 |
+
if model is None or tokenizer is None:
|
45 |
+
print("Model and/or tokenizer loading failed.")
|
46 |
+
else:
|
47 |
+
print("Model and tokenizer are ready for use.")
|
48 |
+
|
49 |
import gradio as gr
|
50 |
from huggingface_hub import InferenceClient
|
51 |
|
52 |
+
# Initialize the Hugging Face API client
|
53 |
+
# The InferenceClient does not take an api_key argument
|
54 |
+
client = InferenceClient()
|
|
|
55 |
|
56 |
+
def retrieval_QA_chain(llm, prompt, db):
|
57 |
+
# Placeholder function - ensure it integrates as needed
|
58 |
+
return RetrievalQA.from_chain_type(
|
59 |
+
llm=llm,
|
60 |
+
chain_type="stuff",
|
61 |
+
retriever=db.as_retriever(search_kwargs={'k': 2}),
|
62 |
+
return_source_documents=True,
|
63 |
+
chain_type_kwargs={'prompt': prompt}
|
64 |
+
)
|
65 |
|
66 |
+
def respond(message, history, system_message, max_tokens, temperature, top_p):
|
67 |
+
"""
|
68 |
+
Handles interaction with the chatbot by sending the conversation history
|
69 |
+
and system message to the Hugging Face Inference API.
|
70 |
+
"""
|
71 |
+
print("Starting respond function")
|
72 |
+
print("Received message:", message)
|
73 |
+
print("Conversation history:", history)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
+
messages = [{"role": "system", "content": system_message}]
|
76 |
+
|
77 |
+
for user_msg, assistant_msg in history:
|
78 |
+
if user_msg:
|
79 |
+
print("Adding user message to messages:", user_msg)
|
80 |
+
messages.append({"role": "user", "content": user_msg})
|
81 |
+
if assistant_msg:
|
82 |
+
print("Adding assistant message to messages:", assistant_msg)
|
83 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
84 |
+
|
85 |
messages.append({"role": "user", "content": message})
|
86 |
+
print("Final message list for the model:", messages)
|
87 |
|
88 |
response = ""
|
89 |
+
try:
|
90 |
+
for message in client.chat_completion(
|
91 |
+
messages,
|
92 |
+
max_tokens=max_tokens,
|
93 |
+
stream=True,
|
94 |
+
temperature=temperature,
|
95 |
+
top_p=top_p,
|
96 |
+
):
|
97 |
+
token = message['choices'][0]['delta']['content']
|
98 |
+
response += token
|
99 |
+
print("Token received:", token)
|
100 |
+
yield response
|
101 |
+
except Exception as e:
|
102 |
+
print("An error occurred:", e)
|
103 |
+
yield f"An error occurred: {e}"
|
104 |
|
105 |
+
print("Response generation completed")
|
106 |
+
|
107 |
+
# Set up the Gradio ChatInterface
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
demo = gr.ChatInterface(
|
109 |
+
fn=respond,
|
110 |
additional_inputs=[
|
111 |
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
112 |
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
113 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
114 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
],
|
116 |
+
title="Human Rights AI Chatbot",
|
117 |
+
description="Ask questions about human rights, and get informed, passionate answers!"
|
118 |
)
|
119 |
|
120 |
+
# Launch the Gradio app
|
121 |
if __name__ == "__main__":
|
122 |
demo.launch()
|