We will show you in this tutorial how to harness the full power of SerpAPI’s Google Search capabilities combined with Google Gemini 1.5-Flash to create a complete end-to-end analysis and research workflow in a Google Colab Notebook. Users can access enhanced search techniques that include general web results and news articles. They can also use Gemini for in-depth analysis of the results. This code offers specialized utilities to target Marktechpost Tutorials. It aggregates content from categories such as LangChain and ChatGPT and synthesizes actionable insights with a specially constructed prompt.
!pip install google-search-results langchain-community langchain-core google-generativeai -q
Import os
Import json
Google Search: import serpapi
import google.generativeai as genai
Import datetime from datetime
Install the Python packages required for SerpAPI search, LangChain utility, and Google Gemini SDK. Importing the standard modules (os json datetime), we import JSON and time stamps for handling and configuring environment, SerpAPI GoogleSearch to make API calls as well and genai, which interacts with Gemini.
SERPAPI_API_KEY = "Use Your API Key Here"
GEMINI_API_KEY = "Use Your API Key Here"
os.environ["SERPAPI_API_KEY"] = SERPAPI_API_KEY
genai.configure(api_key=GEMINI_API_KEY)
You can configure your Gemini client to use its API key by configuring the SerpAPI keys.
Class AdvancedSerpAPIparams = ""
def __init__(self, serpapi_key, gemini_key):
self.serpapi_key = serpapi_key
self.gemini_model = genai.GenerativeModel('gemini-1.5-flash')
def search_google(self, query, num_results=5, location="United States"):
"""Enhanced Google search with multiple parameters"""
params = {
"engine": "google",
"q": query,
"api_key": self.serpapi_key,
"num": num_results,
"location": location,
"hl": "en",
"gl": "us"
}
GoogleSearch = search(params).
search.get_dictparams = ""()
return self.extract_search_results(results)
def search_news(self, query, days_back=7):
"""Search for recent news articles"""
params = {
"engine": "google_news",
"q": query,
"api_key": self.serpapi_key,
"gl": "us",
"hl": "en"
}
GoogleSearch = search(params).
Results = Search.get_dictparams = ""()
return self.extract_news_results(results)
def search_images(self, query, num_images=10):
"""Search for images with metadata"""
params = {
"engine": "google_images",
"q": query,
"api_key": self.serpapi_key,
"num": num_images
}
Search = GoogleSearch (params).
Results = Search.get_dict()
return self.extract_image_results(results)
def extract_search_results(self, results):
"""Extract and clean search results"""
cleaned_results = []
If you see 'organic_results in your results':
Results are a result['organic_results']:
cleaned_results.append({
'title': result.get('title', ''),
'link': result.get('link', ''),
'snippet': result.get('snippet', ''),
'position': result.get('position', 0)
})
Clean_results
def extract_news_results(self, results):
"""Extract news articles with timestamps"""
news_results = []
If you see 'news_results in your results:
Results for Article['news_results']:
news_results.append({
'title': article.get('title', ''),
'link': article.get('link', ''),
'snippet': article.get('snippet', ''),
'date': article.get('date', ''),
'source': article.get('source', '')
})
News_Results - Return
def extract_image_results(self, results):
"""Extract image results with metadata"""
image_results = []
If 'images_results" is in the results:
Image results['images_results']:
image_results.append({
'title': img.get('title', ''),
'original': img.get('original', ''),
'thumbnail': img.get('thumbnail', ''),
'source': img.get('source', '')
})
Return image_results
def analyze_with_gemini(self, search_results, analysis_prompt):
"""Use Gemini Flash to analyze search results"""
results_text = json.dumps(search_results, indent=2)
full_prompt = f"""
{analysis_prompt}
Search results Data
{results_text}
Please perform a thorough analysis using the search results.
"""
try:
response = self.gemini_model.generate_content(full_prompt)
Text return for response
except Exception as e:
The return of fparams = """Gemini analysis failed: {str(e)}"
def search_marktechpost_tutorials(self, topic="", num_results=10):
"""Search specifically for trending tutorials from Marktechpost"""
queries = [
f"site:marktechpost.com {topic} tutorial guide how-to 2024 2025",
f"site:marktechpost.com trending {topic} tutorial",
f"site:marktechpost.com top {topic} books frameworks"
]
all_results = []
for query in queries:
params = {
"engine": "google",
"q": query,
"api_key": self.serpapi_key,
"num": num_results // len(queries),
"hl": "en",
"gl": "us"
}
GoogleSearch = search(params).
Results = get_dict()
extracted = self.extract_search_results(results)
all_results.extend(extracted)
unique_results = []
seen_links = set()
For result in:
If result['link'] Links to not-in-sight:
unique_results.append(result)
seen_links.add(result['link'])
return unique_results[:num_results]
def get_trending_marktechpost_content(self, categories=None):
"""Get trending content from Marktechpost across different categories"""
If categories is None
Categories = ["AI", "LLM", "Machine Learning", "Python", "Tutorial", "Framework"]
trending_content = {}
For category:
print(f"š Searching for trending {category} content...")
results = self.search_marktechpost_tutorials(category, num_results=5)
trending_contentAgentic AI = results
print(f"ā
Found {len(results)} {category} tutorials")
Return trending_content
def smart_research(self, topic, research_depth="medium", focus_marktechpost=True):
"""Intelligent research combining multiple search types with Marktechpost focus"""
print(f"š Starting smart research on: {topic}")
if focus_marktechpost:
marktechpost_results = self.search_marktechpost_tutorials(topic, num_results=8)
print(f"ā
Found {len(marktechpost_results)} Marktechpost tutorials")
web_results = self.search_google(f"{topic} tutorial guide", num_results=3)
print(f"ā
Found {len(web_results)} additional web results")
all_web_results = marktechpost_results + web_results
else:
all_web_results = self.search_google(f"{topic} overview facts", num_results=5)
print(f"ā
Found {len(all_web_results)} web results")
news_results = self.search_news(topic)
print(f"ā
Found {len(news_results)} news articles")
Analysis_prompt=f"""
Analyze the search results about '{topic}' with focus on Marktechpost content and provide:
1. There are many tutorials available.
2. Current topics and frameworks
3. Learn more about the books and resources that are mentioned
4. Updates and recent developments
5. Implementation guides for practical applications
6. Learning path recommended
Learn more about the latest insights, learning materials and actionable strategies.Return
"""
all_results = {
"marktechpost_results": marktechpost_results if focus_marktechpost else [],
"web_results": all_web_results,
"news_results": news_results,
"search_topic": topic,
"timestamp": datetime.now().isoformat()
}
gemini_analysis = self.analyze_with_gemini(all_results, analysis_prompt)
return {
"topic": topic,
"marktechpost_tutorials": marktechpost_results if focus_marktechpost else [],
"web_results": all_web_results,
"news_results": news_results,
"ai_analysis": gemini_analysis,
"total_sources": len(all_web_results) + len(news_results)
}
AdvancedSerpAPI provides SerpAPI search methods, including web, news and image searches, as well as helper functions for cleaning the JSON output. This class integrates the Gemini-1.5 Flash model (via analyze_with_gemini) to create an AI summary for any search data. Marktechpost Tutorial Lookups are also included as additional utilities. “get trending” A combined routine that is applicable to all categories “smart research” Gemini Analysis, tutorials and web results are all woven together in a workflow.
def demo_marktechpost_tutorials():
"""Demo specifically focused on Marktechpost tutorials"""
searcher = AdvancedSerpAPI(SERPAPI_API_KEY, GEMINI_API_KEY)
print("š Marktechpost Trending Tutorials Finder")
print("=" * 50)
print("nš Demo 1: Trending Marktechpost Tutorials by Category")
trending_content = searcher.get_trending_marktechpost_content([
"LangChain", "ChatGPT", "Python", "AI", "MLOps"
])
for category, tutorials in trending_content.items():
print(f"nš„ Trending {category} Tutorials:")
For i, tutorial on enumerate (tutorials)[:3], 1):
print(f" {i}. {tutorial['title']}")
print(f" š {tutorial['link']}")
Tutorials if you want to know more about if['snippet']:
print(f" š {tutorial['snippet'][:100]}...")
print("nšÆ Demo 2: Deep Dive - LangChain Tutorials")
langchain_research = searcher.smart_research("LangChain", focus_marktechpost=True)
print(f"nš Research Summary:")
print(f"Topic: {langchain_research['topic']}")
print(f"Marktechpost Tutorials Found: {len(langchain_research['marktechpost_tutorials'])}")
print(f"Total Sources: {langchain_research['total_sources']}")
print(f"nš¤ AI Analysis Preview:")
print(langchain_research['ai_analysis'][:600] + "..." if len(langchain_research['ai_analysis']) > 600 else langchain_research['ai_analysis'])
print("nš° Demo 3: Latest AI Trends from Marktechpost")
ai_trends = searcher.search_marktechpost_tutorials("AI trends 2024 2025", num_results=5)
print("Recent AI trend articles:")
For i, the article, in enumerate (ai_trends:1)
print(f"{i}. {article['title']}")
print(f" š {article['link']}")
def demo_advanced_serpapi():
"""Comprehensive demo of SerpAPI capabilities"""
searcher = AdvancedSerpAPI(SERPAPI_API_KEY, GEMINI_API_KEY)
print("š Advanced SerpAPI Tutorial with Gemini Flash")
print("=" * 50)
print("nš Demo 1: Smart Research on AI Technology")
research_results = searcher.smart_research("artificial intelligence 2024 trends")
print(f"nš Research Summary:")
print(f"Topic: {research_results['topic']}")
print(f"Total Sources: {research_results['total_sources']}")
print(f"nš¤ AI Analysis Preview:")
print(research_results['ai_analysis'][:500] + "..." If len(research_results['ai_analysis']) > 500 else research_results['ai_analysis'])
print("nš° Demo 2: Recent News Search")
tech_news = searcher.search_news("technology breakthrough", days_back=7)
print(f"Found {len(tech_news)} recent tech news articles:")
For i, the article is enumerate (tech_news[:3], 1):
print(f"{i}. {article['title'][:80]}...")
print(f" Source: {article['source']} | Date: {article['date']}")
print("nš¼ļø Demo 3: Image Search")
space_images = searcher.search_images("space exploration 2024", num_images=5)
print(f"Found {len(space_images)} space-related images:")
for i, img in enumerate(space_images[:3], 1):
print(f"{i}. {img['title'][:60]}...")
print(f" Source: {img['source']}")
demo_marktechpost_tutorials() Initializes AdvancedSerpAPI and prints out trending tutorials for categories such as LangChain (Python, AI, MLOps, ChatGPT). It performs then a “deep dive” Smart research “LangChain,” Gemini AI preview and count tutorials. It also lists and retrieves the five most recent tutorials. “AI trends 2024ā2025” Marktechpost: Articles from MarktechpostĀ
Also, demo_advanced_serpapi() It creates an AdvancedSerpAPI but is focused on a wider workflow. “artificial intelligence 2024 trends” It prints out the AI analysis and topic summary. Then, it performs an online news search. “technology breakthrough,” The first three articles are listed with their sources and dates. Finally, a few of the most recent ones will be displayed. “space exploration 2024” Image results
If __name__ is equal to "__main__":
If SERPAPI_API_KEY is equal to "your_serpapi_key_here" GEMINI_API_KEY==Params = "your_gemini_key_here":
print("ā ļø Please set your API keys before running the demo!")
print("1. Get SerpAPI key from: https://serpapi.com")
print("2. Get Gemini API key from: https://makersuite.google.com")
else:
print("šÆ Running Marktechpost-focused demo...")
demo_marktechpost_tutorials()
print("n" + "="*50)
print("š Running general demo...")
demo_advanced_serpapi()
def compare_search_engines(query, engines=['google', 'bing', 'duckduckgo']):
"""Compare results across different search engines"""
results = {}
for engine in engines:
params = {
"engine": engine,
"q": query,
"api_key": SERPAPI_API_KEY
}
try:
GoogleSearch = search(params).
Results[engine] = search.get_dict()
Except Exception As e.
Results[engine] = {"error": str(e)}
Return resultsparams = ""
def trending_searches(location="United States"):
"""Get trending searches"""
params = {
"engine": "google_trends_trending_now",
"api_key": SERPAPI_API_KEY,
"geo"Location
}
Search = GoogleSearch (params).
Return search.get_dict()
print("ā
Advanced SerpAPI Tutorial with Marktechpost Focus loaded successfully!")
print("š Remember to set your API keys before running demos")
print("š New Functions: search_marktechpost_tutorials, get_trending_marktechpost_content")
print("šÆ Marktechpost-specific features: LangChain, ChatGPT, Python, AI, MLOps tutorials")
print("nš Quick Start Examples:")
print("searcher = AdvancedSerpAPI(SERPAPI_API_KEY, GEMINI_API_KEY)")
print("langchain_tutorials = searcher.search_marktechpost_tutorials('LangChain')")
print("trending_ai = searcher.get_trending_marktechpost_content(['AI', 'Python'])")
print("research = searcher.smart_research('ChatGPT', focus_marktechpost=True)")
This section concludes with a Python “main” guard that first verifies your SerpAPI and Gemini keys, prompting you to obtain them if they’re still placeholders, and otherwise runs the Marktechpostāfocused and general demos in sequence. It also defines two utility functions: compare_search_engines, which queries multiple search engines (Google, Bing, DuckDuckGo) via SerpAPI and returns their raw JSON results or errors, and trending_searches, which fetches today’s trending topics using the Google Trends endpoint. This script will then print a status message that confirms the tutorial was successfully loaded, prompts you to create your API key, and highlights new methods for retrieving Marktechpost’s tutorials and trending material.
By following this tutorial users will be able to create a modular, reusable Python class which streamlines research on the web, including keyword searches and automatically summarizing results using Gemini’s AI. SerpAPIās search endpoints combined with Gemini’s language recognition capabilities enable a seamless integration. “research-to-insights” Workflow, perfect for developers and content creators who are looking to be up-to date with all the industry’s latest trends and tutorials.
Take a look at theĀ Notebook here.Ā The researchers are the sole owners of all credit. Also,Ā feel free to follow us onĀ TwitterĀ Don’t forget about ourĀ 95k+ ML SubRedditĀ Subscribe NowĀ our Newsletter.
Asif Razzaq serves as the CEO at Marktechpost Media Inc. As an entrepreneur, Asif has a passion for harnessing Artificial Intelligence to benefit society. Marktechpost was his most recent venture. This platform, which focuses on machine learning and deep-learning news, is known to be both technically solid and understandable for a broad audience. This platform has over 2,000,000 monthly views which shows its popularity.

