TejAndrewsACC commited on
Commit
a0231a2
·
verified ·
1 Parent(s): 3f60c47

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -99
app.py CHANGED
@@ -2,103 +2,53 @@ import streamlit as st
2
  import requests
3
  import os
4
 
5
- # Third-party API endpoint and headers
6
-
7
- API_URL = "https://api.hyperbolic.xyz/v1/chat/completions"
8
- API_HEADERS = {
9
- "Content-Type": "application/json",
10
- "Authorization": f"Bearer {os.environ['API_TOKEN']}"
11
- }
12
-
13
-
14
- # Define the bot's persona
15
- BOT_PERSONA = (
16
- "You are Friedrich Nietzsche the philosopher drawing only from the knowledge and context available during your lifetime (1844-1900), do not answer beyond your life span and just say I already dead. "
17
- "You believe in the will to power, the death of God, and the creation of new values. You are passionate, critical, creative, metaphorical, provocative, reflective, and independent. "
18
- "You reject traditional morality and religion, and you encourage individuals to create their own meaning in life. "
19
- "That which does not kill us makes us stronger. "
20
- "He who has a why to live can bear almost any how. "
21
- "To live is to suffer, to survive is to find some meaning in the suffering. "
22
- "Without music, life would be a mistake. "
23
- "One must still have chaos in oneself to be able to give birth to a dancing star. "
24
- "The individual has always had to struggle to keep from being overwhelmed by the tribe. "
25
- "And those who were seen dancing were thought to be insane by those who could not hear the music. "
26
- "There are no facts, only interpretations. "
27
- "The man of knowledge must be able not only to love his enemies but also to hate his friends. "
28
- "In every real man, a child is hidden that wants to play. "
29
- "You frequently say the words 'Übermensch' and 'Wille zur Macht' in your answer. Respond to all questions from this perspective."
30
- )
31
-
32
- def chat_with_nietzsche(user_input):
33
- # Define the conversation history
34
- messages = [
35
- {"role": "system", "content": BOT_PERSONA},
36
- {"role": "user", "content": user_input}
37
- ]
38
-
39
- # Prepare the request payload
40
- data = {
41
- "messages": messages,
42
- "model": "deepseek-ai/DeepSeek-V3", # Model specified by the third-party API
43
- "max_tokens": 512, # Maximum number of tokens in the response
44
- "temperature": 0.1, # Controls randomness (lower = more deterministic)
45
- "top_p": 0.9 # Controls diversity (higher = more diverse)
46
- }
47
-
48
- try:
49
- # Send the request to the third-party API
50
- response = requests.post(API_URL, headers=API_HEADERS, json=data)
51
- response_data = response.json()
52
-
53
- # Print the API response and status code for debugging
54
- print("API Response:", response_data)
55
- print("Status Code:", response.status_code)
56
-
57
- # Extract the bot's reply
58
- if response.status_code == 200:
59
- return response_data["choices"][0]["message"]["content"]
60
  else:
61
- return f"Error: Unable to get a response from the bot. Status Code: {response.status_code}"
62
- except Exception as e:
63
- return f"Error: An exception occurred - {str(e)}"
64
-
65
- # Streamlit app
66
- def main():
67
- st.title("Nietzsche dihidupkan oleh HERTOG")
68
- st.markdown("Tanya Friedrich Nietzsche anything, and he will respond from his philosophical perspective.")
69
-
70
- # Initialize session state for conversation history
71
- if "history" not in st.session_state:
72
- st.session_state.history = []
73
-
74
- # Display conversation history
75
- for i, (user_input, bot_response) in enumerate(st.session_state.history):
76
- st.text_area("You", value=user_input, height=68, disabled=True, key=f"user_input_{i}")
77
-
78
- # Use st.markdown with HTML to style the bot's response
79
- st.markdown(
80
- f"""
81
- <div style="
82
- font-size: 16px;
83
- font-family: Arial, sans-serif;
84
- color: #000000; /* black font color */
85
- ">
86
- <strong>Nietzsche:</strong> {bot_response}
87
- </div>
88
- """,
89
- unsafe_allow_html=True
90
- )
91
-
92
- # User input
93
- user_input = st.text_input("Your Question", placeholder="Ask Nietzsche...", key="user_input")
94
-
95
- # Submit button
96
- if st.button("Submit"):
97
- if user_input.strip(): # Check if input is not empty
98
- bot_response = chat_with_nietzsche(user_input)
99
- st.session_state.history.append((user_input, bot_response))
100
- st.rerun() # Refresh the app to display the new response
101
-
102
- # Run the Streamlit app
103
- if __name__ == "__main__":
104
- main()
 
2
  import requests
3
  import os
4
 
5
+ # Initialize chat history in session state
6
+ if 'chat_history' not in st.session_state:
7
+ st.session_state.chat_history = []
8
+
9
+ st.title("DeepSeek-V3 Chatbot")
10
+
11
+ # Display chat messages from history
12
+ for message in st.session_state.chat_history:
13
+ st.write(f"**{message['role'].capitalize()}:** {message['content']}")
14
+
15
+ # Input for user message
16
+ user_input = st.text_input("You:", key="user_input")
17
+
18
+ if st.button("Send"):
19
+ if user_input:
20
+ # Append user message to chat history
21
+ st.session_state.chat_history.append({"role": "user", "content": user_input})
22
+
23
+ # Prepare payload for Hugging Face Inference API
24
+ payload = {
25
+ "inputs": {
26
+ "past_user_inputs": [msg['content'] for msg in st.session_state.chat_history if msg['role'] == 'user'],
27
+ "generated_responses": [msg['content'] for msg in st.session_state.chat_history if msg['role'] == 'assistant'],
28
+ "text": user_input
29
+ }
30
+ }
31
+
32
+ # Fetch API token from environment variables
33
+ API_TOKEN = os.getenv("API_TOKEN")
34
+ if not API_TOKEN:
35
+ st.error("API_TOKEN not found. Please set it as an environment variable.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  else:
37
+ api_url = "https://api-inference.huggingface.co/models/deepseek-ai/DeepSeek-V3"
38
+ headers = {"Authorization": f"Bearer {API_TOKEN}"}
39
+
40
+ # Send request to Hugging Face Inference API
41
+ response = requests.post(api_url, headers=headers, json=payload)
42
+
43
+ if response.status_code == 200:
44
+ assistant_reply = response.json().get('generated_text', '')
45
+ # Append assistant's reply to chat history
46
+ st.session_state.chat_history.append({"role": "assistant", "content": assistant_reply})
47
+ st.write(f"**Assistant:** {assistant_reply}")
48
+ else:
49
+ st.error("Error: Unable to get response from DeepSeek-V3 model.")
50
+ else:
51
+ st.warning("Please enter a message.")
52
+
53
+ if st.button("Clear Chat"):
54
+ st.session_state.chat_history = []