jcleee commited on
Commit
a770f8d
·
verified ·
1 Parent(s): 8472b68

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -170
app.py CHANGED
@@ -1,179 +1,15 @@
1
- import os
2
- import datetime
3
- import requests
4
- import pytz
5
- import yaml
6
- from typing import List
7
-
8
- from langchain.text_splitter import CharacterTextSplitter
9
- from tools.final_answer import FinalAnswerTool
10
- from smolagents import CodeAgent, LiteLLMModel, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
11
- from Gradio_UI import GradioUI
12
-
13
- # === TOOLS ===
14
-
15
- @tool
16
- def web_search(query: str) -> str:
17
- """Allows search through DuckDuckGo.
18
- Args:
19
- query: what you want to search
20
- """
21
- search_tool = DuckDuckGoSearchTool()
22
- results = search_tool(query)
23
- return "\n".join(results)
24
-
25
- @tool
26
- def get_current_time_in_timezone(timezone: str) -> str:
27
- """Fetches the current local time in a specified timezone.
28
- Args:
29
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
30
- """
31
- try:
32
- tz = pytz.timezone(timezone)
33
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
34
- return f"The current local time in {timezone} is: {local_time}"
35
- except Exception as e:
36
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
37
-
38
- @tool
39
- def visit_webpage(url: str) -> str:
40
- """Fetches raw HTML content of a web page.
41
- Args:
42
- url: The url of the webpage.
43
- """
44
- try:
45
- response = requests.get(url, timeout=5)
46
- return response.text[:5000] # Limit length
47
- except Exception as e:
48
- return f"[ERROR fetching {url}]: {str(e)}"
49
-
50
- @tool
51
- def text_splitter(text: str) -> List[str]:
52
- """Splits text into chunks using LangChain's CharacterTextSplitter.
53
- Args:
54
- text: A string of text to split.
55
- """
56
- splitter = CharacterTextSplitter(chunk_size=450, chunk_overlap=10)
57
- return splitter.split_text(text)
58
-
59
- # === FINAL ANSWER TOOL ===
60
- final_answer = FinalAnswerTool()
61
-
62
- # === LOAD PROMPT TEMPLATES ===
63
- with open("prompts.yaml", "r") as stream:
64
- prompt_templates = yaml.safe_load(stream)
65
-
66
- # === LOAD agent.json CONFIG ===
67
- with open("agent.json", "r") as f:
68
- agent_config = yaml.safe_load(f)
69
-
70
- model_config = agent_config["model"]["data"]
71
-
72
- # === BUILD MODEL ===
73
- model = LiteLLMModel(
74
- model_id="gemini/gemini-2.0-flash-lite",
75
- api_key=os.getenv("GEMINI_API_KEY"),
76
- temperature=0.5,
77
- max_tokens=1024,
78
- )
79
-
80
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
81
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' (!!!)
82
-
83
- # model = HfApiModel(
84
- # #model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
85
- # model_id="mistralai/Mistral-7B-Instruct-v0.2",
86
- # token=os.getenv("HF_TOKEN"),
87
- # max_tokens=2096,
88
- # temperature=0.5,
89
- # last_input_token_count=0,
90
- # last_output_token_count=0,
91
- # )
92
-
93
-
94
-
95
-
96
-
97
- # === IMPORT TOOL FROM HUB ===
98
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
99
-
100
- # === BUILD AGENT ===
101
- agent = CodeAgent(
102
- model=model,
103
- tools=[
104
- final_answer,
105
- web_search,
106
- get_current_time_in_timezone,
107
- visit_webpage,
108
- text_splitter,
109
- image_generation_tool
110
- ],
111
- max_steps=6,
112
- verbosity_level=1,
113
- grammar=None,
114
- planning_interval=None,
115
- name=None,
116
- description=None,
117
- prompt_templates=prompt_templates
118
- )
119
-
120
- # === LAUNCH UI ===
121
- GradioUI(agent).launch() # new change 6:36 - for evaluation API
122
-
123
  import gradio as gr
 
 
124
 
125
- # # OLD VERSION
126
- # def run_agent(question):
127
- # try:
128
- # result = agent(question)
129
- # return [str(result)] # Must return a list with one string (like ["answer"])
130
- # except Exception as e:
131
- # return [f"Error: {e}"]
132
-
133
- # # NEW VERSION
134
- # def run_agent(question):
135
- # try:
136
- # # Get all steps from the agent run
137
- # steps = list(agent.run(question, stream=False))
138
-
139
- # # Look through all tool calls to find final_answer
140
- # for step in steps:
141
- # if hasattr(step, "tool_calls") and step.tool_calls:
142
- # for call in step.tool_calls:
143
- # if call.name == "final_answer":
144
- # answer = call.arguments.get("answer", None)
145
- # if answer:
146
- # return [str(answer)]
147
-
148
- # # Fallback: try tool_output or .final_answer if FinalAnswerStep
149
- # for step in reversed(steps):
150
- # if hasattr(step, "tool_output") and step.tool_output:
151
- # return [str(step.tool_output)]
152
- # if hasattr(step, "final_answer") and step.final_answer:
153
- # return [str(step.final_answer)]
154
-
155
- # return ["null"]
156
- # except Exception as e:
157
- # return [f"Error: {e}"]
158
-
159
- # # NEWER VERSION (should just return the result)
160
- # import re
161
-
162
  # def run_agent(question):
163
  # try:
164
  # result = agent(question)
165
-
166
- # # If result is a string and contains "### 1. Task outcome", extract that
167
- # if isinstance(result, str):
168
- # match = re.search(r"### 1\. Task outcome \(short version\):\s*(.+)", result)
169
- # if match:
170
- # return [match.group(1).strip()] # return just the short answer
171
- # return [result.strip()]
172
-
173
  # return [str(result)]
174
  # except Exception as e:
175
  # return [f"Error: {e}"]
176
 
177
-
178
- demo = gr.Interface(fn=run_agent, inputs="text", outputs="text")
179
- demo.launch()
 
1
+ # app.py (for first_agent_template)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
3
+ from agent import agent # Import your refactored agent
4
+ from Gradio_UI import GradioUI
5
 
6
+ # Optional: Uncomment to test agent endpoint separately
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  # def run_agent(question):
8
  # try:
9
  # result = agent(question)
 
 
 
 
 
 
 
 
10
  # return [str(result)]
11
  # except Exception as e:
12
  # return [f"Error: {e}"]
13
 
14
+ if __name__ == "__main__":
15
+ GradioUI(agent).launch(debug=True, share=True)