Spaces:
Paused
Paused
Upload app.py
Browse files
app.py
CHANGED
|
@@ -49,17 +49,27 @@ def sanitize(text: str) -> str:
|
|
| 49 |
MAX_CTX = 4096
|
| 50 |
|
| 51 |
def chat(raw_input, history):
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
|
| 56 |
-
#
|
| 57 |
-
|
| 58 |
-
for prev_raw, prev_resp in history:
|
| 59 |
-
hist += f"User: {sanitize(prev_raw)}\nAssistant: {prev_resp}\n"
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
# Tokenise & manually truncate to last MAX_CTX tokens
|
| 65 |
all_ids = tokenizer.encode(prompt, add_special_tokens=False)
|
|
@@ -70,7 +80,7 @@ def chat(raw_input, history):
|
|
| 70 |
"attention_mask": torch.tensor([[1] * len(all_ids)])
|
| 71 |
}
|
| 72 |
|
| 73 |
-
# Generate
|
| 74 |
out = model.generate(
|
| 75 |
**inputs,
|
| 76 |
max_new_tokens=200,
|
|
@@ -81,8 +91,9 @@ def chat(raw_input, history):
|
|
| 81 |
seen = tokenizer.decode(all_ids, skip_special_tokens=True)
|
| 82 |
resp = full[len(seen):].strip()
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
|
|
|
| 86 |
|
| 87 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 88 |
# Launch Gradio App
|
|
|
|
| 49 |
MAX_CTX = 4096
|
| 50 |
|
| 51 |
def chat(raw_input, history):
|
| 52 |
+
# history is a list of dicts: {"role": "user"/"assistant", "content": str}
|
| 53 |
+
# Initialise history list if None
|
| 54 |
+
history = history or []
|
| 55 |
|
| 56 |
+
# Append new raw user message
|
| 57 |
+
history.append({"role": "user", "content": raw_input})
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
# Sanitize the new user input for the model
|
| 60 |
+
clean = sanitize(raw_input)
|
| 61 |
+
if not clean.strip() or clean == "[redacted]":
|
| 62 |
+
history.append({"role": "assistant", "content": "Iβm not sure what you meantβcould you try phrasing it differently?"})
|
| 63 |
+
return history, history
|
| 64 |
+
|
| 65 |
+
# Build prompt: system prompts + conversation history
|
| 66 |
+
prompt = "\n".join(SYSTEM_PROMPTS) + "\n\n"
|
| 67 |
+
for turn in history:
|
| 68 |
+
if turn["role"] == "user":
|
| 69 |
+
prompt += f"User: {sanitize(turn['content'])}\n"
|
| 70 |
+
else:
|
| 71 |
+
prompt += f"Assistant: {turn['content']}\n"
|
| 72 |
+
prompt += "Assistant:"
|
| 73 |
|
| 74 |
# Tokenise & manually truncate to last MAX_CTX tokens
|
| 75 |
all_ids = tokenizer.encode(prompt, add_special_tokens=False)
|
|
|
|
| 80 |
"attention_mask": torch.tensor([[1] * len(all_ids)])
|
| 81 |
}
|
| 82 |
|
| 83 |
+
# Generate response
|
| 84 |
out = model.generate(
|
| 85 |
**inputs,
|
| 86 |
max_new_tokens=200,
|
|
|
|
| 91 |
seen = tokenizer.decode(all_ids, skip_special_tokens=True)
|
| 92 |
resp = full[len(seen):].strip()
|
| 93 |
|
| 94 |
+
# Append model reply
|
| 95 |
+
history.append({"role": "assistant", "content": resp})
|
| 96 |
+
return history, history
|
| 97 |
|
| 98 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 99 |
# Launch Gradio App
|