id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 53 121 |
|---|---|---|
3adc13d982a8-2 | return llm.client.create(**kwargs)
return _completion_with_retry(**kwargs)
async def acompletion_with_retry(
llm: Union[BaseOpenAI, OpenAIChat], **kwargs: Any
) -> Any:
"""Use tenacity to retry the async completion call."""
retry_decorator = _create_retry_decorator(llm)
@retry_decorator
async de... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-3 | """How many completions to generate for each prompt."""
best_of: int = 1
"""Generates best_of completions server-side and returns the "best"."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
openai_api_ke... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-4 | be the same as the embedding model name. However, there are some cases
where you may want to use this Embedding class with a model name not
supported by tiktoken. This can include when using Azure embeddings or
when using one of the many model providers that expose an OpenAI-like
API but with differ... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-5 | if field_name not in all_required_field_names:
logger.warning(
f"""WARNING! {field_name} is not default parameter.
{field_name} was transferred to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-6 | "Please install it with `pip install openai`."
)
if values["streaming"] and values["n"] > 1:
raise ValueError("Cannot stream results when n > 1.")
if values["streaming"] and values["best_of"] > 1:
raise ValueError("Cannot stream results when best_of > 1.")
ret... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-7 | The full LLM output.
Example:
.. code-block:: python
response = openai.generate(["Tell me a joke."])
"""
# TODO: write a unit test for this
params = self._invocation_params
params = {**params, **kwargs}
sub_prompts = self.get_sub_prompts(params... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-8 | prompts: List[str],
stop: Optional[List[str]] = None,
run_manager: Optional[AsyncCallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
"""Call out to OpenAI's endpoint async with k unique prompts."""
params = self._invocation_params
params = {**params, **kw... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-9 | return self.create_llm_result(choices, prompts, token_usage)
def get_sub_prompts(
self,
params: Dict[str, Any],
prompts: List[str],
stop: Optional[List[str]] = None,
) -> List[List[str]]:
"""Get the sub prompts for llm call."""
if stop is not None:
if ... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-10 | ),
)
for choice in sub_choices
]
)
llm_output = {"token_usage": token_usage, "model_name": self.model_name}
return LLMResult(generations=generations, llm_output=llm_output)
def stream(self, prompt: str, stop: Optional[List[str]] = N... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-11 | @property
def _invocation_params(self) -> Dict[str, Any]:
"""Get the parameters used to invoke the model."""
openai_creds: Dict[str, Any] = {
"api_key": self.openai_api_key,
"api_base": self.openai_api_base,
"organization": self.openai_organization,
}
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-12 | enc = tiktoken.encoding_for_model(model_name)
except KeyError:
logger.warning("Warning: model not found. Using cl100k_base encoding.")
model = "cl100k_base"
enc = tiktoken.get_encoding(model)
return enc.encode(
text,
allowed_special=self.allowe... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-13 | "text-ada-001": 2049,
"ada": 2049,
"text-babbage-001": 2040,
"babbage": 2049,
"text-curie-001": 2049,
"curie": 2049,
"davinci": 2049,
"text-davinci-003": 4097,
"text-davinci-002": 4097,
"code-davinci-002": 8001,
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-14 | max_tokens = openai.max_token_for_prompt("Tell me a joke.")
"""
num_tokens = self.get_num_tokens(prompt)
return self.max_context_size - num_tokens
[docs]class OpenAI(BaseOpenAI):
"""Wrapper around OpenAI large language models.
To use, you should have the ``openai`` python package install... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-15 | openai_api_version: str = ""
@root_validator()
def validate_azure_settings(cls, values: Dict) -> Dict:
values["openai_api_version"] = get_from_dict_or_env(
values,
"openai_api_version",
"OPENAI_API_VERSION",
)
values["openai_api_type"] = get_from_dict_... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-16 | .. code-block:: python
from langchain.llms import OpenAIChat
openaichat = OpenAIChat(model_name="gpt-3.5-turbo")
"""
client: Any #: :meta private:
model_name: str = "gpt-3.5-turbo"
"""Model name to use."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Hol... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-17 | raise ValueError(f"Found {field_name} supplied twice.")
extra[field_name] = values.pop(field_name)
values["model_kwargs"] = extra
return values
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in env... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-18 | "`openai` has no `ChatCompletion` attribute, this is likely "
"due to an old version of the openai package. Try upgrading it "
"with `pip install --upgrade openai`."
)
warnings.warn(
"You are trying to use a chat model. This way of initializing it is "
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-19 | run_manager: Optional[CallbackManagerForLLMRun] = None,
**kwargs: Any,
) -> LLMResult:
messages, params = self._get_chat_params(prompts, stop)
params = {**params, **kwargs}
if self.streaming:
response = ""
params["stream"] = True
for stream_resp in... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-20 | self, messages=messages, **params
):
token = stream_resp["choices"][0]["delta"].get("content", "")
response += token
if run_manager:
await run_manager.on_llm_new_token(
token,
)
return... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
3adc13d982a8-21 | "Please install it with `pip install tiktoken`."
)
enc = tiktoken.encoding_for_model(self.model_name)
return enc.encode(
text,
allowed_special=self.allowed_special,
disallowed_special=self.disallowed_special,
) | https://api.python.langchain.com/en/stable/_modules/langchain/llms/openai.html |
bc62eab14e53-0 | Source code for langchain.llms.self_hosted
"""Run model inference on self-hosted remote hardware."""
import importlib.util
import logging
import pickle
from typing import Any, Callable, List, Mapping, Optional
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llm... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted.html |
bc62eab14e53-1 | )
if device < 0 and cuda_device_count > 0:
logger.warning(
"Device has %d GPUs available. "
"Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 for CPU and "
"can be a positive integer ass... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted.html |
bc62eab14e53-2 | llm = SelfHostedPipeline(
model_load_fn=load_pipeline,
hardware=gpu,
model_reqs=model_reqs, inference_fn=inference_fn
)
Example for <2GB model (can be serialized and sent directly to the server):
.. code-block:: python
from langchain.ll... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted.html |
bc62eab14e53-3 | load_fn_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model load function."""
model_reqs: List[str] = ["./", "torch"]
"""Requirements to install on hardware to inference the model."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted.html |
bc62eab14e53-4 | if not isinstance(pipeline, str):
logger.warning(
"Serializing pipeline to send to remote hardware. "
"Note, it can be quite slow"
"to serialize and send large models with each execution. "
"Consider sending the pipeline"
"to th... | https://api.python.langchain.com/en/stable/_modules/langchain/llms/self_hosted.html |
63d04671c232-0 | Source code for langchain.document_loaders.git
import os
from typing import Callable, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class GitLoader(BaseLoader):
"""Loads files from a Git repository into a list of documents.
Repositor... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/git.html |
63d04671c232-1 | else:
repo = Repo(self.repo_path)
repo.git.checkout(self.branch)
docs: List[Document] = []
for item in repo.tree().traverse():
if not isinstance(item, Blob):
continue
file_path = os.path.join(self.repo_path, item.path)
ignored_f... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/git.html |
25419ff204c9-0 | Source code for langchain.document_loaders.recursive_url_loader
from typing import Iterator, List, Optional, Set
from urllib.parse import urlparse
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class RecursiveUrlLoader(BaseLoader):
"""Lo... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/recursive_url_loader.html |
25419ff204c9-1 | ):
return visited
# Get all links that are relative to the root of the website
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
all_links = [link.get("href") for link in soup.find_all("a")]
# Extract only the links that are children of t... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/recursive_url_loader.html |
8e9c207507db-0 | Source code for langchain.document_loaders.obsidian
"""Loader that loads Obsidian directory dump."""
import re
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class ObsidianLoader(BaseLoader):
"""Loader th... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/obsidian.html |
8e9c207507db-1 | ps = list(Path(self.file_path).glob("**/*.md"))
docs = []
for p in ps:
with open(p, encoding=self.encoding) as f:
text = f.read()
front_matter = self._parse_front_matter(text)
text = self._remove_front_matter(text)
metadata = {
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/obsidian.html |
ff3f3998b6b7-0 | Source code for langchain.document_loaders.json_loader
"""Loader that loads data from JSON."""
import json
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class JSONLoader... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/json_loader.html |
ff3f3998b6b7-1 | """
try:
import jq # noqa:F401
except ImportError:
raise ImportError(
"jq package not found, please install it with `pip install jq`"
)
self.file_path = Path(file_path).resolve()
self._jq_schema = jq.compile(jq_schema)
self._co... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/json_loader.html |
ff3f3998b6b7-2 | else:
content = sample
if self._text_content and not isinstance(content, str):
raise ValueError(
f"Expected page_content is string, got {type(content)} instead. \
Set `text_content=False` if the desired input for \
`page_content` is... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/json_loader.html |
5f9c0973036f-0 | Source code for langchain.document_loaders.whatsapp_chat
import re
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(date: str, sender: str, text: str) -> str:
"""Combine message information i... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/whatsapp_chat.html |
5f9c0973036f-1 | )
if result:
date, sender, text = result.groups()
if text not in ignore_lines:
text_content += concatenate_rows(date, sender, text)
metadata = {"source": str(p)}
return [Document(page_content=text_content, metadata=metadata)] | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/whatsapp_chat.html |
f99a42fdbb29-0 | Source code for langchain.document_loaders.youtube
"""Loader that loads YouTube transcript."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Union
from urllib.parse import parse_qs, urlparse
from pydantic import root_validator
from pyd... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
f99a42fdbb29-1 | """Validate that either folder_id or document_ids is set, but not both."""
if not values.get("credentials_path") and not values.get(
"service_account_path"
):
raise ValueError("Must specify either channel_name or video_ids")
return values
def _load_credentials(self) -... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
f99a42fdbb29-2 | token.write(creds.to_json())
return creds
ALLOWED_SCHEMAS = {"http", "https"}
ALLOWED_NETLOCK = {
"youtu.be",
"m.youtube.com",
"youtube.com",
"www.youtube.com",
"www.youtube-nocookie.com",
"vid.plus",
}
def _parse_video_id(url: str) -> Optional[str]:
"""Parse a youtube url and return... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
f99a42fdbb29-3 | self.add_video_info = add_video_info
self.language = language
if isinstance(language, str):
self.language = [language]
else:
self.language = language
self.translation = translation
self.continue_on_failure = continue_on_failure
[docs] @staticmethod
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
f99a42fdbb29-4 | except TranscriptsDisabled:
return []
try:
transcript = transcript_list.find_transcript(self.language)
except NoTranscriptFound:
en_transcript = transcript_list.find_transcript(["en"])
transcript = en_transcript.translate(self.translation)
transcri... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
f99a42fdbb29-5 | To use, you should have the ``googleapiclient,youtube_transcript_api``
python package installed.
As the service needs a google_api_client, you first have to initialize
the GoogleApiClient.
Additionally you have to either provide a channel name or a list of videoids
"https://developers.google.com/doc... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
f99a42fdbb29-6 | "to use the Google Drive loader"
)
return build("youtube", "v3", credentials=creds)
[docs] @root_validator
def validate_channel_or_videoIds_is_set(
cls, values: Dict[str, Any]
) -> Dict[str, Any]:
"""Validate that either folder_id or document_ids is set, but not both."""
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
f99a42fdbb29-7 | request = self.youtube_client.search().list(
part="id",
q=channel_name,
type="channel",
maxResults=1, # we only need one result since channel names are unique
)
response = request.execute()
channel_id = response["items"][0]["id"]["channelId"]
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
f99a42fdbb29-8 | metadata=meta_data,
)
)
except (TranscriptsDisabled, NoTranscriptFound) as e:
if self.continue_on_failure:
logger.error(
"Error fetching transscript "
+ f" {ite... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
a06439668ecf-0 | Source code for langchain.document_loaders.gutenberg
"""Loader that loads .txt web files."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class GutenbergLoader(BaseLoader):
"""Loader that uses urllib to load .txt web files."""
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/gutenberg.html |
faefdfcc0f11-0 | Source code for langchain.document_loaders.reddit
"""Reddit document loader."""
from __future__ import annotations
from typing import TYPE_CHECKING, Iterable, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHECKING:
import pra... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/reddit.html |
faefdfcc0f11-1 | if self.mode == "subreddit":
for search_query in self.search_queries:
for category in self.categories:
docs = self._subreddit_posts_loader(
search_query=search_query, category=category, reddit=reddit
)
result... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/reddit.html |
faefdfcc0f11-2 | method = getattr(user.submissions, category)
cat_posts = method(limit=self.number_posts)
"""Format reddit posts into a string."""
for post in cat_posts:
metadata = {
"post_subreddit": post.subreddit_name_prefixed,
"post_category": category,
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/reddit.html |
ea55e82fdcc1-0 | Source code for langchain.document_loaders.figma
"""Loader that loads Figma files json dump."""
import json
import urllib.request
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import stringify_dict
[docs]class Fi... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/figma.html |
eca25dbc6afe-0 | Source code for langchain.document_loaders.modern_treasury
"""Loader that fetches data from Modern Treasury"""
import json
import urllib.request
from base64 import b64encode
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from lan... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/modern_treasury.html |
eca25dbc6afe-1 | def __init__(
self,
resource: str,
organization_id: Optional[str] = None,
api_key: Optional[str] = None,
) -> None:
self.resource = resource
organization_id = organization_id or get_from_env(
"organization_id", "MODERN_TREASURY_ORGANIZATION_ID"
)
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/modern_treasury.html |
958120c4ecb7-0 | Source code for langchain.document_loaders.fauna
from typing import Iterator, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class FaunaLoader(BaseLoader):
"""FaunaDB Loader.
Attributes:
query (str): The FQL query st... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/fauna.html |
958120c4ecb7-1 | document_dict = dict(result.items())
page_content = ""
for key, value in document_dict.items():
if key == self.page_content_field:
page_content = value
document: Document = Document(
page_content=page_content... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/fauna.html |
eee3153e438b-0 | Source code for langchain.document_loaders.excel
"""Loader that loads Microsoft Excel files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructured_version,
)
[docs]class UnstructuredExcelLoader(UnstructuredFileLoader):
"""Loader t... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/excel.html |
3aba7cd4d3eb-0 | Source code for langchain.document_loaders.directory
"""Loading logic for loading documents from a directory."""
import concurrent
import logging
from pathlib import Path
from typing import Any, List, Optional, Type, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import Base... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/directory.html |
3aba7cd4d3eb-1 | self.loader_kwargs = loader_kwargs
self.silent_errors = silent_errors
self.recursive = recursive
self.show_progress = show_progress
self.use_multithreading = use_multithreading
self.max_concurrency = max_concurrency
[docs] def load_file(
self, item: Path, path: Path, d... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/directory.html |
3aba7cd4d3eb-2 | logger.warning(e)
else:
raise e
if self.use_multithreading:
with concurrent.futures.ThreadPoolExecutor(
max_workers=self.max_concurrency
) as executor:
executor.map(lambda i: self.load_file(i, p, docs, pbar), items)
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/directory.html |
7c7fd639b620-0 | Source code for langchain.document_loaders.facebook_chat
"""Loader that loads Facebook chat json dump."""
import datetime
import json
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(row: dict) -... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/facebook_chat.html |
3c116a18ec60-0 | Source code for langchain.document_loaders.email
"""Loader that loads email files."""
import os
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
satisfies_... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/email.html |
3c116a18ec60-1 | "`pip install extract_msg`"
)
[docs] def load(self) -> List[Document]:
"""Load data into document objects."""
import extract_msg
msg = extract_msg.Message(self.file_path)
return [
Document(
page_content=msg.body,
metadata={
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/email.html |
eb0de7427837-0 | Source code for langchain.document_loaders.word_document
"""Loader that loads word documents."""
import os
import tempfile
from abc import ABC
from typing import List
from urllib.parse import urlparse
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/word_document.html |
eb0de7427837-1 | if hasattr(self, "temp_file"):
self.temp_file.close()
[docs] def load(self) -> List[Document]:
"""Load given path as single page."""
import docx2txt
return [
Document(
page_content=docx2txt.process(self.file_path),
metadata={"source": se... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/word_document.html |
eb0de7427837-2 | f"You are on unstructured version {__unstructured_version__}. "
"Partitioning .doc files is only supported in unstructured>=0.4.11. "
"Please upgrade the unstructured package and try again."
)
if is_doc:
from unstructured.partition.doc import partition_doc... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/word_document.html |
2fc629d91010-0 | Source code for langchain.document_loaders.html_bs
"""Loader that uses bs4 to load HTML files, enriching metadata with page title."""
import logging
from typing import Dict, List, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__n... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/html_bs.html |
2fc629d91010-1 | title = ""
metadata: Dict[str, Union[str, None]] = {
"source": self.file_path,
"title": title,
}
return [Document(page_content=text, metadata=metadata)] | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/html_bs.html |
ff34cf97aa34-0 | Source code for langchain.document_loaders.stripe
"""Loader that fetches data from Stripe"""
import json
import urllib.request
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import get_from_env, stringify_dic... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/stripe.html |
ff34cf97aa34-1 | if endpoint is None:
return []
return self._make_request(endpoint)
[docs] def load(self) -> List[Document]:
return self._get_resource() | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/stripe.html |
32848c64cfea-0 | Source code for langchain.document_loaders.mastodon
"""Mastodon document loader."""
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/mastodon.html |
32848c64cfea-1 | access_token = access_token or os.environ.get("MASTODON_ACCESS_TOKEN")
self.api = mastodon.Mastodon(
access_token=access_token, api_base_url=api_base_url
)
self.mastodon_accounts = mastodon_accounts
self.number_toots = number_toots
self.exclude_replies = exclude_repli... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/mastodon.html |
63fc48ee47c0-0 | Source code for langchain.document_loaders.discord
"""Load from Discord chat dump"""
from __future__ import annotations
from typing import TYPE_CHECKING, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHECKING:
import pandas as pd
[docs]class Dis... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/discord.html |
617b4c62612d-0 | Source code for langchain.document_loaders.merge
from typing import Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class MergedDataLoader(BaseLoader):
"""Merge documents from a list of loaders"""
def __init__(self, loaders: List):
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/merge.html |
d1ec046510ae-0 | Source code for langchain.document_loaders.s3_file
"""Loading logic for loading documents from an s3 file."""
import os
import tempfile
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import Unst... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/s3_file.html |
d191c1fdf567-0 | Source code for langchain.document_loaders.epub
"""Loader that loads EPub files."""
from typing import List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
satisfies_min_unstructured_version,
)
[docs]class UnstructuredEPubLoader(UnstructuredFileLoader):
"""Loader that uses unst... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/epub.html |
b0928310ca4e-0 | Source code for langchain.document_loaders.duckdb_loader
from typing import Dict, List, Optional, cast
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class DuckDBLoader(BaseLoader):
"""Loads a query result from DuckDB into a list of documents.
Each ... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/duckdb_loader.html |
b0928310ca4e-1 | results = query_result.fetchall()
description = cast(list, query_result.description)
field_names = [c[0] for c in description]
if self.page_content_columns is None:
page_content_columns = field_names
else:
page_content_columns = self.page_c... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/duckdb_loader.html |
5734d0ff7ae6-0 | Source code for langchain.document_loaders.notebook
"""Loader that loads .ipynb notebook files."""
import json
from pathlib import Path
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_cells(
cell: dict, include_outp... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/notebook.html |
5734d0ff7ae6-1 | return f"'{cell_type}' cell: '{source}'\n\n"
return ""
def remove_newlines(x: Any) -> Any:
"""Remove recursively newlines, no matter the data structure they are stored in."""
import pandas as pd
if isinstance(x, str):
return x.replace("\n", "")
elif isinstance(x, list):
return [remov... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/notebook.html |
5734d0ff7ae6-2 | if self.remove_newline:
filtered_data = filtered_data.applymap(remove_newlines)
text = filtered_data.apply(
lambda x: concatenate_cells(
x, self.include_outputs, self.max_output_length, self.traceback
),
axis=1,
).str.cat(sep=" ")
m... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/notebook.html |
72e2c59683e7-0 | Source code for langchain.document_loaders.odt
"""Loader that loads Open Office ODT files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructured_version,
)
[docs]class UnstructuredODTLoader(UnstructuredFileLoader):
"""Loader that ... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/odt.html |
5170790f3585-0 | Source code for langchain.document_loaders.googledrive
"""Loader that loads data from Google Drive."""
# Prerequisites:
# 1. Create a Google Cloud project
# 2. Enable the Google Drive API:
# https://console.cloud.google.com/flows/enableapi?apiid=drive.googleapis.com
# 3. Authorize credentials for desktop app:
# htt... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/googledrive.html |
5170790f3585-1 | # results in pydantic validation errors
file_loader_cls: Any = None
file_loader_kwargs: Dict["str", Any] = {}
@root_validator
def validate_inputs(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that either folder_id or document_ids is set, but not both."""
if values.get("fold... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/googledrive.html |
5170790f3585-2 | if file_type not in allowed_types:
raise ValueError(
f"Given file type {file_type} is not supported. "
f"Supported values are: {short_names}; and "
f"their full-form names: {full_names}"
)
# repla... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/googledrive.html |
5170790f3585-3 | )
if self.token_path.exists():
creds = Credentials.from_authorized_user_file(str(self.token_path), SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
elif "GOOGLE_APPLICATION_CREDENTIAL... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/googledrive.html |
5170790f3585-4 | metadata = {
"source": (
f"https://docs.google.com/spreadsheets/d/{id}/"
f"edit?gid={sheet['properties']['sheetId']}"
),
"title": f"{spreadsheet['properties']['title']} - {sheet_name}",
"row":... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/googledrive.html |
5170790f3585-5 | text = fh.getvalue().decode("utf-8")
metadata = {
"source": f"https://docs.google.com/document/d/{id}/edit",
"title": f"{file.get('name')}",
}
return Document(page_content=text, metadata=metadata)
def _load_documents_from_folder(
self, folder_id: str, *, file_... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/googledrive.html |
5170790f3585-6 | else:
pass
return returns
def _fetch_files_recursive(
self, service: Any, folder_id: str
) -> List[Dict[str, Union[str, List[str]]]]:
"""Fetch all files and subfolders recursively."""
results = (
service.files()
.list(
q=f"'... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/googledrive.html |
5170790f3585-7 | file = service.files().get(fileId=id, supportsAllDrives=True).execute()
request = service.files().get_media(fileId=id)
fh = BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
if self... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/googledrive.html |
5170790f3585-8 | )
elif self.document_ids:
return self._load_documents_from_ids()
else:
return self._load_file_from_ids() | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/googledrive.html |
daad52c0cc3a-0 | Source code for langchain.document_loaders.azure_blob_storage_file
"""Loading logic for loading documents from an Azure Blob Storage file."""
import os
import tempfile
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/azure_blob_storage_file.html |
adf673aefdf8-0 | Source code for langchain.document_loaders.twitter
"""Twitter document loader."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHEC... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/twitter.html |
adf673aefdf8-1 | user = api.get_user(screen_name=username)
docs = self._format_tweets(tweets, user)
results.extend(docs)
return results
def _format_tweets(
self, tweets: List[Dict[str, Any]], user_info: dict
) -> Iterable[Document]:
"""Format tweets into a string."""
for t... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/twitter.html |
adf673aefdf8-2 | access_token=access_token,
access_token_secret=access_token_secret,
consumer_key=consumer_key,
consumer_secret=consumer_secret,
)
return cls(
auth_handler=auth,
twitter_users=twitter_users,
number_tweets=number_tweets,
) | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/twitter.html |
abaecc45eab6-0 | Source code for langchain.document_loaders.hn
"""Loader that loads HN."""
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class HNLoader(WebBaseLoader):
"""Load Hacker News data from either main page results or the com... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/hn.html |
abaecc45eab6-1 | title = lineItem.find("span", {"class": "titleline"}).text.strip()
metadata = {
"source": self.web_path,
"title": title,
"link": link,
"ranking": ranking,
}
documents.append(
Document(
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/hn.html |
c5fbe0070dfc-0 | Source code for langchain.document_loaders.gitbook
"""Loader that loads GitBook."""
from typing import Any, List, Optional
from urllib.parse import urljoin, urlparse
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class GitbookLoader(WebBaseLoader):
... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/gitbook.html |
c5fbe0070dfc-1 | [docs] def load(self) -> List[Document]:
"""Fetch text from one single GitBook page."""
if self.load_all_paths:
soup_info = self.scrape()
relative_paths = self._get_paths(soup_info)
documents = []
for path in relative_paths:
url = urljoi... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/gitbook.html |
a5c3c90f18d6-0 | Source code for langchain.document_loaders.college_confidential
"""Loader that loads College Confidential."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class CollegeConfidentialLoader(WebBaseLoader):
"""Loader that lo... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/college_confidential.html |
b932e0098b30-0 | Source code for langchain.document_loaders.powerpoint
"""Loader that loads powerpoint files."""
import os
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredPowerPointLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to load powe... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/powerpoint.html |
9a1d2e553f93-0 | Source code for langchain.document_loaders.larksuite
"""Loader that loads LarkSuite (FeiShu) document json dump."""
import json
import urllib.request
from typing import Any, Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class LarkSuiteDocLoa... | https://api.python.langchain.com/en/stable/_modules/langchain/document_loaders/larksuite.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.