Ephraimmm commited on
Commit
4770ee5
·
verified ·
1 Parent(s): 4bf38c0

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +354 -77
handler.py CHANGED
@@ -1,18 +1,194 @@
1
  #tope_version
2
  # handler.py
3
  # handler.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  from typing import Any, Dict, List, Union, Optional
5
  import torch
 
6
  from huggingface_inference_toolkit.logging import logger
7
  from unsloth import FastLanguageModel
8
  from peft import PeftModel
9
-
10
  # OpenAI-style prompt:
11
  # - str
12
  # - [{"role": "...", "content": "..." | [{"type":"text","text":"..."}]}]
13
  Prompt = Union[str, List[Dict[str, Any]], Dict[str, Any]]
14
-
15
-
16
  def _to_block_list(content: Any) -> List[Dict[str, str]]:
17
  """Ensure content is a list[{'type':'text','text':...}]."""
18
  if content is None:
@@ -22,20 +198,22 @@ def _to_block_list(content: Any) -> List[Dict[str, str]]:
22
  return content
23
  # Fallback: stringify
24
  return [{"type": "text", "text": str(content)}]
25
-
26
-
27
  class EndpointHandler:
28
  """
29
- HF Inference Endpoint handler that mirrors your Gradio setup:
 
 
30
  - Loads Unsloth 4-bit Gemma-3-4B IT
31
  - Attaches LoRA adapter
32
  - Uses tokenizer.apply_chat_template
33
  - Always replies in Nigerian Pidgin
34
  """
35
-
36
  def __init__(self, model_dir: str, **_: Any):
37
  logger.info(f"Initializing with model_dir={model_dir}")
38
-
39
  base_model_name = "unsloth/gemma-3-4b-it-unsloth-bnb-4bit"
40
  model, tokenizer = FastLanguageModel.from_pretrained(
41
  model_name=base_model_name,
@@ -43,11 +221,11 @@ class EndpointHandler:
43
  dtype=torch.float16,
44
  load_in_4bit=True,
45
  )
46
-
47
  lora_repo = "Ephraimmm/PIDGIN_gemma-3"
48
  model = PeftModel.from_pretrained(model, lora_repo)
49
  FastLanguageModel.for_inference(model)
50
-
51
  self.model = model.eval()
52
  self.tokenizer = tokenizer
53
  self.device = getattr(
@@ -58,83 +236,143 @@ class EndpointHandler:
58
  # Safety: some tokenizers lack pad_token_id
59
  if getattr(self.tokenizer, "pad_token_id", None) is None:
60
  self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
61
-
62
  logger.info(f"Device: {self.device} | eos_id: {self.tokenizer.eos_token_id}")
63
-
64
  self._system_text = (
65
  "You are a Nigerian assistant that speaks PIDGIN ENGLISH. "
66
  "When asked 'how far', reply 'I dey o, how you dey?'. "
67
  "Always answer in Pidgin English."
68
  )
69
-
70
- def _normalize_messages(self, prompt: Prompt) -> List[Dict[str, Any]]:
71
- """Return a list of messages with block-style contents only."""
72
- # Accept single dict
73
- if isinstance(prompt, dict):
74
- prompt = [prompt]
75
-
76
- # Accept raw string
77
- if isinstance(prompt, str):
78
- msgs = [
79
- {"role": "system", "content": _to_block_list(self._system_text)},
80
- {"role": "user", "content": _to_block_list(prompt)},
81
- ]
82
- return msgs
83
-
84
- if not isinstance(prompt, list):
85
- raise ValueError("`inputs` must be a string, a message dict, or a list of messages.")
86
-
87
- # Normalize all contents to blocks
88
  norm = []
89
- for m in prompt:
90
  role = m.get("role", "user")
91
- content = _to_block_list(m.get("content", ""))
 
 
 
 
 
 
 
 
 
 
92
  norm.append({"role": role, "content": content})
93
-
94
  # Ensure a system message exists (prepend if missing)
95
  if not any(m.get("role") == "system" for m in norm):
96
  norm = [{"role": "system", "content": _to_block_list(self._system_text)}] + norm
97
-
98
  return norm
99
-
100
- def _build_model_inputs(self, prompt: Prompt):
101
- messages = self._normalize_messages(prompt)
102
- # Use the same path as your Gradio script
103
  model_inputs = self.tokenizer.apply_chat_template(
104
- messages,
105
  add_generation_prompt=True,
106
  return_tensors="pt",
107
  tokenize=True,
108
  return_dict=True,
109
  ).to(self.device)
110
  return model_inputs
111
-
112
  def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  logger.info(f"Incoming keys: {list(data.keys())}")
114
- if "inputs" not in data:
115
- raise ValueError("Missing `inputs` in request body.")
116
-
117
- prompt: Prompt = data["inputs"]
118
- params: Dict[str, Any] = (data.get("parameters") or {})
119
-
120
- # Defaults aligned with your Gradio code
121
- max_new_tokens = int(params.get("max_new_tokens", 256)) # raise per request if needed
122
- temperature = float(params.get("temperature", 0.1))
123
- top_p = float(params.get("top_p", 1.0))
124
- top_k: Optional[int] = params.get("top_k", None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  use_cache = bool(params.get("use_cache", False))
126
  repetition_penalty = float(params.get("repetition_penalty", 1.0))
127
  eos_token_id = params.get("eos_token_id", self.tokenizer.eos_token_id)
128
  pad_token_id = params.get("pad_token_id", self.tokenizer.pad_token_id)
129
-
130
- inputs = self._build_model_inputs(prompt)
131
-
132
  gen_kwargs = dict(
133
  **inputs,
134
  max_new_tokens=max_new_tokens,
135
  temperature=temperature,
136
  top_p=top_p,
137
- do_sample=True, # streaming-like sampling on
138
  use_cache=use_cache,
139
  repetition_penalty=repetition_penalty,
140
  eos_token_id=eos_token_id,
@@ -142,35 +380,74 @@ class EndpointHandler:
142
  )
143
  if top_k is not None:
144
  gen_kwargs["top_k"] = int(top_k)
145
-
146
  with torch.no_grad():
147
  output_ids = self.model.generate(**gen_kwargs)
148
-
149
- # Return ONLY the continuation (like your streamer)
150
  input_len = inputs["input_ids"].shape[-1]
151
  generated_ids = output_ids[0, input_len:]
152
  reply_text = self.tokenizer.decode(generated_ids, skip_special_tokens=True)
153
-
154
- return {
155
- "reply": [reply_text],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  "usage": {
157
- "prompt_tokens": int(input_len),
158
- "generated_tokens": int(generated_ids.shape[-1]),
159
- },
 
160
  }
161
-
162
-
 
 
163
  if __name__ == "__main__":
164
  h = EndpointHandler(model_dir=".")
165
- # Raw string
166
- print(h({"inputs": "How far?", "parameters": {"max_new_tokens": 64}}))
167
- # Block-style content (your Gradio shape)
168
- print(h({
169
- "inputs": [
170
- {
171
- "role": "user",
172
- "content": [{"type": "text", "text": "Explain why sky dey blue."}]
173
- }
 
 
 
 
 
 
 
 
174
  ],
 
 
 
 
 
 
 
 
175
  "parameters": {"max_new_tokens": 64}
176
- }))
 
 
1
  #tope_version
2
  # handler.py
3
  # handler.py
4
+ # from typing import Any, Dict, List, Union, Optional
5
+ # import torch
6
+ # from huggingface_inference_toolkit.logging import logger
7
+ # from unsloth import FastLanguageModel
8
+ # from peft import PeftModel
9
+
10
+ # # OpenAI-style prompt:
11
+ # # - str
12
+ # # - [{"role": "...", "content": "..." | [{"type":"text","text":"..."}]}]
13
+ # Prompt = Union[str, List[Dict[str, Any]], Dict[str, Any]]
14
+
15
+
16
+ # def _to_block_list(content: Any) -> List[Dict[str, str]]:
17
+ # """Ensure content is a list[{'type':'text','text':...}]."""
18
+ # if content is None:
19
+ # return [{"type": "text", "text": ""}]
20
+ # if isinstance(content, list):
21
+ # # Assume already blocks
22
+ # return content
23
+ # # Fallback: stringify
24
+ # return [{"type": "text", "text": str(content)}]
25
+
26
+
27
+ # class EndpointHandler:
28
+ # """
29
+ # HF Inference Endpoint handler that mirrors your Gradio setup:
30
+ # - Loads Unsloth 4-bit Gemma-3-4B IT
31
+ # - Attaches LoRA adapter
32
+ # - Uses tokenizer.apply_chat_template
33
+ # - Always replies in Nigerian Pidgin
34
+ # """
35
+
36
+ # def __init__(self, model_dir: str, **_: Any):
37
+ # logger.info(f"Initializing with model_dir={model_dir}")
38
+
39
+ # base_model_name = "unsloth/gemma-3-4b-it-unsloth-bnb-4bit"
40
+ # model, tokenizer = FastLanguageModel.from_pretrained(
41
+ # model_name=base_model_name,
42
+ # max_seq_length=2048,
43
+ # dtype=torch.float16,
44
+ # load_in_4bit=True,
45
+ # )
46
+
47
+ # lora_repo = "Ephraimmm/PIDGIN_gemma-3"
48
+ # model = PeftModel.from_pretrained(model, lora_repo)
49
+ # FastLanguageModel.for_inference(model)
50
+
51
+ # self.model = model.eval()
52
+ # self.tokenizer = tokenizer
53
+ # self.device = getattr(
54
+ # self.model,
55
+ # "device",
56
+ # torch.device("cuda" if torch.cuda.is_available() else "cpu"),
57
+ # )
58
+ # # Safety: some tokenizers lack pad_token_id
59
+ # if getattr(self.tokenizer, "pad_token_id", None) is None:
60
+ # self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
61
+
62
+ # logger.info(f"Device: {self.device} | eos_id: {self.tokenizer.eos_token_id}")
63
+
64
+ # self._system_text = (
65
+ # "You are a Nigerian assistant that speaks PIDGIN ENGLISH. "
66
+ # "When asked 'how far', reply 'I dey o, how you dey?'. "
67
+ # "Always answer in Pidgin English."
68
+ # )
69
+
70
+ # def _normalize_messages(self, prompt: Prompt) -> List[Dict[str, Any]]:
71
+ # """Return a list of messages with block-style contents only."""
72
+ # # Accept single dict
73
+ # if isinstance(prompt, dict):
74
+ # prompt = [prompt]
75
+
76
+ # # Accept raw string
77
+ # if isinstance(prompt, str):
78
+ # msgs = [
79
+ # {"role": "system", "content": _to_block_list(self._system_text)},
80
+ # {"role": "user", "content": _to_block_list(prompt)},
81
+ # ]
82
+ # return msgs
83
+
84
+ # if not isinstance(prompt, list):
85
+ # raise ValueError("`inputs` must be a string, a message dict, or a list of messages.")
86
+
87
+ # # Normalize all contents to blocks
88
+ # norm = []
89
+ # for m in prompt:
90
+ # role = m.get("role", "user")
91
+ # content = _to_block_list(m.get("content", ""))
92
+ # norm.append({"role": role, "content": content})
93
+
94
+ # # Ensure a system message exists (prepend if missing)
95
+ # if not any(m.get("role") == "system" for m in norm):
96
+ # norm = [{"role": "system", "content": _to_block_list(self._system_text)}] + norm
97
+
98
+ # return norm
99
+
100
+ # def _build_model_inputs(self, prompt: Prompt):
101
+ # messages = self._normalize_messages(prompt)
102
+ # # Use the same path as your Gradio script
103
+ # model_inputs = self.tokenizer.apply_chat_template(
104
+ # messages,
105
+ # add_generation_prompt=True,
106
+ # return_tensors="pt",
107
+ # tokenize=True,
108
+ # return_dict=True,
109
+ # ).to(self.device)
110
+ # return model_inputs
111
+
112
+ # def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
113
+ # logger.info(f"Incoming keys: {list(data.keys())}")
114
+ # if "inputs" not in data:
115
+ # raise ValueError("Missing `inputs` in request body.")
116
+
117
+ # prompt: Prompt = data["inputs"]
118
+ # params: Dict[str, Any] = (data.get("parameters") or {})
119
+
120
+ # # Defaults aligned with your Gradio code
121
+ # max_new_tokens = int(params.get("max_new_tokens", 256)) # raise per request if needed
122
+ # temperature = float(params.get("temperature", 0.1))
123
+ # top_p = float(params.get("top_p", 1.0))
124
+ # top_k: Optional[int] = params.get("top_k", None)
125
+ # use_cache = bool(params.get("use_cache", False))
126
+ # repetition_penalty = float(params.get("repetition_penalty", 1.0))
127
+ # eos_token_id = params.get("eos_token_id", self.tokenizer.eos_token_id)
128
+ # pad_token_id = params.get("pad_token_id", self.tokenizer.pad_token_id)
129
+
130
+ # inputs = self._build_model_inputs(prompt)
131
+
132
+ # gen_kwargs = dict(
133
+ # **inputs,
134
+ # max_new_tokens=max_new_tokens,
135
+ # temperature=temperature,
136
+ # top_p=top_p,
137
+ # do_sample=True, # streaming-like sampling on
138
+ # use_cache=use_cache,
139
+ # repetition_penalty=repetition_penalty,
140
+ # eos_token_id=eos_token_id,
141
+ # pad_token_id=pad_token_id,
142
+ # )
143
+ # if top_k is not None:
144
+ # gen_kwargs["top_k"] = int(top_k)
145
+
146
+ # with torch.no_grad():
147
+ # output_ids = self.model.generate(**gen_kwargs)
148
+
149
+ # # Return ONLY the continuation (like your streamer)
150
+ # input_len = inputs["input_ids"].shape[-1]
151
+ # generated_ids = output_ids[0, input_len:]
152
+ # reply_text = self.tokenizer.decode(generated_ids, skip_special_tokens=True)
153
+
154
+ # return {
155
+ # "reply": [reply_text],
156
+ # "usage": {
157
+ # "prompt_tokens": int(input_len),
158
+ # "generated_tokens": int(generated_ids.shape[-1]),
159
+ # },
160
+ # }
161
+
162
+
163
+ # if __name__ == "__main__":
164
+ # h = EndpointHandler(model_dir=".")
165
+ # # Raw string
166
+ # print(h({"inputs": "How far?", "parameters": {"max_new_tokens": 64}}))
167
+ # # Block-style content (your Gradio shape)
168
+ # print(h({
169
+ # "inputs": [
170
+ # {
171
+ # "role": "user",
172
+ # "content": [{"type": "text", "text": "Explain why sky dey blue."}]
173
+ # }
174
+ # ],
175
+ # "parameters": {"max_new_tokens": 64}
176
+ # }))
177
+
178
+
179
  from typing import Any, Dict, List, Union, Optional
180
  import torch
181
+ import time
182
  from huggingface_inference_toolkit.logging import logger
183
  from unsloth import FastLanguageModel
184
  from peft import PeftModel
185
+
186
  # OpenAI-style prompt:
187
  # - str
188
  # - [{"role": "...", "content": "..." | [{"type":"text","text":"..."}]}]
189
  Prompt = Union[str, List[Dict[str, Any]], Dict[str, Any]]
190
+
191
+
192
  def _to_block_list(content: Any) -> List[Dict[str, str]]:
193
  """Ensure content is a list[{'type':'text','text':...}]."""
194
  if content is None:
 
198
  return content
199
  # Fallback: stringify
200
  return [{"type": "text", "text": str(content)}]
201
+
202
+
203
  class EndpointHandler:
204
  """
205
+ HF Inference Endpoint handler that mirrors OpenAI API format:
206
+ - Accepts OpenAI-style requests with 'messages', 'model', etc.
207
+ - Returns OpenAI-style responses with 'choices', 'usage', etc.
208
  - Loads Unsloth 4-bit Gemma-3-4B IT
209
  - Attaches LoRA adapter
210
  - Uses tokenizer.apply_chat_template
211
  - Always replies in Nigerian Pidgin
212
  """
213
+
214
  def __init__(self, model_dir: str, **_: Any):
215
  logger.info(f"Initializing with model_dir={model_dir}")
216
+
217
  base_model_name = "unsloth/gemma-3-4b-it-unsloth-bnb-4bit"
218
  model, tokenizer = FastLanguageModel.from_pretrained(
219
  model_name=base_model_name,
 
221
  dtype=torch.float16,
222
  load_in_4bit=True,
223
  )
224
+
225
  lora_repo = "Ephraimmm/PIDGIN_gemma-3"
226
  model = PeftModel.from_pretrained(model, lora_repo)
227
  FastLanguageModel.for_inference(model)
228
+
229
  self.model = model.eval()
230
  self.tokenizer = tokenizer
231
  self.device = getattr(
 
236
  # Safety: some tokenizers lack pad_token_id
237
  if getattr(self.tokenizer, "pad_token_id", None) is None:
238
  self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
239
+
240
  logger.info(f"Device: {self.device} | eos_id: {self.tokenizer.eos_token_id}")
241
+
242
  self._system_text = (
243
  "You are a Nigerian assistant that speaks PIDGIN ENGLISH. "
244
  "When asked 'how far', reply 'I dey o, how you dey?'. "
245
  "Always answer in Pidgin English."
246
  )
247
+
248
+ def _normalize_messages(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
249
+ """Normalize OpenAI-style messages to block-style contents."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  norm = []
251
+ for m in messages:
252
  role = m.get("role", "user")
253
+ content = m.get("content", "")
254
+
255
+ # Convert content to block list format
256
+ if isinstance(content, str):
257
+ content = _to_block_list(content)
258
+ elif isinstance(content, list):
259
+ # Already in block format or needs conversion
260
+ content = _to_block_list(content)
261
+ else:
262
+ content = _to_block_list(str(content))
263
+
264
  norm.append({"role": role, "content": content})
265
+
266
  # Ensure a system message exists (prepend if missing)
267
  if not any(m.get("role") == "system" for m in norm):
268
  norm = [{"role": "system", "content": _to_block_list(self._system_text)}] + norm
269
+
270
  return norm
271
+
272
+ def _build_model_inputs(self, messages: List[Dict[str, Any]]):
273
+ normalized_messages = self._normalize_messages(messages)
 
274
  model_inputs = self.tokenizer.apply_chat_template(
275
+ normalized_messages,
276
  add_generation_prompt=True,
277
  return_tensors="pt",
278
  tokenize=True,
279
  return_dict=True,
280
  ).to(self.device)
281
  return model_inputs
282
+
283
  def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
284
+ """
285
+ Process OpenAI-style requests and return OpenAI-style responses.
286
+
287
+ Input format (OpenAI API):
288
+ {
289
+ "messages": [{"role": "user", "content": "Hello"}],
290
+ "model": "gpt-3.5-turbo", # optional
291
+ "temperature": 0.7, # optional
292
+ "max_tokens": 256, # optional
293
+ "top_p": 1.0, # optional
294
+ ...
295
+ }
296
+
297
+ Output format (OpenAI API):
298
+ {
299
+ "id": "chatcmpl-...",
300
+ "object": "chat.completion",
301
+ "created": 1234567890,
302
+ "model": "gemma-3-4b-pidgin",
303
+ "choices": [{
304
+ "index": 0,
305
+ "message": {
306
+ "role": "assistant",
307
+ "content": "Response text"
308
+ },
309
+ "finish_reason": "stop"
310
+ }],
311
+ "usage": {
312
+ "prompt_tokens": 10,
313
+ "completion_tokens": 20,
314
+ "total_tokens": 30
315
+ }
316
+ }
317
+ """
318
  logger.info(f"Incoming keys: {list(data.keys())}")
319
+
320
+ # Support both OpenAI format ('messages') and legacy format ('inputs')
321
+ if "messages" in data:
322
+ messages = data["messages"]
323
+ if not isinstance(messages, list):
324
+ raise ValueError("`messages` must be a list of message objects.")
325
+ elif "inputs" in data:
326
+ # Legacy support: convert inputs to messages format
327
+ prompt = data["inputs"]
328
+ if isinstance(prompt, str):
329
+ messages = [{"role": "user", "content": prompt}]
330
+ elif isinstance(prompt, dict):
331
+ messages = [prompt]
332
+ elif isinstance(prompt, list):
333
+ messages = prompt
334
+ else:
335
+ raise ValueError("Invalid `inputs` format.")
336
+ else:
337
+ raise ValueError("Missing `messages` or `inputs` in request body.")
338
+
339
+ # Extract parameters (support both OpenAI and custom parameter names)
340
+ params: Dict[str, Any] = data.get("parameters", {})
341
+
342
+ # Map OpenAI parameters to model parameters
343
+ max_new_tokens = int(
344
+ params.get("max_new_tokens") or
345
+ data.get("max_tokens") or
346
+ params.get("max_tokens") or
347
+ 256
348
+ )
349
+ temperature = float(
350
+ params.get("temperature") or
351
+ data.get("temperature") or
352
+ 0.1
353
+ )
354
+ top_p = float(
355
+ params.get("top_p") or
356
+ data.get("top_p") or
357
+ 1.0
358
+ )
359
+ top_k: Optional[int] = (
360
+ params.get("top_k") or
361
+ data.get("top_k")
362
+ )
363
  use_cache = bool(params.get("use_cache", False))
364
  repetition_penalty = float(params.get("repetition_penalty", 1.0))
365
  eos_token_id = params.get("eos_token_id", self.tokenizer.eos_token_id)
366
  pad_token_id = params.get("pad_token_id", self.tokenizer.pad_token_id)
367
+
368
+ inputs = self._build_model_inputs(messages)
369
+
370
  gen_kwargs = dict(
371
  **inputs,
372
  max_new_tokens=max_new_tokens,
373
  temperature=temperature,
374
  top_p=top_p,
375
+ do_sample=True,
376
  use_cache=use_cache,
377
  repetition_penalty=repetition_penalty,
378
  eos_token_id=eos_token_id,
 
380
  )
381
  if top_k is not None:
382
  gen_kwargs["top_k"] = int(top_k)
383
+
384
  with torch.no_grad():
385
  output_ids = self.model.generate(**gen_kwargs)
386
+
387
+ # Extract only the generated tokens (exclude prompt)
388
  input_len = inputs["input_ids"].shape[-1]
389
  generated_ids = output_ids[0, input_len:]
390
  reply_text = self.tokenizer.decode(generated_ids, skip_special_tokens=True)
391
+
392
+ # Calculate tokens
393
+ prompt_tokens = int(input_len)
394
+ completion_tokens = int(generated_ids.shape[-1])
395
+ total_tokens = prompt_tokens + completion_tokens
396
+
397
+ # Return OpenAI-style response
398
+ response = {
399
+ "id": f"chatcmpl-{int(time.time())}",
400
+ "object": "chat.completion",
401
+ "created": int(time.time()),
402
+ "model": data.get("model", "gemma-3-4b-pidgin"),
403
+ "choices": [
404
+ {
405
+ "index": 0,
406
+ "message": {
407
+ "role": "assistant",
408
+ "content": reply_text
409
+ },
410
+ "finish_reason": "stop"
411
+ }
412
+ ],
413
  "usage": {
414
+ "prompt_tokens": prompt_tokens,
415
+ "completion_tokens": completion_tokens,
416
+ "total_tokens": total_tokens
417
+ }
418
  }
419
+
420
+ return response
421
+
422
+
423
  if __name__ == "__main__":
424
  h = EndpointHandler(model_dir=".")
425
+
426
+ # Test with OpenAI-style format
427
+ print("=== OpenAI Format Test ===")
428
+ response = h({
429
+ "messages": [
430
+ {"role": "user", "content": "How far?"}
431
+ ],
432
+ "temperature": 0.7,
433
+ "max_tokens": 64
434
+ })
435
+ print(response)
436
+
437
+ print("\n=== OpenAI Format with System Message ===")
438
+ response = h({
439
+ "messages": [
440
+ {"role": "system", "content": "You are a helpful assistant."},
441
+ {"role": "user", "content": "Explain why sky dey blue."}
442
  ],
443
+ "max_tokens": 64
444
+ })
445
+ print(response)
446
+
447
+ # Legacy format still works
448
+ print("\n=== Legacy Format Test ===")
449
+ response = h({
450
+ "inputs": "How far?",
451
  "parameters": {"max_new_tokens": 64}
452
+ })
453
+ print(response)