s1123725 commited on
Commit
3ba6402
·
verified ·
1 Parent(s): 19dc563

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -56
app.py CHANGED
@@ -1,33 +1,18 @@
1
- from smolagents import CodeAgent, load_tool, tool, HfApiModel
2
- import datetime
3
- import pytz
4
- import yaml
5
  from tools.final_answer import FinalAnswerTool
 
6
 
7
- # ===========================
8
- # 自訂工具示範
9
- # ===========================
10
- @tool
11
- def my_custom_tool(arg1: str, arg2: int) -> str:
12
- """
13
- A tool that does nothing yet.
14
- Args:
15
- arg1: the first argument
16
- arg2: the second argument
17
- Returns:
18
- str: a placeholder string
19
- """
20
- return "What magic will you build?"
21
 
22
- @tool
23
  def get_current_time_in_timezone(timezone: str) -> str:
24
- """
25
- A tool that fetches the current local time in a specified timezone.
26
- Args:
27
- timezone: A string representing a valid timezone (e.g., 'America/New_York')
28
- Returns:
29
- str: current local time in that timezone
30
- """
31
  try:
32
  tz = pytz.timezone(timezone)
33
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
@@ -35,42 +20,59 @@ def get_current_time_in_timezone(timezone: str) -> str:
35
  except Exception as e:
36
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
37
 
38
- # ===========================
39
- # Final Answer Tool
40
- # ===========================
41
- final_answer = FinalAnswerTool()
42
-
43
- # ===========================
44
- # 加載其他工具
45
- # ===========================
46
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
47
-
48
- # ===========================
49
- # 載入 Prompt Templates
50
- # ===========================
51
  with open("prompts.yaml", "r") as f:
52
  prompt_templates = yaml.safe_load(f)
53
 
54
- # ===========================
55
- # 建立 Agent
56
- # ===========================
57
- model = HfApiModel(
 
58
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
59
- max_tokens=2096,
60
  temperature=0.5,
61
- custom_role_conversions=None
62
  )
63
 
64
- agent = CodeAgent(
65
- model=model,
66
- tools=[my_custom_tool, get_current_time_in_timezone, image_generation_tool, final_answer],
67
- prompt_templates=prompt_templates
68
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- # ===========================
71
- # 測試 Agent
72
- # ===========================
73
  if __name__ == "__main__":
74
- question = "What time is it in Tokyo?"
75
- answer = agent(question)
76
- print(answer)
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ from smolagents import CodeAgent, load_tool
 
4
  from tools.final_answer import FinalAnswerTool
5
+ import yaml
6
 
7
+ # -----------------------------
8
+ # 載入工具
9
+ # -----------------------------
10
+ final_answer = FinalAnswerTool()
11
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
 
 
 
 
 
 
 
 
12
 
13
+ # 你自定義工具
14
  def get_current_time_in_timezone(timezone: str) -> str:
15
+ import datetime, pytz
 
 
 
 
 
 
16
  try:
17
  tz = pytz.timezone(timezone)
18
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
 
20
  except Exception as e:
21
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
22
 
23
+ # -----------------------------
24
+ # 載入 prompt templates
25
+ # -----------------------------
 
 
 
 
 
 
 
 
 
 
26
  with open("prompts.yaml", "r") as f:
27
  prompt_templates = yaml.safe_load(f)
28
 
29
+ # -----------------------------
30
+ # 初始化 Agent
31
+ # -----------------------------
32
+ agent = CodeAgent(
33
+ tools=[final_answer, image_generation_tool, get_current_time_in_timezone],
34
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
35
+ max_tokens=2048,
36
  temperature=0.5,
 
37
  )
38
 
39
+ # -----------------------------
40
+ # 模擬問題清單(可換成你的 API fetch)
41
+ # -----------------------------
42
+ questions = [
43
+ {"task_id": "q1", "question": "What is 2+2?"},
44
+ {"task_id": "q2", "question": "Get current time in New York"},
45
+ {"task_id": "q3", "question": "Generate an image of a cat riding a skateboard"}
46
+ ]
47
+
48
+ # -----------------------------
49
+ # Run agent
50
+ # -----------------------------
51
+ def run_agent():
52
+ results = []
53
+ correct_count = 0
54
+ for q in questions:
55
+ answer = agent(q["question"])
56
+ results.append({"ID": q["task_id"], "Question": q["question"], "Answer": answer})
57
+ # 這裡假設你有正確答案可以比對
58
+ # if answer == q["answer"]:
59
+ # correct_count += 1
60
+
61
+ df = pd.DataFrame(results)
62
+ score = round((correct_count / len(questions)) * 100, 2)
63
+ status = f"📊 Score: {score}% ({correct_count}/{len(questions)} correct)"
64
+ return status, df
65
+
66
+ # -----------------------------
67
+ # Gradio UI
68
+ # -----------------------------
69
+ with gr.Blocks() as demo:
70
+ gr.Markdown("## 🎯 Hybrid SmolAgent Demo")
71
+ run_btn = gr.Button("🚀 Run Hybrid Agent", variant="primary", size="lg")
72
+ status_box = gr.Textbox(label="📊 Results", lines=2, interactive=False)
73
+ results_table = gr.DataFrame(label="Questions & Answers", wrap=True)
74
+
75
+ run_btn.click(fn=run_agent, outputs=[status_box, results_table])
76
 
 
 
 
77
  if __name__ == "__main__":
78
+ demo.launch(debug=True)