langchain-apify 0.1.0__py3-none-any.whl
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_apify/__init__.py +19 -0
- langchain_apify/const.py +2 -0
- langchain_apify/document_loaders.py +110 -0
- langchain_apify/error_messages.py +7 -0
- langchain_apify/py.typed +0 -0
- langchain_apify/tools.py +194 -0
- langchain_apify/utils.py +124 -0
- langchain_apify/wrappers.py +283 -0
- langchain_apify-0.1.0.dist-info/LICENSE +201 -0
- langchain_apify-0.1.0.dist-info/METADATA +163 -0
- langchain_apify-0.1.0.dist-info/RECORD +12 -0
- langchain_apify-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from importlib import metadata
|
|
2
|
+
|
|
3
|
+
from langchain_apify.document_loaders import ApifyDatasetLoader
|
|
4
|
+
from langchain_apify.tools import ApifyActorsTool
|
|
5
|
+
from langchain_apify.wrappers import ApifyWrapper
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = metadata.version(__package__)
|
|
9
|
+
except metadata.PackageNotFoundError:
|
|
10
|
+
# Case where package metadata is not available.
|
|
11
|
+
__version__ = ''
|
|
12
|
+
del metadata # optional, avoids polluting the results of dir(__package__)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
'ApifyActorsTool',
|
|
16
|
+
'ApifyDatasetLoader',
|
|
17
|
+
'ApifyWrapper',
|
|
18
|
+
'__version__',
|
|
19
|
+
]
|
langchain_apify/const.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any, Callable
|
|
4
|
+
|
|
5
|
+
from apify_client import ApifyClient
|
|
6
|
+
from langchain_core.document_loaders.base import BaseLoader
|
|
7
|
+
from langchain_core.documents import Document # noqa: TCH002
|
|
8
|
+
from langchain_core.utils import get_from_dict_or_env
|
|
9
|
+
from pydantic import BaseModel, ConfigDict, model_validator
|
|
10
|
+
|
|
11
|
+
from langchain_apify.utils import create_apify_client
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Iterator
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ApifyDatasetLoader(BaseLoader, BaseModel):
|
|
18
|
+
"""Load datasets from Apify web scraping, crawling, and data extraction platform.
|
|
19
|
+
|
|
20
|
+
To use, you should have the environment variable `APIFY_API_TOKEN` set
|
|
21
|
+
with your API key, or pass `apify_api_token`
|
|
22
|
+
as a named parameter to the constructor.
|
|
23
|
+
|
|
24
|
+
For details, see https://docs.apify.com/platform/integrations/langchain
|
|
25
|
+
|
|
26
|
+
Example:
|
|
27
|
+
.. code-block:: python
|
|
28
|
+
|
|
29
|
+
from langchain_apify import ApifyDatasetLoader
|
|
30
|
+
from langchain_core.documents import Document
|
|
31
|
+
|
|
32
|
+
loader = ApifyDatasetLoader(
|
|
33
|
+
dataset_id="YOUR-DATASET-ID",
|
|
34
|
+
dataset_mapping_function=lambda dataset_item: Document(
|
|
35
|
+
page_content=dataset_item["text"], metadata={"source": dataset_item["url"]}
|
|
36
|
+
),
|
|
37
|
+
)
|
|
38
|
+
documents = loader.load()
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
42
|
+
|
|
43
|
+
apify_client: ApifyClient
|
|
44
|
+
"""An instance of the ApifyClient class from the apify-client Python package."""
|
|
45
|
+
dataset_id: str
|
|
46
|
+
"""The ID of the dataset on the Apify platform."""
|
|
47
|
+
dataset_mapping_function: Callable[[dict], Document]
|
|
48
|
+
"""A custom function that takes a single dictionary (an Apify dataset item)
|
|
49
|
+
and converts it to an instance of the Document class."""
|
|
50
|
+
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
dataset_id: str,
|
|
54
|
+
dataset_mapping_function: Callable[[dict], Document],
|
|
55
|
+
apify_api_token: str | None = None,
|
|
56
|
+
) -> None:
|
|
57
|
+
"""Initialize the loader with an Apify dataset ID and a mapping function.
|
|
58
|
+
|
|
59
|
+
Args:
|
|
60
|
+
dataset_id (str): The ID of the dataset on the Apify platform.
|
|
61
|
+
dataset_mapping_function (Callable): A function that takes a single
|
|
62
|
+
dictionary (an Apify dataset item) and converts it to an instance
|
|
63
|
+
of the Document class.
|
|
64
|
+
apify_api_token (str): Apify API token.
|
|
65
|
+
"""
|
|
66
|
+
super().__init__(
|
|
67
|
+
dataset_id=dataset_id,
|
|
68
|
+
dataset_mapping_function=dataset_mapping_function,
|
|
69
|
+
apify_api_token=apify_api_token,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
@model_validator(mode='before')
|
|
73
|
+
@classmethod
|
|
74
|
+
def validate_environment(cls, values: dict) -> Any: # noqa: ANN401
|
|
75
|
+
"""Validate environment.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
values (dict): The values to validate.
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
Any: The validated values.
|
|
82
|
+
"""
|
|
83
|
+
apify_api_token = get_from_dict_or_env(values, 'apify_api_token', 'APIFY_API_TOKEN')
|
|
84
|
+
|
|
85
|
+
client = create_apify_client(ApifyClient, apify_api_token)
|
|
86
|
+
|
|
87
|
+
values['apify_client'] = client
|
|
88
|
+
|
|
89
|
+
return values
|
|
90
|
+
|
|
91
|
+
def load(self) -> list[Document]:
|
|
92
|
+
"""Load documents.
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
list[Document]: A list of mapped Document objects.
|
|
96
|
+
"""
|
|
97
|
+
dataset_items = self.apify_client.dataset(self.dataset_id).list_items(clean=True).items
|
|
98
|
+
return list(map(self.dataset_mapping_function, dataset_items))
|
|
99
|
+
|
|
100
|
+
def lazy_load(self) -> Iterator[Document]:
|
|
101
|
+
"""Lazily load documents.
|
|
102
|
+
|
|
103
|
+
Yields:
|
|
104
|
+
Document: A mapped Document object.
|
|
105
|
+
"""
|
|
106
|
+
dataset_items = self.apify_client.dataset(self.dataset_id).iterate_items(
|
|
107
|
+
clean=True,
|
|
108
|
+
)
|
|
109
|
+
for item in dataset_items:
|
|
110
|
+
yield self.dataset_mapping_function(item)
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
ERROR_APIFY_TOKEN_ENV_VAR_NOT_SET = (
|
|
2
|
+
'APIFY_API_TOKEN environment variable is not set.'
|
|
3
|
+
' Please set it to your Apify API token by using `os.environ["APIFY_API_TOKEN"] = "YOUR_APIFY_API_TOKEN"'
|
|
4
|
+
' in your code or pass it as environment variable.'
|
|
5
|
+
' To pass it as environment variable, you can use the following command:'
|
|
6
|
+
' `APIFY_API_TOKEN="YOUR_APIFY_API_TOKEN" python your_script.py`'
|
|
7
|
+
)
|
langchain_apify/py.typed
ADDED
|
File without changes
|
langchain_apify/tools.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
from typing import TYPE_CHECKING, Any, Union
|
|
6
|
+
|
|
7
|
+
from apify_client import ApifyClient
|
|
8
|
+
from langchain_core.tools import BaseTool
|
|
9
|
+
from pydantic import BaseModel, Field, create_model
|
|
10
|
+
|
|
11
|
+
from langchain_apify.error_messages import ERROR_APIFY_TOKEN_ENV_VAR_NOT_SET
|
|
12
|
+
from langchain_apify.utils import (
|
|
13
|
+
actor_id_to_tool_name,
|
|
14
|
+
create_apify_client,
|
|
15
|
+
get_actor_latest_build,
|
|
16
|
+
prune_actor_input_schema,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from .const import MAX_DESCRIPTION_LEN
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from langchain_core.callbacks import (
|
|
23
|
+
CallbackManagerForToolRun,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ApifyActorsTool(BaseTool): # type: ignore[override, override]
|
|
28
|
+
"""Tool that runs Apify Actors.
|
|
29
|
+
|
|
30
|
+
To use, you should have the environment variable `APIFY_API_TOKEN` set
|
|
31
|
+
with your API key, or pass `apify_api_token`
|
|
32
|
+
as a named parameter to the constructor.
|
|
33
|
+
|
|
34
|
+
For details, see https://docs.apify.com/platform/integrations/langchain
|
|
35
|
+
|
|
36
|
+
Example:
|
|
37
|
+
.. code-block:: python
|
|
38
|
+
|
|
39
|
+
from langchain_apify import ApifyActorsTool
|
|
40
|
+
from langgraph.prebuilt import create_react_agent
|
|
41
|
+
|
|
42
|
+
tool = ApifyActorsTool(actor_id="apify/rag-web-browser")
|
|
43
|
+
# Use the tool directly to call the Apify Actor
|
|
44
|
+
result = tool.invoke(
|
|
45
|
+
input={"run_input": {"query": "what is Apify?", "maxResults": 3}}
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# Use the tool with an agent
|
|
49
|
+
tools = [tool]
|
|
50
|
+
agent = create_react_agent(model, tools)
|
|
51
|
+
|
|
52
|
+
for chunk in agent.stream(
|
|
53
|
+
{"messages": [("human", "search for what is Apify?")]},
|
|
54
|
+
stream_mode="values"
|
|
55
|
+
):
|
|
56
|
+
chunk["messages"][-1].pretty_print()
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
actor_id: str,
|
|
62
|
+
apify_api_token: str | None = None,
|
|
63
|
+
*args: Any, # noqa: ANN401
|
|
64
|
+
**kwargs: Any, # noqa: ANN401
|
|
65
|
+
) -> None:
|
|
66
|
+
"""Initialize the tool with an Apify Actor.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
actor_id (str): Actor name from Apify store to run.
|
|
70
|
+
apify_api_token (Optional[str]): Apify API token.
|
|
71
|
+
*args: Additional arguments.
|
|
72
|
+
**kwargs: Additional keyword arguments.
|
|
73
|
+
|
|
74
|
+
Raises:
|
|
75
|
+
ValueError: If the `APIFY_API_TOKEN` environment variable is not set
|
|
76
|
+
"""
|
|
77
|
+
apify_api_token = apify_api_token or os.getenv('APIFY_API_TOKEN')
|
|
78
|
+
if not apify_api_token:
|
|
79
|
+
msg = ERROR_APIFY_TOKEN_ENV_VAR_NOT_SET
|
|
80
|
+
raise ValueError(msg)
|
|
81
|
+
|
|
82
|
+
apify_client = create_apify_client(ApifyClient, apify_api_token)
|
|
83
|
+
|
|
84
|
+
kwargs.update(
|
|
85
|
+
{
|
|
86
|
+
'name': actor_id_to_tool_name(actor_id),
|
|
87
|
+
'description': self._create_description(apify_client, actor_id),
|
|
88
|
+
'args_schema': self._build_tool_args_schema_model(
|
|
89
|
+
apify_client,
|
|
90
|
+
actor_id,
|
|
91
|
+
),
|
|
92
|
+
},
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
super().__init__(*args, **kwargs)
|
|
96
|
+
|
|
97
|
+
self._apify_client = apify_client
|
|
98
|
+
self._actor_id = actor_id
|
|
99
|
+
|
|
100
|
+
def _run(
|
|
101
|
+
self,
|
|
102
|
+
run_input: str | dict,
|
|
103
|
+
_: CallbackManagerForToolRun | None = None,
|
|
104
|
+
) -> list[dict]:
|
|
105
|
+
"""Use the Apify Actor.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
run_input (Union[str, dict]): JSON input for the Actor.
|
|
109
|
+
|
|
110
|
+
Returns:
|
|
111
|
+
list[dict]: The output dataset.
|
|
112
|
+
"""
|
|
113
|
+
input_dict = json.loads(run_input) if isinstance(run_input, str) else run_input
|
|
114
|
+
# retrieve if nested, just in case
|
|
115
|
+
input_dict = input_dict.get('run_input', input_dict)
|
|
116
|
+
return self._run_actor(input_dict)
|
|
117
|
+
|
|
118
|
+
@staticmethod
|
|
119
|
+
def _create_description(apify_client: ApifyClient, actor_id: str) -> str:
|
|
120
|
+
"""Create a description for the tool.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
apify_client (ApifyClient): Apify client instance.
|
|
124
|
+
actor_id (str): Actor name from Apify store to run.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
str: The description.
|
|
128
|
+
"""
|
|
129
|
+
build = get_actor_latest_build(apify_client, actor_id)
|
|
130
|
+
actor_description = build.get('actorDefinition', {}).get('description', '')
|
|
131
|
+
if len(actor_description) > MAX_DESCRIPTION_LEN:
|
|
132
|
+
actor_description = actor_description[:MAX_DESCRIPTION_LEN] + '...(TRUNCATED, TOO LONG)'
|
|
133
|
+
return actor_description
|
|
134
|
+
|
|
135
|
+
@staticmethod
|
|
136
|
+
def _build_tool_args_schema_model(
|
|
137
|
+
apify_client: ApifyClient,
|
|
138
|
+
actor_id: str,
|
|
139
|
+
) -> type[BaseModel]:
|
|
140
|
+
"""Build a tool class for an agent that runs the Apify Actor.
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
apify_client (ApifyClient): Apify client instance.
|
|
144
|
+
actor_id (str): Actor name from Apify store to run.
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
type[BaseModel]: The tool input model class for the Apify Actor.
|
|
148
|
+
|
|
149
|
+
Raises:
|
|
150
|
+
ValueError: If the input schema is not found in the Actor build.
|
|
151
|
+
"""
|
|
152
|
+
build = get_actor_latest_build(apify_client, actor_id)
|
|
153
|
+
if not (actor_input := build.get('actorDefinition', {}).get('input')):
|
|
154
|
+
msg = f'Input schema not found in the Actor build for Actor: {actor_id}'
|
|
155
|
+
raise ValueError(msg)
|
|
156
|
+
|
|
157
|
+
properties, required = prune_actor_input_schema(actor_input)
|
|
158
|
+
properties = {'run_input': properties}
|
|
159
|
+
|
|
160
|
+
description = (
|
|
161
|
+
"JSON encoded as a string with input schema "
|
|
162
|
+
"(STRICTLY FOLLOW JSON FORMAT AND SCHEMA):\n\n"
|
|
163
|
+
f"{json.dumps(properties, separators=(',', ':'))}"
|
|
164
|
+
"\nIF THE TOOL INPUT SCHEMA SUPPORTS IT LIMIT THE NUMBER OF RESULTS"
|
|
165
|
+
)
|
|
166
|
+
if required:
|
|
167
|
+
description += '\n\nRequired fields:\n' + '\n'.join(required)
|
|
168
|
+
|
|
169
|
+
return create_model(
|
|
170
|
+
'ApifyActorsToolInput',
|
|
171
|
+
run_input=(Union[str, dict], Field(..., description=description)),
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def _run_actor(self, run_input: dict) -> list[dict]:
|
|
175
|
+
"""Run an Apify Actor and return the output dataset.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
run_input: dict, JSON input for the Actor
|
|
179
|
+
|
|
180
|
+
Returns:
|
|
181
|
+
list[dict]: The output dataset
|
|
182
|
+
|
|
183
|
+
Raises:
|
|
184
|
+
ValueError: If the Actor was not started properly or the Run ID was not found in the run details
|
|
185
|
+
"""
|
|
186
|
+
if (details := self._apify_client.actor(actor_id=self._actor_id).call(run_input=run_input)) is None:
|
|
187
|
+
msg = f'Actor: {self._actor_id} was not started properly and details about the run were not returned'
|
|
188
|
+
raise ValueError(msg)
|
|
189
|
+
if (run_id := details.get('id')) is None:
|
|
190
|
+
msg = f'Run ID not found in the run details for Actor: {self._actor_id}'
|
|
191
|
+
raise ValueError(msg)
|
|
192
|
+
run = self._apify_client.run(run_id=run_id)
|
|
193
|
+
|
|
194
|
+
return run.dataset().list_items(clean=True).items
|
langchain_apify/utils.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import string
|
|
4
|
+
from typing import TypeVar
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
from apify_client import ApifyClientAsync
|
|
8
|
+
from apify_client.client import ApifyClient
|
|
9
|
+
|
|
10
|
+
from langchain_apify.const import MAX_DESCRIPTION_LEN, REQUESTS_TIMEOUT_SECS
|
|
11
|
+
|
|
12
|
+
APIFY_API_ENDPOINT_GET_DEFAULT_BUILD = 'https://api.apify.com/v2/acts/{actor_id}/builds/default'
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def prune_actor_input_schema(
|
|
16
|
+
input_schema: dict,
|
|
17
|
+
max_description_len: int = MAX_DESCRIPTION_LEN,
|
|
18
|
+
) -> tuple[dict, list[str]]:
|
|
19
|
+
"""Get the input schema from the Actor build.
|
|
20
|
+
|
|
21
|
+
Trim the description to 250 characters.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
input_schema (dict): The input schema from the Actor build.
|
|
25
|
+
max_description_len (int): The maximum length of the description.
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
tuple[dict, list[str]]: A tuple containing the pruned properties
|
|
29
|
+
and required fields.
|
|
30
|
+
"""
|
|
31
|
+
properties = input_schema.get('properties', {})
|
|
32
|
+
required = input_schema.get('required', [])
|
|
33
|
+
|
|
34
|
+
properties_out: dict = {}
|
|
35
|
+
for item, meta in properties.items():
|
|
36
|
+
properties_out[item] = {}
|
|
37
|
+
if desc := meta.get('description'):
|
|
38
|
+
properties_out[item]['description'] = (
|
|
39
|
+
desc[:max_description_len] + '...' if len(desc) > max_description_len else desc
|
|
40
|
+
)
|
|
41
|
+
for key_name in ('type', 'default', 'prefill', 'enum'):
|
|
42
|
+
if value := meta.get(key_name):
|
|
43
|
+
properties_out[item][key_name] = value
|
|
44
|
+
|
|
45
|
+
return properties_out, required
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
T = TypeVar('T', ApifyClient, ApifyClientAsync)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def create_apify_client(client_cls: type[T], token: str) -> T:
|
|
52
|
+
"""Create an Apify client instance with a custom user-agent.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
client_cls (ApifyClient | ApifyClientAsync): ApifyClient or ApifyClientAsync class.
|
|
56
|
+
token (str): API token.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
T: ApifyClient or ApifyClientAsync instance.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
ValueError: If the API token is not provided.
|
|
63
|
+
"""
|
|
64
|
+
if not token:
|
|
65
|
+
msg = 'API token is required to create an Apify client.'
|
|
66
|
+
raise ValueError(msg)
|
|
67
|
+
client = client_cls(token)
|
|
68
|
+
http_client_attr = 'httpx_async_client' if isinstance(client, ApifyClientAsync) else 'httpx_client'
|
|
69
|
+
if http_client := getattr(client.http_client, http_client_attr):
|
|
70
|
+
http_client.headers['user-agent'] += '; Origin/langchain'
|
|
71
|
+
return client
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def actor_id_to_tool_name(actor_id: str) -> str:
|
|
75
|
+
"""Turn actor_id into a valid tool name.
|
|
76
|
+
|
|
77
|
+
Tool name must only contain letters, numbers, underscores, dashes,
|
|
78
|
+
and cannot contain spaces.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
actor_id (str): Actor ID from Apify store.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
str: A valid tool name.
|
|
85
|
+
"""
|
|
86
|
+
valid_chars = string.ascii_letters + string.digits + '_-'
|
|
87
|
+
return 'apify_actor_' + ''.join(char if char in valid_chars else '_' for char in actor_id)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def get_actor_latest_build(apify_client: ApifyClient, actor_id: str) -> dict:
|
|
91
|
+
"""Get the latest build of an Actor from the default build tag.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
apify_client (ApifyClient): An instance of the ApifyClient class.
|
|
95
|
+
actor_id (str): Actor name from Apify store to run.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
dict: The latest build of the Actor.
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
ValueError: If the Actor is not found or the build data is not found.
|
|
102
|
+
TypeError: If the build is not a dictionary.
|
|
103
|
+
"""
|
|
104
|
+
if not (actor := apify_client.actor(actor_id).get()):
|
|
105
|
+
msg = f'Actor {actor_id} not found.'
|
|
106
|
+
raise ValueError(msg)
|
|
107
|
+
|
|
108
|
+
if not (actor_obj_id := actor.get('id')):
|
|
109
|
+
msg = f'Failed to get the Actor object ID for {actor_id}.'
|
|
110
|
+
raise ValueError(msg)
|
|
111
|
+
|
|
112
|
+
url = APIFY_API_ENDPOINT_GET_DEFAULT_BUILD.format(actor_id=actor_obj_id)
|
|
113
|
+
response = requests.request('GET', url, timeout=REQUESTS_TIMEOUT_SECS)
|
|
114
|
+
|
|
115
|
+
build = response.json()
|
|
116
|
+
if not isinstance(build, dict):
|
|
117
|
+
msg = f'Failed to get the latest build of the Actor {actor_id}.'
|
|
118
|
+
raise TypeError(msg)
|
|
119
|
+
|
|
120
|
+
if (data := build.get('data')) is None:
|
|
121
|
+
msg = f'Failed to get the latest build data of the Actor {actor_id}.'
|
|
122
|
+
raise ValueError(msg)
|
|
123
|
+
|
|
124
|
+
return data
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any, Callable
|
|
4
|
+
|
|
5
|
+
from apify_client import ApifyClient, ApifyClientAsync
|
|
6
|
+
from langchain_core.utils import get_from_dict_or_env
|
|
7
|
+
from pydantic import BaseModel, ConfigDict, model_validator
|
|
8
|
+
|
|
9
|
+
from langchain_apify.document_loaders import ApifyDatasetLoader
|
|
10
|
+
from langchain_apify.utils import create_apify_client
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from langchain_core.documents import Document
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ApifyWrapper(BaseModel):
|
|
17
|
+
"""Wrapper around Apify client for LangChain.
|
|
18
|
+
|
|
19
|
+
To use, you should have the environment variable `APIFY_API_TOKEN` set
|
|
20
|
+
with your API key, or pass `apify_api_token`
|
|
21
|
+
as a named parameter to the constructor.
|
|
22
|
+
|
|
23
|
+
For details, see https://docs.apify.com/platform/integrations/langchain
|
|
24
|
+
|
|
25
|
+
Example:
|
|
26
|
+
.. code-block:: python
|
|
27
|
+
|
|
28
|
+
from langchain_apify import ApifyWrapper
|
|
29
|
+
from langchain_core.documents import Document
|
|
30
|
+
|
|
31
|
+
apify = ApifyWrapper()
|
|
32
|
+
|
|
33
|
+
loader = apify.call_actor(
|
|
34
|
+
actor_id="apify/website-content-crawler",
|
|
35
|
+
run_input={
|
|
36
|
+
"startUrls": [
|
|
37
|
+
{"url": "https://python.langchain.com/docs/introduction/"}
|
|
38
|
+
],
|
|
39
|
+
"maxCrawlPages": 10,
|
|
40
|
+
"crawlerType": "cheerio"
|
|
41
|
+
},
|
|
42
|
+
dataset_mapping_function=lambda item: Document(
|
|
43
|
+
page_content=item["text"] or "",
|
|
44
|
+
metadata={"source": item["url"]}
|
|
45
|
+
),
|
|
46
|
+
)
|
|
47
|
+
documents = loader.load()
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
# allow arbitrary types in the model config for the apify client fields
|
|
51
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
52
|
+
|
|
53
|
+
apify_client: ApifyClient
|
|
54
|
+
apify_client_async: ApifyClientAsync
|
|
55
|
+
apify_api_token: str | None = None
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
apify_api_token: str | None = None,
|
|
60
|
+
*args: Any, # noqa: ANN401
|
|
61
|
+
**kwargs: Any, # noqa: ANN401
|
|
62
|
+
) -> None:
|
|
63
|
+
"""Initialize the loader with an Apify dataset ID and a mapping function.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
dataset_id (str): The ID of the dataset on the Apify platform.
|
|
67
|
+
dataset_mapping_function (Callable): A function that takes a single
|
|
68
|
+
dictionary (an Apify dataset item) and converts it to an instance
|
|
69
|
+
of the Document class.
|
|
70
|
+
apify_api_token (Optional[str]): Apify API token.
|
|
71
|
+
*args: Any: Additional positional arguments.
|
|
72
|
+
**kwargs: Any: Additional keyword arguments.
|
|
73
|
+
"""
|
|
74
|
+
kwargs.update({'apify_api_token': apify_api_token})
|
|
75
|
+
super().__init__(*args, **kwargs)
|
|
76
|
+
|
|
77
|
+
@model_validator(mode='before')
|
|
78
|
+
@classmethod
|
|
79
|
+
def validate_environment(cls, values: dict) -> Any: # noqa: ANN401
|
|
80
|
+
"""Validate environment.
|
|
81
|
+
|
|
82
|
+
Validate that an Apify API token is set and the apify-client
|
|
83
|
+
Python package exists in the current environment.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
Any: The validated values.
|
|
87
|
+
"""
|
|
88
|
+
apify_api_token = get_from_dict_or_env(values, 'apify_api_token', 'APIFY_API_TOKEN')
|
|
89
|
+
|
|
90
|
+
values['apify_client'] = create_apify_client(ApifyClient, apify_api_token)
|
|
91
|
+
values['apify_client_async'] = create_apify_client(ApifyClientAsync, apify_api_token)
|
|
92
|
+
|
|
93
|
+
return values
|
|
94
|
+
|
|
95
|
+
def call_actor( # noqa: PLR0913
|
|
96
|
+
self,
|
|
97
|
+
actor_id: str,
|
|
98
|
+
run_input: dict,
|
|
99
|
+
dataset_mapping_function: Callable[[dict], Document],
|
|
100
|
+
*,
|
|
101
|
+
build: str | None = None,
|
|
102
|
+
memory_mbytes: int | None = None,
|
|
103
|
+
timeout_secs: int | None = None,
|
|
104
|
+
) -> ApifyDatasetLoader:
|
|
105
|
+
"""Run an Actor on the Apify platform and wait for results to be ready.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
actor_id (str): The ID or name of the Actor on the Apify platform.
|
|
109
|
+
run_input (Dict): The input object of the Actor that you're trying to run.
|
|
110
|
+
dataset_mapping_function (Callable): A function that takes a single
|
|
111
|
+
dictionary (an Apify dataset item) and converts it to an
|
|
112
|
+
instance of the Document class.
|
|
113
|
+
build (str, optional): Optionally specifies the actor build to run.
|
|
114
|
+
It can be either a build tag or build number.
|
|
115
|
+
memory_mbytes (int, optional): Optional memory limit for the run,
|
|
116
|
+
in megabytes.
|
|
117
|
+
timeout_secs (int, optional): Optional timeout for the run, in seconds.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
ApifyDatasetLoader: A loader that will fetch the records from the
|
|
121
|
+
Actor run's default dataset.
|
|
122
|
+
|
|
123
|
+
Raises:
|
|
124
|
+
RuntimeError: If the Actor call fails.
|
|
125
|
+
"""
|
|
126
|
+
if (
|
|
127
|
+
actor_call := self.apify_client.actor(actor_id).call(
|
|
128
|
+
run_input=run_input,
|
|
129
|
+
build=build,
|
|
130
|
+
memory_mbytes=memory_mbytes,
|
|
131
|
+
timeout_secs=timeout_secs,
|
|
132
|
+
)
|
|
133
|
+
) is None:
|
|
134
|
+
msg = f'Failed to call Actor {actor_id}.'
|
|
135
|
+
raise RuntimeError(msg)
|
|
136
|
+
|
|
137
|
+
return ApifyDatasetLoader(
|
|
138
|
+
dataset_id=actor_call['defaultDatasetId'],
|
|
139
|
+
dataset_mapping_function=dataset_mapping_function,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
async def acall_actor( # noqa: PLR0913
|
|
143
|
+
self,
|
|
144
|
+
actor_id: str,
|
|
145
|
+
run_input: dict,
|
|
146
|
+
dataset_mapping_function: Callable[[dict], Document],
|
|
147
|
+
*,
|
|
148
|
+
build: str | None = None,
|
|
149
|
+
memory_mbytes: int | None = None,
|
|
150
|
+
timeout_secs: int | None = None,
|
|
151
|
+
) -> ApifyDatasetLoader:
|
|
152
|
+
"""Run an Actor on the Apify platform and wait for results to be ready.
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
actor_id (str): The ID or name of the Actor on the Apify platform.
|
|
156
|
+
run_input (Dict): The input object of the Actor that you're trying to run.
|
|
157
|
+
dataset_mapping_function (Callable): A function that takes a single
|
|
158
|
+
dictionary (an Apify dataset item) and converts it to
|
|
159
|
+
an instance of the Document class.
|
|
160
|
+
build (str, optional): Optionally specifies the actor build to run.
|
|
161
|
+
It can be either a build tag or build number.
|
|
162
|
+
memory_mbytes (int, optional): Optional memory limit for the run,
|
|
163
|
+
in megabytes.
|
|
164
|
+
timeout_secs (int, optional): Optional timeout for the run, in seconds.
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
ApifyDatasetLoader: A loader that will fetch the records from the
|
|
168
|
+
Actor run's default dataset.
|
|
169
|
+
|
|
170
|
+
Raises:
|
|
171
|
+
RuntimeError: If the Actor call fails.
|
|
172
|
+
"""
|
|
173
|
+
if (
|
|
174
|
+
actor_call := await self.apify_client_async.actor(actor_id).call(
|
|
175
|
+
run_input=run_input,
|
|
176
|
+
build=build,
|
|
177
|
+
memory_mbytes=memory_mbytes,
|
|
178
|
+
timeout_secs=timeout_secs,
|
|
179
|
+
)
|
|
180
|
+
) is None:
|
|
181
|
+
msg = f'Failed to call Actor {actor_id}.'
|
|
182
|
+
raise RuntimeError(msg)
|
|
183
|
+
|
|
184
|
+
return ApifyDatasetLoader(
|
|
185
|
+
dataset_id=actor_call['defaultDatasetId'],
|
|
186
|
+
dataset_mapping_function=dataset_mapping_function,
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
def call_actor_task( # noqa: PLR0913
|
|
190
|
+
self,
|
|
191
|
+
task_id: str,
|
|
192
|
+
task_input: dict,
|
|
193
|
+
dataset_mapping_function: Callable[[dict], Document],
|
|
194
|
+
*,
|
|
195
|
+
build: str | None = None,
|
|
196
|
+
memory_mbytes: int | None = None,
|
|
197
|
+
timeout_secs: int | None = None,
|
|
198
|
+
) -> ApifyDatasetLoader:
|
|
199
|
+
"""Run a saved Actor task on Apify and wait for results to be ready.
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
task_id (str): The ID or name of the task on the Apify platform.
|
|
203
|
+
task_input (Dict): The input object of the task that you're trying to run.
|
|
204
|
+
Overrides the task's saved input.
|
|
205
|
+
dataset_mapping_function (Callable): A function that takes a single
|
|
206
|
+
dictionary (an Apify dataset item) and converts it to an
|
|
207
|
+
instance of the Document class.
|
|
208
|
+
build (str, optional): Optionally specifies the actor build to run.
|
|
209
|
+
It can be either a build tag or build number.
|
|
210
|
+
memory_mbytes (int, optional): Optional memory limit for the run,
|
|
211
|
+
in megabytes.
|
|
212
|
+
timeout_secs (int, optional): Optional timeout for the run, in seconds.
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
ApifyDatasetLoader: A loader that will fetch the records from the
|
|
216
|
+
task run's default dataset.
|
|
217
|
+
|
|
218
|
+
Raises:
|
|
219
|
+
RuntimeError: If the task call fails.
|
|
220
|
+
"""
|
|
221
|
+
if (
|
|
222
|
+
task_call := self.apify_client.task(task_id).call(
|
|
223
|
+
task_input=task_input,
|
|
224
|
+
build=build,
|
|
225
|
+
memory_mbytes=memory_mbytes,
|
|
226
|
+
timeout_secs=timeout_secs,
|
|
227
|
+
)
|
|
228
|
+
) is None:
|
|
229
|
+
msg = f'Failed to call task {task_id}.'
|
|
230
|
+
raise RuntimeError(msg)
|
|
231
|
+
|
|
232
|
+
return ApifyDatasetLoader(
|
|
233
|
+
dataset_id=task_call['defaultDatasetId'],
|
|
234
|
+
dataset_mapping_function=dataset_mapping_function,
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
async def acall_actor_task( # noqa: PLR0913
|
|
238
|
+
self,
|
|
239
|
+
task_id: str,
|
|
240
|
+
task_input: dict,
|
|
241
|
+
dataset_mapping_function: Callable[[dict], Document],
|
|
242
|
+
*,
|
|
243
|
+
build: str | None = None,
|
|
244
|
+
memory_mbytes: int | None = None,
|
|
245
|
+
timeout_secs: int | None = None,
|
|
246
|
+
) -> ApifyDatasetLoader:
|
|
247
|
+
"""Run a saved Actor task on Apify and wait for results to be ready.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
task_id (str): The ID or name of the task on the Apify platform.
|
|
251
|
+
task_input (Dict): The input object of the task that you're trying to run.
|
|
252
|
+
Overrides the task's saved input.
|
|
253
|
+
dataset_mapping_function (Callable): A function that takes a single
|
|
254
|
+
dictionary (an Apify dataset item) and converts it to an
|
|
255
|
+
instance of the Document class.
|
|
256
|
+
build (str, optional): Optionally specifies the actor build to run.
|
|
257
|
+
It can be either a build tag or build number.
|
|
258
|
+
memory_mbytes (int, optional): Optional memory limit for the run,
|
|
259
|
+
in megabytes.
|
|
260
|
+
timeout_secs (int, optional): Optional timeout for the run, in seconds.
|
|
261
|
+
|
|
262
|
+
Returns:
|
|
263
|
+
ApifyDatasetLoader: A loader that will fetch the records from the
|
|
264
|
+
task run's default dataset.
|
|
265
|
+
|
|
266
|
+
Raises:
|
|
267
|
+
RuntimeError: If the task call fails.
|
|
268
|
+
"""
|
|
269
|
+
if (
|
|
270
|
+
task_call := await self.apify_client_async.task(task_id).call(
|
|
271
|
+
task_input=task_input,
|
|
272
|
+
build=build,
|
|
273
|
+
memory_mbytes=memory_mbytes,
|
|
274
|
+
timeout_secs=timeout_secs,
|
|
275
|
+
)
|
|
276
|
+
) is None:
|
|
277
|
+
msg = f'Failed to call task {task_id}.'
|
|
278
|
+
raise RuntimeError(msg)
|
|
279
|
+
|
|
280
|
+
return ApifyDatasetLoader(
|
|
281
|
+
dataset_id=task_call['defaultDatasetId'],
|
|
282
|
+
dataset_mapping_function=dataset_mapping_function,
|
|
283
|
+
)
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2025 Apify Technologies s.r.o.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: langchain-apify
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: An integration package connecting Apify and LangChain
|
|
5
|
+
License: Apache-2.0
|
|
6
|
+
Author: Apify Technologies s.r.o.
|
|
7
|
+
Author-email: support@apify.com
|
|
8
|
+
Requires-Python: >=3.9,<4.0
|
|
9
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Requires-Dist: apify-client (>=1.8.1,<2.0.0)
|
|
17
|
+
Requires-Dist: eval-type-backport (>=0.2.2,<0.3.0)
|
|
18
|
+
Requires-Dist: langchain-core (>=0.3.15,<0.4.0)
|
|
19
|
+
Project-URL: Apify Homepage, https://apify.com
|
|
20
|
+
Project-URL: Issue Tracker, https://github.com/apify/langchain-apify/issues
|
|
21
|
+
Project-URL: Repository, https://github.com/apify/langchain-apify
|
|
22
|
+
Project-URL: Release Notes, https://github.com/apify/langchain-apify/releases?expanded=true
|
|
23
|
+
Project-URL: Source Code, https://github.com/apify/langchain-apify/tree/main/
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
<div align="center">
|
|
27
|
+
|
|
28
|
+
<picture>
|
|
29
|
+
<img alt="Apify logo" src="/docs/logo_apify.svg" width="20%" height="20%">
|
|
30
|
+
</picture>
|
|
31
|
+
|
|
32
|
+
LangChain Apify: Full-stack web scraping and data extraction platform enhanced with AI capabilities. Maintained by [Apify](https://apify.com).
|
|
33
|
+
|
|
34
|
+
<h3>
|
|
35
|
+
|
|
36
|
+
[Apify](https://apify.com) | [Documentation](https://docs.apify.org/) | [LangChain](https://langchain.com)
|
|
37
|
+
|
|
38
|
+
</h3>
|
|
39
|
+
|
|
40
|
+
[](https://github.com/apify/langchain-apify/stargazers)
|
|
41
|
+
[](https://github.com/apify/langchain-apify/actions/workflows/run_code_checks.yml/badge.svg)
|
|
42
|
+
|
|
43
|
+
</div>
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
This package allows you to use Apify, a platform for web scraping and data extraction, with LangChain. It provides tools to interact with Apify Actors, datasets, and API.
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install langchain-apify
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Prerequisites
|
|
56
|
+
|
|
57
|
+
You should configure credentials by setting the following environment variables:
|
|
58
|
+
- `APIFY_API_TOKEN` - Apify API token
|
|
59
|
+
|
|
60
|
+
Register your free Apify account [here](https://console.apify.com/sign-up) and learn how to get your API token in the [Apify documentation](https://docs.apify.com/platform/integrations/api).
|
|
61
|
+
|
|
62
|
+
## Tools
|
|
63
|
+
|
|
64
|
+
`ApifyActorsTool` class provides access to [Apify Actors](https://apify.com/store), which are cloud-based web scraping and automation programs that you can run without managing any infrastructure. For more detailed information, see the [Apify Actors documentation](https://docs.apify.com/platform/actors).
|
|
65
|
+
|
|
66
|
+
`ApifyActorsTool` is useful when you need to run an Apify Actor as a tool in LangChain. You can use the tool to interact with the Actor manually or as part of an agent workflow.
|
|
67
|
+
|
|
68
|
+
Example usage of `ApifyActorsTool` with the [RAG Web Browser](https://apify.com/apify/rag-web-browser) Actor, which searches for information on the web:
|
|
69
|
+
```python
|
|
70
|
+
import os
|
|
71
|
+
import json
|
|
72
|
+
from langchain_apify import ApifyActorsTool
|
|
73
|
+
|
|
74
|
+
os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"
|
|
75
|
+
os.environ["APIFY_API_TOKEN"] = "YOUR_APIFY_API_TOKEN"
|
|
76
|
+
|
|
77
|
+
browser = ApifyActorsTool('apify/rag-web-browser')
|
|
78
|
+
search_results = browser.invoke(input={
|
|
79
|
+
"run_input": {"query": "what is Apify Actor?", "maxResults": 3}
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
# use the tool with an agent
|
|
83
|
+
from langchain_openai import ChatOpenAI
|
|
84
|
+
from langgraph.prebuilt import create_react_agent
|
|
85
|
+
|
|
86
|
+
model = ChatOpenAI(model="gpt-4o-mini")
|
|
87
|
+
tools = [browser]
|
|
88
|
+
agent = create_react_agent(model, tools)
|
|
89
|
+
|
|
90
|
+
for chunk in agent.stream(
|
|
91
|
+
{"messages": [("human", "search for what is Apify?")]},
|
|
92
|
+
stream_mode="values"
|
|
93
|
+
):
|
|
94
|
+
chunk["messages"][-1].pretty_print()
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Document loaders
|
|
98
|
+
|
|
99
|
+
`ApifyDatasetLoader` class provides access to [Apify datasets](https://docs.apify.com/platform/storage/dataset) as document loaders. Datasets are storage solutions that store results from web scraping, crawling, or data processing.
|
|
100
|
+
|
|
101
|
+
`ApifyDatasetLoader` is useful when you need to process data from an Apify Actor run. If you are extracting webpage content, you would typically use this loader after running an Apify Actor manually from the [Apify console](https://console.apify.com), where you can access the results stored in the dataset.
|
|
102
|
+
|
|
103
|
+
Example usage for `ApifyDatasetLoader` with a custom dataset mapping function for loading webpage content and source URLs as a list of `Document` objects containing the page content and source URL.
|
|
104
|
+
```python
|
|
105
|
+
import os
|
|
106
|
+
from langchain_apify import ApifyDatasetLoader
|
|
107
|
+
|
|
108
|
+
os.environ["APIFY_API_TOKEN"] = "YOUR_APIFY_API_TOKEN"
|
|
109
|
+
|
|
110
|
+
# Example dataset structure
|
|
111
|
+
# [
|
|
112
|
+
# {
|
|
113
|
+
# "text": "Example text from the website.",
|
|
114
|
+
# "url": "http://example.com"
|
|
115
|
+
# },
|
|
116
|
+
# ...
|
|
117
|
+
# ]
|
|
118
|
+
|
|
119
|
+
loader = ApifyDatasetLoader(
|
|
120
|
+
dataset_id="your-dataset-id",
|
|
121
|
+
dataset_mapping_function=lambda dataset_item: Document(
|
|
122
|
+
page_content=dataset_item["text"],
|
|
123
|
+
metadata={"source": dataset_item["url"]}
|
|
124
|
+
),
|
|
125
|
+
)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Wrappers
|
|
129
|
+
|
|
130
|
+
`ApifyWrapper` class wraps the Apify API to easily convert Apify datasets into documents. It is useful when you need to run an Apify Actor programmatically and process the results in LangChain. Available methods include:
|
|
131
|
+
|
|
132
|
+
- **call_actor**: Runs an Apify Actor and returns an `ApifyDatasetLoader` for the results.
|
|
133
|
+
- **acall_actor**: Asynchronous version of `call_actor`.
|
|
134
|
+
- **call_actor_task**: Runs a saved Actor task and returns an `ApifyDatasetLoader` for the results. Actor tasks allow you to create and reuse multiple configurations of a single Actor for different use cases.
|
|
135
|
+
- **acall_actor_task**: Asynchronous version of `call_actor_task`.
|
|
136
|
+
|
|
137
|
+
For more information, see the [Apify LangChain integration documentation](https://docs.apify.com/platform/integrations/langchain).
|
|
138
|
+
|
|
139
|
+
Example usage for `call_actor` involves running the [Website Content Crawler](https://apify.com/apify/website-content-crawler) Actor, which extracts content from webpages. The wrapper then returns the results as a list of `Document` objects containing the page content and source URL:
|
|
140
|
+
```python
|
|
141
|
+
import os
|
|
142
|
+
from langchain_apify import ApifyWrapper
|
|
143
|
+
from langchain_core.documents import Document
|
|
144
|
+
|
|
145
|
+
os.environ["APIFY_API_TOKEN"] = "YOUR_APIFY_API_TOKEN"
|
|
146
|
+
|
|
147
|
+
apify = ApifyWrapper()
|
|
148
|
+
|
|
149
|
+
loader = apify.call_actor(
|
|
150
|
+
actor_id="apify/website-content-crawler",
|
|
151
|
+
run_input={
|
|
152
|
+
"startUrls": [{"url": "https://python.langchain.com/docs/get_started/introduction"}],
|
|
153
|
+
"maxCrawlPages": 10,
|
|
154
|
+
"crawlerType": "cheerio"
|
|
155
|
+
},
|
|
156
|
+
dataset_mapping_function=lambda item: Document(
|
|
157
|
+
page_content=item["text"] or "",
|
|
158
|
+
metadata={"source": item["url"]}
|
|
159
|
+
),
|
|
160
|
+
)
|
|
161
|
+
documents = loader.load()
|
|
162
|
+
```
|
|
163
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
langchain_apify/__init__.py,sha256=OB-V6J7UtbiFyqTg_etX62Oh0olrShFrD6NsDh09lCo,539
|
|
2
|
+
langchain_apify/const.py,sha256=loqP7Jis39etKlESFrEvLd6OAjkFKassiDW4GQiFVlU,67
|
|
3
|
+
langchain_apify/document_loaders.py,sha256=SPq7UAdCvuK5OyzT7yrSH-5J9tFB8tMxLFjHLXY0lik,3810
|
|
4
|
+
langchain_apify/error_messages.py,sha256=gypXOQJpsMNvO5c2BJ189vxEWE2A23HGQ6qPFEbXeJ8,409
|
|
5
|
+
langchain_apify/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
langchain_apify/tools.py,sha256=zqEic_ogoCaq1K4RhMACOnDqdwy8QWVXW-45coQ-KfE,6700
|
|
7
|
+
langchain_apify/utils.py,sha256=9CU7dKuNDuxgM1GPW2KAq8FGVJ5eSrrpFyb5hGt2JRQ,4083
|
|
8
|
+
langchain_apify/wrappers.py,sha256=ZJhMVIZ38JoXXtBaIS57Z9xA7I2Sqw71NeKbdkplV-o,10864
|
|
9
|
+
langchain_apify-0.1.0.dist-info/LICENSE,sha256=S-WaqybGCIxP-QnIdbFtAostgl1dlA4iRMaV0SptDEQ,11355
|
|
10
|
+
langchain_apify-0.1.0.dist-info/METADATA,sha256=NyNc3o-EyEIjikvPlBAVBbJ1d4zMnrpGw1s8kugSH2U,6770
|
|
11
|
+
langchain_apify-0.1.0.dist-info/WHEEL,sha256=IYZQI976HJqqOpQU6PHkJ8fb3tMNBFjg-Cn-pwAbaFM,88
|
|
12
|
+
langchain_apify-0.1.0.dist-info/RECORD,,
|