Serper.dev provides a simple API for Google Search, including web results, news, and images. This example demonstrates how to integrate real-time search data into your applications, perfect for enriching LLM context or building search-powered features.
This example was tested in real hackathons for real-time data enrichment in applications.
This will demonstrate web search, news search, and context enrichment.
2
Integrate into your application
Import and use the SerperSearch class:
from serper_search_api import SerperSearchsearcher = SerperSearch()results = searcher.search("your topic")# Process resultsfor result in results.get("organic", []): print(result['title'], result['link'])
3
Customize search parameters
Adjust the number of results and query:
# Get more resultsresults = searcher.search("machine learning", num_results=50)# Search specific topicstech_news = searcher.news_search("breakthrough AI")
from serper_search_api import SerperSearchfrom openai import OpenAIsearcher = SerperSearch()client = OpenAI()def answer_with_search(question: str) -> str: """Answer questions using real-time search data""" # Get current information from search search_results = searcher.search(question, num_results=5) # Build context from search results context = "\n\n".join([ f"Source: {r['title']}\n{r['snippet']}" for r in search_results.get("organic", []) ]) # Ask LLM with enriched context response = client.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": f"Use this current information to answer questions:\n{context}"}, {"role": "user", "content": question} ] ) return response.choices[0].message.content# Exampleanswer = answer_with_search("What are the latest developments in quantum computing?")print(answer)
Pro tip: Cache search results to avoid redundant API calls. Serper.dev charges per search, so implement caching for frequently searched queries.
The free tier includes 2,500 searches per month. Monitor your usage in the Serper.dev dashboard to avoid unexpected charges.