# Linux/Macexport SERPER_API_KEY="your-api-key-here"# Windows (Command Prompt)set SERPER_API_KEY=your-api-key-here# Windows (PowerShell)$env:SERPER_API_KEY="your-api-key-here"
from qwen_agent.tools import WebSearchimport json# Initialize the toolweb_search = WebSearch()# Perform a searchresult = web_search.call(params=json.dumps({'query': 'latest AI news'}))print(result)
[1]“Latest breakthrough in AI research
Researchers announce new language model…“2024-03-15[2]“AI companies announce partnerships
Major tech firms collaborate on AI safety…“2024-03-14[3]“New AI regulations proposed
Government proposes framework for AI governance…”
The tool returns search results in a structured markdown format:
[1]"Title of first resultSnippet text from the page..."Date[2]"Title of second resultSnippet text from the page..."Date[3]"Title of third resultSnippet text from the page..."
from qwen_agent.agents import Assistantdef create_research_assistant(): """Create an agent that can search the web for information.""" bot = Assistant( llm={'model': 'qwen-max'}, name='Research Assistant', description='I can search the web to find current information and help answer your questions.', system_message=( 'You are a helpful research assistant. When users ask questions, ' 'use web search to find current information. Always cite your sources ' 'and provide the most recent and relevant information.' ), function_list=['web_search'] ) return bot# Create and use the assistantbot = create_research_assistant()messages = []while True: query = input('\nAsk a question (or "quit"): ') if query.lower() in ['quit', 'exit', 'q']: break messages.append({'role': 'user', 'content': query}) response = [] for response in bot.run(messages=messages): pass # Wait for complete response # Print assistant's response print(f"\nAssistant: {response[-1]['content']}") messages.extend(response)
from qwen_agent.tools import WebSearch# Use the static search method directlyraw_results = WebSearch.search('AI research papers')# raw_results is a list of dictsfor result in raw_results: print(f"Title: {result['title']}") print(f"Link: {result['link']}") print(f"Snippet: {result['snippet']}") if 'date' in result: print(f"Date: {result['date']}") print()
from qwen_agent.tools import WebSearchimport jsonweb_search = WebSearch()try: result = web_search.call( params=json.dumps({'query': 'test search'}) ) print(result)except ValueError as e: if 'SERPER_API_KEY' in str(e): print("Error: API key not set. Please set SERPER_API_KEY environment variable.") else: print(f"Error: {e}")except Exception as e: print(f"Search failed: {e}")
from qwen_agent.tools import WebSearchimport jsonimport timefrom datetime import datetimedef monitor_news_topic(topic, interval_minutes=60): """Monitor a topic and report new results periodically.""" web_search = WebSearch() seen_titles = set() print(f"Monitoring: {topic}") print(f"Checking every {interval_minutes} minutes...\n") while True: try: result = web_search.call( params=json.dumps({'query': f'{topic} latest news'}) ) # Parse results (simplified) lines = result.split('\n') current_titles = [line for line in lines if line.startswith('[')] # Check for new articles new_articles = [t for t in current_titles if t not in seen_titles] if new_articles: print(f"\n[{datetime.now().strftime('%Y-%m-%d %H:%M')}] New articles:") for article in new_articles: print(article) seen_titles.update(new_articles) time.sleep(interval_minutes * 60) except KeyboardInterrupt: print("\nStopping monitor...") break except Exception as e: print(f"Error: {e}") time.sleep(60)# Monitor AI newsif __name__ == '__main__': monitor_news_topic('artificial intelligence', interval_minutes=30)