Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -802,14 +802,12 @@ The question doesn't match documents. If educational and appropriate, provide ge
|
|
| 802 |
|
| 803 |
def generate_response_from_model(prompt, relevant_docs=None):
|
| 804 |
"""Generate response with safety checks and style control."""
|
| 805 |
-
model, tokenizer = get_model() # β ADD THIS LINE FIRST
|
| 806 |
-
print(f"π Model loaded: {model is not None}")
|
| 807 |
-
print(f"π Tokenizer loaded: {tokenizer is not None}")
|
| 808 |
-
if model is not None:
|
| 809 |
-
print(f"π Model device: {next(model.parameters()).device}")
|
| 810 |
-
if model is None or tokenizer is None:
|
| 811 |
-
return "Error: Model could not be loaded."
|
| 812 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 813 |
is_safe, safety_message = check_question_safety(prompt)
|
| 814 |
if not is_safe:
|
| 815 |
return safety_message + generate_educational_alternative(prompt)
|
|
@@ -843,35 +841,55 @@ def generate_response_from_model(prompt, relevant_docs=None):
|
|
| 843 |
|
| 844 |
user_message = f"Question: {prompt}"
|
| 845 |
|
| 846 |
-
try:
|
| 847 |
-
model_device = next(model.parameters()).device
|
| 848 |
-
except:
|
| 849 |
-
model_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 850 |
-
|
| 851 |
# Get style parameters
|
| 852 |
style_config = RESPONSE_STYLES[st.session_state.response_style]
|
| 853 |
temperature = style_config['temperature']
|
| 854 |
max_tokens = style_config['max_tokens']
|
| 855 |
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 870 |
formatted_prompt = f"<|im_start|>system\n{system_message}<|im_end|>\n<|im_start|>user\n{user_message}<|im_end|>\n<|im_start|>assistant\n"
|
| 871 |
inputs = tokenizer(formatted_prompt, return_tensors="pt", padding=False)
|
| 872 |
-
|
| 873 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 874 |
|
|
|
|
|
|
|
|
|
|
| 875 |
outputs = model.generate(
|
| 876 |
inputs,
|
| 877 |
max_new_tokens=max_tokens,
|
|
@@ -879,21 +897,28 @@ def generate_response_from_model(prompt, relevant_docs=None):
|
|
| 879 |
top_p=0.8,
|
| 880 |
do_sample=True,
|
| 881 |
eos_token_id=tokenizer.eos_token_id,
|
| 882 |
-
pad_token_id=tokenizer.eos_token_id,
|
| 883 |
repetition_penalty=1.1,
|
| 884 |
-
attention_mask=None,
|
| 885 |
use_cache=True
|
| 886 |
)
|
| 887 |
|
| 888 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 889 |
return raw_response.strip()
|
|
|
|
| 890 |
except Exception as e:
|
| 891 |
import traceback
|
| 892 |
error_details = traceback.format_exc()
|
| 893 |
-
print(f"β
|
| 894 |
print(error_details)
|
| 895 |
return f"Error generating response: {type(e).__name__}: {str(e)}"
|
| 896 |
-
|
| 897 |
def is_conversational_input(prompt):
|
| 898 |
"""Check if input is conversational."""
|
| 899 |
conversational_patterns = [
|
|
|
|
| 802 |
|
| 803 |
def generate_response_from_model(prompt, relevant_docs=None):
|
| 804 |
"""Generate response with safety checks and style control."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 805 |
try:
|
| 806 |
+
model, tokenizer = get_model()
|
| 807 |
+
|
| 808 |
+
if model is None or tokenizer is None:
|
| 809 |
+
return "Error: Model could not be loaded."
|
| 810 |
+
|
| 811 |
is_safe, safety_message = check_question_safety(prompt)
|
| 812 |
if not is_safe:
|
| 813 |
return safety_message + generate_educational_alternative(prompt)
|
|
|
|
| 841 |
|
| 842 |
user_message = f"Question: {prompt}"
|
| 843 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 844 |
# Get style parameters
|
| 845 |
style_config = RESPONSE_STYLES[st.session_state.response_style]
|
| 846 |
temperature = style_config['temperature']
|
| 847 |
max_tokens = style_config['max_tokens']
|
| 848 |
|
| 849 |
+
# Determine device safely
|
| 850 |
+
try:
|
| 851 |
+
model_device = next(model.parameters()).device
|
| 852 |
+
except Exception as e:
|
| 853 |
+
print(f"β οΈ Could not get model device: {e}")
|
| 854 |
+
model_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 855 |
+
|
| 856 |
+
print(f"π Using device: {model_device}")
|
| 857 |
+
|
| 858 |
+
# Try chat template first, fallback to manual formatting
|
| 859 |
+
try:
|
| 860 |
+
if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template is not None:
|
| 861 |
+
messages = [
|
| 862 |
+
{"role": "system", "content": system_message},
|
| 863 |
+
{"role": "user", "content": user_message}
|
| 864 |
+
]
|
| 865 |
+
inputs = tokenizer.apply_chat_template(
|
| 866 |
+
messages,
|
| 867 |
+
return_tensors="pt",
|
| 868 |
+
add_generation_prompt=True,
|
| 869 |
+
tokenize=True,
|
| 870 |
+
padding=False
|
| 871 |
+
)
|
| 872 |
+
inputs = inputs.to(model_device)
|
| 873 |
+
input_length = inputs.shape[1]
|
| 874 |
+
else:
|
| 875 |
+
raise AttributeError("No chat template available")
|
| 876 |
+
|
| 877 |
+
except (AttributeError, Exception) as e:
|
| 878 |
+
print(f"β οΈ Chat template failed, using fallback: {e}")
|
| 879 |
+
# Fallback to manual prompt formatting
|
| 880 |
formatted_prompt = f"<|im_start|>system\n{system_message}<|im_end|>\n<|im_start|>user\n{user_message}<|im_end|>\n<|im_start|>assistant\n"
|
| 881 |
inputs = tokenizer(formatted_prompt, return_tensors="pt", padding=False)
|
| 882 |
+
|
| 883 |
+
# Handle different tokenizer output formats
|
| 884 |
+
if isinstance(inputs, dict) and "input_ids" in inputs:
|
| 885 |
+
inputs = inputs["input_ids"]
|
| 886 |
+
|
| 887 |
+
inputs = inputs.to(model_device)
|
| 888 |
+
input_length = inputs.shape[1] if hasattr(inputs, 'shape') else inputs.size(1)
|
| 889 |
|
| 890 |
+
# Generate
|
| 891 |
+
print(f"π Generating with {input_length} input tokens...")
|
| 892 |
+
|
| 893 |
outputs = model.generate(
|
| 894 |
inputs,
|
| 895 |
max_new_tokens=max_tokens,
|
|
|
|
| 897 |
top_p=0.8,
|
| 898 |
do_sample=True,
|
| 899 |
eos_token_id=tokenizer.eos_token_id,
|
| 900 |
+
pad_token_id=tokenizer.pad_token_id if tokenizer.pad_token_id is not None else tokenizer.eos_token_id,
|
| 901 |
repetition_penalty=1.1,
|
|
|
|
| 902 |
use_cache=True
|
| 903 |
)
|
| 904 |
|
| 905 |
+
# Decode output
|
| 906 |
+
if hasattr(outputs, 'shape'):
|
| 907 |
+
# outputs is a tensor
|
| 908 |
+
raw_response = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True)
|
| 909 |
+
else:
|
| 910 |
+
# outputs might be in a different format
|
| 911 |
+
raw_response = tokenizer.decode(outputs[input_length:], skip_special_tokens=True)
|
| 912 |
+
|
| 913 |
+
print(f"β
Generated {len(raw_response)} characters")
|
| 914 |
return raw_response.strip()
|
| 915 |
+
|
| 916 |
except Exception as e:
|
| 917 |
import traceback
|
| 918 |
error_details = traceback.format_exc()
|
| 919 |
+
print(f"β Full error traceback:")
|
| 920 |
print(error_details)
|
| 921 |
return f"Error generating response: {type(e).__name__}: {str(e)}"
|
|
|
|
| 922 |
def is_conversational_input(prompt):
|
| 923 |
"""Check if input is conversational."""
|
| 924 |
conversational_patterns = [
|