JUNGU commited on
Commit
758fc3b
·
verified ·
1 Parent(s): 4b4ca7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -74
app.py CHANGED
@@ -1,17 +1,9 @@
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:
@@ -22,13 +14,17 @@ def search_news(topic: str) -> str:
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:
@@ -40,66 +36,60 @@ def write_article(topic: str, search_results: str) -> str:
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()
 
 
 
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, tool, LiteLLMModel
2
+ import yaml
3
+ import traceback
4
  import os
5
+ from tools.final_answer import FinalAnswerTool
6
+ from Gradio_UI import GradioUI
 
 
 
 
 
 
 
 
 
7
 
8
  @tool
9
  def search_news(topic: str) -> str:
 
14
  Returns:
15
  검색된 뉴스 정보
16
  """
17
+ try:
18
+ search_agent = CodeAgent(
19
+ tools=[DuckDuckGoSearchTool()],
20
+ model=model,
21
+ additional_authorized_imports=["requests", "bs4"]
22
+ )
23
+ search_query = f"최신 뉴스 {topic}"
24
+ return search_agent.run(f"Search for: {search_query}")
25
+ except Exception as e:
26
+ traceback.print_exc()
27
+ return f"검색 중 오류 발생: {str(e)}"
28
 
29
  @tool
30
  def write_article(topic: str, search_results: str) -> str:
 
36
  Returns:
37
  작성된 기사
38
  """
39
+ try:
40
+ system_prompt = """
41
+ 당신은 전문 기자입니다. 주어진 주제에 대해 검색된 정보를 바탕으로 새로운 기사를 한국어로 작성해야 합니다.
42
+ 다음 형식으로 기사를 작성해주세요:
43
 
44
+ 1. 제목 (흥미롭고 눈에 띄는 제목)
45
+ 2. 요약 (핵심 내용을 2-3문장으로 요약)
46
+ 3. 본문 (상세한 내용을 단락으로 구분하여 작성)
47
+ 4. 결론 (기사의 의의나 향후 전망)
48
 
49
+ 기사는 객관적이고 사실에 기반하여 작성해야 하며, 검색된 정보를 재구성하여 새로운 시각으로 작성해주세요.
50
+ """
51
+
52
+ prompt = f"""
53
+ 다음 주제와 검색 결과를 바탕으로 새로운 기사를 한국어로 작성해주세요:
 
 
 
 
 
54
 
55
+ 주제: {topic}
56
 
57
+ 검색 결과:
58
+ {search_results}
59
 
60
+ 위 정보를 바탕으로 새롭고 통찰력 있는 기사를 5문단으로 작성해주세요.
61
+ """
62
+ return model.generate(system_prompt + prompt)
63
+ except Exception as e:
64
+ traceback.print_exc()
65
+ return f"기사 작성 중 오류 발생: {str(e)}"
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
+ final_answer = FinalAnswerTool()
69
+ model = LiteLLMModel(
70
+ model_id="gemini/gemini-2.0-flash-exp", # 반드시 model_id 로 지정해야 함
71
+ max_tokens=2096,
72
+ temperature=0.7,
73
+ api_key=os.getenv("GOOGLE_API_KEY")
74
+ )
75
+
76
+ with open("prompts.yaml", 'r') as stream:
77
+ prompt_templates = yaml.safe_load(stream)
78
+
79
+ agent = CodeAgent(
80
+ model=model,
81
+ tools=[search_news, write_article, final_answer],
82
+ max_steps=6,
83
+ verbosity_level=1,
84
+ grammar=None,
85
+ planning_interval=None,
86
+ name=None,
87
+ description=None,
88
+ prompt_templates=prompt_templates
89
+ )
90
 
91
  if __name__ == "__main__":
92
+ try:
93
+ GradioUI(agent).launch()
94
+ except Exception as e:
95
+ print(f"Error launching UI: {str(e)}")