Sergey Parkhomenko commited on
Commit
f432ad1
·
unverified ·
1 Parent(s): 81917a3

Added basic Agent on Qwen

Browse files
Files changed (1) hide show
  1. app.py +46 -4
app.py CHANGED
@@ -3,6 +3,8 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
@@ -13,11 +15,51 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
  class BasicAgent:
14
  def __init__(self):
15
  print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
  print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
@@ -91,7 +133,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
91
  print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
- # 4. Prepare Submission
95
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
  print(status_update)
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ import torch
8
 
9
  # (Keep Constants as is)
10
  # --- Constants ---
 
15
  class BasicAgent:
16
  def __init__(self):
17
  print("BasicAgent initialized.")
18
+ # Load the Qwen model and tokenizer
19
+ self.model_name = "Qwen/Qwen1.5-0.5B-Chat"
20
+ try:
21
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
22
+ self.model = AutoModelForCausalLM.from_pretrained(self.model_name)
23
+ # Move model to GPU if available
24
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
+ self.model.to(self.device)
26
+ print(f"Qwen model '{self.model_name}' loaded successfully on {self.device}.")
27
+ except Exception as e:
28
+ print(f"Error loading Qwen model: {e}")
29
+ raise
30
+
31
  def __call__(self, question: str) -> str:
32
  print(f"Agent received question (first 50 chars): {question[:50]}...")
33
+ try:
34
+ # Create a chat-like prompt for Qwen
35
+ messages = [
36
+ {"role": "system", "content": "You are a helpful assistant."},
37
+ {"role": "user", "content": question}
38
+ ]
39
+ text = self.tokenizer.apply_chat_template(
40
+ messages,
41
+ tokenize=False,
42
+ add_generation_prompt=True
43
+ )
44
+ model_inputs = self.tokenizer([text], return_tensors="pt").to(self.device)
45
+
46
+ # Generate a response
47
+ generated_ids = self.model.generate(
48
+ model_inputs.input_ids,
49
+ max_new_tokens=500, # Limit the response length
50
+ do_sample=True,
51
+ temperature=0.7, # Adjust for creativity vs. consistency
52
+ top_p=0.9
53
+ )
54
+ generated_ids = [
55
+ output_id[len(model_inputs.input_ids[0]):] for output_id in generated_ids
56
+ ]
57
+ response = self.tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
58
+ print(f"Agent returning answer (first 50 chars): {response[:50]}...")
59
+ return response
60
+ except Exception as e:
61
+ print(f"Error during agent's __call__: {e}")
62
+ return f"Error: Could not process the question. {e}"
63
 
64
  def run_and_submit_all( profile: gr.OAuthProfile | None):
65
  """
 
133
  print("Agent did not produce any answers to submit.")
134
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
135
 
136
+ # 4. Prepare Submission
137
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
138
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
139
  print(status_update)