phanerozoic commited on
Commit
2066c13
·
verified ·
1 Parent(s): db081d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -76
app.py CHANGED
@@ -1,115 +1,106 @@
1
  #!/usr/bin/env python
2
  # coding=utf-8
 
 
 
 
3
 
4
- import copy
5
  import datetime
6
- import requests
7
  import pytz
8
  import yaml
9
 
10
- # smolagents imports:
11
- from smolagents import CodeAgent, HfApiModel, load_tool, tool
12
- from smolagents import prompts as _prompts
13
- from smolagents.agents import DEFAULT_PROMPT_TEMPLATES
14
-
15
 
16
- # Tools from your local folder
17
  from tools.final_answer import FinalAnswerTool
18
  from tools.visit_webpage import VisitWebpageTool
19
  from tools.web_search import DuckDuckGoSearchTool
20
 
21
- # Gradio UI from your local file
22
- from Gradio_UI import GradioUI
23
-
24
- ###############################################################
25
- # Example custom tool: a non-functional template
26
  @tool
27
  def my_custom_tool(arg1: str, arg2: int) -> str:
28
- """Example Tool: A non-functional tool provided as a template.
29
-
30
- Args:
31
- arg1: The first argument.
32
- arg2: The second argument.
33
- """
34
  return "What magic will you build ?"
35
 
36
- ###############################################################
37
- # A working tool: get the current time in a given timezone
38
  @tool
39
  def get_current_time_in_timezone(timezone: str) -> str:
40
- """Working Tool: Fetches the current local time in a specified timezone.
41
-
42
- Args:
43
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
44
- """
45
  try:
46
  tz = pytz.timezone(timezone)
47
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
48
- return f"The current local time in {timezone} is: {local_time}"
49
- except Exception as e:
50
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
51
-
52
- ###############################################################
53
- # Instantiate final_answer (required for returning final answers)
54
- final_answer = FinalAnswerTool()
55
 
56
- # Other local tools: web search & visit page
57
- search_tool = DuckDuckGoSearchTool()
58
- visit_tool = VisitWebpageTool()
59
 
60
- ###############################################################
61
- # Define model configuration using HfApiModel
62
  model = HfApiModel(
 
63
  max_tokens=2096,
64
  temperature=0.5,
65
- model_id='Qwen/Qwen3-32B', # Adjust if overloaded or unavailable
66
  custom_role_conversions=None,
67
  )
68
 
69
- ###############################################################
70
- # 1) Read your custom prompts.yaml
71
  try:
72
- with open("prompts.yaml", 'r') as stream:
73
- custom_prompts = yaml.safe_load(stream)
74
- except Exception as e:
75
- print("Error loading prompts.yaml:", e)
76
- custom_prompts = {}
77
-
78
- # 2) Merge with the built-in defaults so no keys or subkeys are missing
79
- prompt_templates = copy.deepcopy(DEFAULT_PROMPT_TEMPLATES)
80
-
81
- def deep_merge(base_dict, override_dict):
82
- """Recursively merge override_dict into base_dict."""
83
- for k, v in override_dict.items():
84
- if isinstance(v, dict) and isinstance(base_dict.get(k), dict):
85
- deep_merge(base_dict[k], v)
86
- else:
87
- base_dict[k] = v
88
-
89
- # Perform the merge
90
- deep_merge(prompt_templates, custom_prompts)
91
-
92
- ###############################################################
93
- # Create the CodeAgent with the merged prompt templates
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  agent = CodeAgent(
95
  model=model,
96
  tools=[
97
- final_answer,
98
- search_tool,
99
- visit_tool,
100
  get_current_time_in_timezone,
101
- my_custom_tool, # Example tool
102
  ],
103
  max_steps=6,
104
  verbosity_level=1,
105
- grammar=None,
106
- planning_interval=None,
107
- name=None,
108
- description=None,
109
- # The merged dictionary—ensures all required keys & structure are present
110
- prompt_templates=prompt_templates
111
  )
112
 
113
- ###############################################################
114
- # Launch Gradio UI
115
  GradioUI(agent).launch()
 
1
  #!/usr/bin/env python
2
  # coding=utf-8
3
+ """
4
+ Robust startup file that guarantees the prompt template dict matches what
5
+ smolagents.CodeAgent expects, without importing internal constants.
6
+ """
7
 
 
8
  import datetime
9
+ import copy
10
  import pytz
11
  import yaml
12
 
13
+ # ------------- smolagents -------------
14
+ from smolagents import CodeAgent, HfApiModel, tool
15
+ # Local Gradio wrapper
16
+ from Gradio_UI import GradioUI
 
17
 
18
+ # ------------ local tools -------------
19
  from tools.final_answer import FinalAnswerTool
20
  from tools.visit_webpage import VisitWebpageTool
21
  from tools.web_search import DuckDuckGoSearchTool
22
 
23
+ # ---------- example custom tool -------
 
 
 
 
24
  @tool
25
  def my_custom_tool(arg1: str, arg2: int) -> str:
26
+ """A placeholder tool to illustrate custom tool wiring."""
 
 
 
 
 
27
  return "What magic will you build ?"
28
 
29
+
 
30
  @tool
31
  def get_current_time_in_timezone(timezone: str) -> str:
32
+ """Return current local time in a given timezone."""
 
 
 
 
33
  try:
34
  tz = pytz.timezone(timezone)
35
+ return datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
36
+ except Exception as exc:
37
+ return f"Invalid timezone ({exc})"
 
 
 
 
 
38
 
 
 
 
39
 
40
+ # ---------------- model ----------------
 
41
  model = HfApiModel(
42
+ model_id="Qwen/Qwen3-32B",
43
  max_tokens=2096,
44
  temperature=0.5,
 
45
  custom_role_conversions=None,
46
  )
47
 
48
+ # ------------- load YAML --------------
 
49
  try:
50
+ with open("prompts.yaml", "r") as f:
51
+ user_templates = yaml.safe_load(f) or {}
52
+ except Exception as exc:
53
+ print("⚠️ Could not load prompts.yaml — using bare-bones defaults.", exc)
54
+ user_templates = {}
55
+
56
+ # --------- repair / fill gaps ---------
57
+ def ensure_block(mapping, key, default):
58
+ """If key missing or wrong type, replace with default."""
59
+ if key not in mapping or not isinstance(mapping[key], type(default)):
60
+ mapping[key] = copy.deepcopy(default)
61
+
62
+ # Minimal viable defaults
63
+ MIN_SYSTEM = "You are a helpful agent."
64
+ MIN_FINAL = "Thought: I now know the answer.\nCode:\n```py\nfinal_answer({{answer}})\n```<end_code>"
65
+ MIN_PLAN_DICT = {
66
+ "initial_facts": "|-\n List any facts.",
67
+ "initial_plan": "|-\n Write a high-level plan.",
68
+ "update_facts_pre_messages": "|-\n Pre facts.",
69
+ "update_facts_post_messages": "|-\n Post facts.",
70
+ "update_plan_pre_messages": "|-\n Pre plan.",
71
+ "update_plan_post_messages": "|-\n Post plan.",
72
+ }
73
+ MIN_AGENT_DICT = {
74
+ "task": "|-\n You are {{name}}.",
75
+ "report": "|-\n {{final_answer}}",
76
+ }
77
+
78
+ # Top-level fix-ups
79
+ ensure_block(user_templates, "system_prompt", MIN_SYSTEM)
80
+ ensure_block(user_templates, "final_answer", MIN_FINAL)
81
+ ensure_block(user_templates, "planning", MIN_PLAN_DICT)
82
+ ensure_block(user_templates, "managed_agent", MIN_AGENT_DICT)
83
+
84
+ # If planning/managed_agent came in as strings, convert to dict with default
85
+ if isinstance(user_templates["planning"], str):
86
+ user_templates["planning"] = copy.deepcopy(MIN_PLAN_DICT)
87
+ if isinstance(user_templates["managed_agent"], str):
88
+ user_templates["managed_agent"] = copy.deepcopy(MIN_AGENT_DICT)
89
+
90
+ # ------------- create agent -----------
91
  agent = CodeAgent(
92
  model=model,
93
  tools=[
94
+ FinalAnswerTool(),
95
+ DuckDuckGoSearchTool(),
96
+ VisitWebpageTool(),
97
  get_current_time_in_timezone,
98
+ my_custom_tool,
99
  ],
100
  max_steps=6,
101
  verbosity_level=1,
102
+ prompt_templates=user_templates,
 
 
 
 
 
103
  )
104
 
105
+ # ------------- launch UI --------------
 
106
  GradioUI(agent).launch()