Skip to content

Commit d0fdc6d

Browse files
Harrison/bing wrapper (#656)
Co-authored-by: Enrico Shippole <[email protected]>
1 parent 207e319 commit d0fdc6d

File tree

4 files changed

+221
-2
lines changed

4 files changed

+221
-2
lines changed
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# Bing Search"
8+
]
9+
},
10+
{
11+
"cell_type": "markdown",
12+
"metadata": {},
13+
"source": [
14+
"This notebook goes over how to use the bing search component.\n",
15+
"\n",
16+
"First, you need to set up the proper API keys and environment variables. To set it up, follow the instructions found here.\n",
17+
"\n",
18+
"Then we will need to set some environment variables."
19+
]
20+
},
21+
{
22+
"cell_type": "code",
23+
"execution_count": 1,
24+
"metadata": {},
25+
"outputs": [],
26+
"source": [
27+
"import os\n",
28+
"os.environ[\"BING_SUBSCRIPTION_KEY\"] = \"\""
29+
]
30+
},
31+
{
32+
"cell_type": "code",
33+
"execution_count": 2,
34+
"metadata": {},
35+
"outputs": [],
36+
"source": [
37+
"from langchain.utilities import BingSearchAPIWrapper"
38+
]
39+
},
40+
{
41+
"cell_type": "code",
42+
"execution_count": 3,
43+
"metadata": {},
44+
"outputs": [],
45+
"source": [
46+
"search = BingSearchAPIWrapper()"
47+
]
48+
},
49+
{
50+
"cell_type": "code",
51+
"execution_count": 4,
52+
"metadata": {},
53+
"outputs": [
54+
{
55+
"data": {
56+
"text/plain": [
57+
"'Thanks to the flexibility of <b>Python</b> and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with <b>Python</b> by Dan Taylor. <b>Python</b> Brochure. <b>Python</b> is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use <b>Python</b> and see almost immediate gains in productivity and lower maintenance costs. Learn more about <b>Python</b> . Learning. Before getting started, you may want to find out which IDEs and text editors are tailored to make <b>Python</b> editing easy, browse the list of introductory books, or look at code samples that you might find helpful.. There is a list of tutorials suitable for experienced programmers on the BeginnersGuide/Tutorials page. There is also a list of resources in other languages which might be ... <b>Python</b> is a popular programming language. <b>Python</b> can be used on a server to create web applications. Start learning <b>Python</b> now ». With <b>Python</b>, you can use while loops to run the same task multiple times and for loops to loop once over list data. In this module, you&#39;ll learn about the two loop types and when to apply each. Manage data with <b>Python</b> dictionaries. <b>Python</b> dictionaries allow you to model complex data. This module explores common scenarios where you could use ... This module is part of these learning paths. Build real world applications with <b>Python</b>. Introduction 1 min. What is <b>Python</b>? 3 min. Use the REPL 2 min. Variables and basic data types in <b>Python</b> 4 min. Exercise - output 1 min. Reading keyboard input 3 min. Exercise - Build a calculator 1 min. <b>Python</b>&#39;s source code is freely available to the public, and its usage and distribution are unrestricted, including for commercial purposes. It is widely used for web development, and using it, practically anything can be created, including mobile apps, online apps, tools, data analytics, machine learning, and so on. ... <b>Python</b> is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation. <b>Python</b> is dynamically-typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly procedural), object-oriented and functional programming.'"
58+
]
59+
},
60+
"execution_count": 4,
61+
"metadata": {},
62+
"output_type": "execute_result"
63+
}
64+
],
65+
"source": [
66+
"search.run(\"python\")"
67+
]
68+
},
69+
{
70+
"cell_type": "markdown",
71+
"metadata": {},
72+
"source": [
73+
"## Number of results\n",
74+
"You can use the `k` parameter to set the number of results"
75+
]
76+
},
77+
{
78+
"cell_type": "code",
79+
"execution_count": 5,
80+
"metadata": {},
81+
"outputs": [],
82+
"source": [
83+
"search = BingSearchAPIWrapper(k=1)"
84+
]
85+
},
86+
{
87+
"cell_type": "code",
88+
"execution_count": 6,
89+
"metadata": {},
90+
"outputs": [
91+
{
92+
"data": {
93+
"text/plain": [
94+
"'Thanks to the flexibility of <b>Python</b> and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with <b>Python</b> by Dan Taylor.'"
95+
]
96+
},
97+
"execution_count": 6,
98+
"metadata": {},
99+
"output_type": "execute_result"
100+
}
101+
],
102+
"source": [
103+
"search.run(\"python\")"
104+
]
105+
},
106+
{
107+
"cell_type": "code",
108+
"execution_count": null,
109+
"metadata": {},
110+
"outputs": [],
111+
"source": []
112+
}
113+
],
114+
"metadata": {
115+
"kernelspec": {
116+
"display_name": "Python 3 (ipykernel)",
117+
"language": "python",
118+
"name": "python3"
119+
},
120+
"language_info": {
121+
"codemirror_mode": {
122+
"name": "ipython",
123+
"version": 3
124+
},
125+
"file_extension": ".py",
126+
"mimetype": "text/x-python",
127+
"name": "python",
128+
"nbconvert_exporter": "python",
129+
"pygments_lexer": "ipython3",
130+
"version": "3.10.9"
131+
},
132+
"vscode": {
133+
"interpreter": {
134+
"hash": "a0a0263b650d907a3bfe41c0f8d6a63a071b884df3cfdc1579f00cdc1aed6b03"
135+
}
136+
}
137+
},
138+
"nbformat": 4,
139+
"nbformat_minor": 2
140+
}

langchain/utilities/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from langchain.requests import RequestsWrapper
44
from langchain.serpapi import SerpAPIWrapper
55
from langchain.utilities.bash import BashProcess
6+
from langchain.utilities.bing_search import BingSearchAPIWrapper
67
from langchain.utilities.google_search import GoogleSearchAPIWrapper
78
from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper
89

@@ -13,4 +14,5 @@
1314
"GoogleSearchAPIWrapper",
1415
"WolframAlphaAPIWrapper",
1516
"SerpAPIWrapper",
17+
"BingSearchAPIWrapper",
1618
]

langchain/utilities/bing_search.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
"""Util that calls Bing Search.
2+
3+
In order to set this up, follow instructions at:
4+
https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
5+
"""
6+
from typing import Dict, List
7+
8+
import requests
9+
from pydantic import BaseModel, Extra, root_validator
10+
11+
from langchain.utils import get_from_dict_or_env
12+
13+
14+
class BingSearchAPIWrapper(BaseModel):
15+
"""Wrapper for Bing Search API.
16+
17+
In order to set this up, follow instructions at:
18+
https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
19+
"""
20+
21+
bing_subscription_key: str
22+
bing_search_url: str
23+
k: int = 10
24+
25+
class Config:
26+
"""Configuration for this pydantic object."""
27+
28+
extra = Extra.forbid
29+
30+
def _bing_search_results(self, search_term: str, count: int) -> List[dict]:
31+
headers = {"Ocp-Apim-Subscription-Key": self.bing_subscription_key}
32+
params = {
33+
"q": search_term,
34+
"count": count,
35+
"textDecorations": True,
36+
"textFormat": "HTML",
37+
}
38+
response = requests.get(
39+
self.bing_search_url, headers=headers, params=params # type: ignore
40+
)
41+
response.raise_for_status()
42+
search_results = response.json()
43+
return search_results["webPages"]["value"]
44+
45+
@root_validator(pre=True)
46+
def validate_environment(cls, values: Dict) -> Dict:
47+
"""Validate that api key and endpoint exists in environment."""
48+
bing_subscription_key = get_from_dict_or_env(
49+
values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY"
50+
)
51+
values["bing_subscription_key"] = bing_subscription_key
52+
53+
bing_search_url = get_from_dict_or_env(
54+
values,
55+
"bing_search_url",
56+
"BING_SEARCH_URL",
57+
default="https://api.bing.microsoft.com/v7.0/search",
58+
)
59+
60+
values["bing_search_url"] = bing_search_url
61+
62+
return values
63+
64+
def run(self, query: str) -> str:
65+
"""Run query through BingSearch and parse result."""
66+
snippets = []
67+
results = self._bing_search_results(query, count=self.k)
68+
if len(results) == 0:
69+
return "No good Bing Search Result was found"
70+
for result in results:
71+
snippets.append(result["snippet"])
72+
73+
return " ".join(snippets)

langchain/utils.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
"""Generic utility functions."""
22
import os
3-
from typing import Any, Dict
3+
from typing import Any, Dict, Optional
44

55

6-
def get_from_dict_or_env(data: Dict[str, Any], key: str, env_key: str) -> str:
6+
def get_from_dict_or_env(
7+
data: Dict[str, Any], key: str, env_key: str, default: Optional[str] = None
8+
) -> str:
79
"""Get a value from a dictionary or an environment variable."""
810
if key in data and data[key]:
911
return data[key]
1012
elif env_key in os.environ and os.environ[env_key]:
1113
return os.environ[env_key]
14+
elif default is not None:
15+
return default
1216
else:
1317
raise ValueError(
1418
f"Did not find {key}, please add an environment variable"

0 commit comments

Comments
 (0)