langchain-apify 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.
@@ -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
+ [![GitHub Repo stars](https://img.shields.io/github/stars/apify/langchain-apify)](https://github.com/apify/langchain-apify/stargazers)
41
+ [![Tests](https://github.com/apify/langchain-apify/actions/workflows/run_code_checks.yml/badge.svg)](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,137 @@
1
+ <div align="center">
2
+
3
+ <picture>
4
+ <img alt="Apify logo" src="/docs/logo_apify.svg" width="20%" height="20%">
5
+ </picture>
6
+
7
+ LangChain Apify: Full-stack web scraping and data extraction platform enhanced with AI capabilities. Maintained by [Apify](https://apify.com).
8
+
9
+ <h3>
10
+
11
+ [Apify](https://apify.com) | [Documentation](https://docs.apify.org/) | [LangChain](https://langchain.com)
12
+
13
+ </h3>
14
+
15
+ [![GitHub Repo stars](https://img.shields.io/github/stars/apify/langchain-apify)](https://github.com/apify/langchain-apify/stargazers)
16
+ [![Tests](https://github.com/apify/langchain-apify/actions/workflows/run_code_checks.yml/badge.svg)](https://github.com/apify/langchain-apify/actions/workflows/run_code_checks.yml/badge.svg)
17
+
18
+ </div>
19
+
20
+ ---
21
+
22
+ 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.
23
+
24
+ ## Installation
25
+
26
+ ```bash
27
+ pip install langchain-apify
28
+ ```
29
+
30
+ ## Prerequisites
31
+
32
+ You should configure credentials by setting the following environment variables:
33
+ - `APIFY_API_TOKEN` - Apify API token
34
+
35
+ 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).
36
+
37
+ ## Tools
38
+
39
+ `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).
40
+
41
+ `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.
42
+
43
+ Example usage of `ApifyActorsTool` with the [RAG Web Browser](https://apify.com/apify/rag-web-browser) Actor, which searches for information on the web:
44
+ ```python
45
+ import os
46
+ import json
47
+ from langchain_apify import ApifyActorsTool
48
+
49
+ os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"
50
+ os.environ["APIFY_API_TOKEN"] = "YOUR_APIFY_API_TOKEN"
51
+
52
+ browser = ApifyActorsTool('apify/rag-web-browser')
53
+ search_results = browser.invoke(input={
54
+ "run_input": {"query": "what is Apify Actor?", "maxResults": 3}
55
+ })
56
+
57
+ # use the tool with an agent
58
+ from langchain_openai import ChatOpenAI
59
+ from langgraph.prebuilt import create_react_agent
60
+
61
+ model = ChatOpenAI(model="gpt-4o-mini")
62
+ tools = [browser]
63
+ agent = create_react_agent(model, tools)
64
+
65
+ for chunk in agent.stream(
66
+ {"messages": [("human", "search for what is Apify?")]},
67
+ stream_mode="values"
68
+ ):
69
+ chunk["messages"][-1].pretty_print()
70
+ ```
71
+
72
+ ## Document loaders
73
+
74
+ `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.
75
+
76
+ `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.
77
+
78
+ 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.
79
+ ```python
80
+ import os
81
+ from langchain_apify import ApifyDatasetLoader
82
+
83
+ os.environ["APIFY_API_TOKEN"] = "YOUR_APIFY_API_TOKEN"
84
+
85
+ # Example dataset structure
86
+ # [
87
+ # {
88
+ # "text": "Example text from the website.",
89
+ # "url": "http://example.com"
90
+ # },
91
+ # ...
92
+ # ]
93
+
94
+ loader = ApifyDatasetLoader(
95
+ dataset_id="your-dataset-id",
96
+ dataset_mapping_function=lambda dataset_item: Document(
97
+ page_content=dataset_item["text"],
98
+ metadata={"source": dataset_item["url"]}
99
+ ),
100
+ )
101
+ ```
102
+
103
+ ## Wrappers
104
+
105
+ `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:
106
+
107
+ - **call_actor**: Runs an Apify Actor and returns an `ApifyDatasetLoader` for the results.
108
+ - **acall_actor**: Asynchronous version of `call_actor`.
109
+ - **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.
110
+ - **acall_actor_task**: Asynchronous version of `call_actor_task`.
111
+
112
+ For more information, see the [Apify LangChain integration documentation](https://docs.apify.com/platform/integrations/langchain).
113
+
114
+ 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:
115
+ ```python
116
+ import os
117
+ from langchain_apify import ApifyWrapper
118
+ from langchain_core.documents import Document
119
+
120
+ os.environ["APIFY_API_TOKEN"] = "YOUR_APIFY_API_TOKEN"
121
+
122
+ apify = ApifyWrapper()
123
+
124
+ loader = apify.call_actor(
125
+ actor_id="apify/website-content-crawler",
126
+ run_input={
127
+ "startUrls": [{"url": "https://python.langchain.com/docs/get_started/introduction"}],
128
+ "maxCrawlPages": 10,
129
+ "crawlerType": "cheerio"
130
+ },
131
+ dataset_mapping_function=lambda item: Document(
132
+ page_content=item["text"] or "",
133
+ metadata={"source": item["url"]}
134
+ ),
135
+ )
136
+ documents = loader.load()
137
+ ```
@@ -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
+ ]
@@ -0,0 +1,2 @@
1
+ REQUESTS_TIMEOUT_SECS: float = 10.0
2
+ MAX_DESCRIPTION_LEN: int = 350
@@ -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
+ )
File without changes