langchain-serpbit 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- langchain_serpbit-0.1.0/LICENSE +21 -0
- langchain_serpbit-0.1.0/PKG-INFO +63 -0
- langchain_serpbit-0.1.0/README.md +42 -0
- langchain_serpbit-0.1.0/pyproject.toml +32 -0
- langchain_serpbit-0.1.0/setup.cfg +4 -0
- langchain_serpbit-0.1.0/src/langchain_serpbit/__init__.py +8 -0
- langchain_serpbit-0.1.0/src/langchain_serpbit/py.typed +0 -0
- langchain_serpbit-0.1.0/src/langchain_serpbit/search.py +131 -0
- langchain_serpbit-0.1.0/src/langchain_serpbit.egg-info/PKG-INFO +63 -0
- langchain_serpbit-0.1.0/src/langchain_serpbit.egg-info/SOURCES.txt +13 -0
- langchain_serpbit-0.1.0/src/langchain_serpbit.egg-info/dependency_links.txt +1 -0
- langchain_serpbit-0.1.0/src/langchain_serpbit.egg-info/requires.txt +2 -0
- langchain_serpbit-0.1.0/src/langchain_serpbit.egg-info/top_level.txt +1 -0
- langchain_serpbit-0.1.0/tests/test_parity.py +57 -0
- langchain_serpbit-0.1.0/tests/test_search.py +91 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Serpbit
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: langchain-serpbit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Google Search for LangChain through Serpbit: GoogleSearchAPIWrapper's tools, on after Google's Custom Search API closes.
|
|
5
|
+
Author-email: Serpbit <support@serpbit.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://serpbit.com/custom-search-api-alternative/
|
|
8
|
+
Project-URL: Documentation, https://serpbit.com/docs/#sdks
|
|
9
|
+
Keywords: langchain,google search,custom search api,serp api,web search,ai agents
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: langchain-core<2,>=0.3
|
|
19
|
+
Requires-Dist: serpbit<1,>=0.3.0
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# langchain-serpbit
|
|
23
|
+
|
|
24
|
+
Google Search for LangChain after Google's Custom Search JSON API stops searching the whole web on January 1, 2027.
|
|
25
|
+
These are the Google Search tools of `langchain-google-community`, with the same calls, names and answers, served by
|
|
26
|
+
[Serpbit](https://serpbit.com/custom-search-api-alternative/) from Google's own results pages.
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
pip install langchain-serpbit
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Moving is two lines: the import and the key. Make a key at https://app.serpbit.com/keys and set `SERPBIT_API_KEY`.
|
|
33
|
+
The search engine id is gone, because the results come from the whole web.
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
# Before
|
|
37
|
+
from langchain_google_community import GoogleSearchAPIWrapper, GoogleSearchResults, GoogleSearchRun
|
|
38
|
+
search = GoogleSearchAPIWrapper(k=5) # GOOGLE_API_KEY, GOOGLE_CSE_ID
|
|
39
|
+
|
|
40
|
+
# After
|
|
41
|
+
from langchain_serpbit import SerpbitSearchAPIWrapper, SerpbitSearchResults, SerpbitSearchRun
|
|
42
|
+
search = SerpbitSearchAPIWrapper(k=5) # SERPBIT_API_KEY
|
|
43
|
+
|
|
44
|
+
search.run("espresso grinder") # the results' snippets
|
|
45
|
+
search.results("espresso grinder", 3, search_params={"gl": "de", "dateRestrict": "m1"})
|
|
46
|
+
|
|
47
|
+
tools = [SerpbitSearchRun(api_wrapper=search), SerpbitSearchResults(api_wrapper=search, num_results=4)]
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The tools keep Google's names, `google_search` and `google_search_results_json`, and Google's descriptions, so
|
|
51
|
+
prompts, traces and evaluations stay as they are. `search_params` are Custom Search's own: `gl`, `hl`, `lr`, `safe`,
|
|
52
|
+
`dateRestrict`, `siteSearch`, `fileType`, `start`, `exactTerms` and the rest
|
|
53
|
+
([the full list](https://serpbit.com/docs/#cse)).
|
|
54
|
+
|
|
55
|
+
What differs from Google's:
|
|
56
|
+
- `siterestrict=True` is refused, because a Custom Search engine's own list of sites does not carry over. To search one
|
|
57
|
+
site, pass `search_params={"siteSearch": "example.com"}`.
|
|
58
|
+
- `results()` has no `image` or `thumbnail`, because Serpbit's answer has no `pagemap`.
|
|
59
|
+
- A failed call raises the [`serpbit`](https://pypi.org/project/serpbit/) client's errors, such as
|
|
60
|
+
`serpbit.InsufficientCreditsError` when the credits run out.
|
|
61
|
+
- A search takes about 2 seconds, against under 1 on Google's API.
|
|
62
|
+
|
|
63
|
+
Each search costs 1 credit. The free plan gives 1,000 credits a month, with no card.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# langchain-serpbit
|
|
2
|
+
|
|
3
|
+
Google Search for LangChain after Google's Custom Search JSON API stops searching the whole web on January 1, 2027.
|
|
4
|
+
These are the Google Search tools of `langchain-google-community`, with the same calls, names and answers, served by
|
|
5
|
+
[Serpbit](https://serpbit.com/custom-search-api-alternative/) from Google's own results pages.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pip install langchain-serpbit
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Moving is two lines: the import and the key. Make a key at https://app.serpbit.com/keys and set `SERPBIT_API_KEY`.
|
|
12
|
+
The search engine id is gone, because the results come from the whole web.
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
# Before
|
|
16
|
+
from langchain_google_community import GoogleSearchAPIWrapper, GoogleSearchResults, GoogleSearchRun
|
|
17
|
+
search = GoogleSearchAPIWrapper(k=5) # GOOGLE_API_KEY, GOOGLE_CSE_ID
|
|
18
|
+
|
|
19
|
+
# After
|
|
20
|
+
from langchain_serpbit import SerpbitSearchAPIWrapper, SerpbitSearchResults, SerpbitSearchRun
|
|
21
|
+
search = SerpbitSearchAPIWrapper(k=5) # SERPBIT_API_KEY
|
|
22
|
+
|
|
23
|
+
search.run("espresso grinder") # the results' snippets
|
|
24
|
+
search.results("espresso grinder", 3, search_params={"gl": "de", "dateRestrict": "m1"})
|
|
25
|
+
|
|
26
|
+
tools = [SerpbitSearchRun(api_wrapper=search), SerpbitSearchResults(api_wrapper=search, num_results=4)]
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The tools keep Google's names, `google_search` and `google_search_results_json`, and Google's descriptions, so
|
|
30
|
+
prompts, traces and evaluations stay as they are. `search_params` are Custom Search's own: `gl`, `hl`, `lr`, `safe`,
|
|
31
|
+
`dateRestrict`, `siteSearch`, `fileType`, `start`, `exactTerms` and the rest
|
|
32
|
+
([the full list](https://serpbit.com/docs/#cse)).
|
|
33
|
+
|
|
34
|
+
What differs from Google's:
|
|
35
|
+
- `siterestrict=True` is refused, because a Custom Search engine's own list of sites does not carry over. To search one
|
|
36
|
+
site, pass `search_params={"siteSearch": "example.com"}`.
|
|
37
|
+
- `results()` has no `image` or `thumbnail`, because Serpbit's answer has no `pagemap`.
|
|
38
|
+
- A failed call raises the [`serpbit`](https://pypi.org/project/serpbit/) client's errors, such as
|
|
39
|
+
`serpbit.InsufficientCreditsError` when the credits run out.
|
|
40
|
+
- A search takes about 2 seconds, against under 1 on Google's API.
|
|
41
|
+
|
|
42
|
+
Each search costs 1 credit. The free plan gives 1,000 credits a month, with no card.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "langchain-serpbit"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Google Search for LangChain through Serpbit: GoogleSearchAPIWrapper's tools, on after Google's Custom Search API closes."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "Serpbit", email = "support@serpbit.com" }]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
dependencies = ["langchain-core>=0.3,<2", "serpbit>=0.3.0,<1"]
|
|
15
|
+
keywords = ["langchain", "google search", "custom search api", "serp api", "web search", "ai agents"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Topic :: Internet :: WWW/HTTP :: Indexing/Search",
|
|
21
|
+
"Typing :: Typed",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://serpbit.com/custom-search-api-alternative/"
|
|
26
|
+
Documentation = "https://serpbit.com/docs/#sdks"
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.packages.find]
|
|
29
|
+
where = ["src"]
|
|
30
|
+
|
|
31
|
+
[tool.setuptools.package-data]
|
|
32
|
+
langchain_serpbit = ["py.typed"]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Google Search for LangChain through Serpbit: Google's Custom Search tools, on after Custom Search stops searching the
|
|
2
|
+
whole web on 2027-01-01."""
|
|
3
|
+
|
|
4
|
+
from langchain_serpbit.search import SerpbitSearchAPIWrapper, SerpbitSearchResults, SerpbitSearchRun
|
|
5
|
+
|
|
6
|
+
__version__ = "0.1.0"
|
|
7
|
+
|
|
8
|
+
__all__ = ["SerpbitSearchAPIWrapper", "SerpbitSearchRun", "SerpbitSearchResults", "__version__"]
|
|
File without changes
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Google Search for LangChain through Serpbit: langchain-google-community's Google Search tools, the same calls and the
|
|
2
|
+
same answers, on Serpbit's Custom Search API in place of Google's, which stops searching the whole web on 2027-01-01."""
|
|
3
|
+
|
|
4
|
+
from typing import Any, Dict, List, Optional
|
|
5
|
+
|
|
6
|
+
from langchain_core.callbacks import CallbackManagerForToolRun
|
|
7
|
+
from langchain_core.tools import BaseTool
|
|
8
|
+
from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
|
|
9
|
+
from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator
|
|
10
|
+
from serpbit import Serpbit
|
|
11
|
+
|
|
12
|
+
NO_RESULT = "No good Google Search Result was found"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SerpbitSearchAPIWrapper(BaseModel):
|
|
16
|
+
"""Google Search through Serpbit, in place of langchain-google-community's ``GoogleSearchAPIWrapper``: ``run()``
|
|
17
|
+
and ``results()`` take and give what Google's did. The key is ``SERPBIT_API_KEY``'s by default (keys are made at
|
|
18
|
+
https://app.serpbit.com/keys). There is no search engine id: the results are the whole web's.
|
|
19
|
+
|
|
20
|
+
Example:
|
|
21
|
+
.. code-block:: python
|
|
22
|
+
|
|
23
|
+
from langchain_serpbit import SerpbitSearchAPIWrapper
|
|
24
|
+
|
|
25
|
+
search = SerpbitSearchAPIWrapper(k=5)
|
|
26
|
+
search.run("espresso grinder")
|
|
27
|
+
search.results("espresso grinder", 3, search_params={"gl": "de", "dateRestrict": "m1"})
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
serpbit_api_key: Optional[SecretStr] = None
|
|
31
|
+
"""Serpbit API key; ``SERPBIT_API_KEY`` by default."""
|
|
32
|
+
|
|
33
|
+
k: int = 10
|
|
34
|
+
"""Number of results ``run()`` reads, 1 to 10."""
|
|
35
|
+
|
|
36
|
+
siterestrict: bool = False
|
|
37
|
+
"""Kept for code written for Google's wrapper. ``True`` is refused: a Custom Search engine's own list of sites does
|
|
38
|
+
not carry over. Ask for one site with ``search_params={"siteSearch": "example.com"}``."""
|
|
39
|
+
|
|
40
|
+
base_url: Optional[str] = None
|
|
41
|
+
"""The API's address; ``SERPBIT_BASE_URL``, else https://api.serpbit.com."""
|
|
42
|
+
|
|
43
|
+
client: Any = None
|
|
44
|
+
"""The Serpbit client, made from the key when not given."""
|
|
45
|
+
|
|
46
|
+
model_config = ConfigDict(extra="forbid")
|
|
47
|
+
|
|
48
|
+
@model_validator(mode="before")
|
|
49
|
+
@classmethod
|
|
50
|
+
def validate_environment(cls, values: Dict) -> Any:
|
|
51
|
+
"""Refuse siterestrict, read the key and make the client."""
|
|
52
|
+
if values.get("siterestrict"):
|
|
53
|
+
raise ValueError(
|
|
54
|
+
"siterestrict searches a Custom Search engine's own sites, which do not carry over to Serpbit: "
|
|
55
|
+
"pass search_params={'siteSearch': 'example.com'} to search one site"
|
|
56
|
+
)
|
|
57
|
+
if values.get("client") is None:
|
|
58
|
+
key = convert_to_secret_str(get_from_dict_or_env(values, "serpbit_api_key", "SERPBIT_API_KEY"))
|
|
59
|
+
values["serpbit_api_key"] = key
|
|
60
|
+
values["client"] = Serpbit(key.get_secret_value(), base_url=values.get("base_url"))
|
|
61
|
+
return values
|
|
62
|
+
|
|
63
|
+
def _custom_search(self, query: str, **params: Any) -> List[dict]:
|
|
64
|
+
return self.client.custom_search(query, **params).get("items", [])
|
|
65
|
+
|
|
66
|
+
def run(self, query: str) -> str:
|
|
67
|
+
"""Run query through Google Search: the results' snippets, joined by spaces."""
|
|
68
|
+
results = self._custom_search(query, num=self.k)
|
|
69
|
+
if not results:
|
|
70
|
+
return NO_RESULT
|
|
71
|
+
return " ".join(r["snippet"] for r in results if "snippet" in r)
|
|
72
|
+
|
|
73
|
+
def results(
|
|
74
|
+
self,
|
|
75
|
+
query: str,
|
|
76
|
+
num_results: int,
|
|
77
|
+
search_params: Optional[Dict[str, str]] = None,
|
|
78
|
+
) -> List[Dict]:
|
|
79
|
+
"""Run query through Google Search and return each result's title, link and snippet.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
query: The query to search for.
|
|
83
|
+
num_results: Number of results to return, 1 to 10.
|
|
84
|
+
search_params: Custom Search's parameters: gl, lr, dateRestrict, siteSearch, start...
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
A dict a result, with title, link and snippet (when the result has one).
|
|
88
|
+
"""
|
|
89
|
+
results = self._custom_search(query, num=num_results, **(search_params or {}))
|
|
90
|
+
if not results:
|
|
91
|
+
return [{"Result": NO_RESULT}]
|
|
92
|
+
out = []
|
|
93
|
+
for r in results:
|
|
94
|
+
row = {"title": r["title"], "link": r["link"]}
|
|
95
|
+
if "snippet" in r:
|
|
96
|
+
row["snippet"] = r["snippet"]
|
|
97
|
+
out.append(row)
|
|
98
|
+
return out
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class SerpbitSearchRun(BaseTool):
|
|
102
|
+
"""Google Search through Serpbit, in place of langchain-google-community's ``GoogleSearchRun``: the same name and
|
|
103
|
+
description, so prompts and traces stay as they are. Returns the results' snippets."""
|
|
104
|
+
|
|
105
|
+
name: str = "google_search"
|
|
106
|
+
description: str = (
|
|
107
|
+
"A wrapper around Google Search. "
|
|
108
|
+
"Useful for when you need to answer questions about current events. "
|
|
109
|
+
"Input should be a search query."
|
|
110
|
+
)
|
|
111
|
+
api_wrapper: SerpbitSearchAPIWrapper = Field(default_factory=SerpbitSearchAPIWrapper)
|
|
112
|
+
|
|
113
|
+
def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> str:
|
|
114
|
+
return self.api_wrapper.run(query)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class SerpbitSearchResults(BaseTool):
|
|
118
|
+
"""Google Search through Serpbit, in place of langchain-google-community's ``GoogleSearchResults``: the same name
|
|
119
|
+
and description. Returns the first ``num_results`` results, each a title, link and snippet."""
|
|
120
|
+
|
|
121
|
+
name: str = "google_search_results_json"
|
|
122
|
+
description: str = (
|
|
123
|
+
"A wrapper around Google Search. "
|
|
124
|
+
"Useful for when you need to answer questions about current events. "
|
|
125
|
+
"Input should be a search query. Output is a JSON array of the query results"
|
|
126
|
+
)
|
|
127
|
+
num_results: int = 4
|
|
128
|
+
api_wrapper: SerpbitSearchAPIWrapper = Field(default_factory=SerpbitSearchAPIWrapper)
|
|
129
|
+
|
|
130
|
+
def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> str:
|
|
131
|
+
return str(self.api_wrapper.results(query, self.num_results))
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: langchain-serpbit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Google Search for LangChain through Serpbit: GoogleSearchAPIWrapper's tools, on after Google's Custom Search API closes.
|
|
5
|
+
Author-email: Serpbit <support@serpbit.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://serpbit.com/custom-search-api-alternative/
|
|
8
|
+
Project-URL: Documentation, https://serpbit.com/docs/#sdks
|
|
9
|
+
Keywords: langchain,google search,custom search api,serp api,web search,ai agents
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: langchain-core<2,>=0.3
|
|
19
|
+
Requires-Dist: serpbit<1,>=0.3.0
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# langchain-serpbit
|
|
23
|
+
|
|
24
|
+
Google Search for LangChain after Google's Custom Search JSON API stops searching the whole web on January 1, 2027.
|
|
25
|
+
These are the Google Search tools of `langchain-google-community`, with the same calls, names and answers, served by
|
|
26
|
+
[Serpbit](https://serpbit.com/custom-search-api-alternative/) from Google's own results pages.
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
pip install langchain-serpbit
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Moving is two lines: the import and the key. Make a key at https://app.serpbit.com/keys and set `SERPBIT_API_KEY`.
|
|
33
|
+
The search engine id is gone, because the results come from the whole web.
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
# Before
|
|
37
|
+
from langchain_google_community import GoogleSearchAPIWrapper, GoogleSearchResults, GoogleSearchRun
|
|
38
|
+
search = GoogleSearchAPIWrapper(k=5) # GOOGLE_API_KEY, GOOGLE_CSE_ID
|
|
39
|
+
|
|
40
|
+
# After
|
|
41
|
+
from langchain_serpbit import SerpbitSearchAPIWrapper, SerpbitSearchResults, SerpbitSearchRun
|
|
42
|
+
search = SerpbitSearchAPIWrapper(k=5) # SERPBIT_API_KEY
|
|
43
|
+
|
|
44
|
+
search.run("espresso grinder") # the results' snippets
|
|
45
|
+
search.results("espresso grinder", 3, search_params={"gl": "de", "dateRestrict": "m1"})
|
|
46
|
+
|
|
47
|
+
tools = [SerpbitSearchRun(api_wrapper=search), SerpbitSearchResults(api_wrapper=search, num_results=4)]
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The tools keep Google's names, `google_search` and `google_search_results_json`, and Google's descriptions, so
|
|
51
|
+
prompts, traces and evaluations stay as they are. `search_params` are Custom Search's own: `gl`, `hl`, `lr`, `safe`,
|
|
52
|
+
`dateRestrict`, `siteSearch`, `fileType`, `start`, `exactTerms` and the rest
|
|
53
|
+
([the full list](https://serpbit.com/docs/#cse)).
|
|
54
|
+
|
|
55
|
+
What differs from Google's:
|
|
56
|
+
- `siterestrict=True` is refused, because a Custom Search engine's own list of sites does not carry over. To search one
|
|
57
|
+
site, pass `search_params={"siteSearch": "example.com"}`.
|
|
58
|
+
- `results()` has no `image` or `thumbnail`, because Serpbit's answer has no `pagemap`.
|
|
59
|
+
- A failed call raises the [`serpbit`](https://pypi.org/project/serpbit/) client's errors, such as
|
|
60
|
+
`serpbit.InsufficientCreditsError` when the credits run out.
|
|
61
|
+
- A search takes about 2 seconds, against under 1 on Google's API.
|
|
62
|
+
|
|
63
|
+
Each search costs 1 credit. The free plan gives 1,000 credits a month, with no card.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/langchain_serpbit/__init__.py
|
|
5
|
+
src/langchain_serpbit/py.typed
|
|
6
|
+
src/langchain_serpbit/search.py
|
|
7
|
+
src/langchain_serpbit.egg-info/PKG-INFO
|
|
8
|
+
src/langchain_serpbit.egg-info/SOURCES.txt
|
|
9
|
+
src/langchain_serpbit.egg-info/dependency_links.txt
|
|
10
|
+
src/langchain_serpbit.egg-info/requires.txt
|
|
11
|
+
src/langchain_serpbit.egg-info/top_level.txt
|
|
12
|
+
tests/test_parity.py
|
|
13
|
+
tests/test_search.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
langchain_serpbit
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""The same answers as langchain-google-community's own tools, read from the same Custom Search JSON. Runs where that
|
|
2
|
+
package is installed: sdk/release.sh installs it beside the built wheel."""
|
|
3
|
+
|
|
4
|
+
import unittest
|
|
5
|
+
|
|
6
|
+
from fake_cse import Handler, start
|
|
7
|
+
from langchain_serpbit import SerpbitSearchAPIWrapper, SerpbitSearchResults, SerpbitSearchRun
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
from googleapiclient.discovery import build
|
|
11
|
+
from langchain_google_community import GoogleSearchAPIWrapper, GoogleSearchResults, GoogleSearchRun
|
|
12
|
+
except ImportError:
|
|
13
|
+
GoogleSearchAPIWrapper = None
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@unittest.skipIf(GoogleSearchAPIWrapper is None, "langchain-google-community is not installed")
|
|
17
|
+
class ParityTest(unittest.TestCase):
|
|
18
|
+
@classmethod
|
|
19
|
+
def setUpClass(cls):
|
|
20
|
+
cls.srv, cls.base = start()
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def tearDownClass(cls):
|
|
24
|
+
cls.srv.shutdown()
|
|
25
|
+
cls.srv.server_close()
|
|
26
|
+
|
|
27
|
+
def google(self):
|
|
28
|
+
g = GoogleSearchAPIWrapper(google_api_key="AIza-test", google_cse_id="cx-test", k=3)
|
|
29
|
+
# Google's client, sent to the fake: the "small tweak" its own wrapper needs to reach another host.
|
|
30
|
+
g.search_engine = build("customsearch", "v1", developerKey="AIza-test", static_discovery=True,
|
|
31
|
+
client_options={"api_endpoint": self.base})
|
|
32
|
+
return g
|
|
33
|
+
|
|
34
|
+
def serpbit(self):
|
|
35
|
+
return SerpbitSearchAPIWrapper(serpbit_api_key="sb_live_test", base_url=self.base, k=3)
|
|
36
|
+
|
|
37
|
+
def test_the_wrappers_give_the_same(self):
|
|
38
|
+
g, s = self.google(), self.serpbit()
|
|
39
|
+
for q in ("espresso grinder", "nothing"):
|
|
40
|
+
self.assertEqual(g.run(q), s.run(q))
|
|
41
|
+
self.assertEqual(g.results(q, 2), s.results(q, 2))
|
|
42
|
+
params = {"gl": "de", "dateRestrict": "m1", "siteSearch": "example.com"}
|
|
43
|
+
self.assertEqual(g.results(q, 3, params), s.results(q, 3, params))
|
|
44
|
+
google_asked, serpbit_asked = Handler.seen[-2]["query"], Handler.seen[-1]["query"]
|
|
45
|
+
self.assertEqual({k: v for k, v in google_asked.items() if k not in ("cx", "key", "alt")}, serpbit_asked)
|
|
46
|
+
|
|
47
|
+
def test_the_tools_give_the_same(self):
|
|
48
|
+
g, s = self.google(), self.serpbit()
|
|
49
|
+
for google_tool, serpbit_tool in ((GoogleSearchRun(api_wrapper=g), SerpbitSearchRun(api_wrapper=s)),
|
|
50
|
+
(GoogleSearchResults(api_wrapper=g), SerpbitSearchResults(api_wrapper=s))):
|
|
51
|
+
self.assertEqual((google_tool.name, google_tool.description), (serpbit_tool.name, serpbit_tool.description))
|
|
52
|
+
self.assertEqual(google_tool.args, serpbit_tool.args)
|
|
53
|
+
self.assertEqual(google_tool.invoke("espresso grinder"), serpbit_tool.invoke("espresso grinder"))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
if __name__ == "__main__":
|
|
57
|
+
unittest.main()
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import os
|
|
3
|
+
import unittest
|
|
4
|
+
from unittest import mock
|
|
5
|
+
|
|
6
|
+
import serpbit
|
|
7
|
+
from pydantic import ValidationError
|
|
8
|
+
|
|
9
|
+
from fake_cse import Handler, start
|
|
10
|
+
from langchain_serpbit import SerpbitSearchAPIWrapper, SerpbitSearchResults, SerpbitSearchRun
|
|
11
|
+
from langchain_serpbit.search import NO_RESULT
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SearchTest(unittest.TestCase):
|
|
15
|
+
@classmethod
|
|
16
|
+
def setUpClass(cls):
|
|
17
|
+
cls.srv, cls.base = start()
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def tearDownClass(cls):
|
|
21
|
+
cls.srv.shutdown()
|
|
22
|
+
cls.srv.server_close()
|
|
23
|
+
|
|
24
|
+
def setUp(self):
|
|
25
|
+
Handler.seen = []
|
|
26
|
+
self.search = SerpbitSearchAPIWrapper(serpbit_api_key="sb_live_test", base_url=self.base, k=3)
|
|
27
|
+
|
|
28
|
+
def test_run_joins_the_snippets_of_k_results(self):
|
|
29
|
+
self.assertEqual(self.search.run("espresso grinder"),
|
|
30
|
+
"We tested 25 grinders over six months. Burrs crush beans to one size; blades chop them unevenly.")
|
|
31
|
+
r = Handler.seen[-1]
|
|
32
|
+
self.assertEqual((r["path"], r["query"], r["auth"]),
|
|
33
|
+
("/customsearch/v1", {"q": "espresso grinder", "num": "3"}, "Bearer sb_live_test"))
|
|
34
|
+
|
|
35
|
+
def test_results_are_title_link_and_snippet_and_take_custom_searchs_parameters(self):
|
|
36
|
+
got = self.search.results("espresso grinder", 2, search_params={"gl": "de", "dateRestrict": "m1",
|
|
37
|
+
"siteSearch": "example.com"})
|
|
38
|
+
self.assertEqual(got, [
|
|
39
|
+
{"title": "The 6 Best Espresso Grinders of 2026", "link": "https://www.example.com/best-espresso-grinders",
|
|
40
|
+
"snippet": "We tested 25 grinders over six months."},
|
|
41
|
+
{"title": "Grinder buying guide", "link": "https://example.org/grinder-guide.pdf"},
|
|
42
|
+
])
|
|
43
|
+
self.assertEqual(Handler.seen[-1]["query"], {"q": "espresso grinder", "num": "2", "gl": "de", "dateRestrict": "m1",
|
|
44
|
+
"siteSearch": "example.com"})
|
|
45
|
+
|
|
46
|
+
def test_no_results_say_so_as_googles_wrapper_does(self):
|
|
47
|
+
self.assertEqual(self.search.run("nothing"), NO_RESULT)
|
|
48
|
+
self.assertEqual(self.search.results("nothing", 4), [{"Result": NO_RESULT}])
|
|
49
|
+
|
|
50
|
+
def test_a_refusal_is_the_clients_error(self):
|
|
51
|
+
with self.assertRaises(serpbit.BadRequestError) as e:
|
|
52
|
+
self.search.run("bad")
|
|
53
|
+
self.assertEqual((e.exception.status, e.exception.code), (400, "invalid"))
|
|
54
|
+
|
|
55
|
+
def test_the_key_comes_from_the_environment_or_is_asked_for(self):
|
|
56
|
+
with mock.patch.dict(os.environ, {"SERPBIT_API_KEY": "sb_env", "SERPBIT_BASE_URL": self.base}):
|
|
57
|
+
SerpbitSearchAPIWrapper().run("espresso grinder")
|
|
58
|
+
self.assertEqual(Handler.seen[-1]["auth"], "Bearer sb_env")
|
|
59
|
+
with mock.patch.dict(os.environ, {}, clear=True):
|
|
60
|
+
with self.assertRaises(ValueError) as e:
|
|
61
|
+
SerpbitSearchAPIWrapper()
|
|
62
|
+
self.assertIn("SERPBIT_API_KEY", str(e.exception))
|
|
63
|
+
self.assertNotIn("sb_live_test", repr(self.search), "the key is a secret")
|
|
64
|
+
|
|
65
|
+
def test_a_custom_search_engines_own_sites_do_not_carry_over(self):
|
|
66
|
+
with self.assertRaises(ValueError) as e:
|
|
67
|
+
SerpbitSearchAPIWrapper(serpbit_api_key="sb_live_test", siterestrict=True)
|
|
68
|
+
self.assertIn("siteSearch", str(e.exception))
|
|
69
|
+
SerpbitSearchAPIWrapper(serpbit_api_key="sb_live_test", siterestrict=False)
|
|
70
|
+
with self.assertRaises(ValidationError):
|
|
71
|
+
SerpbitSearchAPIWrapper(serpbit_api_key="sb_live_test", google_cse_id="cx")
|
|
72
|
+
|
|
73
|
+
def test_the_tools_keep_googles_names(self):
|
|
74
|
+
run = SerpbitSearchRun(api_wrapper=self.search)
|
|
75
|
+
results = SerpbitSearchResults(api_wrapper=self.search, num_results=1)
|
|
76
|
+
self.assertEqual((run.name, results.name), ("google_search", "google_search_results_json"))
|
|
77
|
+
self.assertTrue(run.invoke("espresso grinder").startswith("We tested 25 grinders"))
|
|
78
|
+
self.assertEqual(results.invoke("espresso grinder"), str([{
|
|
79
|
+
"title": "The 6 Best Espresso Grinders of 2026", "link": "https://www.example.com/best-espresso-grinders",
|
|
80
|
+
"snippet": "We tested 25 grinders over six months."}]))
|
|
81
|
+
self.assertEqual(Handler.seen[-1]["query"]["num"], "1")
|
|
82
|
+
self.assertTrue(asyncio.run(run.ainvoke("espresso grinder")).startswith("We tested 25 grinders"))
|
|
83
|
+
|
|
84
|
+
def test_a_tool_makes_its_wrapper_from_the_environment(self):
|
|
85
|
+
with mock.patch.dict(os.environ, {"SERPBIT_API_KEY": "sb_env", "SERPBIT_BASE_URL": self.base}):
|
|
86
|
+
self.assertTrue(SerpbitSearchRun().invoke("espresso grinder").startswith("We tested"))
|
|
87
|
+
self.assertIn("www.example.com", SerpbitSearchResults().invoke("espresso grinder"))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
if __name__ == "__main__":
|
|
91
|
+
unittest.main()
|