Update app.py
Browse files
app.py
CHANGED
|
@@ -8,6 +8,7 @@ from sklearn.metrics.pairwise import cosine_similarity
|
|
| 8 |
# Set up OpenAI API key in HF secrets
|
| 9 |
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
|
| 10 |
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
|
|
|
| 11 |
|
| 12 |
# Set up username and password in HF secrets
|
| 13 |
username = os.getenv('username')
|
|
@@ -57,7 +58,28 @@ except:
|
|
| 57 |
|
| 58 |
instructions = os.getenv('INSTRUCTIONS')
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
def chat_with_assistant(message, history):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
# Find relevant chunks based on the user message
|
| 62 |
relevant_chunks = get_relevant_chunks(message, text_chunks)
|
| 63 |
context = "\n".join(relevant_chunks)
|
|
@@ -99,9 +121,6 @@ def chat_with_assistant(message, history):
|
|
| 99 |
messages.append({"role": "user", "content": message})
|
| 100 |
|
| 101 |
try:
|
| 102 |
-
# Create OpenAI client
|
| 103 |
-
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
|
| 104 |
-
|
| 105 |
# Make the API call
|
| 106 |
response = client.chat.completions.create(
|
| 107 |
model="gpt-4.1-mini",
|
|
|
|
| 8 |
# Set up OpenAI API key in HF secrets
|
| 9 |
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
|
| 10 |
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
| 11 |
+
client = OpenAI(api_key=OPENAI_API_KEY)
|
| 12 |
|
| 13 |
# Set up username and password in HF secrets
|
| 14 |
username = os.getenv('username')
|
|
|
|
| 58 |
|
| 59 |
instructions = os.getenv('INSTRUCTIONS')
|
| 60 |
|
| 61 |
+
def moderate_input(text):
|
| 62 |
+
"""Run input through OpenAI moderation API"""
|
| 63 |
+
try:
|
| 64 |
+
response = client.moderations.create(
|
| 65 |
+
model="omni-moderation-latest",
|
| 66 |
+
input=text
|
| 67 |
+
)
|
| 68 |
+
results = response.results[0]
|
| 69 |
+
if results.flagged:
|
| 70 |
+
return False, results.categories
|
| 71 |
+
return True, None
|
| 72 |
+
except Exception as e:
|
| 73 |
+
# Fail safe: allow text if moderation API is down
|
| 74 |
+
print(f"Moderation API error: {e}")
|
| 75 |
+
return True, None
|
| 76 |
+
|
| 77 |
def chat_with_assistant(message, history):
|
| 78 |
+
# Run moderation before processing
|
| 79 |
+
allowed, categories = moderate_input(message)
|
| 80 |
+
if not allowed:
|
| 81 |
+
return "⚠️ Sorry, I can’t respond to that request because it violates the usage policy."
|
| 82 |
+
|
| 83 |
# Find relevant chunks based on the user message
|
| 84 |
relevant_chunks = get_relevant_chunks(message, text_chunks)
|
| 85 |
context = "\n".join(relevant_chunks)
|
|
|
|
| 121 |
messages.append({"role": "user", "content": message})
|
| 122 |
|
| 123 |
try:
|
|
|
|
|
|
|
|
|
|
| 124 |
# Make the API call
|
| 125 |
response = client.chat.completions.create(
|
| 126 |
model="gpt-4.1-mini",
|