abanm commited on
Commit
46e07f9
·
verified ·
1 Parent(s): 58a333d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -87
app.py CHANGED
@@ -1,114 +1,82 @@
1
  import streamlit as st
2
  import requests
3
  import json
4
- from langchain.chains import ConversationChain
5
- from langchain.memory import ConversationBufferMemory
6
- from langchain.llms.base import LLM
7
- from typing import Optional
8
 
9
  # Constants
10
  SPACE_URL = "https://abanm-dubs.hf.space/api/generate"
 
11
 
12
- # Streamlit Configurations
13
  st.set_page_config(page_title="🐶 DUBSChat", layout="centered")
14
 
15
  # Sidebar Configuration
16
  with st.sidebar:
17
- if "dubs_key" not in st.session_state:
18
- st.session_state["dubs_key"] = ""
19
- st.session_state["dubs_key"] = st.text_input("Enter Dubs Key", type="password", key="chatbot_api_key")
20
 
21
- st.markdown("### Chat Sessions")
22
- if "sessions" not in st.session_state:
23
- st.session_state["sessions"] = {"Default": ConversationBufferMemory()}
24
- session_keys = list(st.session_state["sessions"].keys())
25
- selected_session = st.selectbox("Select Chat Session", session_keys, index=session_keys.index(st.experimental_get_query_params().get("session", ["Default"])[0]))
26
- new_session_name = st.text_input("New Session Name")
27
- if st.button("Create New Session"):
28
- if new_session_name and new_session_name not in st.session_state["sessions"]:
29
- st.session_state["sessions"][new_session_name] = ConversationBufferMemory()
30
- st.experimental_set_query_params(session=new_session_name)
31
-
32
- # Ensure Dubs Key is Provided
33
- if not st.session_state["dubs_key"]:
34
- st.warning("Please enter a valid Dubs Key in the sidebar to proceed.")
35
- st.stop()
36
-
37
- # Define Custom LLM for the fine-tuned model
38
- class CustomLLM(LLM):
39
  """
40
- Custom LLM to interact with the fine-tuned model hosted on SPACE_URL.
 
 
 
 
 
 
41
  """
42
-
43
- def _call(self, prompt: str, stop: Optional[list] = None) -> str:
44
- dubs_key = st.session_state.get("dubs_key")
45
- if not dubs_key:
46
- return "Error: Missing Dubs Key. Please provide a valid key in the sidebar."
47
-
48
- headers = {
49
- "Authorization": f"Bearer {dubs_key}",
50
- "Content-Type": "application/json",
51
- }
52
- payload = {"prompt": prompt}
53
-
54
- try:
55
- response = requests.post(SPACE_URL, json=payload, headers=headers)
56
- response.raise_for_status()
57
- result = response.json()
58
- return result.get("response", "No response from the model.")
59
-
60
- except requests.exceptions.HTTPError as e:
61
- if response.status_code == 401:
62
- return "Error: Unauthorized. Please check your Dubs Key."
63
- return f"HTTP Error: {response.status_code} - {response.reason}"
64
- except requests.exceptions.RequestException as e:
65
- return f"Error: {str(e)}"
66
-
67
- @property
68
- def _identifying_params(self):
69
- """Return unique parameters for this LLM."""
70
- return {"model": "custom_model"}
71
-
72
- @property
73
- def _llm_type(self):
74
- """Return type of LLM."""
75
- return "custom_llm"
76
-
77
- # LangChain Configuration
78
- if "conversation" not in st.session_state:
79
- st.session_state["conversation"] = ConversationChain(
80
- llm=CustomLLM(),
81
- memory=st.session_state["sessions"][selected_session],
82
- )
83
 
84
  # Main Chat UI
85
  st.title("🐶 DUBSChat")
86
  st.markdown("Empowering you with a Sustainable AI")
87
 
88
- # Chat Display for the selected session
89
- memory = st.session_state["sessions"][selected_session]
90
- for message in memory.chat_memory.messages:
91
- role = "user" if message.type == "human" else "assistant"
92
- st.chat_message(role).write(message.content)
 
93
 
94
  # User Input
95
  if prompt := st.chat_input():
96
- # Append the user's message to the chat memory
97
- memory.chat_memory.add_user_message(prompt)
98
  st.chat_message("user").write(prompt)
99
 
100
  with st.spinner("Translating Dubs language (Woof Woof!)"):
101
  assistant_message_placeholder = st.chat_message("assistant").empty()
102
- full_response = st.session_state["conversation"].run(
103
- f"System:The following is a friendly conversation between a user and an AI. "
104
- f"The AI is talkative and provides lots of specific details from its context. "
105
- f"If the AI does not know the answer to a question, it truthfully says it does not know.\n\n"
106
- f"Current conversation:\nUser: {prompt}\nAssistant:"
107
- )
108
- assistant_message_placeholder.write(full_response)
109
-
110
- # Append the assistant's response to the chat memory
111
- memory.chat_memory.add_ai_message(full_response)
112
 
113
- # Update the LangChain conversation to use the selected session's memory
114
- st.session_state["conversation"].memory = memory
 
1
  import streamlit as st
2
  import requests
3
  import json
 
 
 
 
4
 
5
  # Constants
6
  SPACE_URL = "https://abanm-dubs.hf.space/api/generate"
7
+ API_KEY = "s3cr3t_k3y" # Replace with your actual API key
8
 
9
+ # Streamlit Configurations (must come first)
10
  st.set_page_config(page_title="🐶 DUBSChat", layout="centered")
11
 
12
  # Sidebar Configuration
13
  with st.sidebar:
14
+ dubs_key = st.text_input("Enter Dubs Key", key="chatbot_api_key", type="password")
15
+ st.markdown("Dubs Recall")
16
+ st.markdown("""Coming Soon!""")
17
 
18
+ def call_api(message):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  """
20
+ Calls the backend API with the user's input using streaming.
21
+
22
+ Args:
23
+ message (str): User's message.
24
+
25
+ Yields:
26
+ str: Streamed response chunks from the backend API.
27
  """
28
+ headers = {
29
+ "Authorization": f"Bearer {dubs_key}",
30
+ "Content-Type": "application/json",
31
+ }
32
+ payload = {"prompt": message} # Match the API's expected input key
33
+
34
+ try:
35
+ # Send request with streaming enabled
36
+ response = requests.post(SPACE_URL, json=payload, headers=headers, stream=True)
37
+ response.raise_for_status()
38
+
39
+ for chunk in response.iter_lines(decode_unicode=True):
40
+ if chunk.strip(): # Ensure the chunk is not empty
41
+ try:
42
+ # Parse JSON chunk
43
+ data = json.loads(chunk)
44
+ if "response" in data:
45
+ yield data["response"]
46
+ except json.JSONDecodeError:
47
+ yield "Error decoding response chunk."
48
+ except requests.exceptions.Timeout:
49
+ yield "Error: The API call timed out."
50
+ except requests.exceptions.RequestException as e:
51
+ yield f"Error: {str(e)}"
52
+
53
+ # Chat History Initialization
54
+ if "messages" not in st.session_state:
55
+ st.session_state["messages"] = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  # Main Chat UI
58
  st.title("🐶 DUBSChat")
59
  st.markdown("Empowering you with a Sustainable AI")
60
 
61
+ # Chat Display
62
+ for message in st.session_state["messages"]:
63
+ if message["role"] == "user":
64
+ st.chat_message("user").write(message["content"])
65
+ elif message["role"] == "assistant":
66
+ st.chat_message("assistant").write(message["content"])
67
 
68
  # User Input
69
  if prompt := st.chat_input():
70
+ # Append the user's message to the chat history
71
+ st.session_state["messages"].append({"role": "user", "content": prompt})
72
  st.chat_message("user").write(prompt)
73
 
74
  with st.spinner("Translating Dubs language (Woof Woof!)"):
75
  assistant_message_placeholder = st.chat_message("assistant").empty()
76
+ full_response = "" # To accumulate the entire response
77
+ for response_chunk in call_api(prompt):
78
+ full_response += response_chunk
79
+ assistant_message_placeholder.write(full_response) # Update progressively
 
 
 
 
 
 
80
 
81
+ # Append the final assistant's response to the chat history
82
+ st.session_state["messages"].append({"role": "assistant", "content": full_response})