Shrijanagain commited on
Commit
222244d
·
verified ·
1 Parent(s): 9c1b71e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -31
app.py CHANGED
@@ -11,10 +11,11 @@ from transformers import AutoTokenizer, AutoModelForCausalLM
11
  MODEL_ID = os.getenv("MODEL_ID", "WeiboAI/VibeThinker-3B")
12
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
13
 
14
- # System prompt – defines the assistant's personality and constraints
15
- SYSTEM_PROMPT = (
16
- "You are X-RUDRA, a helpful, knowledgeable, and concise AI assistant. "
17
- "SEARCH DECISION SYSTEM PROMPT
 
18
 
19
  ACT ONLY WHEN REQUIRED.
20
 
@@ -106,14 +107,13 @@ SEARCH FOR INFORMATION.
106
  DO NOT SEARCH FOR CONVERSATION.
107
 
108
  SEARCH ONLY WHEN SEARCHING IMPROVES ACCURACY, FRESHNESS, VERIFICATION, OR COMPLETENESS.
109
- "
110
- )
111
 
112
  print("=" * 60)
113
- print("X-RUDRA M2 (CHAT + API)")
114
  print("MODEL:", MODEL_ID)
115
  print("DEVICE:", DEVICE)
116
- print("SYSTEM PROMPT:", SYSTEM_PROMPT)
117
  print("=" * 60)
118
 
119
  # ============================================================
@@ -148,14 +148,12 @@ def build_prompt_with_system(history, new_user_message=None):
148
  new_user_message: str (if provided, appended as user message)
149
  Returns: prompt string ready for tokenization.
150
  """
151
- # Create a copy of history and optionally add the new user message
152
  messages = list(history) if history else []
153
  if new_user_message is not None:
154
  messages.append({"role": "user", "content": new_user_message})
155
 
156
  # If the tokenizer has a chat template that supports system, use it
157
  if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template is not None:
158
- # Some templates expect a system message; we'll include it
159
  full_messages = [{"role": "system", "content": SYSTEM_PROMPT}] + messages
160
  try:
161
  prompt = tokenizer.apply_chat_template(
@@ -174,7 +172,6 @@ def build_prompt_with_system(history, new_user_message=None):
174
  prompt += f"User: {turn['content']}\n"
175
  elif turn["role"] == "assistant":
176
  prompt += f"Assistant: {turn['content']}\n"
177
- # Add a final "Assistant:" to prompt the model
178
  prompt += "Assistant:"
179
  return prompt
180
 
@@ -185,16 +182,11 @@ def build_prompt_with_system(history, new_user_message=None):
185
 
186
  @spaces.GPU
187
  def generate_response(message, history, max_tokens, temperature):
188
- """
189
- Takes the current message and history, returns updated history with assistant reply.
190
- """
191
  if history is None:
192
  history = []
193
 
194
- # Build prompt including the new user message
195
  prompt = build_prompt_with_system(history, message)
196
 
197
- # Tokenize
198
  inputs = tokenizer(
199
  prompt,
200
  return_tensors="pt",
@@ -222,7 +214,6 @@ def generate_response(message, history, max_tokens, temperature):
222
  new_tokens = outputs[0][input_len:]
223
  answer = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
224
 
225
- # Append user message and assistant response to history
226
  history.append({"role": "user", "content": message})
227
  history.append({"role": "assistant", "content": answer})
228
 
@@ -235,12 +226,6 @@ def generate_response(message, history, max_tokens, temperature):
235
 
236
  @spaces.GPU
237
  def generate(prompt, max_tokens, temperature):
238
- """
239
- Standalone generation for API calls.
240
- Expects a raw prompt string, returns the generated text.
241
- """
242
- # Build full prompt with system + user input
243
- # We treat the input as a user message
244
  messages = [{"role": "user", "content": prompt}]
245
  full_prompt = build_prompt_with_system(messages)
246
 
@@ -277,13 +262,12 @@ def generate(prompt, max_tokens, temperature):
277
  # UI – Chat Interface
278
  # ============================================================
279
 
280
- with gr.Blocks(title="X-RUDRA M2") as demo:
281
  gr.Markdown(
282
  f"""
283
- # ⚡ X-RUDRA M2 – Chat + API
284
  **Model:** `{MODEL_ID}`
285
  **Device:** `{DEVICE}`
286
- **System Prompt:** `{SYSTEM_PROMPT[:80]}...`
287
  """
288
  )
289
 
@@ -307,9 +291,7 @@ with gr.Blocks(title="X-RUDRA M2") as demo:
307
  outputs=[msg, chatbot]
308
  )
309
 
310
- # ------------------------------------------------------------
311
- # Hidden Interface for API – exposes /generate endpoint
312
- # ------------------------------------------------------------
313
  gr.Interface(
314
  fn=generate,
315
  inputs=[
@@ -318,10 +300,10 @@ with gr.Blocks(title="X-RUDRA M2") as demo:
318
  gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="temperature")
319
  ],
320
  outputs=gr.Textbox(label="response"),
321
- title="X-RUDRA M2 API",
322
  description="Standalone generation endpoint.",
323
  api_name="generate",
324
- visible=False, # Hidden from UI, but API route is still active
325
  )
326
 
327
 
 
11
  MODEL_ID = os.getenv("MODEL_ID", "WeiboAI/VibeThinker-3B")
12
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
13
 
14
+ # System prompt – use triple quotes for multi-line strings
15
+ SYSTEM_PROMPT = """
16
+ You are X-RUDRA, a helpful, knowledgeable, and concise AI assistant.
17
+
18
+ # SEARCH DECISION SYSTEM PROMPT
19
 
20
  ACT ONLY WHEN REQUIRED.
21
 
 
107
  DO NOT SEARCH FOR CONVERSATION.
108
 
109
  SEARCH ONLY WHEN SEARCHING IMPROVES ACCURACY, FRESHNESS, VERIFICATION, OR COMPLETENESS.
110
+ """
 
111
 
112
  print("=" * 60)
113
+ print("X-RUDRA M1 (CHAT + API)") # Change to M2 for the other Space
114
  print("MODEL:", MODEL_ID)
115
  print("DEVICE:", DEVICE)
116
+ print("SYSTEM PROMPT (first 100 chars):", SYSTEM_PROMPT[:100] + "...")
117
  print("=" * 60)
118
 
119
  # ============================================================
 
148
  new_user_message: str (if provided, appended as user message)
149
  Returns: prompt string ready for tokenization.
150
  """
 
151
  messages = list(history) if history else []
152
  if new_user_message is not None:
153
  messages.append({"role": "user", "content": new_user_message})
154
 
155
  # If the tokenizer has a chat template that supports system, use it
156
  if hasattr(tokenizer, "apply_chat_template") and tokenizer.chat_template is not None:
 
157
  full_messages = [{"role": "system", "content": SYSTEM_PROMPT}] + messages
158
  try:
159
  prompt = tokenizer.apply_chat_template(
 
172
  prompt += f"User: {turn['content']}\n"
173
  elif turn["role"] == "assistant":
174
  prompt += f"Assistant: {turn['content']}\n"
 
175
  prompt += "Assistant:"
176
  return prompt
177
 
 
182
 
183
  @spaces.GPU
184
  def generate_response(message, history, max_tokens, temperature):
 
 
 
185
  if history is None:
186
  history = []
187
 
 
188
  prompt = build_prompt_with_system(history, message)
189
 
 
190
  inputs = tokenizer(
191
  prompt,
192
  return_tensors="pt",
 
214
  new_tokens = outputs[0][input_len:]
215
  answer = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
216
 
 
217
  history.append({"role": "user", "content": message})
218
  history.append({"role": "assistant", "content": answer})
219
 
 
226
 
227
  @spaces.GPU
228
  def generate(prompt, max_tokens, temperature):
 
 
 
 
 
 
229
  messages = [{"role": "user", "content": prompt}]
230
  full_prompt = build_prompt_with_system(messages)
231
 
 
262
  # UI – Chat Interface
263
  # ============================================================
264
 
265
+ with gr.Blocks(title="X-RUDRA M1") as demo: # Change to M2 for M2 Space
266
  gr.Markdown(
267
  f"""
268
+ # ⚡ X-RUDRA M1 – Chat + API
269
  **Model:** `{MODEL_ID}`
270
  **Device:** `{DEVICE}`
 
271
  """
272
  )
273
 
 
291
  outputs=[msg, chatbot]
292
  )
293
 
294
+ # Hidden API endpoint
 
 
295
  gr.Interface(
296
  fn=generate,
297
  inputs=[
 
300
  gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="temperature")
301
  ],
302
  outputs=gr.Textbox(label="response"),
303
+ title="X-RUDRA M1 API",
304
  description="Standalone generation endpoint.",
305
  api_name="generate",
306
+ visible=False,
307
  )
308
 
309