girishwangikar commited on
Commit
a98e519
Β·
verified Β·
1 Parent(s): d8a9363

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -47
app.py CHANGED
@@ -1,9 +1,33 @@
1
  import streamlit as st
2
  import pandas as pd
3
- from smolagents import CodeAgent, DuckDuckGoSearchTool
4
  from typing import Union, List, Dict
5
  from groq import Groq
6
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  class GroqLLM:
9
  """Compatible LLM interface for smolagents CodeAgent"""
@@ -13,13 +37,8 @@ class GroqLLM:
13
 
14
  def __call__(self, prompt: Union[str, dict, List[Dict]]) -> str:
15
  try:
16
- # Handle different prompt formats
17
- if isinstance(prompt, (dict, list)):
18
- prompt_str = str(prompt)
19
- else:
20
- prompt_str = str(prompt)
21
 
22
- # Create a properly formatted message
23
  completion = self.client.chat.completions.create(
24
  model=self.model_name,
25
  messages=[{
@@ -41,14 +60,30 @@ def create_analysis_prompt(topic: str, search_results: str) -> str:
41
  return f"""Analyze the following news information about {topic}.
42
  Search Results: {search_results}
43
 
44
- Please provide:
45
- 1. Summary of key points
46
- 2. Main stakeholders involved
47
- 3. Potential implications
48
- 4. Analysis of different perspectives
49
- 5. Fact-check of major claims (if applicable)
 
 
 
 
 
 
 
 
 
 
 
50
 
51
- Format the analysis in a clear, journalistic style."""
 
 
 
 
 
52
 
53
  def log_agent_activity(prompt: str, result: str, agent_name: str):
54
  """Logs agent activities in the Streamlit interface"""
@@ -65,22 +100,16 @@ st.set_page_config(page_title="News Analysis Tool", layout="wide")
65
  # Title and description
66
  st.title("πŸ” AI News Analysis Tool")
67
  st.write("""
68
- This tool uses advanced AI to analyze news topics, providing comprehensive insights
69
- and analysis using real-time data from the web. Powered by Groq's LLama 3.1 8B
70
- Instant model and DuckDuckGo search.
71
  """)
72
 
73
- # Initialize the agents
74
  try:
75
- # Initialize LLM and tools
76
  llm = GroqLLM()
77
- search_tool = DuckDuckGoSearchTool()
78
-
79
- # Create the analysis agent
80
- news_agent = CodeAgent(
81
- tools=[search_tool],
82
- model=llm
83
- )
84
 
85
  # Input section
86
  news_topic = st.text_input(
@@ -108,28 +137,32 @@ try:
108
  if news_topic:
109
  with st.spinner("Gathering information and analyzing..."):
110
  try:
111
- # First, get search results
112
- search_results = search_tool.run(
113
- f"Latest news about {news_topic} last 7 days"
114
- )
115
-
116
- # Create analysis prompt
117
- analysis_prompt = create_analysis_prompt(news_topic, search_results)
118
-
119
- # Get analysis from the agent
120
- analysis_result = news_agent.run(analysis_prompt)
121
-
122
- # Display results
123
- st.subheader("πŸ“Š Analysis Results")
124
- st.markdown(analysis_result)
125
-
126
- # Log the activity
127
- log_agent_activity(
128
- analysis_prompt,
129
- analysis_result,
130
- "News Analysis Agent"
131
  )
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  except Exception as e:
134
  st.error(f"An error occurred during analysis: {str(e)}")
135
  else:
@@ -142,6 +175,7 @@ try:
142
  - Use keywords related to recent events for timely information
143
  - Consider including timeframes in your query
144
  - Try different analysis types for various perspectives
 
145
  """)
146
 
147
  except Exception as e:
@@ -150,7 +184,8 @@ except Exception as e:
150
 
151
  Please ensure:
152
  1. Your GROQ_API_KEY is properly set in environment variables
153
- 2. All required packages are installed
 
154
  3. You have internet connectivity for DuckDuckGo searches
155
  """)
156
 
 
1
  import streamlit as st
2
  import pandas as pd
3
+ from smolagents import CodeAgent
4
  from typing import Union, List, Dict
5
  from groq import Groq
6
  import os
7
+ from duckduckgo_search import DDGS
8
+
9
+ class DuckDuckGoSearch:
10
+ """Custom DuckDuckGo search implementation"""
11
+ def __init__(self):
12
+ self.ddgs = DDGS()
13
+
14
+ def __call__(self, query: str, max_results: int = 5) -> str:
15
+ try:
16
+ # Perform the search and get results
17
+ search_results = list(self.ddgs.text(query, max_results=max_results))
18
+
19
+ # Format the results into a readable string
20
+ formatted_results = []
21
+ for idx, result in enumerate(search_results, 1):
22
+ formatted_results.append(
23
+ f"{idx}. Title: {result['title']}\n"
24
+ f" Summary: {result['body']}\n"
25
+ f" Source: {result['link']}\n"
26
+ )
27
+
28
+ return "\n".join(formatted_results)
29
+ except Exception as e:
30
+ return f"Search error: {str(e)}"
31
 
32
  class GroqLLM:
33
  """Compatible LLM interface for smolagents CodeAgent"""
 
37
 
38
  def __call__(self, prompt: Union[str, dict, List[Dict]]) -> str:
39
  try:
40
+ prompt_str = str(prompt) if isinstance(prompt, (dict, list)) else prompt
 
 
 
 
41
 
 
42
  completion = self.client.chat.completions.create(
43
  model=self.model_name,
44
  messages=[{
 
60
  return f"""Analyze the following news information about {topic}.
61
  Search Results: {search_results}
62
 
63
+ Please provide a comprehensive analysis including:
64
+ 1. Key Points Summary:
65
+ - Main events and developments
66
+ - Critical updates and changes
67
+
68
+ 2. Stakeholder Analysis:
69
+ - Primary parties involved
70
+ - Their roles and positions
71
+
72
+ 3. Impact Assessment:
73
+ - Immediate implications
74
+ - Potential long-term effects
75
+ - Broader context and significance
76
+
77
+ 4. Multiple Perspectives:
78
+ - Different viewpoints on the issue
79
+ - Areas of agreement and contention
80
 
81
+ 5. Fact Check & Reliability:
82
+ - Verification of major claims
83
+ - Consistency across sources
84
+ - Source credibility assessment
85
+
86
+ Please format the analysis in a clear, journalistic style with section headers."""
87
 
88
  def log_agent_activity(prompt: str, result: str, agent_name: str):
89
  """Logs agent activities in the Streamlit interface"""
 
100
  # Title and description
101
  st.title("πŸ” AI News Analysis Tool")
102
  st.write("""
103
+ This tool combines the power of Groq's LLama 3.1 8B Instant model with DuckDuckGo
104
+ search to provide in-depth news analysis. Get comprehensive insights and multiple
105
+ perspectives on any news topic.
106
  """)
107
 
108
+ # Initialize the components
109
  try:
110
+ # Initialize LLM and search tool
111
  llm = GroqLLM()
112
+ search_tool = DuckDuckGoSearch()
 
 
 
 
 
 
113
 
114
  # Input section
115
  news_topic = st.text_input(
 
137
  if news_topic:
138
  with st.spinner("Gathering information and analyzing..."):
139
  try:
140
+ # Perform search
141
+ search_results = search_tool(
142
+ f"Latest news about {news_topic} last 7 days",
143
+ max_results=search_depth
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  )
145
 
146
+ if not search_results.startswith("Search error"):
147
+ # Create analysis prompt
148
+ analysis_prompt = create_analysis_prompt(news_topic, search_results)
149
+
150
+ # Get analysis from LLM
151
+ analysis_result = llm(analysis_prompt)
152
+
153
+ # Display results
154
+ st.subheader("πŸ“Š Analysis Results")
155
+ st.markdown(analysis_result)
156
+
157
+ # Log the activity
158
+ log_agent_activity(
159
+ analysis_prompt,
160
+ analysis_result,
161
+ "News Analysis Agent"
162
+ )
163
+ else:
164
+ st.error(f"Search failed: {search_results}")
165
+
166
  except Exception as e:
167
  st.error(f"An error occurred during analysis: {str(e)}")
168
  else:
 
175
  - Use keywords related to recent events for timely information
176
  - Consider including timeframes in your query
177
  - Try different analysis types for various perspectives
178
+ - For complex topics, start with a broader search and then narrow down
179
  """)
180
 
181
  except Exception as e:
 
184
 
185
  Please ensure:
186
  1. Your GROQ_API_KEY is properly set in environment variables
187
+ 2. All required packages are installed:
188
+ - pip install streamlit groq duckduckgo-search
189
  3. You have internet connectivity for DuckDuckGo searches
190
  """)
191