Spaces:
Sleeping
Sleeping
File size: 3,606 Bytes
be841be 287efac be841be 287efac be841be 30c70a5 be841be 287efac 3d4cfce 30c70a5 3d4cfce 287efac be841be 30c70a5 287efac 30c70a5 3d4cfce 30c70a5 287efac 30c70a5 287efac 30c70a5 287efac 30c70a5 287efac 30c70a5 287efac be841be 30c70a5 be841be 3d4cfce be841be 30c70a5 be841be 287efac 30c70a5 287efac 30c70a5 287efac be841be 287efac |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
import streamlit as st
from openai import OpenAI
import os
# --- CONFIGURATION ---
CHOSEN_BREED = "Golden Retrievers"
# Page setup
st.set_page_config(page_title=f"The {CHOSEN_BREED} Expert", page_icon="๐")
st.title(f"๐ Only {CHOSEN_BREED}")
st.caption(f"Powered by Perplexity API. Strictly restricted to {CHOSEN_BREED}.")
# --- AUTHENTICATION ---
perplexity_api_key = os.getenv("PERPLEXITY_API_KEY")
if not perplexity_api_key:
st.error("โ ๏ธ PERPLEXITY_API_KEY not found in secrets.")
st.stop()
client = OpenAI(
api_key=perplexity_api_key,
base_url="https://api.perplexity.ai"
)
# --- CHAT LOGIC ---
if "messages" not in st.session_state:
st.session_state["messages"] = [
{"role": "assistant", "content": f"Hello! I am an expert on {CHOSEN_BREED}. Ask me anything about them!"}
]
for msg in st.session_state.messages:
st.chat_message(msg["role"]).write(msg["content"])
if user_input := st.chat_input():
# 1. Clean up previous failed user messages
if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
st.session_state.messages.pop()
# 2. Display User Message
st.session_state.messages.append({"role": "user", "content": user_input})
st.chat_message("user").write(user_input)
# 3. PREPARE CONTEXT FOR THE AI
# We grab the last 2 exchanges so the AI knows what "this" or "it" refers to.
conversation_context = ""
start_index = max(0, len(st.session_state.messages) - 5) # Get last 5 messages max
for msg in st.session_state.messages[start_index:]:
conversation_context += f"{msg['role'].upper()}: {msg['content']}\n"
# 4. CONSTRUCT THE SMART STRICT PROMPT
# We give the AI the context so it can resolve pronouns.
strict_content = f"""
You are a specialized assistant for {CHOSEN_BREED}.
Here is the recent conversation history for context:
---
{conversation_context}
---
Your Task: Respond to the "USER" based *strictly* on the following logic:
1. ANALYZE: Does the USER's latest message relate to {CHOSEN_BREED}?
(Check the context! If they say "tell me more" or "how do they eat", assume they mean {CHOSEN_BREED}).
2. IF YES (Valid Topic):
- Answer the question helpfuly and accurately.
- DO NOT explain that you are validating the query. Just give the answer.
3. IF NO (Invalid Topic):
- If the user asks about cats, cars, weather, or other dog breeds:
- YOU MUST OUTPUT EXACTLY: "REFUSAL_TRIGGERED"
"""
# 5. Prepare Messages (We strip the history here because we manually injected it into the prompt above)
api_messages = [
{"role": "system", "content": "You are a helpful assistant tailored to a specific topic."},
{"role": "user", "content": strict_content}
]
# 6. Call API
try:
response = client.chat.completions.create(
model="sonar",
messages=api_messages,
temperature=0.1,
)
bot_reply = response.choices[0].message.content.strip()
# 7. POST-PROCESSING GUARDRAIL
if "REFUSAL_TRIGGERED" in bot_reply:
final_reply = f"๐ซ I cannot answer that. I am strictly programmed to discuss **{CHOSEN_BREED}** only."
else:
final_reply = bot_reply
# 8. Show Result
st.session_state.messages.append({"role": "assistant", "content": final_reply})
st.chat_message("assistant").write(final_reply)
except Exception as e:
st.error(f"An error occurred: {e}") |