xenjin450 commited on
Commit
f604625
·
verified ·
1 Parent(s): ae7a494

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -25
app.py CHANGED
@@ -1,69 +1,130 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
  import datetime
3
- import requests
4
  import pytz
5
  import yaml
6
- from tools.final_answer import FinalAnswerTool
7
 
 
 
8
  from Gradio_UI import GradioUI
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
  Args:
16
  arg1: the first argument
17
  arg2: the second argument
18
  """
19
  return "What magic will you build ?"
20
 
 
21
  @tool
22
  def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
24
  Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
26
  """
27
  try:
28
- # Create timezone object
29
  tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
  return f"The current local time in {timezone} is: {local_time}"
33
  except Exception as e:
34
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- final_answer = FinalAnswerTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # 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:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
 
 
42
  model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
  )
48
 
49
-
50
- # Import tool from Hub
51
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
 
 
53
  with open("prompts.yaml", 'r') as stream:
54
  prompt_templates = yaml.safe_load(stream)
55
 
 
56
  agent = CodeAgent(
57
  model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
  max_steps=6,
60
  verbosity_level=1,
61
  grammar=None,
62
  planning_interval=None,
63
- name=None,
64
- description=None,
65
  prompt_templates=prompt_templates
66
  )
67
 
68
-
69
- GradioUI(agent).launch()
 
 
1
  import datetime
 
2
  import pytz
3
  import yaml
4
+ import yfinance as yf
5
 
6
+ from smolagents import CodeAgent, HfApiModel, load_tool, tool
7
+ from tools.final_answer import FinalAnswerTool
8
  from Gradio_UI import GradioUI
9
 
10
+ # A dummy tool that does nothing (for demonstration)
11
  @tool
12
+ def my_custom_tool(arg1: str, arg2: int) -> str:
13
+ """A tool that does nothing yet.
 
14
  Args:
15
  arg1: the first argument
16
  arg2: the second argument
17
  """
18
  return "What magic will you build ?"
19
 
20
+ # Tool to get the current time in a given timezone.
21
  @tool
22
  def get_current_time_in_timezone(timezone: str) -> str:
23
+ """Fetches the current local time in the specified timezone.
24
  Args:
25
+ timezone: A valid timezone string (e.g., 'America/New_York').
26
  """
27
  try:
 
28
  tz = pytz.timezone(timezone)
 
29
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
30
  return f"The current local time in {timezone} is: {local_time}"
31
  except Exception as e:
32
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
33
 
34
+ # Tool to fetch the current stock price using yfinance.
35
+ @tool
36
+ def get_current_stock_price(symbol: str) -> str:
37
+ """Fetches the current stock price for the given stock symbol.
38
+
39
+ Args:
40
+ symbol: The stock ticker symbol (e.g., 'AAPL').
41
+
42
+ Returns:
43
+ A string reporting the current stock price.
44
+ """
45
+ try:
46
+ ticker = yf.Ticker(symbol)
47
+ price = ticker.info.get("regularMarketPrice", None)
48
+ if price is None:
49
+ return f"Could not fetch current price for {symbol}."
50
+ return f"The current price of {symbol} is {price:.2f} USD."
51
+ except Exception as e:
52
+ return f"Error fetching current price for {symbol}: {str(e)}"
53
 
54
+ # Tool to fetch and summarize historical stock data using yfinance.
55
+ @tool
56
+ def get_stock_historical_data(symbol: str, timeline: str) -> str:
57
+ """Fetches historical stock data for a given symbol and timeline.
58
+
59
+ Args:
60
+ symbol: The stock ticker symbol (e.g., 'AAPL').
61
+ timeline: The timeframe for data. Acceptable values: '1h', '1day', '1week', '1year'.
62
+
63
+ Returns:
64
+ A summary string of the historical price data.
65
+ """
66
+ try:
67
+ ticker = yf.Ticker(symbol)
68
+ if timeline == "1h":
69
+ # For 1h data, fetch 1 day of data at 1-minute intervals and take the last 60 minutes.
70
+ df = ticker.history(period="1d", interval="1m").tail(60)
71
+ elif timeline == "1day":
72
+ df = ticker.history(period="1d", interval="5m")
73
+ elif timeline == "1week":
74
+ df = ticker.history(period="7d", interval="30m")
75
+ elif timeline == "1year":
76
+ df = ticker.history(period="1y", interval="1d")
77
+ else:
78
+ return f"Timeline '{timeline}' is not supported. Use '1h', '1day', '1week', or '1year'."
79
+
80
+ if df.empty:
81
+ return f"No historical data available for {symbol} over timeline {timeline}."
82
+
83
+ start_price = df['Close'].iloc[0]
84
+ end_price = df['Close'].iloc[-1]
85
+ min_price = df['Close'].min()
86
+ max_price = df['Close'].max()
87
+ summary = (
88
+ f"For {symbol} over {timeline}:\n"
89
+ f"Start Price: {start_price:.2f} USD\n"
90
+ f"End Price: {end_price:.2f} USD\n"
91
+ f"Min Price: {min_price:.2f} USD\n"
92
+ f"Max Price: {max_price:.2f} USD"
93
+ )
94
+ return summary
95
+ except Exception as e:
96
+ return f"Error fetching historical data for {symbol} over {timeline}: {str(e)}"
97
 
98
+ # Final answer tool that should always be included.
99
+ final_answer = FinalAnswerTool()
100
 
101
+ # Define the model with appropriate configuration.
102
  model = HfApiModel(
103
+ max_tokens=2096,
104
+ temperature=0.5,
105
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct', # if overloaded, consider an alternative endpoint
106
+ custom_role_conversions=None,
107
  )
108
 
109
+ # Optional: Load an additional tool from the Hub (e.g., a text-to-image tool)
 
110
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
111
 
112
+ # Load prompt templates from a YAML file.
113
  with open("prompts.yaml", 'r') as stream:
114
  prompt_templates = yaml.safe_load(stream)
115
 
116
+ # Initialize the CodeAgent with the new yfinance tools along with other tools.
117
  agent = CodeAgent(
118
  model=model,
119
+ tools=[final_answer, get_current_time_in_timezone, get_current_stock_price, get_stock_historical_data, my_custom_tool],
120
  max_steps=6,
121
  verbosity_level=1,
122
  grammar=None,
123
  planning_interval=None,
124
+ name="TradingAgent",
125
+ description="An AI agent that analyzes stock data using yfinance and advises on long-term trading decisions (buy, sell, or hold).",
126
  prompt_templates=prompt_templates
127
  )
128
 
129
+ # Launch the Gradio UI to interact with the agent.
130
+ GradioUI(agent).launch()