Spaces:
Runtime error
Runtime error
| # ai_web_agent.py | |
| from duckduckgo_search import DDGS | |
| from transformers import pipeline | |
| import gradio as gr | |
| # Load Hugging Face summarization pipeline | |
| print("Loading model...") | |
| summarizer = pipeline("summarization", model="facebook/bart-large-cnn") | |
| print("Model loaded.") | |
| # Function to search the web | |
| def search_web(query, max_results=5): | |
| results = [] | |
| with DDGS() as ddgs: | |
| for r in ddgs.text(query, region='wt-wt', safesearch='Moderate', max_results=max_results): | |
| snippet = f"{r['title']}: {r['body']} ({r['href']})" | |
| results.append(snippet) | |
| return results | |
| # Function to summarize search results | |
| def summarize_results(results): | |
| if not results: | |
| return "No relevant information found." | |
| combined = "\n".join(results) | |
| # Truncate if input is too long | |
| max_input_length = 1024 | |
| input_text = combined[:max_input_length] | |
| summary = summarizer(input_text)[0]['summary_text'] | |
| return summary | |
| # Full agent workflow | |
| def ai_agent(question): | |
| try: | |
| search_results = search_web(question) | |
| summary = summarize_results(search_results) | |
| return summary | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| # Optional: Web UI | |
| interface = gr.Interface( | |
| fn=ai_agent, | |
| inputs=gr.Textbox(lines=2, placeholder="Ask me anything..."), | |
| outputs="text", | |
| title="🧠 AI Web Search Agent", | |
| description="This agent searches the web and summarizes the best answer for you." | |
| ) | |
| if __name__ == "__main__": | |
| interface.launch() | |