id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
494b51e3b578-10 | class Tokenizer:
chunk_overlap: int
tokens_per_chunk: int
decode: Callable[[list[int]], str]
encode: Callable[[str], List[int]]
[docs]def split_text_on_tokens(*, text: str, tokenizer: Tokenizer) -> List[str]:
"""Split incoming text and return chunks using tokenizer."""
splits: List[str] = []
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-11 | "Please install it with `pip install tiktoken`."
)
if model_name is not None:
enc = tiktoken.encoding_for_model(model_name)
else:
enc = tiktoken.get_encoding(encoding_name)
self._tokenizer = enc
self._allowed_special = allowed_special
self._dis... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-12 | "Please install it with `pip install sentence-transformers`."
)
self.model_name = model_name
self._model = SentenceTransformer(self.model_name)
self.tokenizer = self._model.tokenizer
self._initialize_chunk_configuration(tokens_per_chunk=tokens_per_chunk)
def _initialize_c... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-13 | def _encode(self, text: str) -> List[int]:
token_ids_with_start_and_end_token_ids = self.tokenizer.encode(
text,
max_length=self._max_length_equal_32_bit_integer,
truncation="do_not_truncate",
)
return token_ids_with_start_and_end_token_ids
[docs]class Languag... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-14 | self._is_separator_regex = is_separator_regex
def _split_text(self, text: str, separators: List[str]) -> List[str]:
"""Split incoming text and return chunks."""
final_chunks = []
# Get appropriate separator to use
separator = separators[-1]
new_separators = []
for i, ... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-15 | [docs] def split_text(self, text: str) -> List[str]:
return self._split_text(text, self._separators)
[docs] @classmethod
def from_language(
cls, language: Language, **kwargs: Any
) -> RecursiveCharacterTextSplitter:
separators = cls.get_separators_for_language(language)
ret... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-16 | "\nclass ",
# Split along method definitions
"\npublic ",
"\nprotected ",
"\nprivate ",
"\nstatic ",
# Split along control flow statements
"\nif ",
"\nfor ",
"\nwhile ",
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-17 | "",
]
elif language == Language.PHP:
return [
# Split along function definitions
"\nfunction ",
# Split along class definitions
"\nclass ",
# Split along control flow statements
"\nif ",
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-18 | "\n\n",
"\n",
" ",
"",
]
elif language == Language.RUBY:
return [
# Split along method definitions
"\ndef ",
"\nclass ",
# Split along control flow statements
"... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-19 | return [
# Split along function definitions
"\nfunc ",
# Split along class definitions
"\nclass ",
"\nstruct ",
"\nenum ",
# Split along control flow statements
"\nif ",
"\nfor... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-20 | "\n\\\\begin{description}",
"\n\\\\begin{list}",
"\n\\\\begin{quote}",
"\n\\\\begin{quotation}",
"\n\\\\begin{verse}",
"\n\\\\begin{verbatim}",
# Now split by math environments
"\n\\\begin{align}",
... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-21 | "\nif ",
"\ncontinue ",
"\nfor ",
"\nforeach ",
"\nwhile ",
"\nswitch ",
"\nbreak ",
"\ncase ",
"\nelse ",
# Split by exceptions
"\ntry ",
"\nth... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-22 | ) -> None:
"""Initialize the NLTK splitter."""
super().__init__(**kwargs)
try:
from nltk.tokenize import sent_tokenize
self._tokenizer = sent_tokenize
except ImportError:
raise ImportError(
"NLTK is not installed, please install it with... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
494b51e3b578-23 | [docs]class PythonCodeTextSplitter(RecursiveCharacterTextSplitter):
"""Attempts to split the text along Python syntax."""
[docs] def __init__(self, **kwargs: Any) -> None:
"""Initialize a PythonCodeTextSplitter."""
separators = self.get_separators_for_language(Language.PYTHON)
super().__i... | https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html |
03b43c6a34d9-0 | Source code for langchain.hub
"""Push and pull to the LangChain Hub."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional
from langchain.load.dump import dumps
from langchain.load.load import loads
if TYPE_CHECKING:
from langchainhub import Client
def _get_client(api_url: Optional[s... | https://api.python.langchain.com/en/latest/_modules/langchain/hub.html |
03b43c6a34d9-1 | :param parent_commit_hash: The commit hash of the parent commit to push to. Defaults
to the latest commit automatically.
:param new_repo_is_public: Whether the repo should be public. Defaults to
True (Public by default).
:param new_repo_description: The description of the repo. Defaults to an em... | https://api.python.langchain.com/en/latest/_modules/langchain/hub.html |
4c4259abcb11-0 | Source code for langchain.output_parsers.json
from __future__ import annotations
import json
import re
from json import JSONDecodeError
from typing import Any, Callable, List, Optional
import jsonpatch
from langchain.schema.output_parser import (
BaseCumulativeTransformOutputParser,
OutputParserException,
)
def... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html |
4c4259abcb11-1 | # Attempt to parse the string as-is.
try:
return json.loads(s, strict=strict)
except json.JSONDecodeError:
pass
# Initialize variables.
new_s = ""
stack = []
is_inside_string = False
escaped = False
# Process each character in the string one at a time.
for char in s:
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html |
4c4259abcb11-2 | return json.loads(new_s, strict=strict)
except json.JSONDecodeError:
# If we still can't parse the string as JSON, return None to indicate failure.
return None
[docs]def parse_json_markdown(
json_string: str, *, parser: Callable[[str], Any] = json.loads
) -> dict:
"""
Parse a JSON string... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html |
4c4259abcb11-3 | """
try:
json_obj = parse_json_markdown(text)
except json.JSONDecodeError as e:
raise OutputParserException(f"Got invalid JSON object. Error: {e}")
for key in expected_keys:
if key not in json_obj:
raise OutputParserException(
f"Got invalid return object. ... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/json.html |
6582e620960f-0 | Source code for langchain.output_parsers.pydantic
import json
import re
from typing import Type, TypeVar
from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS
from langchain.pydantic_v1 import BaseModel, ValidationError
from langchain.schema import BaseOutputParser, OutputParserException... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
6582e620960f-1 | # Ensure json in context is well-formed with double quotes.
schema_str = json.dumps(reduced_schema)
return PYDANTIC_FORMAT_INSTRUCTIONS.format(schema=schema_str)
@property
def _type(self) -> str:
return "pydantic" | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
f92023133b35-0 | Source code for langchain.output_parsers.list
from __future__ import annotations
import re
from abc import abstractmethod
from typing import List
from langchain.schema import BaseOutputParser
[docs]class ListOutputParser(BaseOutputParser[List[str]]):
"""Parse the output of an LLM call to a list."""
@property
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html |
f92023133b35-1 | """Parse the output of an LLM call."""
pattern = r"\d+\.\s([^\n]+)"
# Extract the text of each item
matches = re.findall(pattern, text)
return matches
@property
def _type(self) -> str:
return "numbered-list" | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html |
1bb4a13fa6d9-0 | Source code for langchain.output_parsers.structured
from __future__ import annotations
from typing import Any, List
from langchain.output_parsers.format_instructions import (
STRUCTURED_FORMAT_INSTRUCTIONS,
STRUCTURED_FORMAT_SIMPLE_INSTRUCTIONS,
)
from langchain.output_parsers.json import parse_and_check_json_m... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
1bb4a13fa6d9-1 | response_schemas = [
ResponseSchema(
name="foo",
description="a list of strings",
type="List[string]"
),
ResponseSchema(
name="bar",
description="a string",
type="string"
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
82b4add42ba5-0 | Source code for langchain.output_parsers.regex_dict
from __future__ import annotations
import re
from typing import Dict, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexDictParser(BaseOutputParser):
"""Parse the output of an LLM call into a Dictionary using a regex."""
regex_pattern: st... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html |
82b4add42ba5-1 | continue
else:
result[output_key] = matches[0]
return result | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html |
6598a11eb1d9-0 | Source code for langchain.output_parsers.xml
import re
import xml.etree.ElementTree as ET
from typing import Any, Dict, List, Optional
from langchain.output_parsers.format_instructions import XML_FORMAT_INSTRUCTIONS
from langchain.schema import BaseOutputParser
[docs]class XMLOutputParser(BaseOutputParser):
"""Pars... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/xml.html |
6598a11eb1d9-1 | return result
@property
def _type(self) -> str:
return "xml" | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/xml.html |
825f6688f949-0 | Source code for langchain.output_parsers.regex
from __future__ import annotations
import re
from typing import Dict, List, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexParser(BaseOutputParser):
"""Parse the output of an LLM call using a regex."""
[docs] @classmethod
def is_lc_seria... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/regex.html |
129e14fdadd9-0 | Source code for langchain.output_parsers.retry
from __future__ import annotations
from typing import Any, TypeVar
from langchain.prompts.prompt import PromptTemplate
from langchain.schema import (
BaseOutputParser,
BasePromptTemplate,
OutputParserException,
PromptValue,
)
from langchain.schema.language_... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
129e14fdadd9-1 | prompt: BasePromptTemplate = NAIVE_RETRY_PROMPT,
) -> RetryOutputParser[T]:
from langchain.chains.llm import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)
return cls(parser=parser, retry_chain=chain)
[docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
129e14fdadd9-2 | )
[docs] def get_format_instructions(self) -> str:
return self.parser.get_format_instructions()
@property
def _type(self) -> str:
return "retry"
[docs]class RetryWithErrorOutputParser(BaseOutputParser[T]):
"""Wraps a parser and tries to fix parsing errors.
Does this by passing the ori... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
129e14fdadd9-3 | try:
parsed_completion = self.parser.parse(completion)
except OutputParserException as e:
new_completion = self.retry_chain.run(
prompt=prompt_value.to_string(), completion=completion, error=repr(e)
)
parsed_completion = self.parser.parse(new_compl... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
b82ec6b502d5-0 | Source code for langchain.output_parsers.openai_functions
import copy
import json
from typing import Any, Dict, List, Optional, Type, Union
import jsonpatch
from langchain.output_parsers.json import parse_partial_json
from langchain.pydantic_v1 import BaseModel, root_validator
from langchain.schema import (
ChatGen... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html |
b82ec6b502d5-1 | """
args_only: bool = True
"""Whether to only return the arguments to the function call."""
def _diff(self, prev: Optional[Any], next: Any) -> Any:
return jsonpatch.make_patch(prev, next).patch
[docs] def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:
if le... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html |
b82ec6b502d5-2 | return {
**function_call,
"arguments": json.loads(
function_call["arguments"], strict=self.strict
),
}
except (json.JSONDecodeError, TypeError) as exc:
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html |
b82ec6b502d5-3 | " False."
)
return values
[docs] def parse_result(self, result: List[Generation], *, partial: bool = False) -> Any:
_result = super().parse_result(result)
if self.args_only:
pydantic_args = self.pydantic_schema.parse_raw(_result) # type: ignore
else:
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/openai_functions.html |
d127cc4185f1-0 | Source code for langchain.output_parsers.combining
from __future__ import annotations
from typing import Any, Dict, List
from langchain.pydantic_v1 import root_validator
from langchain.schema import BaseOutputParser
[docs]class CombiningOutputParser(BaseOutputParser):
"""Combine multiple output parsers into one."""... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/combining.html |
d127cc4185f1-1 | """Parse the output of an LLM call."""
texts = text.split("\n\n")
output = dict()
for txt, parser in zip(texts, self.parsers):
output.update(parser.parse(txt.strip()))
return output | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/combining.html |
c6ad6b2e842a-0 | Source code for langchain.output_parsers.boolean
from langchain.schema import BaseOutputParser
[docs]class BooleanOutputParser(BaseOutputParser[bool]):
"""Parse the output of an LLM call to a boolean."""
true_val: str = "YES"
"""The string value that should be parsed as True."""
false_val: str = "NO"
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/boolean.html |
602707c7ffe9-0 | Source code for langchain.output_parsers.fix
from __future__ import annotations
from typing import Any, TypeVar
from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT
from langchain.schema import BaseOutputParser, BasePromptTemplate, OutputParserException
from langchain.schema.language_model import BaseLanguageM... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html |
602707c7ffe9-1 | completion=completion,
error=repr(e),
)
parsed_completion = self.parser.parse(new_completion)
return parsed_completion
[docs] async def aparse(self, completion: str) -> T:
try:
parsed_completion = self.parser.parse(completion)
except OutputP... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html |
b6b075ca4a89-0 | Source code for langchain.output_parsers.enum
from enum import Enum
from typing import Any, Dict, List, Type
from langchain.pydantic_v1 import root_validator
from langchain.schema import BaseOutputParser, OutputParserException
[docs]class EnumOutputParser(BaseOutputParser):
"""Parse an output that is one of a set o... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/enum.html |
d73af9a31b6c-0 | Source code for langchain.output_parsers.datetime
import random
from datetime import datetime, timedelta
from typing import List
from langchain.schema import BaseOutputParser, OutputParserException
from langchain.utils import comma_list
def _generate_random_datetime_strings(
pattern: str,
n: int = 3,
start_... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html |
d73af9a31b6c-1 | return datetime.strptime(response.strip(), self.format)
except ValueError as e:
raise OutputParserException(
f"Could not parse datetime string: {response}"
) from e
@property
def _type(self) -> str:
return "datetime" | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html |
b97316eeedab-0 | Source code for langchain.output_parsers.loading
from langchain.output_parsers.regex import RegexParser
[docs]def load_output_parser(config: dict) -> dict:
"""Load an output parser.
Args:
config: config dict
Returns:
config dict with output parser loaded
"""
if "output_parsers" in co... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/loading.html |
2ba9d3c3854f-0 | Source code for langchain.output_parsers.rail_parser
from __future__ import annotations
from typing import Any, Callable, Dict, Optional
from langchain.schema import BaseOutputParser
[docs]class GuardrailsOutputParser(BaseOutputParser):
"""Parse the output of an LLM call using Guardrails."""
guard: Any
"""T... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
2ba9d3c3854f-1 | guard=Guard.from_rail(rail_file, num_reasks=num_reasks),
api=api,
args=args,
kwargs=kwargs,
)
[docs] @classmethod
def from_rail_string(
cls,
rail_str: str,
num_reasks: int = 1,
api: Optional[Callable] = None,
*args: Any,
... | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
2ba9d3c3854f-2 | return self.guard.raw_prompt.format_instructions
[docs] def parse(self, text: str) -> Dict:
return self.guard.parse(text, llm_api=self.api, *self.args, **self.kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
8304d100ad02-0 | Source code for langchain.document_loaders.obsidian
import logging
import re
from pathlib import Path
from typing import List
import yaml
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__name__)
[docs]class ObsidianLoader(BaseLoader):
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html |
8304d100ad02-1 | match = self.FRONT_MATTER_REGEX.search(content)
if not match:
return {}
try:
front_matter = yaml.safe_load(match.group(1))
# If tags are a string, split them into a list
if "tags" in front_matter and isinstance(front_matter["tags"], str):
f... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html |
8304d100ad02-2 | for match in self.DATAVIEW_INLINE_PAREN_REGEX.findall(content)
},
**{
match[0]: match[1]
for match in self.DATAVIEW_INLINE_BRACKET_REGEX.findall(content)
},
}
def _remove_front_matter(self, content: str) -> str:
"""Remove front matt... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html |
83c6c2c9cdad-0 | Source code for langchain.document_loaders.sitemap
import itertools
import re
from typing import Any, Callable, Generator, Iterable, List, Optional
from langchain.document_loaders.web_base import WebBaseLoader
from langchain.schema import Document
def _default_parsing_function(content: Any) -> str:
return str(conte... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
83c6c2c9cdad-1 | Default: 0
meta_function: Function to parse bs4.Soup output for metadata
remember when setting this method to also copy metadata["loc"]
to metadata["source"] if you are using this field
is_local: whether the sitemap is a local file. Default: False
cont... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
83c6c2c9cdad-2 | for url in soup.find_all("url"):
loc = url.find("loc")
if not loc:
continue
# Strip leading and trailing whitespace and newlines
loc_text = loc.text.strip()
if self.filter_urls and not any(
re.match(r, loc_text) for r in self.fi... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
83c6c2c9cdad-3 | "Selected sitemap does not contain enough blocks for given blocknum"
)
else:
els = elblocks[self.blocknum]
results = self.scrape_all([el["loc"].strip() for el in els if "loc" in el])
return [
Document(
page_content=self.parsing_func... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html |
4991155d91a7-0 | Source code for langchain.document_loaders.image
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredImageLoader(UnstructuredFileLoader):
"""Load `PNG` and `JPG` files using `Unstructured`.
You can run the loader in one of two modes: "single... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image.html |
d02d87416af5-0 | Source code for langchain.document_loaders.bigquery
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHECKING:
from google.auth.credentials import Credentials
[docs]clas... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html |
d02d87416af5-1 | self.project = project
self.page_content_columns = page_content_columns
self.metadata_columns = metadata_columns
self.credentials = credentials
[docs] def load(self) -> List[Document]:
try:
from google.cloud import bigquery
except ImportError as ex:
rai... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html |
e67fc181d6bc-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):
"""Load `Git` repository files.
The Repository can be local on disk avai... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html |
e67fc181d6bc-1 | raise ImportError(
"Could not import git python package. "
"Please install it with `pip install GitPython`."
) from ex
if not os.path.exists(self.repo_path) and self.clone_url is None:
raise ValueError(f"Path {self.repo_path} does not exist")
elif ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html |
e67fc181d6bc-2 | content = f.read()
file_type = os.path.splitext(item.name)[1]
# loads only text files
try:
text_content = content.decode("utf-8")
except UnicodeDecodeError:
continue
metada... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html |
39a1b56276fe-0 | Source code for langchain.document_loaders.notiondb
from typing import Any, Dict, List, Optional
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
NOTION_BASE_URL = "https://api.notion.com/v1"
DATABASE_URL = NOTION_BASE_URL + "/databases/{database_id... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
39a1b56276fe-1 | Returns:
List[Document]: List of documents.
"""
page_summaries = self._retrieve_page_summaries()
return list(self.load_page(page_summary) for page_summary in page_summaries)
def _retrieve_page_summaries(
self, query_dict: Dict[str, Any] = {"page_size": 100}
) -> List[... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
39a1b56276fe-2 | )
elif prop_type == "multi_select":
value = (
[item["name"] for item in prop_data["multi_select"]]
if prop_data["multi_select"]
else []
)
elif prop_type == "url":
value = prop_data["url"]
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
39a1b56276fe-3 | cur_block_id: str = block_id
while cur_block_id:
data = self._request(BLOCK_URL.format(block_id=cur_block_id))
for result in data["results"]:
result_obj = result[result["type"]]
if "rich_text" not in result_obj:
continue
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
21a2a0a83e1b-0 | Source code for langchain.document_loaders.mastodon
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_CHECKING:
import mastodon
d... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
21a2a0a83e1b-1 | Defaults to "https://mastodon.social".
"""
mastodon = _dependable_mastodon_import()
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_accoun... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
717bf9cc7987-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... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
717bf9cc7987-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/latest/_modules/langchain/document_loaders/youtube.html |
717bf9cc7987-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/latest/_modules/langchain/document_loaders/youtube.html |
717bf9cc7987-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/latest/_modules/langchain/document_loaders/youtube.html |
717bf9cc7987-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/latest/_modules/langchain/document_loaders/youtube.html |
717bf9cc7987-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/latest/_modules/langchain/document_loaders/youtube.html |
717bf9cc7987-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/latest/_modules/langchain/document_loaders/youtube.html |
717bf9cc7987-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/latest/_modules/langchain/document_loaders/youtube.html |
717bf9cc7987-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/latest/_modules/langchain/document_loaders/youtube.html |
79d3a2cd6a62-0 | Source code for langchain.document_loaders.gcs_directory
from typing import Callable, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.gcs_file import GCSFileLoader
[docs]class GCSDirectoryLoader(BaseLoader):
"""Lo... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html |
79d3a2cd6a62-1 | # intermediate directories on the fly
if blob.name.endswith("/"):
continue
loader = GCSFileLoader(
self.project_name, self.bucket, blob.name, loader_func=self._loader_func
)
docs.extend(loader.load())
return docs | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html |
d91f42c3f214-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... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tomarkdown.html |
5745e111d534-0 | Source code for langchain.document_loaders.recursive_url_loader
from __future__ import annotations
import asyncio
import logging
import re
from typing import (
TYPE_CHECKING,
Callable,
Iterator,
List,
Optional,
Sequence,
Set,
Union,
)
import requests
from langchain.docstore.document impo... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5745e111d534-1 | extractor: Optional[Callable[[str], str]] = None,
metadata_extractor: Optional[Callable[[str, str], str]] = None,
exclude_dirs: Optional[Sequence[str]] = (),
timeout: Optional[int] = 10,
prevent_outside: Optional[bool] = True,
link_regex: Union[str, re.Pattern, None] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5745e111d534-2 | URLs with error responses (400-599).
"""
self.url = url
self.max_depth = max_depth if max_depth is not None else 2
self.use_async = use_async if use_async is not None else False
self.extractor = extractor if extractor is not None else lambda x: x
self.metadata_extractor =... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5745e111d534-3 | try:
response = requests.get(url, timeout=self.timeout, headers=self.headers)
if self.check_response_status and 400 <= response.status_code <= 599:
raise ValueError(f"Received HTTP status {response.status_code}")
except Exception as e:
logger.warning(
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5745e111d534-4 | try:
import aiohttp
except ImportError:
raise ImportError(
"The aiohttp package is required for the RecursiveUrlLoader. "
"Please install it with `pip install aiohttp`."
)
if depth >= self.max_depth:
return []
# Disa... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5745e111d534-5 | url,
base_url=self.url,
pattern=self.link_regex,
prevent_outside=self.prevent_outside,
exclude_prefixes=self.exclude_dirs,
)
# Recursively call the function to get the children of the children
sub_tasks = []
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
5745e111d534-6 | """Load web pages."""
return list(self.lazy_load()) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html |
b5a2b38f330b-0 | Source code for langchain.document_loaders.srt
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class SRTLoader(BaseLoader):
"""Load `.srt` (subtitle) files."""
[docs] def __init__(self, file_path: str):
"""Initialize wi... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/srt.html |
1eef145d6a36-0 | Source code for langchain.document_loaders.tencent_cos_directory
from typing import Any, Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.tencent_cos_file import TencentCOSFileLoader
[docs]class TencentCOSDirectoryLoad... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tencent_cos_directory.html |
1eef145d6a36-1 | if content["Key"].endswith("/"):
continue
loader = TencentCOSFileLoader(self.conf, self.bucket, content["Key"])
yield loader.load()[0] | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tencent_cos_directory.html |
57695a516a30-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... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
57695a516a30-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._... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
57695a516a30-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... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
57695a516a30-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... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
57695a516a30-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... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
57695a516a30-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.
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
57695a516a30-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
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte.html |
0732117b3058-0 | Source code for langchain.document_loaders.joplin
import json
import urllib
from datetime import datetime
from typing import Iterator, List, Optional
from langchain.document_loaders.base import BaseLoader
from langchain.schema import Document
from langchain.utils import get_from_env
LINK_NOTE_TEMPLATE = "joplin://x-cal... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.