Alpha108 commited on
Commit
3d4cfce
·
verified ·
1 Parent(s): be841be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -14
app.py CHANGED
@@ -3,7 +3,6 @@ from openai import OpenAI
3
  import os
4
 
5
  # --- CONFIGURATION ---
6
- # You can change this to any breed you want (e.g., "Pugs", "German Shepherds")
7
  CHOSEN_BREED = "Golden Retrievers"
8
 
9
  # Page setup
@@ -12,21 +11,19 @@ st.title(f"🐕 Only {CHOSEN_BREED}")
12
  st.caption(f"Powered by Perplexity API. I strictly refuse to talk about cats, other dogs, or anything else!")
13
 
14
  # --- AUTHENTICATION ---
15
- # This retrieves the key you will save in Hugging Face Secrets
16
  perplexity_api_key = os.getenv("PERPLEXITY_API_KEY")
17
 
18
  if not perplexity_api_key:
19
  st.error("⚠️ PERPLEXITY_API_KEY not found in secrets. Please add it to your Hugging Face Space settings.")
20
  st.stop()
21
 
22
- # Initialize the Client (Perplexity is compatible with the OpenAI library)
23
  client = OpenAI(
24
  api_key=perplexity_api_key,
25
  base_url="https://api.perplexity.ai"
26
  )
27
 
28
  # --- STRICT SYSTEM PROMPT ---
29
- # This is the "Brain" that restricts the AI.
30
  system_instruction = f"""
31
  You are a highly specialized AI assistant with a STRICT filter.
32
  You must adhere to the following funnel of allowed topics:
@@ -47,35 +44,49 @@ Refusal Message Style: Be polite but firm. Do not apologize profusely, just stat
47
 
48
  # --- CHAT LOGIC ---
49
 
50
- # Initialize chat history in session state if it doesn't exist
51
  if "messages" not in st.session_state:
 
52
  st.session_state["messages"] = [
53
  {"role": "assistant", "content": f"Hello! I am your expert on {CHOSEN_BREED}. Ask me anything about them!"}
54
  ]
55
 
56
- # Display previous chat messages
57
  for msg in st.session_state.messages:
58
  st.chat_message(msg["role"]).write(msg["content"])
59
 
60
  # Handle new user input
61
  if prompt := st.chat_input():
62
- # 1. Display user message
 
 
 
 
 
 
 
63
  st.session_state.messages.append({"role": "user", "content": prompt})
64
  st.chat_message("user").write(prompt)
65
 
66
- # 2. Prepare messages for API (System Prompt + History)
 
67
  api_messages = [{"role": "system", "content": system_instruction}]
68
 
69
- # Add recent conversation history (limit to last 10 messages to save context)
70
- for msg in st.session_state.messages[-10:]:
71
- api_messages.append(msg)
 
 
 
 
 
72
 
73
  # 3. Call Perplexity API
74
  try:
75
  response = client.chat.completions.create(
76
- model="sonar", # 'sonar' is a good general-purpose Perplexity model
77
  messages=api_messages,
78
- temperature=0.1, # Low temperature keeps it strict and factual
79
  )
80
 
81
  bot_reply = response.choices[0].message.content
@@ -85,4 +96,6 @@ if prompt := st.chat_input():
85
  st.chat_message("assistant").write(bot_reply)
86
 
87
  except Exception as e:
88
- st.error(f"An error occurred: {e}")
 
 
 
3
  import os
4
 
5
  # --- CONFIGURATION ---
 
6
  CHOSEN_BREED = "Golden Retrievers"
7
 
8
  # Page setup
 
11
  st.caption(f"Powered by Perplexity API. I strictly refuse to talk about cats, other dogs, or anything else!")
12
 
13
  # --- AUTHENTICATION ---
 
14
  perplexity_api_key = os.getenv("PERPLEXITY_API_KEY")
15
 
16
  if not perplexity_api_key:
17
  st.error("⚠️ PERPLEXITY_API_KEY not found in secrets. Please add it to your Hugging Face Space settings.")
18
  st.stop()
19
 
20
+ # Initialize Client
21
  client = OpenAI(
22
  api_key=perplexity_api_key,
23
  base_url="https://api.perplexity.ai"
24
  )
25
 
26
  # --- STRICT SYSTEM PROMPT ---
 
27
  system_instruction = f"""
28
  You are a highly specialized AI assistant with a STRICT filter.
29
  You must adhere to the following funnel of allowed topics:
 
44
 
45
  # --- CHAT LOGIC ---
46
 
47
+ # Initialize chat history
48
  if "messages" not in st.session_state:
49
+ # We keep the greeting in the UI state, but we will filter it out for the API later
50
  st.session_state["messages"] = [
51
  {"role": "assistant", "content": f"Hello! I am your expert on {CHOSEN_BREED}. Ask me anything about them!"}
52
  ]
53
 
54
+ # Display chat messages
55
  for msg in st.session_state.messages:
56
  st.chat_message(msg["role"]).write(msg["content"])
57
 
58
  # Handle new user input
59
  if prompt := st.chat_input():
60
+
61
+ # --- ERROR FIX: CLEANUP STALE MESSAGES ---
62
+ # If the last message was from the user, it means the previous API call failed.
63
+ # We must remove it to prevent sending "User, User" sequence which breaks the API.
64
+ if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
65
+ st.session_state.messages.pop()
66
+
67
+ # 1. Display current user message
68
  st.session_state.messages.append({"role": "user", "content": prompt})
69
  st.chat_message("user").write(prompt)
70
 
71
+ # 2. Prepare messages for API
72
+ # Start with System Prompt
73
  api_messages = [{"role": "system", "content": system_instruction}]
74
 
75
+ # Add history, but SKIP the very first artificial greeting to ensure System -> User flow
76
+ # Perplexity prefers the conversation to start with a User query, not an Assistant greeting.
77
+ history_to_send = st.session_state.messages[-10:] # Get last 10
78
+
79
+ for msg in history_to_send:
80
+ # Only append if it's NOT that initial fake greeting
81
+ if msg["content"] != f"Hello! I am your expert on {CHOSEN_BREED}. Ask me anything about them!":
82
+ api_messages.append(msg)
83
 
84
  # 3. Call Perplexity API
85
  try:
86
  response = client.chat.completions.create(
87
+ model="sonar",
88
  messages=api_messages,
89
+ temperature=0.1,
90
  )
91
 
92
  bot_reply = response.choices[0].message.content
 
96
  st.chat_message("assistant").write(bot_reply)
97
 
98
  except Exception as e:
99
+ st.error(f"An error occurred: {e}")
100
+ # Optional: Print the message structure for debugging if needed
101
+ # st.write(api_messages)