Bing Search
Microsoft Bing, commonly referred to as Bing
or Bing Search
, is a web search engine owned and operated by Microsoft
.
Setupβ
Following the instruction to create Azure Bing Search v7 service, and get the subscription key
The integration lives in the langchain-community
package.
%pip install -U langchain-community
import getpass
import os
os.environ["BING_SUBSCRIPTION_KEY"] = getpass.getpass()
os.environ["BING_SEARCH_URL"] = "https://api.bing.microsoft.com/v7.0/search"
from langchain_community.utilities import BingSearchAPIWrapper
API Reference:BingSearchAPIWrapper
search = BingSearchAPIWrapper(k=4)
search.run("python")
'<b>Python is a</b> versatile and powerful language that lets you work quickly and integrate systems more effectively. Learn how to get started, download the latest version, access documentation, find jobs, and join the Python community. <b>Python is a</b> popular programming language for various purposes. Find the latest version of Python for different operating systems, download release notes, and learn about the development process. Learn <b>Python,</b> a popular programming language for web applications, with examples, exercises, and references. Get certified by completing the PYTHON <b>course</b> at W3Schools. Learn the basic concepts and features of <b>Python,</b> a powerful and easy to learn programming language. The tutorial covers topics such as data structures, modules, classes, exceptions, input and output, and more. Learn why and how to use <b>Python,</b> a popular and easy-to-learn programming language. Find installation guides, tutorials, documentation, resources and FAQs for beginners and experienced programmers. Learn about <b>Python,</b> a high-level, general-purpose programming language with a focus on code readability and multiple paradigms. Find out its history, design, features, libraries, implementations, popularity, uses, and influences. Real <b>Python</b> offers tutorials, books, courses, and news for <b>Python</b> developers of all skill levels. Whether you want to learn <b>Python</b> basics, web development, data science, or machine learning, you can find useful articles and code examples here. Learn how to install, use, and extend <b>Python</b> 3.12.3, a popular programming language. Find tutorials, library references, API guides, FAQs, and more. <b>Python</b> is a powerful, fast, friendly and open-source language that runs everywhere. Learn how to get started, explore applications, join the community and access the latest news and events. Learn the basics of <b>Python</b> programming language with examples of numbers, text, variables, and operators. This tutorial covers the syntax, types, and features of <b>Python</b> for beginners.'
Number of resultsβ
You can use the k
parameter to set the number of results
search = BingSearchAPIWrapper(k=1)
search.run("python")
'<b>Python</b> is a versatile and powerful language that lets you work quickly and integrate systems more effectively. Learn how to get started, download the latest version, access documentation, find jobs, and join the Python community.'
Metadata Resultsβ
Run query through BingSearch and return snippet, title, and link metadata.
- Snippet: The description of the result.
- Title: The title of the result.
- Link: The link to the result.
search = BingSearchAPIWrapper()
search.results("apples", 5)
[{'snippet': 'Learn about the nutrients, antioxidants, and potential health effects of<b> apples.</b> Find out how<b> apples</b> may help with weight loss, diabetes, heart disease, and cancer.',
'title': 'Apples 101: Nutrition Facts and Health Benefits',
'link': 'https://www.healthline.com/nutrition/foods/apples'},
{'snippet': 'Learn how<b> apples</b> can improve your health with their fiber, antioxidants, and phytochemicals. Find out the best types of<b> apples</b> for different purposes, how to buy and store them, and what side effects to watch out for.',
'title': 'Apples: Nutrition and Health Benefits - WebMD',
'link': 'https://www.webmd.com/food-recipes/benefits-apples'},
{'snippet': '<b>Apples</b> are nutritious, filling, and versatile fruits that may lower your risk of various diseases. Learn how<b> apples</b> can support your weight loss, heart health, gut health, and brain health with scientific evidence.',
'title': '10 Impressive Health Benefits of Apples',
'link': 'https://www.healthline.com/nutrition/10-health-benefits-of-apples'},
{'snippet': 'An apple is a round, edible fruit produced by an apple tree (Malus spp., among them the domestic or orchard apple; Malus domestica).Apple trees are cultivated worldwide and are the most widely grown species in the genus Malus.The tree originated in Central Asia, where its wild ancestor, Malus sieversii, is still found.<b>Apples</b> have been grown for thousands of years in Eurasia and were introduced ...',
'title': 'Apple - Wikipedia',
'link': 'https://en.wikipedia.org/wiki/Apple'},
{'snippet': 'Learn about the most popular and diverse<b> apples</b> in the world, from ambrosia to winesap, with photos and descriptions. Find out their origins, flavors, uses, and nutritional benefits in this comprehensive guide to<b> apples.</b>',
'title': '29 Types Of Apples From A to Z (With Photos!) - Live Eat Learn',
'link': 'https://www.liveeatlearn.com/types-of-apples/'}]
Tool Usageβ
import os
from langchain_community.tools.bing_search import BingSearchResults
from langchain_community.utilities import BingSearchAPIWrapper
api_wrapper = BingSearchAPIWrapper()
tool = BingSearchResults(api_wrapper=api_wrapper)
tool
API Reference:BingSearchResults | BingSearchAPIWrapper
BingSearchResults(api_wrapper=BingSearchAPIWrapper(bing_subscription_key='<your subscription key>', bing_search_url='https://api.bing.microsoft.com/v7.0/search', k=10, search_kwargs={}))
# .invoke wraps utility.results
response = tool.invoke("What is the weather in Shanghai")
for item in list(response):
print(item)
{'snippet': 'This chart shows the 14 day <b>weather</b> trend for 33.74Β°N 89.59Β°E with daily <b>weather</b> symbols, minimum and maximum temperatures, precipitation amount and probability.. The deviance is coloured within the temperature graph. The stronger the ups and downs, the more uncertain the forecast will be.', 'title': '14 Day Weather 33.74Β°N 89.59Β°E - meteoblue', 'link': 'https://www.meteoblue.com/en/weather/14-days/33.739N89.594E6216_Asia%2FShanghai'}
{'snippet': 'Get the monthly <b>weather</b> forecast for Huangpu District, <b>Shanghai</b>, China, including daily high/low, historical averages, to help you plan ahead.', 'title': 'Huangpu District, Shanghai, China Monthly Weather | AccuWeather', 'link': 'https://www.accuweather.com/en/cn/huangpu-district/60782/june-weather/60782'}
{'snippet': '<b>Shanghai</b> Hongqiao Airport is 60 miles from 31Β°31'42.7"N, 120Β°24'12.7"E, so the actual climate in 31Β°31'42.7"N, 120Β°24'12.7"E can vary a bit. Based on <b>weather</b> reports collected during 1992β2021. Showing: All Year January February March April May June July August September October November December', 'title': 'Climate & Weather Averages in 31Β°31'42.7"N, 120Β°24'12.7"E, China', 'link': 'https://www.timeanddate.com/weather/@31.52853,120.40355/climate'}
{'snippet': 'Air Quality gives information using <b>weather</b> conditions, pollutants, and research from The <b>Weather</b> Channel and <b>weather</b>.com ... Today's Air Quality-<b>Shanghai</b>, People's Republic of China. 76.', 'title': 'Shanghai, People's Republic of China Weather', 'link': 'https://weather.com/forecast/air-quality/l/80415bb74d7ded500f89b569c51da53325719ddea6e1394485ad846e812e61d2'}
Chainingβ
We show here how to use it as part of an agent. We use the OpenAI Functions Agent, so we will need to setup and install the required dependencies for that. We will also use LangSmith Hub to pull the prompt from, so we will need to install that.
# you need a model to use in the chain
%pip install --upgrade --quiet langchain langchain-openai langchainhub langchain-community
import getpass
import os
from langchain import hub
from langchain.agents import AgentExecutor, create_openai_functions_agent
from langchain_openai import AzureChatOpenAI
os.environ["AZURE_OPENAI_API_KEY"] = getpass.getpass()
os.environ["AZURE_OPENAI_ENDPOINT"] = "https://<your-endpoint>.openai.azure.com/"
os.environ["AZURE_OPENAI_API_VERSION"] = "2023-06-01-preview"
os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"] = "<your-deployment-name>"
instructions = """You are an assistant."""
base_prompt = hub.pull("langchain-ai/openai-functions-template")
prompt = base_prompt.partial(instructions=instructions)
llm = AzureChatOpenAI(
openai_api_key=os.environ["AZURE_OPENAI_API_KEY"],
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
openai_api_version=os.environ["AZURE_OPENAI_API_VERSION"],
)
tool = BingSearchResults(api_wrapper=api_wrapper)
tools = [tool]
agent = create_openai_functions_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True,
)
agent_executor.invoke({"input": "What happened in the latest burning man floods?"})
[1m> Entering new AgentExecutor chain...[0m
[32;1m[1;3m
Invoking: `bing_search_results_json` with `{'query': 'latest burning man floods'}`
[0m[36;1m[1;3m[{'snippet': 'Some festivalgoers have shared stories of their successful 6-mile hikes away from <b>Burning</b> <b>Man</b>. The worst of the rain Sunday is expected between 12 p.m. and 4 p.m. local time (3 p.m. to 7 p.m. ET ...', 'title': 'Live updates: Burning Man festival rain strands thousands in ... - CNN', 'link': 'https://www.cnn.com/us/live-news/nevada-desert-burning-man-weather-rain-09-03-23/index.html'}, {'snippet': 'Black Rock Forest, where around 70,000 <b>Burning</b> <b>Man</b> attendees are gathered for the festival, is in the northwest. "Flash <b>flooding</b> caused by excessive rainfall" is possible in parts of eastern ...', 'title': 'Burning Man flooding keeps thousands stranded at Nevada site as ...', 'link': 'https://www.nbcnews.com/news/us-news/live-blog/live-updates-burning-man-flooding-keeps-thousands-stranded-nevada-site-rcna103193'}, {'snippet': 'Thousands of <b>Burning</b> <b>Man</b> attendees finally made their mass exodus after intense rain over the weekend flooded camp sites and filled them with thick, ankle-deep mud β stranding more than 70,000 ...', 'title': 'Burning Man attendees make a mass exodus after a dramatic weekend ... - CNN', 'link': 'https://www.cnn.com/2023/09/05/us/burning-man-storms-shelter-exodus-tuesday/index.html'}, {'snippet': 'Youβre going to get stuck,β hosts on <b>Burning</b> <b>Man</b> Information Radio, broadcasting from within the event, told festivalgoers early on Sept. 4. According to NBC News, the Pershing County Sheriff ...', 'title': 'Burning Man attendees make mass exodus after being stranded in ... - TODAY', 'link': 'https://www.today.com/news/what-is-burning-man-flood-death-rcna103231'}][0m[32;1m[1;3mThe latest Burning Man festival experienced heavy rain and flooding, which resulted in thousands of festivalgoers being stranded. Some attendees had to hike for miles to safety. The rain caused flash flooding in parts of the festival site, including the Black Rock Forest where the event takes place. Campsites were flooded, and thick mud made movement difficult. Eventually, after the intense rain over the weekend, attendees were able to make a mass exodus from the festival. The Pershing County Sheriff's Office warned festivalgoers about the flooding and encouraged them to leave for safety.[0m
[1m> Finished chain.[0m
{'input': 'What happened in the latest burning man floods?',
'output': "The latest Burning Man festival experienced heavy rain and flooding, which resulted in thousands of festivalgoers being stranded. Some attendees had to hike for miles to safety. The rain caused flash flooding in parts of the festival site, including the Black Rock Forest where the event takes place. Campsites were flooded, and thick mud made movement difficult. Eventually, after the intense rain over the weekend, attendees were able to make a mass exodus from the festival. The Pershing County Sheriff's Office warned festivalgoers about the flooding and encouraged them to leave for safety."}