JUNGU commited on
Commit
8732509
·
verified ·
1 Parent(s): a0bc87d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -62
app.py CHANGED
@@ -1,80 +1,105 @@
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
- import traceback
8
 
9
- from Gradio_UI import GradioUI
 
 
 
 
 
 
 
10
 
11
  @tool
12
- def nse_stock_price_tool(stock_ticker:str)-> str:
13
- """A tool that is used to retrieve the latest closing price of a stock based on the stock ticker from the Indian Stock Exchange (NSE).
14
- example: 'RELIANCE.NS'
15
  Args:
16
- stock_ticker: The stock ticker/symbol for the stock listed in NSE. The exact string input needs to be provided to the function.
17
  Returns:
18
- result_string: A string containing the stock_ticker along with the amount in Rupees.
19
- example: "RELIANCE NS: 1237.22 Rupees."
20
  """
21
- try:
22
- import math
23
- import yfinance as yf
24
- stock_symbol = stock_ticker
25
- data = yf.download(tickers=stock_symbol, period='1d', interval='1m')
26
- if len(data):
27
- latest_data = data.tail(1)
28
- latest_price = latest_data['Close'].values[0]
29
- return (f"{stock_symbol}: {round(latest_price, 2)} Rupees.")
30
- else:
31
- return "INVALID TICKER/STOCK"
32
- except Exception as e:
33
- traceback.print_exc()
34
- return "INVALID REQUEST"
35
 
36
  @tool
37
- def get_current_time_in_timezone(timezone: str) -> str:
38
- """A tool that fetches the current local time in a specified timezone.
 
39
  Args:
40
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
 
 
41
  """
42
- try:
43
- # Create timezone object
44
- tz = pytz.timezone(timezone)
45
- # Get current time in that timezone
46
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
47
- return f"The current local time in {timezone} is: {local_time}"
48
- except Exception as e:
49
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
50
 
 
 
 
 
51
 
52
- final_answer = FinalAnswerTool()
53
- model = HfApiModel(
54
- max_tokens=2096,
55
- temperature=0.5,
56
- model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',
57
- custom_role_conversions=None,
58
- )
 
 
 
 
 
59
 
 
 
60
 
61
- # Import tool from Hub
62
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
63
 
64
- with open("prompts.yaml", 'r') as stream:
65
- prompt_templates = yaml.safe_load(stream)
 
 
 
 
66
 
67
- agent = CodeAgent(
68
- model=model,
69
- tools=[nse_stock_price_tool, final_answer], ## add your tools here (don't remove final answer)
70
- max_steps=6,
71
- verbosity_level=1,
72
- grammar=None,
73
- planning_interval=None,
74
- name=None,
75
- description=None,
76
- prompt_templates=prompt_templates
77
- )
 
 
 
 
 
 
 
 
 
78
 
 
 
 
79
 
80
- GradioUI(agent).launch()
 
 
1
+ from smolagents import CodeAgent, ToolCallingAgent, DuckDuckGoSearchTool, LiteLLMModel, tool
2
+ from typing import Optional
3
+ import os
4
+ from dotenv import load_dotenv
5
+ import gradio as gr
 
 
6
 
7
+ # .env 파일에서 환경 변수를 로드
8
+ load_dotenv()
9
+
10
+ # Gemini AI 모델 초기화
11
+ model = LiteLLMModel(
12
+ model_id="gemini/gemini-2.0-flash-exp",
13
+ api_key=os.getenv("GOOGLE_API_KEY")
14
+ )
15
 
16
  @tool
17
+ def search_news(topic: str) -> str:
18
+ """
19
+ 주어진 주제에 대한 최신 뉴스를 검색하는 도구입니다.
20
  Args:
21
+ topic: 검색할 뉴스 주제
22
  Returns:
23
+ 검색된 뉴스 정보
 
24
  """
25
+ search_agent = CodeAgent(
26
+ tools=[DuckDuckGoSearchTool()],
27
+ model=model,
28
+ additional_authorized_imports=["requests", "bs4"]
29
+ )
30
+ search_query = f"최신 뉴스 {topic}"
31
+ return search_agent.run(f"Search for: {search_query}")
 
 
 
 
 
 
 
32
 
33
  @tool
34
+ def write_article(topic: str, search_results: str) -> str:
35
+ """
36
+ 검색 결과를 바탕으로 새로운 기사를 작성하는 도구입니다.
37
  Args:
38
+ topic: 기사 주제
39
+ search_results: 검색된 뉴스 정보
40
+ Returns:
41
+ 작성된 기사
42
  """
43
+ NEWS_WRITER_PROMPT = """
44
+ 당신은 전문 기자입니다. 주어진 주제에 대해 검색된 정보를 바탕으로 새로운 기사를 한국어로 작성해야 합니다.
45
+ 다음 형식으로 기사를 작성해주세요:
 
 
 
 
 
46
 
47
+ 1. 제목 (흥미롭고 눈에 띄는 제목)
48
+ 2. 요약 (핵심 내용을 2-3문장으로 요약)
49
+ 3. 본문 (상세한 내용을 단락으로 구분하여 작성)
50
+ 4. 결론 (기사의 의의나 향후 전망)
51
 
52
+ 기사는 객관적이고 사실에 기반하여 작성해야 하며, 검색된 정보를 재구성하여 새로운 시각으로 작성해주세요.
53
+ """
54
+
55
+ writer_agent = ToolCallingAgent(
56
+ model=model,
57
+ system_prompt=NEWS_WRITER_PROMPT
58
+ )
59
+
60
+ prompt = f"""
61
+ 다음 주제와 검색 결과를 바탕으로 새로운 기사를 한국어로 작성해주세요:
62
+
63
+ 주제: {topic}
64
 
65
+ 검색 결과:
66
+ {search_results}
67
 
68
+ 정보를 바탕으로 새롭고 통찰력 있는 기사를 한국어로 작성해주세요.
69
+ """
70
+ return writer_agent.run(prompt)
71
 
72
+ class NewsWriterGradioUI:
73
+ def __init__(self):
74
+ self.agent = CodeAgent(
75
+ tools=[search_news, write_article],
76
+ model=model
77
+ )
78
 
79
+ def generate_article(self, topic: str) -> str:
80
+ try:
81
+ prompt = f"""
82
+ 1. '{topic}' 주제에 대해 search_news 도구를 사용하여 최신 뉴스를 검색하세요.
83
+ 2. 검색된 결과를 바탕으로 write_article 도구를 사용하여 새로운 기사를 작성하세요.
84
+ """
85
+ result = self.agent.run(prompt)
86
+ return result
87
+ except Exception as e:
88
+ return f"에러가 발생했습니다: {str(e)}"
89
+
90
+ def launch(self):
91
+ interface = gr.Interface(
92
+ fn=self.generate_article,
93
+ inputs=gr.Textbox(label="뉴스 주제를 입력하세요"),
94
+ outputs=gr.Textbox(label="생성된 기사"),
95
+ title="AI 기자",
96
+ description="주제를 입력하면 관련 뉴스를 검색하고 새로운 기사를 작성합니다."
97
+ )
98
+ interface.launch()
99
 
100
+ def main():
101
+ ui = NewsWriterGradioUI()
102
+ ui.launch()
103
 
104
+ if __name__ == "__main__":
105
+ main()