id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
42f369046712-2 | vectorstore = self.vectorstore_cls.from_documents(
sub_docs, self.embedding, **self.vectorstore_kwargs
)
return VectorStoreIndexWrapper(vectorstore=vectorstore) | lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/vectorstore.html |
4778ec15a92d-0 | Source code for langchain.indexes.base
from __future__ import annotations
import uuid
from abc import ABC, abstractmethod
from typing import List, Optional, Sequence
NAMESPACE_UUID = uuid.UUID(int=1984)
[docs]class RecordManager(ABC):
"""An abstract base class representing the interface for a record manager."""
[do... | lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/base.html |
4778ec15a92d-1 | *,
group_ids: Optional[Sequence[Optional[str]]] = None,
time_at_least: Optional[float] = None,
) -> None:
"""Upsert records into the database.
Args:
keys: A list of record keys to upsert.
group_ids: A list of group IDs corresponding to the keys.
ti... | lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/base.html |
4778ec15a92d-2 | """Check if the provided keys exist in the database.
Args:
keys: A list of keys to check.
Returns:
A list of boolean values indicating the existence of each key.
"""
[docs] @abstractmethod
def list_keys(
self,
*,
before: Optional[float] = No... | lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/base.html |
4778ec15a92d-3 | def delete_keys(self, keys: Sequence[str]) -> None:
"""Delete specified records from the database.
Args:
keys: A list of keys to delete.
"""
[docs] @abstractmethod
async def adelete_keys(self, keys: Sequence[str]) -> None:
"""Delete specified records from the database.... | lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/base.html |
970df907b09b-0 | Source code for langchain.indexes.graph
"""Graph Index Creator."""
from typing import Optional, Type
from langchain.chains.llm import LLMChain
from langchain.graphs.networkx_graph import NetworkxEntityGraph, parse_triples
from langchain.indexes.prompts.knowledge_triplet_extraction import (
KNOWLEDGE_TRIPLE_EXTRACTI... | lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/graph.html |
970df907b09b-1 | chain = LLMChain(llm=self.llm, prompt=prompt)
output = await chain.apredict(text=text)
knowledge = parse_triples(output)
for triple in knowledge:
graph.add_triple(triple)
return graph | lang/api.python.langchain.com/en/latest/_modules/langchain/indexes/graph.html |
5c25de5b34be-0 | Source code for langchain.utils.iter
from collections import deque
from itertools import islice
from typing import (
Any,
ContextManager,
Deque,
Generator,
Generic,
Iterable,
Iterator,
List,
Optional,
Tuple,
TypeVar,
Union,
overload,
)
from typing_extensions import Li... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html |
5c25de5b34be-1 | # are fetching items concurrently. They may have buffered their
# item already.
for peer_buffer in peers:
peer_buffer.append(item)
yield buffer.popleft()
finally:
with lock:
# this peer is done – remove its b... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html |
5c25de5b34be-2 | immediately closes all children, and it can be used in an ``async with`` context
for the same effect.
If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
provide these items. Also, ``tee`` must internally buffer each item until the
last iterator has yielded it; if the most and least ad... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html |
5c25de5b34be-3 | ...
@overload
def __getitem__(self, item: slice) -> Tuple[Iterator[T], ...]:
...
def __getitem__(
self, item: Union[int, slice]
) -> Union[Iterator[T], Tuple[Iterator[T], ...]]:
return self._children[item]
def __iter__(self) -> Iterator[Iterator[T]]:
yield from self._... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/iter.html |
5bc70a4a41df-0 | Source code for langchain.utils.aiter
"""
Adapted from
https://github.com/maxfischer2781/asyncstdlib/blob/master/asyncstdlib/itertools.py
MIT License
"""
from collections import deque
from typing import (
Any,
AsyncContextManager,
AsyncGenerator,
AsyncIterator,
Awaitable,
Callable,
Deque,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html |
5bc70a4a41df-1 | # The C code is way more low-level than this, as it implements
# all methods of the iterator protocol. In this implementation
# we're relying on higher-level coroutine concepts, but that's
# exactly what we want -- crosstest pure-Python high-level
# implementation and low... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html |
5bc70a4a41df-2 | # This ensures the proper item ordering if any of our peers
# are fetching items concurrently. They may have buffered their
# item already.
for peer_buffer in peers:
peer_buffer.append(item)
yield buffer.popl... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html |
5bc70a4a41df-3 | to get the child iterators. In addition, its :py:meth:`~.tee.aclose` method
immediately closes all children, and it can be used in an ``async with`` context
for the same effect.
If ``iterable`` is an iterator and read elsewhere, ``tee`` will *not*
provide these items. Also, ``tee`` must internally buffe... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html |
5bc70a4a41df-4 | )
def __len__(self) -> int:
return len(self._children)
@overload
def __getitem__(self, item: int) -> AsyncIterator[T]:
...
@overload
def __getitem__(self, item: slice) -> Tuple[AsyncIterator[T], ...]:
...
def __getitem__(
self, item: Union[int, slice]
) -> Uni... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/aiter.html |
bfda83f3e387-0 | Source code for langchain.utils.env
import os
from typing import Any, Dict, Optional
[docs]def get_from_dict_or_env(
data: Dict[str, Any], key: str, env_key: str, default: Optional[str] = None
) -> str:
"""Get a value from a dictionary or an environment variable."""
if key in data and data[key]:
ret... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/env.html |
e8e17d8d09be-0 | Source code for langchain.utils.pydantic
"""Utilities for tests."""
[docs]def get_pydantic_major_version() -> int:
"""Get the major version of Pydantic."""
try:
import pydantic
return int(pydantic.__version__.split(".")[0])
except ImportError:
return 0
PYDANTIC_MAJOR_VERSION = get_py... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/pydantic.html |
8f93ca75ae42-0 | Source code for langchain.utils.math
"""Math utils."""
import logging
from typing import List, Optional, Tuple, Union
import numpy as np
logger = logging.getLogger(__name__)
Matrix = Union[List[List[float]], List[np.ndarray], np.ndarray]
[docs]def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray:
"""Row-wise c... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/math.html |
8f93ca75ae42-1 | similarity = np.dot(X, Y.T) / np.outer(X_norm, Y_norm)
similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0
return similarity
[docs]def cosine_similarity_top_k(
X: Matrix,
Y: Matrix,
top_k: Optional[int] = 5,
score_threshold: Optional[float] = None,
) -> Tuple[List[Tuple[int, in... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/math.html |
5c6b15563446-0 | Source code for langchain.utils.json_schema
from __future__ import annotations
from copy import deepcopy
from typing import Any, List, Optional, Sequence
def _retrieve_ref(path: str, schema: dict) -> dict:
components = path.split("/")
if components[0] != "#":
raise ValueError(
"ref paths are... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/json_schema.html |
5c6b15563446-1 | keys += _infer_skip_keys(ref, full_schema)
elif isinstance(v, (list, dict)):
keys += _infer_skip_keys(v, full_schema)
elif isinstance(obj, list):
for el in obj:
keys += _infer_skip_keys(el, full_schema)
return keys
[docs]def dereference_refs(
schema_obj: dict,... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/json_schema.html |
83e5ddab3fbb-0 | Source code for langchain.utils.input
"""Handle chained inputs."""
from typing import Dict, List, Optional, TextIO
_TEXT_COLOR_MAPPING = {
"blue": "36;1",
"yellow": "33;1",
"pink": "38;5;200",
"green": "32;1",
"red": "31;1",
}
[docs]def get_color_mapping(
items: List[str], excluded_colors: Optio... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/input.html |
83e5ddab3fbb-1 | print(text_to_print, end=end, file=file)
if file:
file.flush() # ensure all printed content are written to file | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/input.html |
6fa2e44b0899-0 | Source code for langchain.utils.utils
"""Generic utility functions."""
import contextlib
import datetime
import functools
import importlib
import warnings
from importlib.metadata import version
from typing import Any, Callable, Dict, Optional, Set, Tuple, Union
from packaging.version import parse
from requests import H... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
6fa2e44b0899-1 | """Context manager for mocking out datetime.now() in unit tests.
Example:
with mock_now(datetime.datetime(2011, 2, 3, 10, 11)):
assert datetime.datetime.now() == datetime.datetime(2011, 2, 3, 10, 11)
"""
class MockDateTime(datetime.datetime):
"""Mock datetime.datetime.now() with a fixed ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
6fa2e44b0899-2 | gte_version: Optional[str] = None,
) -> None:
"""Check the version of a package."""
imported_version = parse(version(package))
if lt_version is not None and imported_version >= parse(lt_version):
raise ValueError(
f"Expected {package} version to be < {lt_version}. Received "
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
6fa2e44b0899-3 | values: Dict[str, Any],
all_required_field_names: Set[str],
) -> Dict[str, Any]:
"""Build extra kwargs from values and extra_kwargs.
Args:
extra_kwargs: Extra kwargs passed in by user.
values: Values passed in by user.
all_required_field_names: All required field names for the pydant... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/utils.html |
439bb05afb24-0 | Source code for langchain.utils.loading
"""Utilities for loading configurations from langchain-hub."""
import os
import re
import tempfile
from pathlib import Path, PurePosixPath
from typing import Any, Callable, Optional, Set, TypeVar, Union
from urllib.parse import urljoin
import requests
DEFAULT_REF = os.environ.get... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/loading.html |
439bb05afb24-1 | # when working with URLs that use forward slashes as the path separator.
# Instead, use PurePosixPath to ensure that forward slashes are used as the
# path separator, regardless of the operating system.
full_url = urljoin(URL_BASE.format(ref=ref), PurePosixPath(remote_path).__str__())
r = requests.get(f... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/loading.html |
99c9a7258161-0 | Source code for langchain.utils.openai_functions
from typing import Literal, Optional, Type, TypedDict
from langchain.pydantic_v1 import BaseModel
from langchain.utils.json_schema import dereference_refs
[docs]class FunctionDescription(TypedDict):
"""Representation of a callable function to the OpenAI API."""
n... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/openai_functions.html |
2d0db9c9e5db-0 | Source code for langchain.utils.html
import re
from typing import List, Optional, Sequence, Union
from urllib.parse import urljoin, urlparse
PREFIXES_TO_IGNORE = ("javascript:", "mailto:", "#")
SUFFIXES_TO_IGNORE = (
".css",
".js",
".ico",
".png",
".jpg",
".jpeg",
".gif",
".svg",
".c... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/html.html |
2d0db9c9e5db-1 | pattern: Union[str, re.Pattern, None] = None,
prevent_outside: bool = True,
exclude_prefixes: Sequence[str] = (),
) -> List[str]:
"""Extract all links from a raw html string and convert into absolute paths.
Args:
raw_html: original html.
url: the url of the html.
base_url: the ba... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/html.html |
387b0737e61b-0 | Source code for langchain.utils.strings
from typing import Any, List
[docs]def stringify_value(val: Any) -> str:
"""Stringify a value.
Args:
val: The value to stringify.
Returns:
str: The stringified value.
"""
if isinstance(val, str):
return val
elif isinstance(val, dict... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/strings.html |
ee25dac83a6d-0 | Source code for langchain.utils.openai
from __future__ import annotations
from importlib.metadata import version
from packaging.version import parse
[docs]def is_openai_v1() -> bool:
_version = parse(version("openai"))
return _version.major >= 1 | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/openai.html |
e2abdfcbafba-0 | Source code for langchain.utils.formatting
"""Utilities for formatting strings."""
from string import Formatter
from typing import Any, List, Mapping, Sequence, Union
[docs]class StrictFormatter(Formatter):
"""A subclass of formatter that checks for extra keys."""
[docs] def check_unused_args(
self,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utils/formatting.html |
7f01b8e69988-0 | Source code for langchain.adapters.openai
from __future__ import annotations
import importlib
from typing import (
Any,
AsyncIterator,
Dict,
Iterable,
List,
Mapping,
Sequence,
Union,
overload,
)
from typing_extensions import Literal
from langchain.schema.chat import ChatSession
from ... | lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
7f01b8e69988-1 | additional_kwargs["tool_calls"] = _dict["tool_calls"]
return AIMessage(content=content, additional_kwargs=additional_kwargs)
elif role == "system":
return SystemMessage(content=_dict["content"])
elif role == "function":
return FunctionMessage(content=_dict["content"], name=_dict["name"])... | lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
7f01b8e69988-2 | message_dict["content"] = None
elif isinstance(message, SystemMessage):
message_dict = {"role": "system", "content": message.content}
elif isinstance(message, FunctionMessage):
message_dict = {
"role": "function",
"content": message.content,
"name": message.na... | lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
7f01b8e69988-3 | # not missing, but None.
if i == 0:
_dict["content"] = None
else:
_dict["content"] = chunk.content
else:
raise ValueError(f"Got unexpected streaming chunk type: {type(chunk)}")
# This only happens at the end of streams, and OpenAI returns as empty dict
... | lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
7f01b8e69988-4 | return {"choices": [{"message": convert_message_to_dict(result)}]}
else:
return (
_convert_message_chunk_to_delta(c, i)
for i, c in enumerate(model_config.stream(converted_messages))
)
@overload
@staticmethod
async def acreate(
messages... | lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
7f01b8e69988-5 | )
def _has_assistant_message(session: ChatSession) -> bool:
"""Check if chat session has an assistant message."""
return any([isinstance(m, AIMessage) for m in session["messages"]])
[docs]def convert_messages_for_finetuning(
sessions: Iterable[ChatSession],
) -> List[List[dict]]:
"""Convert messages to ... | lang/api.python.langchain.com/en/latest/_modules/langchain/adapters/openai.html |
e883dc0a3205-0 | Source code for langchain.document_loaders.geodataframe
from typing import Any, Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class GeoDataFrameLoader(BaseLoader):
"""Load `geopandas` Dataframe."""
[docs] def __init__(self, data_frame... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/geodataframe.html |
e883dc0a3205-1 | # assumes all geometries in GeoSeries are same CRS and Geom Type
crs_str = self.data_frame.crs.to_string() if self.data_frame.crs else None
geometry_type = self.data_frame.geometry.geom_type.iloc[0]
for _, row in self.data_frame.iterrows():
geom = row[self.page_content_column]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/geodataframe.html |
280183bb8e43-0 | Source code for langchain.document_loaders.mhtml
import email
import logging
from typing import Dict, List, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__name__)
[docs]class MHTMLLoader(BaseLoader):
"""Parse `MHTML` files w... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mhtml.html |
280183bb8e43-1 | with open(self.file_path, "r", encoding=self.open_encoding) as f:
message = email.message_from_string(f.read())
parts = message.get_payload()
if not isinstance(parts, list):
parts = [message]
for part in parts:
if part.get_content_type() ==... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mhtml.html |
f1fbedb3bbee-0 | Source code for langchain.document_loaders.onedrive
"""Loads data from OneDrive"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Iterator, List, Optional, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base_o365 import (
O365Bas... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html |
f1fbedb3bbee-1 | located at the specified path.
Raises:
FileNotFoundError: If the path does not exist.
"""
subfolder_drive = drive
if self.folder_path is None:
return subfolder_drive
subfolders = [f for f in self.folder_path.split("/") if f != ""]
if len(subfolders... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html |
f1fbedb3bbee-2 | """Load all documents."""
return list(self.lazy_load()) | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive.html |
ea6ad28f84de-0 | Source code for langchain.document_loaders.weather
"""Simple reader that reads weather data from OpenWeatherMap API"""
from __future__ import annotations
from datetime import datetime
from typing import Iterator, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.b... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/weather.html |
1352c8d83cf7-0 | Source code for langchain.document_loaders.powerpoint
import os
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredPowerPointLoader(UnstructuredFileLoader):
"""Load `Microsoft PowerPoint` files using `Unstructured`.
Works with both .ppt and... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
1352c8d83cf7-1 | try:
import magic # noqa: F401
is_ppt = detect_filetype(self.file_path) == FileType.PPT
except ImportError:
_, extension = os.path.splitext(str(self.file_path))
is_ppt = extension == ".ppt"
if is_ppt and unstructured_version < (0, 4, 11):
rais... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
dcdff638cd2f-0 | Source code for langchain.document_loaders.diffbot
import logging
from typing import Any, List
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__name__)
[docs]class DiffbotLoader(BaseLoader):
"""Load `Diffbot` json fi... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html |
dcdff638cd2f-1 | for url in self.urls:
try:
data = self._get_diffbot_data(url)
text = data["objects"][0]["text"] if "objects" in data else ""
metadata = {"source": url}
docs.append(Document(page_content=text, metadata=metadata))
except Exception as ... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html |
c77110fb1ca9-0 | Source code for langchain.document_loaders.bibtex
import logging
import re
from pathlib import Path
from typing import Any, Iterator, List, Mapping, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utilities.bibtex import BibtexparserWrapper... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
c77110fb1ca9-1 | self.parser = parser or BibtexparserWrapper()
self.max_docs = max_docs
self.max_content_chars = max_content_chars
self.load_extra_metadata = load_extra_metadata
self.file_regex = re.compile(file_pattern)
def _load_entry(self, entry: Mapping[str, Any]) -> Optional[Document]:
i... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
c77110fb1ca9-2 | "`pip install pymupdf`"
)
entries = self.parser.load_bibtex_entries(self.file_path)
if self.max_docs:
entries = entries[: self.max_docs]
for entry in entries:
doc = self._load_entry(entry)
if doc:
yield doc
[docs] def load(self) ... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
c915d77a46c1-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):
"""Load from `DuckDB`.
Each document represents one row of the resu... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html |
c915d77a46c1-1 | [docs] def load(self) -> List[Document]:
try:
import duckdb
except ImportError:
raise ImportError(
"Could not import duckdb python package. "
"Please install it with `pip install duckdb`."
)
docs = []
with duckdb.conn... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html |
72135e104cd5-0 | Source code for langchain.document_loaders.sharepoint
"""Loader that loads data from Sharepoint Document Library"""
from __future__ import annotations
from typing import Iterator, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base_o365 import (
O365BaseLoa... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sharepoint.html |
72135e104cd5-1 | raise ValueError(f"There isn't a Drive with id {self.document_library_id}.")
blob_parser = get_parser("default")
if self.folder_path:
target_folder = drive.get_item_by_path(self.folder_path)
if not isinstance(target_folder, Folder):
raise ValueError(f"There isn't ... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sharepoint.html |
fd27d02d40de-0 | Source code for langchain.document_loaders.airbyte
from typing import Any, Callable, Iterator, List, Mapping, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils.utils import guard_import
RecordHandler = Callable[[Any, Optional[str]], Doc... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
fd27d02d40de-1 | if record_handler:
return record_handler(record, id)
return Document(page_content="", metadata=record.data)
self._integration = CDKIntegration(
config=config,
runner=CDKRunner(source=source_class(), name=source_class.__name__),
)
self._... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
fd27d02d40de-2 | ).SourceHubspot
super().__init__(
config=config,
source_class=source_class,
stream_name=stream_name,
record_handler=record_handler,
state=state,
)
[docs]class AirbyteStripeLoader(AirbyteCDKLoader):
"""Load from `Stripe` using an `Airbyte` s... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
fd27d02d40de-3 | state: Optional[Any] = None,
) -> None:
"""Initializes the loader.
Args:
config: The config to pass to the source connector.
stream_name: The name of the stream to load.
record_handler: A function that takes in a record and an optional id and
retur... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
fd27d02d40de-4 | """
source_class = guard_import(
"source_zendesk_support", pip_name="airbyte-source-zendesk-support"
).SourceZendeskSupport
super().__init__(
config=config,
source_class=source_class,
stream_name=stream_name,
record_handler=record_handl... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
fd27d02d40de-5 | [docs] def __init__(
self,
config: Mapping[str, Any],
stream_name: str,
record_handler: Optional[RecordHandler] = None,
state: Optional[Any] = None,
) -> None:
"""Initializes the loader.
Args:
config: The config to pass to the source connector.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
fd27d02d40de-6 | returns a Document. If None, the record will be used as the document.
Defaults to None.
state: The state to pass to the source connector. Defaults to None.
"""
source_class = guard_import(
"source_gong", pip_name="airbyte-source-gong"
).SourceGong
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
300a65591966-0 | Source code for langchain.document_loaders.tomarkdown
from __future__ import annotations
from typing import Iterator, List
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class ToMarkdownLoader(BaseLoader):
"""Load `HTML` using `2markdown... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tomarkdown.html |
2c49e40e7938-0 | Source code for langchain.document_loaders.blockchain
import os
import re
import time
from enum import Enum
from typing import List, Optional
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class BlockchainType(Enum):
"""Enumerator of the... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html |
2c49e40e7938-1 | """
[docs] def __init__(
self,
contract_address: str,
blockchainType: BlockchainType = BlockchainType.ETH_MAINNET,
api_key: str = "docs-demo",
startToken: str = "",
get_all_tokens: bool = False,
max_execution_time: Optional[int] = None,
):
"""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html |
2c49e40e7938-2 | f"&startToken={current_start_token}"
)
response = requests.get(url)
if response.status_code != 200:
raise ValueError(
f"Request failed with status code {response.status_code}"
)
items = response.json()["nfts"]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html |
2c49e40e7938-3 | else:
value_int = int(tokenId)
result = value_int + 1
if value_type == "hex_0x":
return "0x" + format(result, "0" + str(len(tokenId) - 2) + "x")
elif value_type == "hex_0xbf":
return "0xbf" + format(result, "0" + str(len(tokenId) - 4) + "x")
else:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html |
93305f02f1c4-0 | Source code for langchain.document_loaders.cube_semantic
import json
import logging
import time
from typing import List
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__name__)
[docs]class CubeSemanticLoader(BaseLoader):... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/cube_semantic.html |
93305f02f1c4-1 | self.dimension_values_retry_delay = dimension_values_retry_delay
def _get_dimension_values(self, dimension_name: str) -> List[str]:
"""Makes a call to Cube's REST API load endpoint to retrieve
values for dimensions.
These values can be used to achieve a more accurate filtering.
"""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/cube_semantic.html |
93305f02f1c4-2 | """Makes a call to Cube's REST API metadata endpoint.
Returns:
A list of documents with attributes:
- page_content=column_title + column_description
- metadata
- table_name
- column_name
- column_data_type
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/cube_semantic.html |
93305f02f1c4-3 | dimension_values = []
item_name = str(item.get("name"))
item_type = str(item.get("type"))
if (
self.load_dimension_values
and column_member_type == "dimension"
and item_type == "string"
):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/cube_semantic.html |
a6ea3d39fb4c-0 | Source code for langchain.document_loaders.helpers
"""Document loader helpers."""
import concurrent.futures
from typing import List, NamedTuple, Optional, cast
[docs]class FileEncoding(NamedTuple):
"""File encoding as the NamedTuple."""
encoding: Optional[str]
"""The encoding of the file."""
confidence:... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/helpers.html |
8b07365564b5-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):
"""Load from `FaunaDB`.
Attributes:
query (str): The FQL que... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/fauna.html |
8b07365564b5-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/fauna.html |
88da779658e5-0 | Source code for langchain.document_loaders.evernote
"""Load documents from Evernote.
https://gist.github.com/foxmask/7b29c43a161e001ff04afdb2f181e31c
"""
import hashlib
import logging
from base64 import b64decode
from time import strptime
from typing import Any, Dict, Iterator, List, Optional
from langchain.docstore.do... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
88da779658e5-1 | """Initialize with file path."""
self.file_path = file_path
self.load_single_document = load_single_document
[docs] def load(self) -> List[Document]:
"""Load documents from EverNote export file."""
documents = [
Document(
page_content=note["content"],
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
88da779658e5-2 | if elem.tag == "data":
# Sometimes elem.text is None
rsc_dict[elem.tag] = b64decode(elem.text) if elem.text else b""
rsc_dict["hash"] = hashlib.md5(rsc_dict[elem.tag]).hexdigest()
else:
rsc_dict[elem.tag] = elem.text
return rsc_dict
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
88da779658e5-3 | @staticmethod
def _parse_note_xml(xml_file: str) -> Iterator[Dict[str, Any]]:
"""Parse Evernote xml."""
# Without huge_tree set to True, parser may complain about huge text node
# Try to recover, because there may be " ", which will cause
# "XMLSyntaxError: Entity 'nbsp' not def... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html |
15fe36f305fa-0 | Source code for langchain.document_loaders.discord
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 DiscordChatLoader(BaseLoader):
""... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/discord.html |
2a7eb74f17ec-0 | Source code for langchain.document_loaders.open_city_data
from typing import Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class OpenCityDataLoader(BaseLoader):
"""Load from `Open City`."""
[docs] def __init__(self, city_id: str, data... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/open_city_data.html |
9a481241dfc3-0 | Source code for langchain.document_loaders.airbyte_json
import json
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import stringify_dict
[docs]class AirbyteJSONLoader(BaseLoader):
"""Load local `Airbyte` json files... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte_json.html |
570e12937aee-0 | Source code for langchain.document_loaders.url
"""Loader that uses unstructured to load HTML files."""
import logging
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__name__)
[docs]class UnstructuredURLLoade... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html |
570e12937aee-1 | from unstructured.__version__ import __version__ as __unstructured_version__
self.__version = __unstructured_version__
except ImportError:
raise ImportError(
"unstructured package not found, please install it with "
"`pip install unstructured`"
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html |
570e12937aee-2 | _unstructured_version = self.__version.split("-")[0]
unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")])
return unstructured_version >= (0, 5, 13)
def __is_non_html_available(self) -> bool:
_unstructured_version = self.__version.split("-")[0]
unstructured... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html |
570e12937aee-3 | except Exception as e:
if self.continue_on_failure:
logger.error(f"Error fetching or processing {url}, exception: {e}")
continue
else:
raise e
if self.mode == "single":
text = "\n\n".join([str(el) for... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html |
a7960eea77b0-0 | Source code for langchain.document_loaders.youtube
"""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 langchain.docstore.document import Document
from la... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
a7960eea77b0-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) -... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
a7960eea77b0-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
a7960eea77b0-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
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
a7960eea77b0-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
a7960eea77b0-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
a7960eea77b0-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."""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
a7960eea77b0-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"]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
a7960eea77b0-8 | metadata=meta_data,
)
)
except (TranscriptsDisabled, NoTranscriptFound) as e:
if self.continue_on_failure:
logger.error(
"Error fetching transscript "
+ f" {ite... | lang/api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.