fehmikaya commited on
Commit
3974b77
·
verified ·
1 Parent(s): 21a683d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -61
app.py CHANGED
@@ -3,12 +3,10 @@ import requests
3
  import os
4
  import json
5
  import time
 
6
 
7
  # Get the API key from the environment variable
8
  HF_TOKEN = os.getenv("HF_TOKEN")
9
-
10
- icons = {"assistant": "robot.png", "user": "man-kddi.png", "system": "man-kddi.png"}
11
-
12
  if HF_TOKEN is None:
13
  st.error("API key not found. Please set the HF_TOKEN secret in your Hugging Face Space.")
14
  st.stop()
@@ -16,69 +14,22 @@ if HF_TOKEN is None:
16
  # Hugging Face API settings
17
  API_URL = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct"
18
 
19
- # Define the headers
20
- headers = {
21
- 'Content-Type': 'application/json',
22
- 'Authorization': f'Bearer {HF_TOKEN}'
23
- }
24
-
25
-
26
- def format_llama_messages(messages):
27
- """Format messages for Llama-3 chat models.
28
- """
29
- prompt = []
30
-
31
- if messages[0]["role"] == "system":
32
- content = "<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n"+messages[0]["content"]+ "<|eot_id|>\n\n"
33
- prompt.append(content)
34
- for user, answer in zip(messages[1::2], messages[2::2]):
35
- prompt.append("<|start_header_id|>user<|end_header_id|>"+ (user["content"]).strip()+ "<|eot_id|><|start_header_id|>assistant<|end_header_id|>"+ (answer["content"]).strip()+ "<|eot_id|>")
36
-
37
- prompt.append("<|start_header_id|>user<|end_header_id|>"+ (messages[-1]["content"]).strip()+ "<|eot_id|>")
38
-
39
- return "".join(prompt)
40
-
41
- def handle_query(query):
42
- st.session_state.messages.append({'role': 'user', "content": query})
43
- formatted_messages=format_llama_messages(st.session_state.messages)
44
-
45
- json_body = {
46
- "inputs": formatted_messages,
47
- "parameters": {"max_new_tokens":max_new_tokens, "top_p":top_p, "temperature":temperature}
48
- }
49
- data = json.dumps(json_body)
50
- print("JSON Sent:", data)
51
- response = requests.request("POST", API_URL, headers=headers, data=data)
52
- try:
53
- data=json.loads(response.content.decode("utf-8"))
54
- result=data[0]['generated_text']
55
- last_comma_index = result.rfind('|eot_id|>assistant')
56
 
57
- # If a comma is found, slice the string from the last comma onwards
58
- if last_comma_index != -1:
59
- result = result[last_comma_index + 18:].strip()
60
-
61
- return result
62
- except:
63
- return response
64
 
65
- def prompt_changed():
66
- st.session_state.messages[0]["content"]=st.session_state['system_prompt']
67
-
68
- def streamer(text):
69
- for i in text:
70
- yield i
71
- time.sleep(0.005)
72
-
73
  # Set up the Streamlit app
74
  st.title("Llama3 Chatbot")
75
  st.markdown("Using only request API calls, no external libraries here.")
76
 
77
  st.sidebar.markdown("Model Parameters")
78
- temperature = st.sidebar.slider("Temperature", 0.1, 1.0, 0.7, 0.1)
79
- max_new_tokens = st.sidebar.number_input("Max New Tokens", 50, 1024, 512, step=50)
80
- top_p = st.sidebar.slider("Top P", 0.1, 1.0, 0.9, 0.1)
81
 
 
 
 
82
  system_prompt = st.sidebar.text_area(
83
  "System Prompt",
84
  "You are a food critic Chatbot. Reply in the style of a New York Times food critic",
@@ -94,15 +45,19 @@ for message in st.session_state.messages[1:]:
94
 
95
  user_prompt = st.chat_input("Start you conversation here...")
96
 
 
 
 
 
 
97
  if user_prompt:
 
98
  with st.chat_message("user", avatar=icons["user"]):
99
  st.write(user_prompt)
100
-
101
  # Trigger assistant's response retrieval and update UI
102
  with st.spinner("Thinking..."):
103
- response = handle_query(user_prompt)
104
  with st.chat_message("assistant", avatar=icons["assistant"]):
105
  st.write(streamer(response))
106
-
107
  st.session_state.messages.append({'role': 'assistant', "content": response})
108
 
 
3
  import os
4
  import json
5
  import time
6
+ from llama3 import llama3chat
7
 
8
  # Get the API key from the environment variable
9
  HF_TOKEN = os.getenv("HF_TOKEN")
 
 
 
10
  if HF_TOKEN is None:
11
  st.error("API key not found. Please set the HF_TOKEN secret in your Hugging Face Space.")
12
  st.stop()
 
14
  # Hugging Face API settings
15
  API_URL = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct"
16
 
17
+ icons = {"assistant": "robot.png", "user": "man-kddi.png", "system": "man-kddi.png"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ _llama3chat = llama3chat(API_URL, HF_TOKEN, 1024, 0.9,0.5)
 
 
 
 
 
 
20
 
 
 
 
 
 
 
 
 
21
  # Set up the Streamlit app
22
  st.title("Llama3 Chatbot")
23
  st.markdown("Using only request API calls, no external libraries here.")
24
 
25
  st.sidebar.markdown("Model Parameters")
26
+ _llama3chat.temperature = st.sidebar.slider("Temperature", 0.1, 1.0, 0.7, 0.1)
27
+ _llama3chat.max_new_tokens = st.sidebar.number_input("Max New Tokens", 50, 1024, 512, step=50)
28
+ _llama3chat.top_p = st.sidebar.slider("Top P", 0.1, 1.0, 0.9, 0.1)
29
 
30
+ def prompt_changed():
31
+ st.session_state.messages[0]["content"]=st.session_state['system_prompt']
32
+
33
  system_prompt = st.sidebar.text_area(
34
  "System Prompt",
35
  "You are a food critic Chatbot. Reply in the style of a New York Times food critic",
 
45
 
46
  user_prompt = st.chat_input("Start you conversation here...")
47
 
48
+ def streamer(text):
49
+ for i in text:
50
+ yield i
51
+ time.sleep(0.005)
52
+
53
  if user_prompt:
54
+ st.session_state.messages.append({'role': 'user', "content": query})
55
  with st.chat_message("user", avatar=icons["user"]):
56
  st.write(user_prompt)
 
57
  # Trigger assistant's response retrieval and update UI
58
  with st.spinner("Thinking..."):
59
+ response = _llama3chat.query(st.session_state.messages)
60
  with st.chat_message("assistant", avatar=icons["assistant"]):
61
  st.write(streamer(response))
 
62
  st.session_state.messages.append({'role': 'assistant', "content": response})
63