SumanDhanu commited on
Commit
aa0b994
·
verified ·
1 Parent(s): dd5cd2b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -34
app.py CHANGED
@@ -3,8 +3,12 @@ from duckduckgo_search import DDGS
3
  from datetime import datetime
4
  import os
5
  import asyncio
 
6
  from openai import OpenAI # Using standard OpenAI client
7
- from agents import Agent, Runner, function_tool # Assuming agents package is installed
 
 
 
8
 
9
  # Set up environment variables
10
  # For Hugging Face Spaces, set these in the Settings > Repository secrets
@@ -13,17 +17,10 @@ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") # You'll need to add this to
13
  # Get current date for default value
14
  default_date = datetime.now().strftime("%Y-%m-%d")
15
 
16
- # Configure OpenAI client to use HuggingFace or OpenAI API
17
- client = OpenAI(
18
- api_key=OPENAI_API_KEY,
19
- # If using OpenAI directly
20
- # If using a different API endpoint (e.g., HF Inference API), uncomment and adjust:
21
- # base_url="https://api-inference.huggingface.co/models/meta-llama/Llama-3.2-70b-instruct"
22
- )
23
-
24
- # Define the model - assuming the agents library supports standard OpenAI client
25
- from agents import OpenAIChatCompletionsModel # Adjust import if needed
26
 
 
27
  model = OpenAIChatCompletionsModel(
28
  model="gpt-4o-mini", # Using GPT-4o-mini for better performance at a lower cost
29
  openai_client=client
@@ -70,14 +67,17 @@ def get_news_articles(topic, language="English", search_date=None):
70
  # Add language to search query if it's not English
71
  search_query = f"{topic} {lang_keyword} {search_date}" if language != "English" else f"{topic} {search_date}"
72
 
73
- # DuckDuckGo search
74
- ddg_api = DDGS()
75
- results = ddg_api.text(search_query, max_results=5)
76
- if results:
77
- news_results = "\n\n".join([f"Title: {result['title']}\nURL: {result['href']}\nDescription: {result['body']}" for result in results])
78
- return news_results
79
- else:
80
- return f"Could not find news results for {topic} in {language} for {search_date}."
 
 
 
81
 
82
  # Create agents
83
  news_agent = Agent(
@@ -93,32 +93,34 @@ editor_agent = Agent(
93
  model=model
94
  )
95
 
 
 
 
 
 
 
 
 
96
  # Workflow function for Gradio
97
  def fetch_and_edit_news(topic, language, search_date):
98
  try:
99
- # Create a new event loop for this thread
100
- loop = asyncio.new_event_loop()
101
- asyncio.set_event_loop(loop)
102
 
103
  # Step 1: Run the news agent
104
- news_result = Runner.run_sync(
105
- news_agent,
106
- f"Get me the news about {topic} in {language} for date {search_date}")
107
 
108
- raw_news = news_result.final_output
 
109
 
110
  # Step 2: Pass news to editor for final review
111
- editor_news_response = Runner.run_sync(
112
- editor_agent,
113
- f"Please edit the following news in {language} language. Maintain the original language: \n\n{raw_news}")
114
-
115
- edited_news = editor_news_response.final_output
116
 
117
  return edited_news
118
-
119
  except Exception as e:
120
- # Return the error message for debugging
121
- return f"Error: {str(e)}\n\nThis could be due to API key issues or problems with the openai-agents package. Please check the logs for more details."
122
 
123
  # Create Gradio interface
124
  with gr.Blocks(title="Multilingual AI News Generator") as demo:
 
3
  from datetime import datetime
4
  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()
12
 
13
  # Set up environment variables
14
  # For Hugging Face Spaces, set these in the Settings > Repository secrets
 
17
  # Get current date for default value
18
  default_date = datetime.now().strftime("%Y-%m-%d")
19
 
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
 
67
  # Add language to search query if it's not English
68
  search_query = f"{topic} {lang_keyword} {search_date}" if language != "English" else f"{topic} {search_date}"
69
 
70
+ try:
71
+ # DuckDuckGo search
72
+ ddg_api = DDGS()
73
+ results = ddg_api.text(search_query, max_results=5)
74
+ if results:
75
+ news_results = "\n\n".join([f"Title: {result['title']}\nURL: {result['href']}\nDescription: {result['body']}" for result in results])
76
+ return news_results
77
+ else:
78
+ return f"Could not find news results for {topic} in {language} for {search_date}."
79
+ except Exception as e:
80
+ return f"Error searching for news: {str(e)}"
81
 
82
  # Create agents
83
  news_agent = Agent(
 
93
  model=model
94
  )
95
 
96
+ # Helper function to safely run the agent
97
+ async def run_agent_async(agent, prompt):
98
+ try:
99
+ result = await Runner.arun(agent, prompt)
100
+ return result.final_output
101
+ except Exception as e:
102
+ return f"Error running agent: {str(e)}"
103
+
104
  # Workflow function for Gradio
105
  def fetch_and_edit_news(topic, language, search_date):
106
  try:
107
+ # Create a new asyncio loop that works with nest_asyncio
108
+ loop = asyncio.get_event_loop()
 
109
 
110
  # Step 1: Run the news agent
111
+ news_prompt = f"Get me the news about {topic} in {language} for date {search_date}"
112
+ raw_news = loop.run_until_complete(run_agent_async(news_agent, news_prompt))
 
113
 
114
+ if raw_news.startswith("Error"):
115
+ return raw_news
116
 
117
  # Step 2: Pass news to editor for final review
118
+ editor_prompt = f"Please edit the following news in {language} language. Maintain the original language: \n\n{raw_news}"
119
+ edited_news = loop.run_until_complete(run_agent_async(editor_agent, editor_prompt))
 
 
 
120
 
121
  return edited_news
 
122
  except Exception as e:
123
+ return f"Error: {str(e)}\n\nPlease check your OpenAI API key and ensure it has been set correctly in the repository secrets."
 
124
 
125
  # Create Gradio interface
126
  with gr.Blocks(title="Multilingual AI News Generator") as demo: