OzTianlu commited on
Commit
e98313b
·
verified ·
1 Parent(s): 937e44a

Upload handler.py

Browse files
Files changed (1) hide show
  1. handler.py +15 -12
handler.py CHANGED
@@ -101,18 +101,21 @@ class EndpointHandler:
101
 
102
  if _is_messages(item):
103
  # Chat template path exists in repo; tokenizer.apply_chat_template will use it if configured
104
- result = self.tokenizer.apply_chat_template(
105
- item,
106
- return_tensors="pt",
107
- add_generation_prompt=True,
108
- )
109
- # Handle both single tensor and tuple/dict returns
110
- if isinstance(result, dict):
111
- input_ids = result["input_ids"]
112
- elif isinstance(result, tuple):
113
- input_ids = result[0]
114
- else:
115
- input_ids = result
 
 
 
116
  else:
117
  if not isinstance(item, str):
118
  item = str(item)
 
101
 
102
  if _is_messages(item):
103
  # Chat template path exists in repo; tokenizer.apply_chat_template will use it if configured
104
+ try:
105
+ # Use tokenize=False to get the formatted string first
106
+ prompt = self.tokenizer.apply_chat_template(
107
+ item,
108
+ tokenize=False,
109
+ add_generation_prompt=True,
110
+ )
111
+ # Then tokenize it separately to avoid unpacking issues
112
+ enc = self.tokenizer(prompt, return_tensors="pt")
113
+ input_ids = enc["input_ids"]
114
+ except Exception:
115
+ # Fallback: if chat template fails, use the last user message
116
+ last_user_msg = next((m["content"] for m in reversed(item) if m.get("role") == "user"), "")
117
+ enc = self.tokenizer(last_user_msg, return_tensors="pt")
118
+ input_ids = enc["input_ids"]
119
  else:
120
  if not isinstance(item, str):
121
  item = str(item)