Environment variables have been set successfully.
You can alternatively set API keys, such as OPENAI_API_KEY in a .env file and load them.
[Note] This is not necessary if you've already set the required API keys in previous steps.
Note
When using tools, warning messages may be displayed.
For example, there are security warnings in the REPL environment.PythonREPLTool is a tool for executing Python code and can potentially execute commands (e.g., file system access, network requests) that may pose security risks.
In such cases, LangChain or Python itself may output warning messages.
To ignore these warning messages, you can use the following code:
Built-in tools
You can use pre-defined tools and toolkits provided by LangChain.
A tool refers to a single utility, while a toolkit combines multiple tools that can be used as one.
You can find the relevant tools at the link below.
Set the issued API key as an environment variable.
For example, configure the .env file as follows:
TavilySearchResults
Description
Calls the Tavily Search API and returns results in JSON format.
A search engine optimized for comprehensive, accurate, and reliable results.
Useful for answering questions about current events.
Key Parameters
max_results (int): Max search results to return(default: 5).
search_depth (str): The depth of the search("basic" or "advanced").
include_domains (List[str]): A list of domains to specifically include in the search results.
exclude_domains (List[str]): A list of domains to specifically exclude from the search results.
include_answer (bool): Include a short answer to original query in the search results(defalut: False).
include_raw_content (bool): Include cleaned and parsed HTML of each site search results(defalut: False).
include_images (bool): Include a list of query related images in the response.(defalut: False)
Return Value
A JSON-formatted string containing the search results (url, content).
Image Generation Tool (DALL-E)
DallEAPIWrapper Class : A wrapper for OpenAI's DALL-E image generator.
This tool allows easy integration of the DALL-E API to implement text-based image generation functionality. With various configuration options, it can be utilized as a flexible and powerful image generation tool.
Key Properties
model : The name of the DALL-E model to use ( dall-e-2, dall-e-3 ).
n : Number of images to generate (default: 1).
size : Size of the generated image:
"dall-e-2": "1024x1024", "512x512", "256x256"
"dall-e-3": "1024x1024", "1792x1024", "1024x1792"
style : Style of the generated image ( natural , vivid ).
quality : Quality of the generated image ( standard, hd ).
max_retries : Maximum number of retries for generation.
Key Features
Generates images based on text descriptions using the DALL-E API.
Workflow Summary
The following is an example of generating images using the DALL-E Image Generator.
This time, we will use the DallEAPIWrapper to generate images.
The input prompt will request the LLM model to write a prompt for generating images.
Let’s use the previously generated image prompt as input to the DallEAPIWrapper to generate an image.
The image below was generated by DALL-E.
dall-e_image.png
Custom Tools
In addition to the built-in tools provided by LangChain, you can define and use your own custom tools.
To do this, use the @tool decorator provided by the langchain.tools module to convert a function into a tool.
@tool Decorator
This decorator allows you to transform a function into a tool. It provides various options to customize the behavior of the tool.
How to Use
Apply the @tool decorator above the function.
Set the decorator parameters as needed.
Using this decorator, you can easily convert regular Python functions into powerful tools, enabling automated documentation and flexible interface creation.
Tavily Custom Tool: Enhancing Tool Control through Custom Tool Configuration
By using @tool Decorator , you can create a tool with improved control by leveraging the TavilyClient provided by the Tavily package.
Below are the key parameters used in the Tavily.
Basic Search Configuration
query (str): The keyword or phrase to search for.
search_depth (str): The level of detail for the search. Choose between basic or advanced . (default: basic)
topic (str): The topic area of the search. Choose between general or news . (default: general)
days (int): The recency of search results. Only results within the specified number of days will be returned. (default: 3)
max_results (int): The maximum number of search results to retrieve. (default: 5)
Domain Filtering
include_domains (list): A list of domains that must be included in the search results.
exclude_domains (list): A list of domains to exclude from the search results.
Detailed Result Settings
include_answer (bool): Whether to include answers generated by the API.
include_raw_content (bool): Whether to include the original HTML content of the webpage.
include_images (bool): Whether to include related image information.
format_output (bool): Whether to apply formatting to the search results.
Miscellaneous
kwargs : Additional keyword arguments. These may be used for future API updates or special features.
The following example code performs a news search for the query "Tell me about LangChain".
The search conditions used are a maximum of 10 results, within the last 7 days, advanced search, and general topic.
The following example code performs a news search for the query "Latest AI technology trends".
The search conditions used are a maximum of 5 results, within the last 3 days, basic search, and news topic.
The following example code performs a search for the query "Python programming tips".
The search conditions used are a maximum of 3 results, advanced search, and results only from the github.io domain.
The following example code performs a search for the query "Healthy diet".
The search conditions used are a maximum of 7 results, within the last 30 days, basic search, and excluding the domains ads.com and spam.com.
Creating a Custom Tool for Google News Article Search
Implementing a Custom Tool in LangGraph is not just about using basic functionalities; it is a crucial strategy to meet project-specific requirements while optimizing system flexibility, scalability, and performance.
In this example, we will build a Google News RSS-based custom tool and explain why it is a better alternative to LangChain’s existing Google Search Tool.
The LangChain Google Search Tool is suitable for searching the entire web, but it requires API calls, which may lead to usage-based costs. Additionally, since it relies on Google’s indexing, there may be delays in reflecting the latest news.
The Google News RSS-based custom tool is more suitable for quickly retrieving only the latest news.
It provides real-time news without relying on Google’s indexing, is free to use without an API key, and offers more intuitive region and language filtering.
Now, let's implement the Google News search functionality by defining the GoogleNews class, which will serve as a tool to search for Google News articles.
Note
No API key is required (because it uses RSS feeds).
This tool searches for news articles provided by news.google.com .
Description
Uses the Google News search API to retrieve the latest news.
Allows searching for news based on keywords.
Key Parameters
k (int): Maximum number of search results to return (default: 5).
In the code, you can adjust the search results' language and region by modifying the language (hl), region (gl), and region and language code (ceid).
Note
Save the provided code as google_news.py , and then you can import it in other files using from google_news import GoogleNews .
from langchain_experimental.tools import PythonREPLTool
# Creates a tool for executing Python code.
python_tool = PythonREPLTool()
# Executes Python code and returns the results.
print(python_tool.invoke("print(100 + 200)"))
Python REPL can execute arbitrary code. Use with caution.
300
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableLambda
# A function that executes Python code, outputs intermediate steps, and returns the tool execution results.
def print_and_execute(code, debug=True):
if debug:
print("CODE:")
print(code)
return python_tool.invoke(code)
# A prompt requesting Python code to be written.
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are Raymond Hetting, an expert python programmer, well versed in meta-programming and elegant, concise and short but well documented code. You follow the PEP8 style guide. "
"Return only the code, no intro, no explanation, no chatty, no markdown, no code block, no nothing. Just the code.",
),
("human", "{input}"),
]
)
# Create LLM model.
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# Create a chain using the prompt and the LLM model.
chain = prompt | llm | StrOutputParser() | RunnableLambda(print_and_execute)
# Outputting the results.
print(chain.invoke("Write code to generate Powerball numbers."))
# Execute tool.
tool.invoke({"query": "What is Langchain Tools?"})
[{'url': 'https://stonefishy.github.io/2024/11/12/introduction-to-langchain-make-ai-smarter-and-easy-to-use/',
'content': 'LangChain makes it easier by offering ready-made building blocks to connect these models to other tools, data, and even databases. Think of LangChain like a set of Lego blocks that you can use to build cool things with AI.'},
{'url': 'https://kirenz.github.io/lab-langchain-functions/slides/05_tools_routing.html',
'content': 'Langchain Functions - Tools and Routing from langchain.agents import tool from langchain.tools.render import format_tool_to_openai_function format_tool_to_openai_function(get_current_temperature) {‘name’: ‘get_current_temperature’, ‘description’: ‘get_current_temperature(latitude: float, longitude: float) -> dict - Fetch current temperature for given coordinates.’, ‘parameters’: {‘title’: ‘OpenMeteoInput’, ‘type’: ‘object’, ‘properties’: {‘latitude’: {‘title’: ‘Latitude’, ‘description’: ‘Latitude of the location to fetch weather data for’, ‘type’: ‘number’}, ‘longitude’: {‘title’: ‘Longitude’, ‘description’: ‘Longitude of the location to fetch weather data for’, ‘type’: ‘number’}}, ‘required’: [‘latitude’, ‘longitude’]}} {‘name’: ‘search_wikipedia’, ‘description’: ‘search_wikipedia(query: str) -> str - Run Wikipedia search and get page summaries.’, ‘parameters’: {‘title’: ‘search_wikipediaSchemaSchema’, ‘type’: ‘object’, ‘properties’: {‘query’: {‘title’: ‘Query’, ‘type’: ‘string’}}, ‘required’: [‘query’]}} format_tool_to_openai_function(search_wikipedia) search_wikipedia, get_current_temperature result = chain.invoke({"input": "what is the weather in stuttgart right now"}) result.tool_input get_current_temperature(result.tool_input) result = chain.invoke({"input": "What is the weather in stuttgart right now?"}) result = chain.invoke({"input": "What is langchain?"})'},
{'url': 'https://j3ffyang.github.io/langchain_project_book/fundamentals/index.html',
'content': 'The fundamental ideas and elements of LangChain, a framework for creating language-model-powered applications, are covered in this chapter. LangChain aims to develop data-aware and agentic applications that enable language models to communicate with their surroundings and establish connections with other data sources, rather than only calling out to a language model via an API. Moreover, LangChain is context-aware, allowing applications to make decisions depending on the context that is supplied by linking a language model to context-giving sources. LangChain is an open-source framework designed to help build applications powered by LLMs, like ChatGPT, and create more advanced use cases around LLMs by chaining together different components from several modules.'},
{'url': 'https://aws-samples.github.io/amazon-bedrock-samples/agents-and-function-calling/function-calling/tool_binding/tool_bindings/',
'content': "Tool binding with Langchain Langchain's bind_tools function takes a list of Langchain Tool, Pydantic classes or JSON schemas. We set our tools through Python functions and use the a weather agent example. With this agent, a requester can get up-to-date weather information based on a given location. Tool definition We define ToolsList to include get_lat_long, which gets a set of coordinates for"},
{'url': 'https://langchain-ai.github.io/langgraph/how-tos/tool-calling/',
'content': "How to call tools using ToolNode This guide covers how to use LangGraph's prebuilt ToolNode for tool calling. ToolNode is a LangChain Runnable that takes graph state (with a list of messages) as input and outputs state update with the result of tool calls. It is designed to work well out-of-box with LangGraph's prebuilt ReAct agent, but can also work with any StateGraph as long as its state"},
{'url': 'https://langchain-ai.github.io/langgraph/',
'content': 'from typing import Annotated, Literal, TypedDict from langchain_core.messages import HumanMessage from langchain_anthropic import ChatAnthropic from langchain_core.tools import tool from langgraph.checkpoint.memory import MemorySaver from langgraph.graph import END, START, StateGraph, MessagesState from langgraph.prebuilt import ToolNode'}]
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
# Initialize the ChatOpenAI model
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.9, max_tokens=1000)
# Define a prompt template for DALL-E image generation
prompt = PromptTemplate.from_template(
"Generate a detailed IMAGE GENERATION prompt for DALL-E based on the following description. "
"Return only the prompt, no intro, no explanation, no chatty, no markdown, no code block, no nothing. Just the prompt"
"Output should be less than 1000 characters. Write in English only."
"Image Description: \n{image_desc}",
)
# Create a chain connecting the prompt, LLM, and output parser
chain = prompt | llm | StrOutputParser()
# Execute the chain
image_prompt = chain.invoke(
{"image_desc": "A Neo-Classicism painting satirizing people looking at their smartphones."}
)
# Output the image prompt
print(image_prompt)
A Neo-Classicism painting depicting a grand, opulent setting reminiscent of classical art, featuring elegantly dressed figures in flowing robes and togas, gathered in a lush, sunlit garden. Each figure is engrossed in their smartphones, completely absorbed in their screens, creating a stark contrast between their traditional attire and modern technology. The lush greenery and marble statues serve as a backdrop, highlighting the absurdity of their distraction. Subtle expressions of amusement and bewilderment are visible on their faces as they interact with their devices, oblivious to the beauty around them. Incorporate classical architectural elements like columns and arches in the background to emphasize the Neo-Classical style. The color palette should be rich and vibrant, with soft, diffused lighting to enhance the dreamlike quality of the scene while maintaining a satirical tone.
# Importing the DALL-E API Wrapper
from langchain_community.utilities.dalle_image_generator import DallEAPIWrapper
from IPython.display import Image
dalle = DallEAPIWrapper(
model="dall-e-3",
size="1024x1024",
quality="standard",
n=1,
)
# query
query = "A Neo-Classicism painting satirizing people looking at their smartphones."
# Generate image and retrieve URL
# Use chain.invoke() to convert the image description into a DALL-E prompt
# Use dalle.run() to generate the actual image
image_url = dalle.run(chain.invoke({"image_desc": query}))
# Display the generated image.
Image(url=image_url, width=500)
from langchain.tools import tool
# Convert a function into a tool using a decorator.
@tool
def add_numbers(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
@tool
def multiply_numbers(a: int, b: int) -> int:
"""Multiply two numbers"""
return a * b
# Import the TavilyClient class from the Tavily package.
from tavily import TavilyClient
tavily_tool = TavilyClient()
# Example of a search using various parameters.
result1 = tavily_tool.search(
query="Tell me about LangChain", # Search query
search_depth="advanced", # Advanced search depth
topic="general", # General topic
days=7, # Results from the last 7 days
max_results=10, # Maximum of 10 results
include_answer=True, # Include answers
include_raw_content=True, # Include raw content
include_images=True, # Include images
format_output=True, # Format the output
)
# Print the results
print("Basic search results:", result1)
# Example of a news search.
result2 = tavily_tool.search(
query="Latest AI technology trends", # Search query
search_depth="basic", # Basic search depth
topic="news", # News topic
days=3, # Results from the last 3 days
max_results=5, # Maximum of 5 results
include_answer=False, # Exclude answers
include_raw_content=False, # Exclude raw content
include_images=False, # Exclude images
format_output=True, # Format the output
)
print("News search results:", result2)
News search results: {'query': 'Latest AI technology trends', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'url': 'https://techxplore.com/news/2025-01-lithium-sodium-ion-batteries-breakthroughs.html', 'title': 'Losing to lithium: Research shows sodium-ion batteries need breakthroughs to compete - Tech Xplore', 'score': 0.58976424, 'published_date': 'Mon, 13 Jan 2025 10:00:01 GMT', 'content': '##### Bias and discrimination in AI: Why sociolinguistics holds the key to better LLMs and a fairer world 5 hours ago ##### Sustainable cement: An electrochemical process to help neutralize cement industry CO₂ emissions Jan 11, 2025 ##### Smart glasses enter new era with sleeker designs, lower prices Jan 11, 2025 ##### Robots set to move beyond factory as AI advances Jan 10, 2025 ##### Light, flexible and radiation-resistant: Organic solar cells for space Jan 10, 2025 ##### Exploring quinone-based carbon capture: A promising path to safer CO₂ removal Jan 10, 2025 ##### Microsoft introduces rStar-Math, an SLM for math reasoning and problem solving Jan 10, 2025 ##### AI-enabled technology is 98% accurate at spotting illegal contraband Jan 10, 2025 ##### A Minecraft-based benchmark to train and test multi-modal multi-agent systems Jan 10, 2025 ##### Sustainable building components use passive dehumidification to create a good indoor climate Jan 10, 2025'}, {'url': 'https://www.roboticstomorrow.com/story/2025/01/ieee-reveals-predictions-for-top-technology-trends-of-2025/23881/', 'title': 'IEEE Reveals Predictions for Top Technology Trends of 2025 - Robotics Tomorrow', 'score': 0.52086246, 'published_date': 'Wed, 15 Jan 2025 13:56:44 GMT', 'content': 'Home News Industrial Robotics Mobile Robots Factory Automation Other Topics Site Services In addition to these top technology developments, the Committee also anticipates the following technologies will experience significant growth over the next year: IT/energy convergence; augmented AI; autonomous driving; SmartAg; functional safety/autonomous vehicles; AI-assisted drug discovery; sustainable computing; mis/disinformation; AI-based medical diagnosis, AI-optimized green high-performance computing; next-gen cyberwarfare; new battery chemistries; data feudalism; nuclear-powered data centers; tools and policies for AI regulation; brain-computer interfaces (ones that enhance interfaces between humans and computers, particularly for those with disabilities); and space computing. Beyond outlining computer science and engineering trends, the 2025 Technology Predictions Committee offers insights into how industry, government, academia, and professional organizations can support and advance these developments.'}, {'url': 'https://www.geeky-gadgets.com/self-improving-ai-models/', 'title': 'Researchers Stunned as AI Improves Itself Towards Superintelligence - Geeky Gadgets', 'score': 0.40768766, 'published_date': 'Mon, 13 Jan 2025 09:15:10 GMT', 'content': 'Self-Improving AI Models: The Future of Cost-Effective Intelligence - Geeky Gadgets Researchers at Microsoft have unveiled a new AI model, RStar-Math, that’s rewriting the rules of how machines learn and improve. Unlike traditional models that rely on massive datasets or guidance from larger systems, RStar-Math takes a bold new approach: it teaches itself, paving the way for smaller, more efficient AI systems to outperform even the most resource-intensive giants like GPT-4 in specific tasks. RStar-Math Self-Improving AI Model By demonstrating that smaller models can achieve exceptional results, RStar-Math challenges the conventional emphasis on scale and opens new possibilities for resource-efficient AI development. Filed Under: AI, Technology News, Top NewsLatest Geeky Gadgets Deals'}, {'url': 'https://www.mobihealthnews.com/video/upside-ai-technology-2025', 'title': 'The upside of AI technology in 2025 - Mobihealth News', 'score': 0.38630086, 'published_date': 'Tue, 14 Jan 2025 15:42:44 GMT', 'content': 'The upside of AI technology in 2025 | MobiHealthNews Main Menu AI The upside of AI technology in 2025 Healthcare AI technology is additive and complementary, not punitive. More regional news Exclusive: Century Heath, Nira Medical partner to provide AI-curated EHR data Q&A: Hackensack Meridian Health on its AI expenditures in 2025 The upside of AI technology in 2025 Q&A: Qventus announces $105M investment during JPM Healthcare Conference More News Healthcare IT News Healthcare IT News Australia Healthcare Finance News HIMSS25 Global Health Conference & Exhibition Get ready to immerse yourself in the epicenter of healthcare innovation at the 2025 HIMSS Global Health Conference & Exhibition in Las Vegas! HIMSS25 European Health Conference & Exhibition HEALWELL AI buying Orion Health for $115M'}, {'url': 'https://towardsdatascience.com/the-ai-r-evolution-looking-from-2024-into-the-immediate-future-0261a5db7103', 'title': 'The AI (R)Evolution, Looking From 2024 Into the Immediate Future - Towards Data Science', 'score': 0.36683974, 'published_date': 'Wed, 15 Jan 2025 00:01:26 GMT', 'content': 'The AI (R)Evolution, Looking From 2024 Into the Immediate Future | by LucianoSphere (Luciano Abriata, PhD) | Jan, 2025 | Towards Data Science After half to one decade of technical developments that included the transformer architecture for AI systems together with several other computer science breakthroughs, the last 3–4 years have been crazily active in the development of specific applications resulting in (AI-based) software that we didn’t even dream about just 10–20 years ago. We can now reliably use LLMs to summarize texts, look for pieces of information, or even solve simple to mid-complexity problems; we can boost software writing, scripting, data analysis and software utilization with LLMs that possess vast amounts of knowledge and behave like experts available 24/7. Published in Towards Data Science --------------------------------- Your home for data science and AI.'}], 'response_time': 0.61}
# Example of a search with specific domain inclusion.
result3 = tavily_tool.search(
query="Python programming tips", # Search query
search_depth="advanced", # Advanced search depth
max_results=3, # Maximum of 3 results
include_domains=["github.io"]
)
print("Search results with specific domain inclusion:", result3)
Search results with specific domain inclusion: {'query': 'Python programming tips', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': 'Python Tips - williamkpchan.github.io', 'url': 'https://williamkpchan.github.io/LibDocs/Python+Tips.html', 'content': "In the past, we'd shared a list of Python programming tips for beginners that aimed to optimize code and reduce coding efforts. And our readers still enjoy reading it. So today, we're back with one more set of essential Python tips and tricks. All these tips can help you minify the code and optimize execution.", 'score': 0.7752821, 'raw_content': None}, {'title': "Python Tips | Ming's Blog - byrzhm.github.io", 'url': 'https://byrzhm.github.io/blog/posts/python-tips/', 'content': 'Python Tips. Posted Dec 20, 2024 . By Hongming Zhu. 1 min read. Python Tips. Contents. Python Tips ** Special Usages 1. Unpacking a dictionary into keyword arguments in a function call ... Programming Languages, Python. python. This post is licensed under CC BY 4.0 by the author. Share. Recently Updated. HPC; PyTorch Internals; Python Tips', 'score': 0.756376, 'raw_content': None}, {'title': 'Awesome Python Tips & Tricks | DevRa - rafed.github.io', 'url': 'https://rafed.github.io/devra/sections/awesome-python-tips--tricks/', 'content': 'Awesome Python Tips & Tricks - (Page 1/1) A better dictionary in python. A Python dictionary is a very useful data structure that stores key value pairs. A python dictionary is declared like the following- ... Become a Python Ninja with the below one-liners. programming python. Reduce Too Many if-elif in Python. if-elif statements are one of', 'score': 0.6519982, 'raw_content': None}], 'response_time': 3.21}
# Example of a search excluding specific domains.
result4 = tavily_tool.search(
query="Healthy diet", # Search query
search_depth="basic", # Basic search depth
days=30, # Results from the last 30 days
max_results=7, # Maximum of 7 results
exclude_domains=["ads.com", "spam.com"]
)
print("Search results excluding specific domains:", result4)
# hl: Language, gl: Region, ceid: Region and Language Code
url = f"{self.base_url}?hl=en&gl=US&ceid=US:en"
#%pip install feedparser
import feedparser
from urllib.parse import quote
from typing import List, Dict, Optional
class GoogleNews:
"""
This is a class for searching Google News and returning the results.
"""
def __init__(self):
"""
Initializes the GoogleNews class.
Sets the base_url attribute.
"""
self.base_url = "https://news.google.com/rss"
def _fetch_news(self, url: str, k: int = 3) -> List[Dict[str, str]]:
"""
Fetches news from the given URL.
Args:
url (str): The URL to fetch the news from.
k (int): The maximum number of news articles to fetch (default: 3).
Returns:
List[Dict[str, str]]: A list of dictionaries containing news titles and links.
"""
news_data = feedparser.parse(url)
return [
{"title": entry.title, "link": entry.link}
for entry in news_data.entries[:k]
]
def _collect_news(self, news_list: List[Dict[str, str]]) -> List[Dict[str, str]]:
"""
Formats and returns the list of news articles.
Args:
news_list (List[Dict[str, str]]): A list of dictionaries containing news information.
Returns:
List[Dict[str, str]]: A list of dictionaries containing URLs and content.
"""
if not news_list:
print("No news available for the given keyword.")
return []
result = []
for news in news_list:
result.append({"url": news["link"], "content": news["title"]})
return result
def search_latest(self, k: int = 3) -> List[Dict[str, str]]:
"""
Searches for the latest news.
Args:
k (int): The maximum number of news articles to search for (default: 3).
Returns:
List[Dict[str, str]]: A list of dictionaries containing URLs and content.
"""
#url = f"{self.base_url}?hl=ko&gl=KR&ceid=KR:ko"
url = f"{self.base_url}?hl=en&gl=US&ceid=US:en" # hl: 언어, gl: 지역, ceid: 지역 및 언어 코드
news_list = self._fetch_news(url, k)
return self._collect_news(news_list)
def search_by_keyword(
self, keyword: Optional[str] = None, k: int = 3
) -> List[Dict[str, str]]:
"""
Searches for news using a keyword.
Args:
keyword (Optional[str]): The keyword to search for (default: None).
k (int): The maximum number of news articles to search for (default: 3).
Returns:
List[Dict[str, str]]: A list of dictionaries containing URLs and content.
"""
if keyword:
encoded_keyword = quote(keyword)
url = f"{self.base_url}/search?q={encoded_keyword}&hl=en&gl=US&ceid=US:en"
else:
url = f"{self.base_url}?hl=en&gl=US&ceid=US:en"
news_list = self._fetch_news(url, k)
return self._collect_news(news_list)
google_tool = GoogleNews()
google_tool.search_by_keyword("AI Investment")
[{'url': 'https://news.google.com/rss/articles/CBMimAFBVV95cUxNaThyMnBjNjJpQjlQQTcwQjdoTEZPc1plbDdYU29YWlNVakE1NzVkV2ZNZHRyYlFSSjg1VDRNX2ZPT1NZdkM0ckVxMmxwaW1PbTdpay1EX2lUbFNqblIxOXdUZ3VDTVZoVmRlWVZXLTBUNG5SSUJZa3RieEFST0VjQ1hSRkxWNzRXSlBYb3k3QzEzUGdtNHo2dg?oc=5',
'content': "A Once-in-a-Decade Investment Opportunity: 1 Artificial Intelligence (AI) Semiconductor Stock to Buy Hand Over Fist and Hold for the Next 10 Years (Hint: It's Not Nvidia) - The Motley Fool"},
{'url': 'https://news.google.com/rss/articles/CBMipAFBVV95cUxNendoZ0U1eXVkVk5pYnljLThfWVotZENTbUJYZTVYRUhNOEFZNnlaYUZmT29FemhnQmJKRFptMml1cl9oQWdpM0NCQ3FhVkppcWlyeTNpUjdXOF9lNXQwR201eXM1UGxmazIzLTVLYVF2OEE1TVdBeHVwYk1uX0F3aHM0Q2p2R2R2S0p4eV8wZnFYVU9mdWJfd1VwS2I5RjVqTDZVQQ?oc=5',
'content': 'AI Avatar Startup Synthesia Valued at $2.1 Billion - PYMNTS.com'},
{'url': 'https://news.google.com/rss/articles/CBMie0FVX3lxTE9NbWttZW12S1BPLXJtM3Fhb1Z3NndndEZKRHo4Tk5sdzV3U0xvTFJHYmxjZ0lGUmNTRDcwLUlpZ3BCX0RrZmVvNDlXcFNVR3g4bEFlaTBjS2UwR016U1pSOFB2NTQzdGRuS2FwVEFDQVBnR3pHYUJaTmY2Yw?oc=5',
'content': 'EU Asks for Risk Assessments of Chip, AI, Quantum Investments - Yahoo! Voices'}]
from langchain.tools import tool
from typing import List, Dict
# Create a tool for searching news by keyword
@tool
def search_keyword(query: str) -> List[Dict[str, str]]:
"""Look up news by keyword"""
print(query)
news_tool = GoogleNews()
return news_tool.search_by_keyword(query, k=5)
[{'url': 'https://news.google.com/rss/articles/CBMid0FVX3lxTFBUVGIzM04zT1RYOC03QUxJenZLU3F4NVpoRmhvbFJRSnNZQVJIeUNyV2ktdERiSlplb2xQcXgyQWpHYS1DbEVRbk40alVBTzNQREFaQW40czNyNkdJcWxlQVgzdjVyZXI3UTN1aVVvYkdIS0tTU2lv?oc=5',
'content': 'LangChain Unveils Innovative Ambient Agents for AI Interaction - Blockchain News'},
{'url': 'https://news.google.com/rss/articles/CBMib0FVX3lxTE9qeUFQd08yN3pXenFYeWRTM1dHN3ZtTGVvaDAzREVNRU02ZVhNRFZCWmFpRm9obTN5QXF1TlpaYUI3d2VJYTBNeHNyUGJ3MXdVQWNDVW5MTVk4UDlfazFfX1hRRWpUeHBfUGRfS0pBdw?oc=5',
'content': 'Vulnerabilities in LangChain Gen AI - Unit 42'},
{'url': 'https://news.google.com/rss/articles/CBMixgFBVV95cUxNUzhFZEtsS2FrNTZ1ejVDejBQRThtSDA5TUtMbWRHOUxfUEtBVl8teERpZXp5U2wzbktZeWdTWnhKc2V4RnM2SXc0TzBsNVlQMktqUXRwNDliQW9yaTVnT3lzZ0lxeThobTliUEJRd05VM3V1anJ3bUh4cGJRbk44a1V0MVMzSEZfc2c4am04QnJBM2ZhZThTQ1NvYlhQUVBZbmhJWVZQdzlWWjE0UVdQRjYtWU1iSWl6WFBBTXdsQ2ROSHUxWmc?oc=5',
'content': 'LangChain Meets Home Assistant: Unlock the Power of Generative AI in Your Smart Home - Towards Data Science'},
{'url': 'https://news.google.com/rss/articles/CBMi6wFBVV95cUxPNEtmajI2MWxEb2FRSUNLWkhBQmV5VThPUVllNkRzbGEwOW1mRDZVZEhxYnI3X3BxZUZ1WThGbmF6WUV6MnVSaDJtN0ZUd2VZdGt5NV9CNHJRVXllVElnZE5DaVJDdFBSZHU5aGI3XzM3RTR1YVdyU19pYjJER2NTM080dlYyVjd6MDNFOTFudm5WRG1zdk9WNUxJTVpoakxEWlZxR3RaSmZiQ2FOdVA4YnFjUXBjeDdaRzNxNzVzbEU1ak9RSkY1bVVIRGFrdFBfNEhkcVhJNS0xdFFDY1IyMXBNSEUxZlJQeGlF?oc=5',
'content': 'Create a next generation chat assistant with Amazon Bedrock, Amazon Connect, Amazon Lex, LangChain, and WhatsApp - AWS Blog'},
{'url': 'https://news.google.com/rss/articles/CBMitgFBVV95cUxNSmpOTkdfRFl4WlBqWTdHLWRGajllZVdMZklQaE5mRVNfc1lYLU9vZHNHWlZ0SFJET1ljVzcxVWRDQWRxMnQ3MnBlc0w3RnFlajIwdnk1a0tya05tQTRhOVN2UExLUy1YNEE1U3Jwa3F0YU1hT1kxRHlqYmU0SWpyNW94WXFtSC1zNVh3WkxZWkdWZ0tKX3ZwdTdqeVZrVDBTMG5KQUhia2hXZkY3NmxfMmk5RDlZdw?oc=5',
'content': "Google Case Study: Five Sigma's Clive Redefines Claims Management with LangChain and Vertex AI - Coverager"}]