langchain-scrapingrabbit 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_scrapingrabbit-0.1.0/.github/workflows/ci.yml +27 -0
- langchain_scrapingrabbit-0.1.0/.github/workflows/publish.yml +45 -0
- langchain_scrapingrabbit-0.1.0/.gitignore +6 -0
- langchain_scrapingrabbit-0.1.0/LICENSE +21 -0
- langchain_scrapingrabbit-0.1.0/PKG-INFO +83 -0
- langchain_scrapingrabbit-0.1.0/README.md +64 -0
- langchain_scrapingrabbit-0.1.0/langchain_scrapingrabbit/__init__.py +5 -0
- langchain_scrapingrabbit-0.1.0/langchain_scrapingrabbit/document_loaders.py +32 -0
- langchain_scrapingrabbit-0.1.0/langchain_scrapingrabbit/tools.py +79 -0
- langchain_scrapingrabbit-0.1.0/pyproject.toml +27 -0
- langchain_scrapingrabbit-0.1.0/tests/test_langchain.py +99 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
permissions:
|
|
9
|
+
contents: read
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
test:
|
|
13
|
+
runs-on: ubuntu-latest
|
|
14
|
+
strategy:
|
|
15
|
+
matrix:
|
|
16
|
+
include:
|
|
17
|
+
- python: "3.10"
|
|
18
|
+
langchain-core: "langchain-core==0.3.*" # oldest supported
|
|
19
|
+
- python: "3.13"
|
|
20
|
+
langchain-core: "langchain-core" # newest
|
|
21
|
+
steps:
|
|
22
|
+
- uses: actions/checkout@v4
|
|
23
|
+
- uses: actions/setup-python@v5
|
|
24
|
+
with:
|
|
25
|
+
python-version: ${{ matrix.python }}
|
|
26
|
+
- run: python -m pip install . "${{ matrix.langchain-core }}"
|
|
27
|
+
- run: python -m unittest discover -s tests
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
# Push a version tag (for example v0.1.0 after bumping `version` in pyproject.toml) and this publishes that commit.
|
|
4
|
+
# No PyPI token is stored: PyPI trusts this workflow through "trusted publishing" (OIDC), set once on pypi.org
|
|
5
|
+
# (repo scrapingrabbit/langchain-scrapingrabbit, workflow publish.yml, environment pypi).
|
|
6
|
+
on:
|
|
7
|
+
push:
|
|
8
|
+
tags: ["v*"]
|
|
9
|
+
|
|
10
|
+
permissions:
|
|
11
|
+
contents: read
|
|
12
|
+
|
|
13
|
+
jobs:
|
|
14
|
+
build:
|
|
15
|
+
runs-on: ubuntu-latest
|
|
16
|
+
steps:
|
|
17
|
+
- uses: actions/checkout@v4
|
|
18
|
+
- uses: actions/setup-python@v5
|
|
19
|
+
with:
|
|
20
|
+
python-version: "3.12"
|
|
21
|
+
- name: Tag must match pyproject.toml
|
|
22
|
+
run: |
|
|
23
|
+
PKG="v$(python -c "import tomllib;print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")"
|
|
24
|
+
if [ "$GITHUB_REF_NAME" != "$PKG" ]; then echo "Tag $GITHUB_REF_NAME does not match pyproject.toml $PKG"; exit 1; fi
|
|
25
|
+
- run: python -m pip install build twine .
|
|
26
|
+
- run: python -m unittest discover -s tests
|
|
27
|
+
- run: python -m build
|
|
28
|
+
- run: python -m twine check --strict dist/*
|
|
29
|
+
- uses: actions/upload-artifact@v4
|
|
30
|
+
with:
|
|
31
|
+
name: dist
|
|
32
|
+
path: dist/
|
|
33
|
+
|
|
34
|
+
publish:
|
|
35
|
+
needs: build
|
|
36
|
+
runs-on: ubuntu-latest
|
|
37
|
+
environment: pypi
|
|
38
|
+
permissions:
|
|
39
|
+
id-token: write
|
|
40
|
+
steps:
|
|
41
|
+
- uses: actions/download-artifact@v4
|
|
42
|
+
with:
|
|
43
|
+
name: dist
|
|
44
|
+
path: dist/
|
|
45
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ScrapingRabbit
|
|
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,83 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: langchain-scrapingrabbit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LangChain tools and document loader for the ScrapingRabbit web data API: YouTube transcripts and comments, TikTok, Instagram, X, Amazon, Google and SEO data for agents and RAG.
|
|
5
|
+
Project-URL: Homepage, https://scrapingrabbit.com
|
|
6
|
+
Project-URL: Documentation, https://scrapingrabbit.com/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/scrapingrabbit/langchain-scrapingrabbit
|
|
8
|
+
Project-URL: Issues, https://github.com/scrapingrabbit/langchain-scrapingrabbit/issues
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: agents,document-loader,instagram,langchain,rag,scraping,seo,tiktok,tools,youtube-transcript
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Requires-Dist: langchain-core<2.0.0,>=0.3.0
|
|
17
|
+
Requires-Dist: scrapingrabbit<1.0.0,>=0.2.0
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# langchain-scrapingrabbit
|
|
21
|
+
|
|
22
|
+
LangChain tools and a document loader for the [ScrapingRabbit](https://scrapingrabbit.com) web data API: YouTube transcripts and comments, TikTok, Instagram, X, Amazon, Google and SEO data for agents and RAG pipelines.
|
|
23
|
+
|
|
24
|
+
- Every API endpoint as a LangChain tool, with typed, described arguments.
|
|
25
|
+
- API refusals come back to the agent as text it can act on, not as an exception that stops the run.
|
|
26
|
+
- You pay credits only when a call returns data. Failed calls are free.
|
|
27
|
+
- New accounts get 100 free credits and a first key, no card needed: [scrapingrabbit.com/login](https://scrapingrabbit.com/login).
|
|
28
|
+
|
|
29
|
+
## Install
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install langchain-scrapingrabbit
|
|
33
|
+
export SCRAPINGRABBIT_API_KEY=sr_live_...
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Tools for agents
|
|
37
|
+
|
|
38
|
+
The agent example also needs LangChain itself and a model package: `pip install langchain langchain-anthropic` and `export ANTHROPIC_API_KEY=...`.
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from langchain.agents import create_agent
|
|
42
|
+
from langchain_scrapingrabbit import ScrapingRabbitToolkit
|
|
43
|
+
|
|
44
|
+
tools = ScrapingRabbitToolkit(include=["youtube_transcript", "domain_age_checker"]).get_tools()
|
|
45
|
+
agent = create_agent("anthropic:claude-sonnet-5-5", tools=tools)
|
|
46
|
+
agent.invoke({"messages": [{"role": "user", "content": "Summarise https://www.youtube.com/watch?v=dQw4w9WgXcQ"}]})
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Leave out `include` to get every endpoint. Names come from `scrapingrabbit.ENDPOINTS`:
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from scrapingrabbit import ENDPOINTS
|
|
53
|
+
print([e["name"] for e in ENDPOINTS])
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Each tool returns the answer's data as JSON text, cut at 60,000 characters (change with `max_chars=`).
|
|
57
|
+
|
|
58
|
+
## YouTube transcripts as documents
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from langchain_scrapingrabbit import ScrapingRabbitYouTubeTranscriptLoader
|
|
62
|
+
|
|
63
|
+
docs = ScrapingRabbitYouTubeTranscriptLoader(["https://www.youtube.com/watch?v=dQw4w9WgXcQ"]).load()
|
|
64
|
+
docs[0].page_content # the transcript as plain text
|
|
65
|
+
docs[0].metadata # source, video_id, language, is_auto_generated
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
One credit per video that returns a transcript. A video without captions raises `scrapingrabbit.ScrapingRabbitError` with code `UPSTREAM_NOT_FOUND`.
|
|
69
|
+
|
|
70
|
+
## Also available
|
|
71
|
+
|
|
72
|
+
[Python client](https://github.com/scrapingrabbit/scrapingrabbit-python) · [Node.js client](https://github.com/scrapingrabbit/scrapingrabbit-node) · [MCP server](https://github.com/scrapingrabbit/scrapingrabbit-mcp) · [Agent skill](https://github.com/scrapingrabbit/scrapingrabbit-skills)
|
|
73
|
+
|
|
74
|
+
## Develop
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pip install -e .
|
|
78
|
+
python -m unittest discover -s tests # runs the tools against a local fake API
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## License
|
|
82
|
+
|
|
83
|
+
MIT
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# langchain-scrapingrabbit
|
|
2
|
+
|
|
3
|
+
LangChain tools and a document loader for the [ScrapingRabbit](https://scrapingrabbit.com) web data API: YouTube transcripts and comments, TikTok, Instagram, X, Amazon, Google and SEO data for agents and RAG pipelines.
|
|
4
|
+
|
|
5
|
+
- Every API endpoint as a LangChain tool, with typed, described arguments.
|
|
6
|
+
- API refusals come back to the agent as text it can act on, not as an exception that stops the run.
|
|
7
|
+
- You pay credits only when a call returns data. Failed calls are free.
|
|
8
|
+
- New accounts get 100 free credits and a first key, no card needed: [scrapingrabbit.com/login](https://scrapingrabbit.com/login).
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install langchain-scrapingrabbit
|
|
14
|
+
export SCRAPINGRABBIT_API_KEY=sr_live_...
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Tools for agents
|
|
18
|
+
|
|
19
|
+
The agent example also needs LangChain itself and a model package: `pip install langchain langchain-anthropic` and `export ANTHROPIC_API_KEY=...`.
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from langchain.agents import create_agent
|
|
23
|
+
from langchain_scrapingrabbit import ScrapingRabbitToolkit
|
|
24
|
+
|
|
25
|
+
tools = ScrapingRabbitToolkit(include=["youtube_transcript", "domain_age_checker"]).get_tools()
|
|
26
|
+
agent = create_agent("anthropic:claude-sonnet-5-5", tools=tools)
|
|
27
|
+
agent.invoke({"messages": [{"role": "user", "content": "Summarise https://www.youtube.com/watch?v=dQw4w9WgXcQ"}]})
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Leave out `include` to get every endpoint. Names come from `scrapingrabbit.ENDPOINTS`:
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
from scrapingrabbit import ENDPOINTS
|
|
34
|
+
print([e["name"] for e in ENDPOINTS])
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Each tool returns the answer's data as JSON text, cut at 60,000 characters (change with `max_chars=`).
|
|
38
|
+
|
|
39
|
+
## YouTube transcripts as documents
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from langchain_scrapingrabbit import ScrapingRabbitYouTubeTranscriptLoader
|
|
43
|
+
|
|
44
|
+
docs = ScrapingRabbitYouTubeTranscriptLoader(["https://www.youtube.com/watch?v=dQw4w9WgXcQ"]).load()
|
|
45
|
+
docs[0].page_content # the transcript as plain text
|
|
46
|
+
docs[0].metadata # source, video_id, language, is_auto_generated
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
One credit per video that returns a transcript. A video without captions raises `scrapingrabbit.ScrapingRabbitError` with code `UPSTREAM_NOT_FOUND`.
|
|
50
|
+
|
|
51
|
+
## Also available
|
|
52
|
+
|
|
53
|
+
[Python client](https://github.com/scrapingrabbit/scrapingrabbit-python) · [Node.js client](https://github.com/scrapingrabbit/scrapingrabbit-node) · [MCP server](https://github.com/scrapingrabbit/scrapingrabbit-mcp) · [Agent skill](https://github.com/scrapingrabbit/scrapingrabbit-skills)
|
|
54
|
+
|
|
55
|
+
## Develop
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pip install -e .
|
|
59
|
+
python -m unittest discover -s tests # runs the tools against a local fake API
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## License
|
|
63
|
+
|
|
64
|
+
MIT
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""LangChain tools and document loader for the ScrapingRabbit web data API."""
|
|
2
|
+
from .document_loaders import ScrapingRabbitYouTubeTranscriptLoader
|
|
3
|
+
from .tools import ScrapingRabbitToolkit, build_tool
|
|
4
|
+
|
|
5
|
+
__all__ = ["ScrapingRabbitToolkit", "ScrapingRabbitYouTubeTranscriptLoader", "build_tool"]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""YouTube transcripts as LangChain Documents, for RAG pipelines."""
|
|
2
|
+
from typing import Any, Iterator, Optional, Sequence, Union
|
|
3
|
+
|
|
4
|
+
from langchain_core.document_loaders import BaseLoader
|
|
5
|
+
from langchain_core.documents import Document
|
|
6
|
+
from scrapingrabbit import ScrapingRabbit
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ScrapingRabbitYouTubeTranscriptLoader(BaseLoader):
|
|
10
|
+
"""One Document per video: the transcript as plain text, with video id and language in the metadata.
|
|
11
|
+
|
|
12
|
+
Each video costs 1 credit when it returns a transcript; failures are free. A video without captions raises
|
|
13
|
+
scrapingrabbit.ScrapingRabbitError (code UPSTREAM_NOT_FOUND).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(self, urls: Union[str, Sequence[str]], api_key: Optional[str] = None, client: Optional[Any] = None):
|
|
17
|
+
self.urls = [urls] if isinstance(urls, str) else list(urls)
|
|
18
|
+
self._client = client or ScrapingRabbit(api_key=api_key)
|
|
19
|
+
|
|
20
|
+
def lazy_load(self) -> Iterator[Document]:
|
|
21
|
+
for url in self.urls:
|
|
22
|
+
data = self._client.youtube_transcript(url=url)
|
|
23
|
+
lines = data.get("transcript") or []
|
|
24
|
+
yield Document(
|
|
25
|
+
page_content=" ".join(line["text"] for line in lines if line.get("text")),
|
|
26
|
+
metadata={
|
|
27
|
+
"source": url,
|
|
28
|
+
"video_id": data.get("videoId"),
|
|
29
|
+
"language": data.get("language"),
|
|
30
|
+
"is_auto_generated": data.get("isAutoGenerated"),
|
|
31
|
+
},
|
|
32
|
+
)
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""One LangChain tool per ScrapingRabbit endpoint, built from the SDK's ENDPOINTS list.
|
|
2
|
+
|
|
3
|
+
A new API endpoint shows up here after `pip install -U scrapingrabbit`; nothing in this package lists endpoints by hand.
|
|
4
|
+
"""
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, Dict, List, Optional
|
|
7
|
+
|
|
8
|
+
from langchain_core.tools import BaseTool, BaseToolkit, StructuredTool, ToolException
|
|
9
|
+
from pydantic import ConfigDict, Field, create_model
|
|
10
|
+
from scrapingrabbit import ENDPOINTS, ScrapingRabbit, ScrapingRabbitError
|
|
11
|
+
|
|
12
|
+
# Long answers (a full transcript, a big search page) are cut here so one call cannot flood the model's context.
|
|
13
|
+
DEFAULT_MAX_CHARS = 60_000
|
|
14
|
+
TOOL_PREFIX = "scrapingrabbit_"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _input_model(endpoint: Dict[str, Any]) -> Any:
|
|
18
|
+
fields: Dict[str, Any] = {}
|
|
19
|
+
for param in endpoint["params"]:
|
|
20
|
+
if param["required"]:
|
|
21
|
+
fields[param["name"]] = (str, Field(..., description=param["description"]))
|
|
22
|
+
else:
|
|
23
|
+
fields[param["name"]] = (Optional[str], Field(None, description=param["description"]))
|
|
24
|
+
model_name = "".join(part.capitalize() for part in endpoint["name"].split("_")) + "Input"
|
|
25
|
+
return create_model(model_name, **fields)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _as_text(data: Any, max_chars: int) -> str:
|
|
29
|
+
text = json.dumps(data, ensure_ascii=False)
|
|
30
|
+
if len(text) > max_chars:
|
|
31
|
+
return f"{text[:max_chars]}\n[cut at {max_chars} characters]"
|
|
32
|
+
return text
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def build_tool(client: Any, endpoint: Dict[str, Any], max_chars: int = DEFAULT_MAX_CHARS) -> BaseTool:
|
|
36
|
+
"""A StructuredTool that calls one endpoint. API refusals come back to the agent as text, not as a crash."""
|
|
37
|
+
method = getattr(client, endpoint["name"])
|
|
38
|
+
|
|
39
|
+
def run(**kwargs: Any) -> str:
|
|
40
|
+
try:
|
|
41
|
+
data = method(**{name: value for name, value in kwargs.items() if value is not None})
|
|
42
|
+
except ScrapingRabbitError as error:
|
|
43
|
+
raise ToolException(f"{error.code}: {error.message} (failed calls are not charged)") from error
|
|
44
|
+
return _as_text(data, max_chars)
|
|
45
|
+
|
|
46
|
+
return StructuredTool(
|
|
47
|
+
name=TOOL_PREFIX + endpoint["name"],
|
|
48
|
+
description=endpoint["description"],
|
|
49
|
+
args_schema=_input_model(endpoint),
|
|
50
|
+
func=run,
|
|
51
|
+
handle_tool_error=True,
|
|
52
|
+
# A missing or wrong argument goes back to the model as text instead of raising in hand-written agent loops.
|
|
53
|
+
handle_validation_error=True,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ScrapingRabbitToolkit(BaseToolkit):
|
|
58
|
+
"""Every ScrapingRabbit endpoint as a LangChain tool.
|
|
59
|
+
|
|
60
|
+
`ScrapingRabbitToolkit().get_tools()` reads SCRAPINGRABBIT_API_KEY. Pass `include=["youtube_transcript", ...]`
|
|
61
|
+
(endpoint names from `scrapingrabbit.ENDPOINTS`) to give the agent only some of them.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
65
|
+
|
|
66
|
+
api_key: Optional[str] = None
|
|
67
|
+
include: Optional[List[str]] = None
|
|
68
|
+
max_chars: int = DEFAULT_MAX_CHARS
|
|
69
|
+
client: Optional[Any] = Field(default=None, description="A configured scrapingrabbit.ScrapingRabbit to reuse.")
|
|
70
|
+
|
|
71
|
+
def get_tools(self) -> List[BaseTool]:
|
|
72
|
+
known = {endpoint["name"] for endpoint in ENDPOINTS}
|
|
73
|
+
if self.include is not None:
|
|
74
|
+
unknown = sorted(set(self.include) - known)
|
|
75
|
+
if unknown:
|
|
76
|
+
raise ValueError(f"Unknown ScrapingRabbit endpoints: {', '.join(unknown)}. Valid names are in scrapingrabbit.ENDPOINTS.")
|
|
77
|
+
client = self.client or ScrapingRabbit(api_key=self.api_key)
|
|
78
|
+
chosen = [e for e in ENDPOINTS if self.include is None or e["name"] in self.include]
|
|
79
|
+
return [build_tool(client, endpoint, self.max_chars) for endpoint in chosen]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "langchain-scrapingrabbit"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "LangChain tools and document loader for the ScrapingRabbit web data API: YouTube transcripts and comments, TikTok, Instagram, X, Amazon, Google and SEO data for agents and RAG."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["langchain-core>=0.3.0,<2.0.0", "scrapingrabbit>=0.2.0,<1.0.0"]
|
|
13
|
+
keywords = ["langchain", "tools", "agents", "rag", "document-loader", "scraping", "youtube-transcript", "tiktok", "instagram", "seo"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Operating System :: OS Independent",
|
|
17
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://scrapingrabbit.com"
|
|
22
|
+
Documentation = "https://scrapingrabbit.com/docs"
|
|
23
|
+
Repository = "https://github.com/scrapingrabbit/langchain-scrapingrabbit"
|
|
24
|
+
Issues = "https://github.com/scrapingrabbit/langchain-scrapingrabbit/issues"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["langchain_scrapingrabbit"]
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Runs the tools and loader through the real scrapingrabbit client against a local HTTP server that plays the API."""
|
|
2
|
+
import json
|
|
3
|
+
import threading
|
|
4
|
+
import unittest
|
|
5
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
6
|
+
from urllib.parse import parse_qs, urlparse
|
|
7
|
+
|
|
8
|
+
from scrapingrabbit import ENDPOINTS, ScrapingRabbit
|
|
9
|
+
|
|
10
|
+
from langchain_scrapingrabbit import ScrapingRabbitToolkit, ScrapingRabbitYouTubeTranscriptLoader
|
|
11
|
+
|
|
12
|
+
REQUESTS = []
|
|
13
|
+
TRANSCRIPT = {"videoId": "abc", "language": "en", "isAutoGenerated": False, "transcript": [{"start": 0, "duration": 1, "text": "hello"}, {"start": 1, "duration": 1, "text": "world"}]}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Handler(BaseHTTPRequestHandler):
|
|
17
|
+
def do_GET(self):
|
|
18
|
+
url = urlparse(self.path)
|
|
19
|
+
REQUESTS.append({"path": url.path, "query": parse_qs(url.query), "key": self.headers.get("x-api-key")})
|
|
20
|
+
if url.path == "/v1/youtube/transcript" and parse_qs(url.query).get("url") == ["nocaptions"]:
|
|
21
|
+
status, body = 404, {"success": False, "code": "UPSTREAM_NOT_FOUND", "message": "This video has no captions"}
|
|
22
|
+
elif url.path == "/v1/youtube/transcript":
|
|
23
|
+
status, body = 200, {"success": True, "data": TRANSCRIPT}
|
|
24
|
+
else:
|
|
25
|
+
status, body = 200, {"success": True, "data": {"path": url.path, "big": "x" * 500}}
|
|
26
|
+
payload = json.dumps(body).encode()
|
|
27
|
+
self.send_response(status)
|
|
28
|
+
self.send_header("content-type", "application/json")
|
|
29
|
+
self.send_header("content-length", str(len(payload)))
|
|
30
|
+
self.end_headers()
|
|
31
|
+
self.wfile.write(payload)
|
|
32
|
+
|
|
33
|
+
def log_message(self, *args):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class LangChainTests(unittest.TestCase):
|
|
38
|
+
@classmethod
|
|
39
|
+
def setUpClass(cls):
|
|
40
|
+
cls.server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
41
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
42
|
+
cls.client = ScrapingRabbit("sr_live_testkey", base_url=f"http://127.0.0.1:{cls.server.server_port}/v1", max_retries=0)
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def tearDownClass(cls):
|
|
46
|
+
cls.server.shutdown()
|
|
47
|
+
|
|
48
|
+
def setUp(self):
|
|
49
|
+
REQUESTS.clear()
|
|
50
|
+
|
|
51
|
+
def tools(self, **kwargs):
|
|
52
|
+
return {tool.name: tool for tool in ScrapingRabbitToolkit(client=self.client, **kwargs).get_tools()}
|
|
53
|
+
|
|
54
|
+
def test_one_tool_per_endpoint_with_param_descriptions(self):
|
|
55
|
+
tools = self.tools()
|
|
56
|
+
self.assertEqual(len(tools), len(ENDPOINTS))
|
|
57
|
+
tool = tools["scrapingrabbit_youtube_comment_extractor"]
|
|
58
|
+
schema = tool.args_schema.model_json_schema()
|
|
59
|
+
self.assertEqual(schema["required"], ["url"])
|
|
60
|
+
self.assertIn("next_page_token", schema["properties"])
|
|
61
|
+
self.assertTrue(schema["properties"]["url"]["description"])
|
|
62
|
+
for name in tools:
|
|
63
|
+
self.assertLessEqual(len(name), 64) # OpenAI's tool name limit
|
|
64
|
+
|
|
65
|
+
def test_tool_call_sends_only_given_params_and_returns_json_text(self):
|
|
66
|
+
result = self.tools()["scrapingrabbit_youtube_comment_extractor"].invoke({"url": "https://youtu.be/abc"})
|
|
67
|
+
self.assertEqual(REQUESTS[0]["path"], "/v1/youtube/comments")
|
|
68
|
+
self.assertEqual(REQUESTS[0]["query"], {"url": ["https://youtu.be/abc"]})
|
|
69
|
+
self.assertEqual(REQUESTS[0]["key"], "sr_live_testkey")
|
|
70
|
+
self.assertEqual(json.loads(result)["path"], "/v1/youtube/comments")
|
|
71
|
+
|
|
72
|
+
def test_refusal_is_returned_to_the_agent_as_text(self):
|
|
73
|
+
result = self.tools()["scrapingrabbit_youtube_transcript"].invoke({"url": "nocaptions"})
|
|
74
|
+
self.assertEqual(result, "UPSTREAM_NOT_FOUND: This video has no captions (failed calls are not charged)")
|
|
75
|
+
|
|
76
|
+
def test_missing_argument_comes_back_as_text(self):
|
|
77
|
+
result = self.tools()["scrapingrabbit_youtube_transcript"].invoke({})
|
|
78
|
+
self.assertIsInstance(result, str)
|
|
79
|
+
self.assertEqual(REQUESTS, [])
|
|
80
|
+
|
|
81
|
+
def test_long_answers_are_cut(self):
|
|
82
|
+
result = self.tools(max_chars=100)["scrapingrabbit_account_credits"].invoke({})
|
|
83
|
+
self.assertTrue(result.endswith("[cut at 100 characters]"))
|
|
84
|
+
self.assertLess(len(result), 140)
|
|
85
|
+
|
|
86
|
+
def test_include_limits_tools_and_rejects_unknown_names(self):
|
|
87
|
+
self.assertEqual(list(self.tools(include=["youtube_transcript"])), ["scrapingrabbit_youtube_transcript"])
|
|
88
|
+
with self.assertRaises(ValueError):
|
|
89
|
+
self.tools(include=["no_such_endpoint"])
|
|
90
|
+
|
|
91
|
+
def test_loader_returns_one_document_per_video(self):
|
|
92
|
+
docs = ScrapingRabbitYouTubeTranscriptLoader(["https://youtu.be/abc"], client=self.client).load()
|
|
93
|
+
self.assertEqual(len(docs), 1)
|
|
94
|
+
self.assertEqual(docs[0].page_content, "hello world")
|
|
95
|
+
self.assertEqual(docs[0].metadata, {"source": "https://youtu.be/abc", "video_id": "abc", "language": "en", "is_auto_generated": False})
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
if __name__ == "__main__":
|
|
99
|
+
unittest.main()
|