HAMMALE commited on
Commit
949e803
·
verified ·
1 Parent(s): 72a94de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -49
app.py CHANGED
@@ -8,9 +8,8 @@ from datetime import datetime
8
  import ast
9
  import operator as op
10
  import wikipedia
11
- from huggingface_hub import snapshot_download
12
  import torch
13
- from transformers import GPT2LMHeadModel, GPT2Tokenizer
14
 
15
  class Tool:
16
  def __init__(self, name: str, description: str, func):
@@ -175,31 +174,20 @@ MODEL_NAME = "openai/gpt-oss-20b"
175
  model = None
176
  tokenizer = None
177
  model_loaded = False
178
- model_path = None
179
 
180
  def download_and_load_model(progress=gr.Progress()):
181
  """Download and load the model."""
182
- global model, tokenizer, model_loaded, model_path
183
 
184
  try:
185
  progress(0, desc="Starting model download...")
186
 
187
- progress(0.1, desc="Downloading model files (this will take several minutes)...")
188
- model_path = snapshot_download(
189
- repo_id=MODEL_NAME,
190
- cache_dir="./model_cache",
191
- resume_download=True
192
- )
193
-
194
- progress(0.6, desc="Loading tokenizer...")
195
- tokenizer = GPT2Tokenizer.from_pretrained(model_path)
196
-
197
- if tokenizer.pad_token is None:
198
- tokenizer.pad_token = tokenizer.eos_token
199
 
200
- progress(0.7, desc="Loading model into memory...")
201
- model = GPT2LMHeadModel.from_pretrained(
202
- model_path,
203
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
204
  device_map="auto" if torch.cuda.is_available() else None,
205
  low_cpu_mem_usage=True
@@ -209,7 +197,7 @@ def download_and_load_model(progress=gr.Progress()):
209
  model_loaded = True
210
 
211
  progress(1.0, desc="Model loaded successfully!")
212
- return f"Model 'openai/gpt-oss-20b' loaded successfully! Model path: {model_path}"
213
 
214
  except Exception as e:
215
  return f"Error loading model: {str(e)}"
@@ -290,7 +278,7 @@ def call_tool(tool_name: str, tool_input: str) -> str:
290
  return tool(tool_input)
291
  return f"Error: Tool '{tool_name}' not found. Available tools: {', '.join([t.name for t in TOOLS])}"
292
 
293
- def call_llm(messages: List[Dict], temperature: float = 0.7, max_tokens: int = 500) -> str:
294
  """Call the local LLM."""
295
  global model, tokenizer, model_loaded
296
 
@@ -298,11 +286,15 @@ def call_llm(messages: List[Dict], temperature: float = 0.7, max_tokens: int = 5
298
  return "Error: Model not loaded. Please click 'Download & Load Model' first."
299
 
300
  try:
301
- prompt = messages[0]["content"]
302
 
303
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048)
304
- if torch.cuda.is_available():
305
- inputs = {k: v.to(model.device) for k, v in inputs.items()}
 
 
 
 
306
 
307
  with torch.no_grad():
308
  outputs = model.generate(
@@ -310,11 +302,10 @@ def call_llm(messages: List[Dict], temperature: float = 0.7, max_tokens: int = 5
310
  max_new_tokens=max_tokens,
311
  temperature=temperature,
312
  do_sample=True,
313
- top_p=0.9,
314
- pad_token_id=tokenizer.eos_token_id
315
  )
316
 
317
- response = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True)
318
  return response.strip()
319
 
320
  except Exception as e:
@@ -326,12 +317,11 @@ def think_only_mode(question: str) -> str:
326
  return "Error: Model not loaded. Please click 'Download & Load Model' first."
327
 
328
  prompt = THINK_ONLY_PROMPT.format(question=question)
329
- messages = [{"role": "user", "content": prompt}]
330
 
331
  output = "**Mode: Think-Only (Chain-of-Thought)**\n\n"
332
  output += "Generating thoughts...\n\n"
333
 
334
- response = call_llm(messages, temperature=0.7, max_tokens=800)
335
 
336
  lines = response.split('\n')
337
  for line in lines:
@@ -356,13 +346,13 @@ def act_only_mode(question: str, max_iterations: int = 5) -> str:
356
 
357
  output = "**Mode: Act-Only (Tool Use Only)**\n\n"
358
 
359
- messages = [{"role": "user", "content": prompt}]
360
  iteration = 0
 
361
 
362
  while iteration < max_iterations:
363
  iteration += 1
364
 
365
- response = call_llm(messages, temperature=0.5, max_tokens=300)
366
 
367
  if 'Answer:' in response:
368
  answer_match = re.search(r'Answer:\s*(.+)', response, re.IGNORECASE | re.DOTALL)
@@ -379,8 +369,7 @@ def act_only_mode(question: str, max_iterations: int = 5) -> str:
379
  observation = call_tool(action_name, action_input)
380
  output += f"**Observation:** {observation}\n\n"
381
 
382
- messages.append({"role": "assistant", "content": response})
383
- messages.append({"role": "user", "content": f"Observation: {observation}\n\nContinue with another action or provide the final answer."})
384
  else:
385
  output += f"Could not parse action from response. Response: {response}\n\n"
386
  break
@@ -401,13 +390,13 @@ def react_mode(question: str, max_iterations: int = 5) -> str:
401
 
402
  output = "**Mode: ReAct (Thought + Action + Observation)**\n\n"
403
 
404
- messages = [{"role": "user", "content": prompt}]
405
  iteration = 0
 
406
 
407
  while iteration < max_iterations:
408
  iteration += 1
409
 
410
- response = call_llm(messages, temperature=0.7, max_tokens=400)
411
 
412
  thought_matches = re.findall(r'Thought:\s*(.+?)(?=\n(?:Action:|Answer:|$))', response, re.IGNORECASE | re.DOTALL)
413
  for thought in thought_matches:
@@ -428,8 +417,7 @@ def react_mode(question: str, max_iterations: int = 5) -> str:
428
  observation = call_tool(action_name, action_input)
429
  output += f"**Observation:** {observation}\n\n"
430
 
431
- messages.append({"role": "assistant", "content": response})
432
- messages.append({"role": "user", "content": f"Observation: {observation}\n\nThought:"})
433
  else:
434
  if 'Answer:' not in response:
435
  output += f"No action found. Response: {response}\n\n"
@@ -464,17 +452,6 @@ def run_comparison(question: str, mode: str):
464
  return "Invalid mode selected.", "", ""
465
 
466
  with gr.Blocks(title="LLM Reasoning Modes Comparison") as demo:
467
- gr.Markdown("""
468
- # LLM Reasoning Modes Comparison
469
-
470
- Compare three reasoning approaches using **openai/gpt-oss-20b**:
471
-
472
- - **Think-Only**: Chain-of-Thought reasoning only (no tools)
473
- - **Act-Only**: Tool use only (no explicit reasoning)
474
- - **ReAct**: Interleaved Thought, Action, Observation
475
-
476
- **Available Tools:** DuckDuckGo Search | Wikipedia | Weather API | Calculator | Python REPL
477
- """)
478
 
479
  with gr.Row():
480
  download_btn = gr.Button("Download & Load Model", variant="primary", size="lg")
 
8
  import ast
9
  import operator as op
10
  import wikipedia
 
11
  import torch
12
+ from transformers import AutoTokenizer, AutoModelForCausalLM
13
 
14
  class Tool:
15
  def __init__(self, name: str, description: str, func):
 
174
  model = None
175
  tokenizer = None
176
  model_loaded = False
 
177
 
178
  def download_and_load_model(progress=gr.Progress()):
179
  """Download and load the model."""
180
+ global model, tokenizer, model_loaded
181
 
182
  try:
183
  progress(0, desc="Starting model download...")
184
 
185
+ progress(0.3, desc="Downloading tokenizer...")
186
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
 
 
 
 
 
 
 
 
 
 
187
 
188
+ progress(0.5, desc="Downloading model (this may take several minutes)...")
189
+ model = AutoModelForCausalLM.from_pretrained(
190
+ MODEL_NAME,
191
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
192
  device_map="auto" if torch.cuda.is_available() else None,
193
  low_cpu_mem_usage=True
 
197
  model_loaded = True
198
 
199
  progress(1.0, desc="Model loaded successfully!")
200
+ return f"Model '{MODEL_NAME}' loaded successfully!"
201
 
202
  except Exception as e:
203
  return f"Error loading model: {str(e)}"
 
278
  return tool(tool_input)
279
  return f"Error: Tool '{tool_name}' not found. Available tools: {', '.join([t.name for t in TOOLS])}"
280
 
281
+ def call_llm(prompt: str, temperature: float = 0.7, max_tokens: int = 500) -> str:
282
  """Call the local LLM."""
283
  global model, tokenizer, model_loaded
284
 
 
286
  return "Error: Model not loaded. Please click 'Download & Load Model' first."
287
 
288
  try:
289
+ messages = [{"role": "user", "content": prompt}]
290
 
291
+ inputs = tokenizer.apply_chat_template(
292
+ messages,
293
+ add_generation_prompt=True,
294
+ tokenize=True,
295
+ return_dict=True,
296
+ return_tensors="pt",
297
+ ).to(model.device)
298
 
299
  with torch.no_grad():
300
  outputs = model.generate(
 
302
  max_new_tokens=max_tokens,
303
  temperature=temperature,
304
  do_sample=True,
305
+ top_p=0.9
 
306
  )
307
 
308
+ response = tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
309
  return response.strip()
310
 
311
  except Exception as e:
 
317
  return "Error: Model not loaded. Please click 'Download & Load Model' first."
318
 
319
  prompt = THINK_ONLY_PROMPT.format(question=question)
 
320
 
321
  output = "**Mode: Think-Only (Chain-of-Thought)**\n\n"
322
  output += "Generating thoughts...\n\n"
323
 
324
+ response = call_llm(prompt, temperature=0.7, max_tokens=800)
325
 
326
  lines = response.split('\n')
327
  for line in lines:
 
346
 
347
  output = "**Mode: Act-Only (Tool Use Only)**\n\n"
348
 
 
349
  iteration = 0
350
+ conversation_history = prompt
351
 
352
  while iteration < max_iterations:
353
  iteration += 1
354
 
355
+ response = call_llm(conversation_history, temperature=0.5, max_tokens=300)
356
 
357
  if 'Answer:' in response:
358
  answer_match = re.search(r'Answer:\s*(.+)', response, re.IGNORECASE | re.DOTALL)
 
369
  observation = call_tool(action_name, action_input)
370
  output += f"**Observation:** {observation}\n\n"
371
 
372
+ conversation_history += f"\n{response}\nObservation: {observation}\n\nContinue with another action or provide the final answer.\n"
 
373
  else:
374
  output += f"Could not parse action from response. Response: {response}\n\n"
375
  break
 
390
 
391
  output = "**Mode: ReAct (Thought + Action + Observation)**\n\n"
392
 
 
393
  iteration = 0
394
+ conversation_history = prompt
395
 
396
  while iteration < max_iterations:
397
  iteration += 1
398
 
399
+ response = call_llm(conversation_history, temperature=0.7, max_tokens=400)
400
 
401
  thought_matches = re.findall(r'Thought:\s*(.+?)(?=\n(?:Action:|Answer:|$))', response, re.IGNORECASE | re.DOTALL)
402
  for thought in thought_matches:
 
417
  observation = call_tool(action_name, action_input)
418
  output += f"**Observation:** {observation}\n\n"
419
 
420
+ conversation_history += f"\n{response}\nObservation: {observation}\n\nThought:"
 
421
  else:
422
  if 'Answer:' not in response:
423
  output += f"No action found. Response: {response}\n\n"
 
452
  return "Invalid mode selected.", "", ""
453
 
454
  with gr.Blocks(title="LLM Reasoning Modes Comparison") as demo:
 
 
 
 
 
 
 
 
 
 
 
455
 
456
  with gr.Row():
457
  download_btn = gr.Button("Download & Load Model", variant="primary", size="lg")