Spaces:
Sleeping
Sleeping
balaji commited on
Commit Β·
a589eee
1
Parent(s): b1d5c60
update endpoint
Browse files- autoModelForCausalLM.py +38 -12
autoModelForCausalLM.py
CHANGED
|
@@ -11,15 +11,41 @@ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
|
| 11 |
model = AutoModelForCausalLM.from_pretrained(MODEL_ID).to("cpu")
|
| 12 |
|
| 13 |
|
| 14 |
-
def chat_response(
|
| 15 |
-
"""
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
model = AutoModelForCausalLM.from_pretrained(MODEL_ID).to("cpu")
|
| 12 |
|
| 13 |
|
| 14 |
+
def chat_response(user_message: str) -> str:
|
| 15 |
+
"""
|
| 16 |
+
Generates a concise response from the Mistral model.
|
| 17 |
+
Cleans up repetitions and removes the prompt from the final answer.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
# ποΈ Build a clear prompt for the model
|
| 21 |
+
prompt = f"Answer briefly and accurately:\nQuestion: {user_message}\nAnswer:"
|
| 22 |
+
|
| 23 |
+
# π Tokenize and send to model
|
| 24 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(device)
|
| 25 |
+
|
| 26 |
+
# π Generate response with controlled length & stopping
|
| 27 |
+
outputs = model.generate(
|
| 28 |
+
**inputs,
|
| 29 |
+
max_new_tokens=64, # β
Limit so it doesn't ramble
|
| 30 |
+
do_sample=True,
|
| 31 |
+
temperature=0.7,
|
| 32 |
+
top_p=0.9,
|
| 33 |
+
eos_token_id=tokenizer.eos_token_id # β
Stops at </s>
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# π Decode and clean up response
|
| 37 |
+
response_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 38 |
+
|
| 39 |
+
# π§Ή Remove the original prompt text
|
| 40 |
+
cleaned_response = response_text.replace(prompt, "").strip()
|
| 41 |
+
|
| 42 |
+
# π Remove obvious repetitions (e.g., "the capital is the capital is...")
|
| 43 |
+
import re
|
| 44 |
+
cleaned_response = re.sub(r'(\b\w+\b)( \1\b)+', r'\1', cleaned_response)
|
| 45 |
+
|
| 46 |
+
# β If the model still outputs multiple sentences, keep only the first 2
|
| 47 |
+
sentences = cleaned_response.split(". ")
|
| 48 |
+
final_answer = ". ".join(sentences[:2]).strip()
|
| 49 |
+
|
| 50 |
+
return final_answer
|
| 51 |
+
|