langchain-huntapi 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_huntapi-0.1.0/.gitignore +14 -0
- langchain_huntapi-0.1.0/LICENSE +21 -0
- langchain_huntapi-0.1.0/PKG-INFO +83 -0
- langchain_huntapi-0.1.0/README.md +52 -0
- langchain_huntapi-0.1.0/langchain_huntapi/__init__.py +29 -0
- langchain_huntapi-0.1.0/langchain_huntapi/_client.py +202 -0
- langchain_huntapi-0.1.0/langchain_huntapi/py.typed +1 -0
- langchain_huntapi-0.1.0/langchain_huntapi/tools.py +182 -0
- langchain_huntapi-0.1.0/pyproject.toml +64 -0
- langchain_huntapi-0.1.0/tests/__init__.py +1 -0
- langchain_huntapi-0.1.0/tests/unit_tests/__init__.py +1 -0
- langchain_huntapi-0.1.0/tests/unit_tests/test_huntapi.py +192 -0
- langchain_huntapi-0.1.0/tests/unit_tests/test_standard.py +49 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 HuntAPI
|
|
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-huntapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: LangChain tools for HuntAPI: read the metadata of public videos and download them as video or audio.
|
|
5
|
+
Project-URL: Homepage, https://www.huntapi.com
|
|
6
|
+
Project-URL: Documentation, https://github.com/huntapi/langchain-huntapi#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/huntapi/langchain-huntapi
|
|
8
|
+
Project-URL: Issues, https://github.com/huntapi/langchain-huntapi/issues
|
|
9
|
+
Author-email: HuntAPI <contact@huntapi.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: agents,audio,download,huntapi,langchain,media,tiktok,tools,video,youtube
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.10
|
|
23
|
+
Requires-Dist: httpx<1,>=0.27
|
|
24
|
+
Requires-Dist: langchain-core<2,>=0.3.15
|
|
25
|
+
Provides-Extra: test
|
|
26
|
+
Requires-Dist: langchain-tests>=0.3.5; extra == 'test'
|
|
27
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'test'
|
|
28
|
+
Requires-Dist: pytest>=8.3; extra == 'test'
|
|
29
|
+
Requires-Dist: ruff<1,>=0.8; extra == 'test'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# langchain-huntapi
|
|
33
|
+
|
|
34
|
+
[LangChain](https://www.langchain.com) integration for [HuntAPI](https://www.huntapi.com): read the metadata of public videos and download them as video or audio.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install -U langchain-huntapi
|
|
40
|
+
export HUNTAPI_API_KEY="your-api-key"
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Get an API key at [app.huntapi.com](https://app.huntapi.com).
|
|
44
|
+
|
|
45
|
+
## Tools
|
|
46
|
+
|
|
47
|
+
| Class | Tool name | What it does |
|
|
48
|
+
| --- | --- | --- |
|
|
49
|
+
| `HuntAPIMediaMetadata` | `huntapi_media_metadata` | Read the metadata of a public video through HuntAPI. |
|
|
50
|
+
| `HuntAPIVideoDownload` | `huntapi_video_download` | Download a public video through HuntAPI and return the download link. |
|
|
51
|
+
| `HuntAPIAudioDownload` | `huntapi_audio_download` | Extract the audio of a public video through HuntAPI and return the download link. |
|
|
52
|
+
|
|
53
|
+
Each tool takes `api_key` (defaults to `HUNTAPI_API_KEY`), `base_url` and `timeout`, plus the settings shown in its docstring. Errors (invalid key, no credits, rate limit, timeout) come back to the model as a `ToolException` message, without the API key. Every tool has an async version.
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from langchain_huntapi import HuntAPIMediaMetadata
|
|
57
|
+
|
|
58
|
+
tool = HuntAPIMediaMetadata()
|
|
59
|
+
print(tool.invoke({"url": "https://www.youtube.com/watch?v=jNQXAC9IVRw"}))
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### In an agent
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from langchain.agents import create_agent
|
|
66
|
+
from langchain_huntapi import HuntAPIMediaMetadata, HuntAPIVideoDownload, HuntAPIAudioDownload
|
|
67
|
+
|
|
68
|
+
agent = create_agent(
|
|
69
|
+
"openai:gpt-4.1-mini", tools=[HuntAPIMediaMetadata(), HuntAPIVideoDownload(), HuntAPIAudioDownload()]
|
|
70
|
+
)
|
|
71
|
+
result = agent.invoke({"messages": [{"role": "user", "content": "..."}]})
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Development
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pip install -e ".[test]"
|
|
78
|
+
pytest tests/unit_tests
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## License
|
|
82
|
+
|
|
83
|
+
MIT
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# langchain-huntapi
|
|
2
|
+
|
|
3
|
+
[LangChain](https://www.langchain.com) integration for [HuntAPI](https://www.huntapi.com): read the metadata of public videos and download them as video or audio.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install -U langchain-huntapi
|
|
9
|
+
export HUNTAPI_API_KEY="your-api-key"
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Get an API key at [app.huntapi.com](https://app.huntapi.com).
|
|
13
|
+
|
|
14
|
+
## Tools
|
|
15
|
+
|
|
16
|
+
| Class | Tool name | What it does |
|
|
17
|
+
| --- | --- | --- |
|
|
18
|
+
| `HuntAPIMediaMetadata` | `huntapi_media_metadata` | Read the metadata of a public video through HuntAPI. |
|
|
19
|
+
| `HuntAPIVideoDownload` | `huntapi_video_download` | Download a public video through HuntAPI and return the download link. |
|
|
20
|
+
| `HuntAPIAudioDownload` | `huntapi_audio_download` | Extract the audio of a public video through HuntAPI and return the download link. |
|
|
21
|
+
|
|
22
|
+
Each tool takes `api_key` (defaults to `HUNTAPI_API_KEY`), `base_url` and `timeout`, plus the settings shown in its docstring. Errors (invalid key, no credits, rate limit, timeout) come back to the model as a `ToolException` message, without the API key. Every tool has an async version.
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from langchain_huntapi import HuntAPIMediaMetadata
|
|
26
|
+
|
|
27
|
+
tool = HuntAPIMediaMetadata()
|
|
28
|
+
print(tool.invoke({"url": "https://www.youtube.com/watch?v=jNQXAC9IVRw"}))
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### In an agent
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from langchain.agents import create_agent
|
|
35
|
+
from langchain_huntapi import HuntAPIMediaMetadata, HuntAPIVideoDownload, HuntAPIAudioDownload
|
|
36
|
+
|
|
37
|
+
agent = create_agent(
|
|
38
|
+
"openai:gpt-4.1-mini", tools=[HuntAPIMediaMetadata(), HuntAPIVideoDownload(), HuntAPIAudioDownload()]
|
|
39
|
+
)
|
|
40
|
+
result = agent.invoke({"messages": [{"role": "user", "content": "..."}]})
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Development
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install -e ".[test]"
|
|
47
|
+
pytest tests/unit_tests
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## License
|
|
51
|
+
|
|
52
|
+
MIT
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""LangChain integration for HuntAPI."""
|
|
2
|
+
|
|
3
|
+
from importlib import metadata
|
|
4
|
+
|
|
5
|
+
from langchain_huntapi._client import HuntAPIError
|
|
6
|
+
from langchain_huntapi.tools import (
|
|
7
|
+
HuntAPIAudioDownload,
|
|
8
|
+
HuntAPIAudioDownloadInput,
|
|
9
|
+
HuntAPIMediaMetadata,
|
|
10
|
+
HuntAPIMediaMetadataInput,
|
|
11
|
+
HuntAPIVideoDownload,
|
|
12
|
+
HuntAPIVideoDownloadInput,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
__version__ = metadata.version(__package__)
|
|
17
|
+
except metadata.PackageNotFoundError:
|
|
18
|
+
__version__ = ""
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"HuntAPIAudioDownload",
|
|
22
|
+
"HuntAPIAudioDownloadInput",
|
|
23
|
+
"HuntAPIError",
|
|
24
|
+
"HuntAPIMediaMetadata",
|
|
25
|
+
"HuntAPIMediaMetadataInput",
|
|
26
|
+
"HuntAPIVideoDownload",
|
|
27
|
+
"HuntAPIVideoDownloadInput",
|
|
28
|
+
"__version__",
|
|
29
|
+
]
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""HTTP client for the HuntAPI API (https://www.huntapi.com)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
from typing import Any
|
|
9
|
+
from urllib.parse import quote
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
DEFAULT_BASE_URL = "https://api.huntapi.com"
|
|
14
|
+
DEFAULT_TIMEOUT = 60.0
|
|
15
|
+
USER_AGENT = "langchain-huntapi"
|
|
16
|
+
ENV = "HUNTAPI_API_KEY"
|
|
17
|
+
|
|
18
|
+
_ERROR_DETAIL_LIMIT = 300
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class HuntAPIError(Exception):
|
|
22
|
+
"""A HuntAPI request failed. The message never contains the API key."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, status_code: int | None = None) -> None:
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
self.status_code = status_code
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def resolve_api_key(value: str | None) -> str:
|
|
30
|
+
"""Return ``value`` or ``HUNTAPI_API_KEY``, stripped. Raises if neither is set."""
|
|
31
|
+
key = (value or os.environ.get(ENV) or "").strip()
|
|
32
|
+
if not key:
|
|
33
|
+
raise HuntAPIError(f"Set {ENV} or pass api_key. Get a key at https://app.huntapi.com")
|
|
34
|
+
return key
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def required(value: Any, name: str) -> str:
|
|
38
|
+
"""Return ``value`` stripped, or raise if it is empty."""
|
|
39
|
+
text = str(value or "").strip()
|
|
40
|
+
if not text:
|
|
41
|
+
raise HuntAPIError(f"{name} is empty.")
|
|
42
|
+
return text
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def clean(values: dict[str, Any]) -> dict[str, Any]:
|
|
46
|
+
"""Drop unset values; send booleans as true/false."""
|
|
47
|
+
out: dict[str, Any] = {}
|
|
48
|
+
for key, value in values.items():
|
|
49
|
+
if value is None or value == "":
|
|
50
|
+
continue
|
|
51
|
+
out[key] = ("true" if value else "false") if isinstance(value, bool) else value
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _redact(text: str, api_key: str) -> str:
|
|
56
|
+
return text.replace(api_key, "***") if api_key else text
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _error(response: httpx.Response, api_key: str) -> HuntAPIError:
|
|
60
|
+
detail = ""
|
|
61
|
+
try:
|
|
62
|
+
body = response.json()
|
|
63
|
+
except ValueError:
|
|
64
|
+
detail = response.text.strip()
|
|
65
|
+
else:
|
|
66
|
+
if isinstance(body, dict):
|
|
67
|
+
error = body.get("error") or body.get("message") or ""
|
|
68
|
+
if isinstance(error, dict):
|
|
69
|
+
error = error.get("message") or ""
|
|
70
|
+
detail = str(error)
|
|
71
|
+
detail = _redact(detail, api_key)[:_ERROR_DETAIL_LIMIT]
|
|
72
|
+
status = response.status_code
|
|
73
|
+
# HuntAPI answers a rate limit with HTTP 401 and a "Rate limit exceeded" message.
|
|
74
|
+
if status == 429 or (status == 401 and "rate limit" in detail.lower()):
|
|
75
|
+
label = "HuntAPI rate limit exceeded"
|
|
76
|
+
elif status == 401:
|
|
77
|
+
label = "HuntAPI rejected the API key"
|
|
78
|
+
elif status == 402:
|
|
79
|
+
label = "HuntAPI account is out of credits"
|
|
80
|
+
else:
|
|
81
|
+
label = "HuntAPI API error"
|
|
82
|
+
return HuntAPIError(f"{label} (HTTP {status})" + (f": {detail}" if detail else ""), status)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _headers(api_key: str) -> dict[str, str]:
|
|
86
|
+
headers = {"Accept": "application/json", "User-Agent": USER_AGENT}
|
|
87
|
+
headers["x-api-key"] = api_key
|
|
88
|
+
return headers
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _decode(response: httpx.Response, api_key: str) -> Any:
|
|
92
|
+
if not response.is_success:
|
|
93
|
+
raise _error(response, api_key)
|
|
94
|
+
try:
|
|
95
|
+
return response.json()
|
|
96
|
+
except ValueError as exc:
|
|
97
|
+
raise HuntAPIError("HuntAPI returned a response that is not JSON.") from exc
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def request(
|
|
101
|
+
method: str,
|
|
102
|
+
path: str,
|
|
103
|
+
*,
|
|
104
|
+
params: dict[str, Any] | None = None,
|
|
105
|
+
json: dict[str, Any] | None = None,
|
|
106
|
+
api_key: str,
|
|
107
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
108
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
109
|
+
) -> Any:
|
|
110
|
+
"""Call ``path`` and return the decoded JSON body."""
|
|
111
|
+
try:
|
|
112
|
+
with httpx.Client(timeout=timeout) as client:
|
|
113
|
+
response = client.request(
|
|
114
|
+
method, f"{base_url.rstrip('/')}{path}", params=params, json=json, headers=_headers(api_key)
|
|
115
|
+
)
|
|
116
|
+
except httpx.TimeoutException as exc:
|
|
117
|
+
raise HuntAPIError(f"HuntAPI did not answer within {timeout:g} seconds.") from exc
|
|
118
|
+
except httpx.HTTPError as exc:
|
|
119
|
+
raise HuntAPIError(f"Could not reach HuntAPI: {_redact(str(exc), api_key)}") from exc
|
|
120
|
+
return _decode(response, api_key)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
async def arequest(
|
|
124
|
+
method: str,
|
|
125
|
+
path: str,
|
|
126
|
+
*,
|
|
127
|
+
params: dict[str, Any] | None = None,
|
|
128
|
+
json: dict[str, Any] | None = None,
|
|
129
|
+
api_key: str,
|
|
130
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
131
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
132
|
+
) -> Any:
|
|
133
|
+
"""Async version of :func:`request`."""
|
|
134
|
+
try:
|
|
135
|
+
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
136
|
+
response = await client.request(
|
|
137
|
+
method, f"{base_url.rstrip('/')}{path}", params=params, json=json, headers=_headers(api_key)
|
|
138
|
+
)
|
|
139
|
+
except httpx.TimeoutException as exc:
|
|
140
|
+
raise HuntAPIError(f"HuntAPI did not answer within {timeout:g} seconds.") from exc
|
|
141
|
+
except httpx.HTTPError as exc:
|
|
142
|
+
raise HuntAPIError(f"Could not reach HuntAPI: {_redact(str(exc), api_key)}") from exc
|
|
143
|
+
return _decode(response, api_key)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
JOB_WAIT = 140.0
|
|
147
|
+
POLL_EVERY = 3.0
|
|
148
|
+
_FAILED = ("Error", "NotFound", "BadRequest")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _job_result(job_id: str, job: Any) -> dict[str, Any]:
|
|
152
|
+
job = job if isinstance(job, dict) else {}
|
|
153
|
+
result = job.get("result") if isinstance(job.get("result"), dict) else {}
|
|
154
|
+
metadata = result.get("metadata") if isinstance(result.get("metadata"), dict) else {}
|
|
155
|
+
status = job.get("status")
|
|
156
|
+
out: dict[str, Any] = {"job_id": job_id, "status": status, "progress": job.get("progress")}
|
|
157
|
+
if status == "CompletedJob":
|
|
158
|
+
out["download_url"] = result.get("response")
|
|
159
|
+
out["title"] = metadata.get("title")
|
|
160
|
+
elif status in _FAILED:
|
|
161
|
+
out["error"] = job.get("error") or "private, deleted, age-restricted or unsupported content"
|
|
162
|
+
else:
|
|
163
|
+
out["note"] = "Still running: check it later with the job id."
|
|
164
|
+
return out
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _job_id(start: Any) -> str:
|
|
168
|
+
job_id = start.get("job_id") if isinstance(start, dict) else None
|
|
169
|
+
if not isinstance(job_id, str) or not job_id:
|
|
170
|
+
raise HuntAPIError("HuntAPI did not return a job id.")
|
|
171
|
+
return job_id
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def download(
|
|
175
|
+
path: str, params: dict[str, Any], *, api_key: str, base_url: str, timeout: float, wait: float = JOB_WAIT
|
|
176
|
+
) -> dict[str, Any]:
|
|
177
|
+
"""Start a download job and wait up to ``wait`` seconds for its link."""
|
|
178
|
+
job_id = _job_id(request("GET", path, params=params, api_key=api_key, base_url=base_url, timeout=timeout))
|
|
179
|
+
deadline = time.monotonic() + wait
|
|
180
|
+
while True:
|
|
181
|
+
job = request("GET", f"/v1/jobs/{quote(job_id, safe='')}", api_key=api_key, base_url=base_url, timeout=timeout)
|
|
182
|
+
status = job.get("status") if isinstance(job, dict) else None
|
|
183
|
+
if status == "CompletedJob" or status in _FAILED or time.monotonic() >= deadline:
|
|
184
|
+
return _job_result(job_id, job)
|
|
185
|
+
time.sleep(POLL_EVERY)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
async def adownload(
|
|
189
|
+
path: str, params: dict[str, Any], *, api_key: str, base_url: str, timeout: float, wait: float = JOB_WAIT
|
|
190
|
+
) -> dict[str, Any]:
|
|
191
|
+
"""Async version of :func:`download`."""
|
|
192
|
+
start = await arequest("GET", path, params=params, api_key=api_key, base_url=base_url, timeout=timeout)
|
|
193
|
+
job_id = _job_id(start)
|
|
194
|
+
deadline = time.monotonic() + wait
|
|
195
|
+
while True:
|
|
196
|
+
job = await arequest(
|
|
197
|
+
"GET", f"/v1/jobs/{quote(job_id, safe='')}", api_key=api_key, base_url=base_url, timeout=timeout
|
|
198
|
+
)
|
|
199
|
+
status = job.get("status") if isinstance(job, dict) else None
|
|
200
|
+
if status == "CompletedJob" or status in _FAILED or time.monotonic() >= deadline:
|
|
201
|
+
return _job_result(job_id, job)
|
|
202
|
+
await asyncio.sleep(POLL_EVERY)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""HuntAPI tools for LangChain agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Literal
|
|
6
|
+
|
|
7
|
+
from langchain_core.callbacks import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun
|
|
8
|
+
from langchain_core.tools import BaseTool, ToolException
|
|
9
|
+
from pydantic import BaseModel, Field, SecretStr
|
|
10
|
+
|
|
11
|
+
from langchain_huntapi import _client
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class _HuntAPITool(BaseTool):
|
|
15
|
+
"""Shared settings and request handling for the HuntAPI tools."""
|
|
16
|
+
|
|
17
|
+
handle_tool_error: bool = True
|
|
18
|
+
api_key: SecretStr | None = Field(default=None, description="HuntAPI API key. Defaults to HUNTAPI_API_KEY.")
|
|
19
|
+
base_url: str = _client.DEFAULT_BASE_URL
|
|
20
|
+
timeout: float = _client.DEFAULT_TIMEOUT
|
|
21
|
+
|
|
22
|
+
def _key(self) -> str:
|
|
23
|
+
return _client.resolve_api_key(self.api_key.get_secret_value() if self.api_key else None)
|
|
24
|
+
|
|
25
|
+
def _output(self, data: Any) -> Any:
|
|
26
|
+
return data
|
|
27
|
+
|
|
28
|
+
def _send(self, method: str, path: str, params: dict[str, Any] | None, body: dict[str, Any] | None) -> Any:
|
|
29
|
+
if method == "DOWNLOAD":
|
|
30
|
+
return _client.download(
|
|
31
|
+
path, _client.clean(params or {}), api_key=self._key(), base_url=self.base_url, timeout=self.timeout
|
|
32
|
+
)
|
|
33
|
+
return _client.request(
|
|
34
|
+
method,
|
|
35
|
+
path,
|
|
36
|
+
params=_client.clean(params) if params else None,
|
|
37
|
+
json=body,
|
|
38
|
+
api_key=self._key(),
|
|
39
|
+
base_url=self.base_url,
|
|
40
|
+
timeout=self.timeout,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
async def _asend(self, method: str, path: str, params: dict[str, Any] | None, body: dict[str, Any] | None) -> Any:
|
|
44
|
+
if method == "DOWNLOAD":
|
|
45
|
+
return await _client.adownload(
|
|
46
|
+
path, _client.clean(params or {}), api_key=self._key(), base_url=self.base_url, timeout=self.timeout
|
|
47
|
+
)
|
|
48
|
+
return await _client.arequest(
|
|
49
|
+
method,
|
|
50
|
+
path,
|
|
51
|
+
params=_client.clean(params) if params else None,
|
|
52
|
+
json=body,
|
|
53
|
+
api_key=self._key(),
|
|
54
|
+
base_url=self.base_url,
|
|
55
|
+
timeout=self.timeout,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class HuntAPIMediaMetadataInput(BaseModel):
|
|
60
|
+
"""Arguments the model can set."""
|
|
61
|
+
|
|
62
|
+
url: str = Field(default=..., description="The public video or audio URL.")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class HuntAPIMediaMetadata(_HuntAPITool):
|
|
66
|
+
"""Read the metadata of a public video through HuntAPI.
|
|
67
|
+
|
|
68
|
+
Setup:
|
|
69
|
+
.. code-block:: bash
|
|
70
|
+
|
|
71
|
+
pip install -U langchain-huntapi
|
|
72
|
+
export HUNTAPI_API_KEY="your-api-key"
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
name: str = "huntapi_media_metadata"
|
|
76
|
+
description: str = "Get the metadata of a public video or audio URL (YouTube, TikTok, Instagram, Vimeo, X, Reddit and more) without downloading it: title, channel, duration, views, likes, upload date and thumbnail. Input is the URL."
|
|
77
|
+
args_schema: type[BaseModel] = HuntAPIMediaMetadataInput
|
|
78
|
+
|
|
79
|
+
def _request(self, url: str) -> tuple[str, str, dict[str, Any] | None, dict[str, Any] | None]:
|
|
80
|
+
return "GET", "/v1/media/metadata", {"query": _client.required(url, "url")}, None
|
|
81
|
+
|
|
82
|
+
def _run(self, url: str, run_manager: CallbackManagerForToolRun | None = None) -> Any:
|
|
83
|
+
try:
|
|
84
|
+
return self._output(self._send(*self._request(url)))
|
|
85
|
+
except _client.HuntAPIError as exc:
|
|
86
|
+
raise ToolException(str(exc)) from exc
|
|
87
|
+
|
|
88
|
+
async def _arun(self, url: str, run_manager: AsyncCallbackManagerForToolRun | None = None) -> Any:
|
|
89
|
+
try:
|
|
90
|
+
return self._output(await self._asend(*self._request(url)))
|
|
91
|
+
except _client.HuntAPIError as exc:
|
|
92
|
+
raise ToolException(str(exc)) from exc
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class HuntAPIVideoDownloadInput(BaseModel):
|
|
96
|
+
"""Arguments the model can set."""
|
|
97
|
+
|
|
98
|
+
url: str = Field(default=..., description="The public video URL.")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class HuntAPIVideoDownload(_HuntAPITool):
|
|
102
|
+
"""Download a public video through HuntAPI and return the download link.
|
|
103
|
+
|
|
104
|
+
Setup:
|
|
105
|
+
.. code-block:: bash
|
|
106
|
+
|
|
107
|
+
pip install -U langchain-huntapi
|
|
108
|
+
export HUNTAPI_API_KEY="your-api-key"
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
name: str = "huntapi_video_download"
|
|
112
|
+
description: str = "Download a public video (YouTube, TikTok, Instagram, Vimeo, X, Reddit and more) and get a download link. Waits up to 140 seconds; a longer job returns its job id. Input is the URL."
|
|
113
|
+
args_schema: type[BaseModel] = HuntAPIVideoDownloadInput
|
|
114
|
+
quality: Literal["best", "1080p", "720p", "480p", "360p"] = "best"
|
|
115
|
+
"""Video quality."""
|
|
116
|
+
video_format: Literal["mp4", "webm", "mkv"] = "mp4"
|
|
117
|
+
"""Output format."""
|
|
118
|
+
|
|
119
|
+
def _request(self, url: str) -> tuple[str, str, dict[str, Any] | None, dict[str, Any] | None]:
|
|
120
|
+
return (
|
|
121
|
+
"DOWNLOAD",
|
|
122
|
+
"/v1/video/download",
|
|
123
|
+
{"query": _client.required(url, "url"), "video_quality": self.quality, "video_format": self.video_format},
|
|
124
|
+
None,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
def _run(self, url: str, run_manager: CallbackManagerForToolRun | None = None) -> Any:
|
|
128
|
+
try:
|
|
129
|
+
return self._output(self._send(*self._request(url)))
|
|
130
|
+
except _client.HuntAPIError as exc:
|
|
131
|
+
raise ToolException(str(exc)) from exc
|
|
132
|
+
|
|
133
|
+
async def _arun(self, url: str, run_manager: AsyncCallbackManagerForToolRun | None = None) -> Any:
|
|
134
|
+
try:
|
|
135
|
+
return self._output(await self._asend(*self._request(url)))
|
|
136
|
+
except _client.HuntAPIError as exc:
|
|
137
|
+
raise ToolException(str(exc)) from exc
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class HuntAPIAudioDownloadInput(BaseModel):
|
|
141
|
+
"""Arguments the model can set."""
|
|
142
|
+
|
|
143
|
+
url: str = Field(default=..., description="The public video or audio URL.")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class HuntAPIAudioDownload(_HuntAPITool):
|
|
147
|
+
"""Extract the audio of a public video through HuntAPI and return the download link.
|
|
148
|
+
|
|
149
|
+
Setup:
|
|
150
|
+
.. code-block:: bash
|
|
151
|
+
|
|
152
|
+
pip install -U langchain-huntapi
|
|
153
|
+
export HUNTAPI_API_KEY="your-api-key"
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
name: str = "huntapi_audio_download"
|
|
157
|
+
description: str = "Extract the audio of a public video or audio URL (a podcast, a talk, a song) and get a download link. Waits up to 140 seconds; a longer job returns its job id. Input is the URL."
|
|
158
|
+
args_schema: type[BaseModel] = HuntAPIAudioDownloadInput
|
|
159
|
+
audio_format: Literal["mp3", "m4a", "wav"] = "mp3"
|
|
160
|
+
"""Output format."""
|
|
161
|
+
quality: Literal["best", "320kbps", "256kbps", "128kbps"] = "best"
|
|
162
|
+
"""Audio quality."""
|
|
163
|
+
|
|
164
|
+
def _request(self, url: str) -> tuple[str, str, dict[str, Any] | None, dict[str, Any] | None]:
|
|
165
|
+
return (
|
|
166
|
+
"DOWNLOAD",
|
|
167
|
+
"/v1/audio/download",
|
|
168
|
+
{"query": _client.required(url, "url"), "audio_format": self.audio_format, "audio_quality": self.quality},
|
|
169
|
+
None,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
def _run(self, url: str, run_manager: CallbackManagerForToolRun | None = None) -> Any:
|
|
173
|
+
try:
|
|
174
|
+
return self._output(self._send(*self._request(url)))
|
|
175
|
+
except _client.HuntAPIError as exc:
|
|
176
|
+
raise ToolException(str(exc)) from exc
|
|
177
|
+
|
|
178
|
+
async def _arun(self, url: str, run_manager: AsyncCallbackManagerForToolRun | None = None) -> Any:
|
|
179
|
+
try:
|
|
180
|
+
return self._output(await self._asend(*self._request(url)))
|
|
181
|
+
except _client.HuntAPIError as exc:
|
|
182
|
+
raise ToolException(str(exc)) from exc
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.26,<2"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "langchain-huntapi"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "LangChain tools for HuntAPI: read the metadata of public videos and download them as video or audio."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "HuntAPI", email = "contact@huntapi.com" },
|
|
15
|
+
]
|
|
16
|
+
keywords = ["langchain", "huntapi", "tools", "agents", "video", "audio", "youtube", "tiktok", "media", "download"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
dependencies = [
|
|
29
|
+
"langchain-core>=0.3.15,<2",
|
|
30
|
+
"httpx>=0.27,<1",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
test = [
|
|
35
|
+
"langchain-tests>=0.3.5",
|
|
36
|
+
"pytest>=8.3",
|
|
37
|
+
"pytest-asyncio>=0.24",
|
|
38
|
+
"ruff>=0.8,<1",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://www.huntapi.com"
|
|
43
|
+
Documentation = "https://github.com/huntapi/langchain-huntapi#readme"
|
|
44
|
+
Repository = "https://github.com/huntapi/langchain-huntapi"
|
|
45
|
+
Issues = "https://github.com/huntapi/langchain-huntapi/issues"
|
|
46
|
+
|
|
47
|
+
[tool.hatch.build.targets.sdist]
|
|
48
|
+
include = ["/langchain_huntapi", "/tests", "/LICENSE", "/README.md", "/pyproject.toml"]
|
|
49
|
+
|
|
50
|
+
[tool.hatch.build.targets.wheel]
|
|
51
|
+
packages = ["langchain_huntapi"]
|
|
52
|
+
|
|
53
|
+
[tool.pytest.ini_options]
|
|
54
|
+
addopts = "-ra"
|
|
55
|
+
asyncio_mode = "auto"
|
|
56
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
57
|
+
testpaths = ["tests"]
|
|
58
|
+
|
|
59
|
+
[tool.ruff]
|
|
60
|
+
target-version = "py310"
|
|
61
|
+
line-length = 120
|
|
62
|
+
|
|
63
|
+
[tool.ruff.lint]
|
|
64
|
+
select = ["E4", "E7", "E9", "F", "I", "UP", "B"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Offline tests: every request goes through an httpx.MockTransport."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
import langchain_huntapi as pkg
|
|
12
|
+
from langchain_huntapi import _client
|
|
13
|
+
|
|
14
|
+
API_KEY = "test-huntapi-key-placeholder" # pragma: allowlist secret
|
|
15
|
+
BASE = "https://api.huntapi.com"
|
|
16
|
+
CASES = [
|
|
17
|
+
{
|
|
18
|
+
"cls": "HuntAPIMediaMetadata",
|
|
19
|
+
"config": {},
|
|
20
|
+
"sample": {"url": "https://www.youtube.com/watch?v=jNQXAC9IVRw"},
|
|
21
|
+
"method": "GET",
|
|
22
|
+
"path": "/v1/media/metadata",
|
|
23
|
+
"params": {"query": "https://www.youtube.com/watch?v=jNQXAC9IVRw"},
|
|
24
|
+
"body": None,
|
|
25
|
+
"response": {"metadata": {"title": "Me at the zoo", "duration": 19}},
|
|
26
|
+
"result": {"metadata": {"title": "Me at the zoo", "duration": 19}},
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
Handler = Callable[[httpx.Request], httpx.Response]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@pytest.fixture
|
|
34
|
+
def mock_http(monkeypatch: pytest.MonkeyPatch) -> Callable[[Handler], list[httpx.Request]]:
|
|
35
|
+
def install(handler: Handler) -> list[httpx.Request]:
|
|
36
|
+
seen: list[httpx.Request] = []
|
|
37
|
+
|
|
38
|
+
def record(request: httpx.Request) -> httpx.Response:
|
|
39
|
+
seen.append(request)
|
|
40
|
+
return handler(request)
|
|
41
|
+
|
|
42
|
+
transport = httpx.MockTransport(record)
|
|
43
|
+
real_client, real_async = httpx.Client, httpx.AsyncClient
|
|
44
|
+
monkeypatch.setattr(_client.httpx, "Client", lambda **kw: real_client(transport=transport, **kw))
|
|
45
|
+
monkeypatch.setattr(_client.httpx, "AsyncClient", lambda **kw: real_async(transport=transport, **kw))
|
|
46
|
+
return seen
|
|
47
|
+
|
|
48
|
+
return install
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _params(request: httpx.Request) -> dict[str, str]:
|
|
52
|
+
return dict(request.url.params)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _body(request: httpx.Request) -> object:
|
|
56
|
+
return json.loads(request.content) if request.content else None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@pytest.mark.parametrize("case", CASES, ids=[c["cls"] for c in CASES])
|
|
60
|
+
def test_request_and_result(mock_http, case) -> None:
|
|
61
|
+
seen = mock_http(lambda request: httpx.Response(200, json=case["response"]))
|
|
62
|
+
tool = getattr(pkg, case["cls"])(api_key=API_KEY, **case["config"])
|
|
63
|
+
|
|
64
|
+
result = tool.invoke(case["sample"])
|
|
65
|
+
|
|
66
|
+
request = seen[0]
|
|
67
|
+
assert request.method == case["method"]
|
|
68
|
+
assert request.url.copy_with(query=None) == httpx.URL(BASE + case["path"])
|
|
69
|
+
assert _params(request) == (case["params"] or {})
|
|
70
|
+
assert _body(request) == case["body"]
|
|
71
|
+
assert request.headers["x-api-key"] == API_KEY
|
|
72
|
+
expected = case["result"]
|
|
73
|
+
assert (json.loads(result) if isinstance(result, str) and not isinstance(expected, str) else result) == expected
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@pytest.mark.parametrize("case", CASES, ids=[c["cls"] for c in CASES])
|
|
77
|
+
async def test_async_matches_sync(mock_http, case) -> None:
|
|
78
|
+
mock_http(lambda request: httpx.Response(200, json=case["response"]))
|
|
79
|
+
tool = getattr(pkg, case["cls"])(api_key=API_KEY, **case["config"])
|
|
80
|
+
result = await tool.ainvoke(case["sample"])
|
|
81
|
+
expected = case["result"]
|
|
82
|
+
assert (json.loads(result) if isinstance(result, str) and not isinstance(expected, str) else result) == expected
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@pytest.mark.parametrize(
|
|
86
|
+
("status", "body", "message"),
|
|
87
|
+
[
|
|
88
|
+
(401, {"error": f"Invalid key {API_KEY}"}, "HuntAPI rejected the API key (HTTP 401): Invalid key ***"),
|
|
89
|
+
(401, {"error": "Rate limit exceeded"}, "HuntAPI rate limit exceeded (HTTP 401): Rate limit exceeded"),
|
|
90
|
+
(402, {"error": {"message": "No credits"}}, "HuntAPI account is out of credits (HTTP 402): No credits"),
|
|
91
|
+
(500, {"error": "Internal Error"}, "HuntAPI API error (HTTP 500): Internal Error"),
|
|
92
|
+
],
|
|
93
|
+
)
|
|
94
|
+
def test_errors_reach_the_model_without_the_key(mock_http, status, body, message) -> None:
|
|
95
|
+
mock_http(lambda request: httpx.Response(status, json=body))
|
|
96
|
+
tool = pkg.HuntAPIMediaMetadata(api_key=API_KEY, **{})
|
|
97
|
+
assert tool.invoke({"url": "https://www.youtube.com/watch?v=jNQXAC9IVRw"}) == message
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_network_errors(mock_http) -> None:
|
|
101
|
+
def fail(request: httpx.Request) -> httpx.Response:
|
|
102
|
+
raise httpx.ConnectError(f"failed with {API_KEY}")
|
|
103
|
+
|
|
104
|
+
mock_http(fail)
|
|
105
|
+
tool = pkg.HuntAPIMediaMetadata(api_key=API_KEY, **{})
|
|
106
|
+
assert (
|
|
107
|
+
tool.invoke({"url": "https://www.youtube.com/watch?v=jNQXAC9IVRw"})
|
|
108
|
+
== "Could not reach HuntAPI: failed with ***"
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def test_missing_key_sends_no_request(mock_http, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
113
|
+
monkeypatch.delenv("HUNTAPI_API_KEY", raising=False)
|
|
114
|
+
seen = mock_http(lambda request: httpx.Response(200, json={}))
|
|
115
|
+
result = pkg.HuntAPIMediaMetadata(**{}).invoke({"url": "https://www.youtube.com/watch?v=jNQXAC9IVRw"})
|
|
116
|
+
assert "HUNTAPI_API_KEY" in result
|
|
117
|
+
assert seen == []
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_key_from_the_environment(mock_http, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
121
|
+
monkeypatch.setenv("HUNTAPI_API_KEY", f" {API_KEY} ")
|
|
122
|
+
seen = mock_http(lambda request: httpx.Response(200, json={"metadata": {"title": "Me at the zoo", "duration": 19}}))
|
|
123
|
+
pkg.HuntAPIMediaMetadata(**{}).invoke({"url": "https://www.youtube.com/watch?v=jNQXAC9IVRw"})
|
|
124
|
+
assert seen[0].headers["x-api-key"] == API_KEY
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def test_exports() -> None:
|
|
128
|
+
for name in ["HuntAPIAudioDownload", "HuntAPIMediaMetadata", "HuntAPIVideoDownload"] + ["HuntAPIError"]:
|
|
129
|
+
assert name in pkg.__all__
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
DONE = {
|
|
133
|
+
"status": "CompletedJob",
|
|
134
|
+
"progress": 100,
|
|
135
|
+
"result": {"metadata": {"title": "Me at the zoo"}, "response": "https://s3.huntapi.com/videos/x.mp4"},
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@pytest.fixture
|
|
140
|
+
def clock(monkeypatch: pytest.MonkeyPatch) -> list[float]:
|
|
141
|
+
now = [0.0]
|
|
142
|
+
monkeypatch.setattr(_client.time, "monotonic", lambda: now[0])
|
|
143
|
+
monkeypatch.setattr(_client.time, "sleep", lambda seconds: now.__setitem__(0, now[0] + seconds))
|
|
144
|
+
|
|
145
|
+
async def fake_sleep(seconds: float) -> None:
|
|
146
|
+
now[0] += seconds
|
|
147
|
+
|
|
148
|
+
monkeypatch.setattr(_client.asyncio, "sleep", fake_sleep)
|
|
149
|
+
return now
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _jobs(*steps):
|
|
153
|
+
queue = list(steps)
|
|
154
|
+
|
|
155
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
156
|
+
return httpx.Response(200, json=queue.pop(0) if len(queue) > 1 else queue[0])
|
|
157
|
+
|
|
158
|
+
return handler
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def test_video_download_waits_for_the_link(mock_http, clock) -> None:
|
|
162
|
+
seen = mock_http(_jobs({"job_id": "j1"}, {"status": "Running", "progress": 40}, DONE))
|
|
163
|
+
out = pkg.HuntAPIVideoDownload(api_key=API_KEY, quality="720p").invoke({"url": "https://youtu.be/x"})
|
|
164
|
+
assert seen[0].url.path == "/v1/video/download"
|
|
165
|
+
assert _params(seen[0]) == {"query": "https://youtu.be/x", "video_quality": "720p", "video_format": "mp4"}
|
|
166
|
+
assert [r.url.path for r in seen[1:]] == ["/v1/jobs/j1", "/v1/jobs/j1"]
|
|
167
|
+
assert dict(out) == {
|
|
168
|
+
"job_id": "j1",
|
|
169
|
+
"status": "CompletedJob",
|
|
170
|
+
"progress": 100,
|
|
171
|
+
"download_url": "https://s3.huntapi.com/videos/x.mp4",
|
|
172
|
+
"title": "Me at the zoo",
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def test_audio_download_still_running(mock_http, clock) -> None:
|
|
177
|
+
mock_http(_jobs({"job_id": "j2"}, {"status": "Running", "progress": 10}))
|
|
178
|
+
out = dict(pkg.HuntAPIAudioDownload(api_key=API_KEY).invoke({"url": "https://youtu.be/x"}))
|
|
179
|
+
assert out["status"] == "Running" and out["job_id"] == "j2" and "note" in out
|
|
180
|
+
assert clock[0] >= 140
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def test_download_failure(mock_http, clock) -> None:
|
|
184
|
+
mock_http(_jobs({"job_id": "j3"}, {"status": "Error", "error": "Private video"}))
|
|
185
|
+
out = dict(pkg.HuntAPIAudioDownload(api_key=API_KEY).invoke({"url": "https://youtu.be/x"}))
|
|
186
|
+
assert out == {"job_id": "j3", "status": "Error", "progress": None, "error": "Private video"}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
async def test_download_async(mock_http, clock) -> None:
|
|
190
|
+
mock_http(_jobs({"job_id": "j4"}, DONE))
|
|
191
|
+
out = await pkg.HuntAPIVideoDownload(api_key=API_KEY).ainvoke({"url": "https://youtu.be/x"})
|
|
192
|
+
assert out["download_url"] == "https://s3.huntapi.com/videos/x.mp4"
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""LangChain standard unit tests for every tool."""
|
|
2
|
+
|
|
3
|
+
from langchain_tests.unit_tests import ToolsUnitTests
|
|
4
|
+
|
|
5
|
+
import langchain_huntapi as pkg
|
|
6
|
+
|
|
7
|
+
KEY = "test-huntapi-key-placeholder" # pragma: allowlist secret
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class TestHuntAPIMediaMetadataStandard(ToolsUnitTests):
|
|
11
|
+
@property
|
|
12
|
+
def tool_constructor(self) -> type:
|
|
13
|
+
return pkg.HuntAPIMediaMetadata
|
|
14
|
+
|
|
15
|
+
@property
|
|
16
|
+
def tool_constructor_params(self) -> dict:
|
|
17
|
+
return {"api_key": KEY, **{}}
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def tool_invoke_params_example(self) -> dict:
|
|
21
|
+
return {"url": "https://www.youtube.com/watch?v=jNQXAC9IVRw"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class TestHuntAPIVideoDownloadStandard(ToolsUnitTests):
|
|
25
|
+
@property
|
|
26
|
+
def tool_constructor(self) -> type:
|
|
27
|
+
return pkg.HuntAPIVideoDownload
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def tool_constructor_params(self) -> dict:
|
|
31
|
+
return {"api_key": KEY, **{}}
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def tool_invoke_params_example(self) -> dict:
|
|
35
|
+
return {"url": "https://example.com"}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class TestHuntAPIAudioDownloadStandard(ToolsUnitTests):
|
|
39
|
+
@property
|
|
40
|
+
def tool_constructor(self) -> type:
|
|
41
|
+
return pkg.HuntAPIAudioDownload
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def tool_constructor_params(self) -> dict:
|
|
45
|
+
return {"api_key": KEY, **{}}
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def tool_invoke_params_example(self) -> dict:
|
|
49
|
+
return {"url": "https://example.com"}
|