SumanDhanu commited on
Commit
fce7c2b
·
verified ·
1 Parent(s): c67e9f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -64
app.py CHANGED
@@ -5,7 +5,14 @@ import os
5
  import asyncio
6
  import nest_asyncio
7
  from openai import OpenAI # Using standard OpenAI client
8
- from agents import Agent, Runner, function_tool, OpenAIChatCompletionsModel # Assuming agents package is installed
 
 
 
 
 
 
 
9
 
10
  # Apply nest_asyncio to allow nested event loops
11
  nest_asyncio.apply()
@@ -20,15 +27,9 @@ default_date = datetime.now().strftime("%Y-%m-%d")
20
  # Configure OpenAI client
21
  client = OpenAI(api_key=OPENAI_API_KEY)
22
 
23
- # Define the model
24
- model = OpenAIChatCompletionsModel(
25
- model="gpt-4o-mini", # Using GPT-4o-mini for better performance at a lower cost
26
- openai_client=client
27
- )
28
-
29
- # News search tool
30
- @function_tool
31
- def get_news_articles(topic, language="English", search_date=None):
32
  # Use provided date or default to current date
33
  if not search_date:
34
  search_date = datetime.now().strftime("%Y-%m")
@@ -79,22 +80,9 @@ def get_news_articles(topic, language="English", search_date=None):
79
  except Exception as e:
80
  return f"Error searching for news: {str(e)}"
81
 
82
- # Create agents
83
- news_agent = Agent(
84
- name="News Agent",
85
- instructions="You provide the latest news articles for a given topic using DuckDuckGo search. You can search for news in different languages when specified.",
86
- tools=[get_news_articles],
87
- model=model
88
- )
89
-
90
- editor_agent = Agent(
91
- name="Editor Assistant",
92
- instructions="Rewrite and give me a news article ready for publishing. Each news story should be in a separate section. Maintain the original language of the news stories. If the content is in a language other than English, edit and format in that same language.",
93
- model=model
94
- )
95
-
96
- # Fallback to direct OpenAI API if agents don't work
97
  def generate_with_openai(prompt):
 
98
  try:
99
  response = client.chat.completions.create(
100
  model="gpt-4o-mini",
@@ -106,57 +94,97 @@ def generate_with_openai(prompt):
106
  except Exception as e:
107
  return f"Error with OpenAI API: {str(e)}"
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  # Workflow function for Gradio
110
  def fetch_and_edit_news(topic, language, search_date):
 
111
  try:
112
- # Initialize new event loop
113
- loop = asyncio.new_event_loop()
114
- asyncio.set_event_loop(loop)
115
-
116
- # Try to use Runner.run_sync with the proper event loop context
117
- try:
118
- # Step 1: Run the news agent to get news
119
- news_prompt = f"Get me the news about {topic} in {language} for date {search_date}"
120
- news_result = Runner.run_sync(news_agent, news_prompt)
121
- raw_news = news_result.final_output
122
-
123
- # Step 2: Run the editor agent to edit the news
124
- editor_prompt = f"Please edit the following news in {language} language. Maintain the original language: \n\n{raw_news}"
125
- editor_result = Runner.run_sync(editor_agent, editor_prompt)
126
- edited_news = editor_result.final_output
127
-
128
- return edited_news
129
-
130
- except Exception as agent_error:
131
- print(f"Agent error: {agent_error}")
132
-
133
- # Fallback to direct use of DuckDuckGo and OpenAI if agents fail
134
  try:
135
- print("Falling back to direct search and API calls...")
136
- # Get news directly
137
- raw_news = get_news_articles(topic, language, search_date)
138
 
139
- if raw_news.startswith("Error") or raw_news.startswith("Could not find"):
140
- return raw_news
 
141
 
142
- # Format prompt for OpenAI
143
- editor_prompt = f"""
144
- Please edit and reformat the following news into a cohesive, publication-ready format.
145
- Maintain the original language ({language}).
146
- Each news story should be in a separate section with a clear headline:
147
 
148
- {raw_news}
149
- """
 
 
150
 
151
- # Call OpenAI directly
152
- edited_news = generate_with_openai(editor_prompt)
153
  return edited_news
154
 
155
- except Exception as fallback_error:
156
- return f"Both agent-based and fallback approaches failed.\nError details: {str(fallback_error)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  except Exception as e:
159
- return f"Error: {str(e)}\n\nPlease check your OpenAI API key and ensure it has been set correctly in the repository secrets."
 
 
 
160
 
161
  # Create Gradio interface
162
  with gr.Blocks(title="Multilingual AI News Generator") as demo:
 
5
  import asyncio
6
  import nest_asyncio
7
  from openai import OpenAI # Using standard OpenAI client
8
+ import traceback
9
+
10
+ try:
11
+ from agents import Agent, Runner, function_tool, OpenAIChatCompletionsModel
12
+ AGENTS_AVAILABLE = True
13
+ except Exception:
14
+ print("WARNING: openai-agents package not fully functional, using fallback mode")
15
+ AGENTS_AVAILABLE = False
16
 
17
  # Apply nest_asyncio to allow nested event loops
18
  nest_asyncio.apply()
 
27
  # Configure OpenAI client
28
  client = OpenAI(api_key=OPENAI_API_KEY)
29
 
30
+ # Direct search function that doesn't depend on the agents package
31
+ def direct_news_search(topic, language="English", search_date=None):
32
+ """Search for news articles using DuckDuckGo directly"""
 
 
 
 
 
 
33
  # Use provided date or default to current date
34
  if not search_date:
35
  search_date = datetime.now().strftime("%Y-%m")
 
80
  except Exception as e:
81
  return f"Error searching for news: {str(e)}"
82
 
83
+ # Direct OpenAI API call
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  def generate_with_openai(prompt):
85
+ """Use OpenAI API directly to generate content"""
86
  try:
87
  response = client.chat.completions.create(
88
  model="gpt-4o-mini",
 
94
  except Exception as e:
95
  return f"Error with OpenAI API: {str(e)}"
96
 
97
+ # Try to set up agents if available
98
+ if AGENTS_AVAILABLE:
99
+ try:
100
+ # Define the model
101
+ model = OpenAIChatCompletionsModel(
102
+ model="gpt-4o-mini",
103
+ openai_client=client
104
+ )
105
+
106
+ # News search tool
107
+ @function_tool
108
+ def get_news_articles(topic, language="English", search_date=None):
109
+ return direct_news_search(topic, language, search_date)
110
+
111
+ # Create agents
112
+ news_agent = Agent(
113
+ name="News Agent",
114
+ instructions="You provide the latest news articles for a given topic using DuckDuckGo search. You can search for news in different languages when specified.",
115
+ tools=[get_news_articles],
116
+ model=model
117
+ )
118
+
119
+ editor_agent = Agent(
120
+ name="Editor Assistant",
121
+ instructions="Rewrite and give me a news article ready for publishing. Each news story should be in a separate section. Maintain the original language of the news stories. If the content is in a language other than English, edit and format in that same language.",
122
+ model=model
123
+ )
124
+
125
+ print("Successfully initialized agent-based workflow")
126
+ except Exception as e:
127
+ print(f"Failed to initialize agents: {e}")
128
+ AGENTS_AVAILABLE = False
129
+
130
  # Workflow function for Gradio
131
  def fetch_and_edit_news(topic, language, search_date):
132
+ """Process news request using agents if available, otherwise fall back to direct API calls"""
133
  try:
134
+ # Try agent-based approach if available
135
+ if AGENTS_AVAILABLE:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  try:
137
+ print("Attempting to use agent-based workflow...")
 
 
138
 
139
+ # Initialize event loop
140
+ loop = asyncio.new_event_loop()
141
+ asyncio.set_event_loop(loop)
142
 
143
+ # Run the news agent
144
+ news_prompt = f"Get me the news about {topic} in {language} for date {search_date}"
145
+ news_result = Runner.run_sync(news_agent, news_prompt)
146
+ raw_news = news_result.final_output
 
147
 
148
+ # Run the editor agent
149
+ editor_prompt = f"Please edit the following news in {language} language. Maintain the original language: \n\n{raw_news}"
150
+ editor_result = Runner.run_sync(editor_agent, editor_prompt)
151
+ edited_news = editor_result.final_output
152
 
153
+ print("Agent-based workflow completed successfully")
 
154
  return edited_news
155
 
156
+ except Exception as agent_error:
157
+ print(f"Agent-based workflow failed: {agent_error}")
158
+ print(traceback.format_exc())
159
+ print("Falling back to direct API approach...")
160
+ # Fall through to the direct approach
161
+ else:
162
+ print("Using direct API approach (agents not available)...")
163
+
164
+ # Direct approach (used when agents fail or aren't available)
165
+ # Step 1: Get news directly
166
+ raw_news = direct_news_search(topic, language, search_date)
167
+
168
+ if raw_news.startswith("Error") or raw_news.startswith("Could not find"):
169
+ return raw_news
170
+
171
+ # Step 2: Edit the news with OpenAI
172
+ editor_prompt = f"""
173
+ Please edit and reformat the following news into a cohesive, publication-ready format.
174
+ Maintain the original language ({language}).
175
+ Each news story should be in a separate section with a clear headline:
176
+
177
+ {raw_news}
178
+ """
179
+
180
+ edited_news = generate_with_openai(editor_prompt)
181
+ return edited_news
182
 
183
  except Exception as e:
184
+ error_details = traceback.format_exc()
185
+ print(f"Error in workflow: {e}")
186
+ print(error_details)
187
+ return f"Error processing your request: {str(e)}\n\nPlease check that your OpenAI API key is correctly set in the repository secrets."
188
 
189
  # Create Gradio interface
190
  with gr.Blocks(title="Multilingual AI News Generator") as demo: