id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
1eb62ad31047-1 | return AgentExecutor.from_agent_and_tools(
agent=agent,
tools=tools,
callback_manager=callback_manager,
verbose=verbose,
**(agent_executor_kwargs or {}),
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/json/base.html |
6f3114951990-0 | Source code for langchain.prompts.few_shot_with_templates
"""Prompt template that contains few shot examples."""
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.prompts.base import DEFAULT_FORMATTER_MAPPING, StringPromptTemplate
from langchain.prompts.example_selec... | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
6f3114951990-1 | examples = values.get("examples", None)
example_selector = values.get("example_selector", None)
if examples and example_selector:
raise ValueError(
"Only one of 'examples' and 'example_selector' should be provided"
)
if examples is None and example_selecto... | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
6f3114951990-2 | kwargs: Any arguments to be passed to the prompt template.
Returns:
A formatted string.
Example:
.. code-block:: python
prompt.format(variable1="foo")
"""
kwargs = self._merge_partial_and_user_variables(**kwargs)
# Get the examples to use.
... | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
6f3114951990-3 | if self.example_selector:
raise ValueError("Saving an example selector is not currently supported")
return super().dict(**kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html |
1a3ba25d85e1-0 | Source code for langchain.prompts.few_shot
"""Prompt template that contains few shot examples."""
from typing import Any, Dict, List, Optional
from pydantic import Extra, root_validator
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
StringPromptTemplate,
check_valid_template,
)
from langcha... | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
1a3ba25d85e1-1 | """Check that one and only one of examples/example_selector are provided."""
examples = values.get("examples", None)
example_selector = values.get("example_selector", None)
if examples and example_selector:
raise ValueError(
"Only one of 'examples' and 'example_select... | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
1a3ba25d85e1-2 | # Get the examples to use.
examples = self._get_examples(**kwargs)
examples = [
{k: e[k] for k in self.example_prompt.input_variables} for e in examples
]
# Format the examples.
example_strings = [
self.example_prompt.format(**example) for example in examp... | https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html |
3a985bec72f3-0 | Source code for langchain.prompts.prompt
"""Prompt schema definition."""
from __future__ import annotations
from pathlib import Path
from string import Formatter
from typing import Any, Dict, List, Union
from pydantic import Extra, root_validator
from langchain.prompts.base import (
DEFAULT_FORMATTER_MAPPING,
S... | https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
3a985bec72f3-1 | """
kwargs = self._merge_partial_and_user_variables(**kwargs)
return DEFAULT_FORMATTER_MAPPING[self.template_format](self.template, **kwargs)
@root_validator()
def template_is_valid(cls, values: Dict) -> Dict:
"""Check that template and input variables are consistent."""
if value... | https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
3a985bec72f3-2 | [docs] @classmethod
def from_file(
cls, template_file: Union[str, Path], input_variables: List[str], **kwargs: Any
) -> PromptTemplate:
"""Load a prompt from a file.
Args:
template_file: The path to the file containing the prompt template.
input_variables: A li... | https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html |
3ef1818b91e0-0 | Source code for langchain.prompts.base
"""BasePrompt schema definition."""
from __future__ import annotations
import json
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Union
import yaml
from pydantic import BaseModel, Extra, Field, roo... | https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
3ef1818b91e0-1 | "jinja2 not installed, which is needed to use the jinja2_formatter. "
"Please install it with `pip install jinja2`."
)
env = Environment()
ast = env.parse(template)
variables = meta.find_undeclared_variables(ast)
return variables
DEFAULT_FORMATTER_MAPPING: Dict[str, Callable] = {
... | https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
3ef1818b91e0-2 | """Base class for all prompt templates, returning a prompt."""
input_variables: List[str]
"""A list of the names of the variables the prompt template expects."""
output_parser: Optional[BaseOutputParser] = None
"""How to parse the output of calling an LLM on this formatted prompt."""
partial_variabl... | https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
3ef1818b91e0-3 | prompt_dict["input_variables"] = list(
set(self.input_variables).difference(kwargs)
)
prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs}
return type(self)(**prompt_dict)
def _merge_partial_and_user_variables(self, **kwargs: Any) -> Dict[str, Any]:
# G... | https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
3ef1818b91e0-4 | # Convert file to Path object.
if isinstance(file_path, str):
save_path = Path(file_path)
else:
save_path = file_path
directory_path = save_path.parent
directory_path.mkdir(parents=True, exist_ok=True)
# Fetch dictionary to save
prompt_dict = self.... | https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html |
f8219b95718b-0 | Source code for langchain.prompts.chat
"""Chat prompt template."""
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any, Callable, List, Sequence, Tuple, Type, TypeVar, Union
from pydantic import BaseModel, Field
from langchain.memory.buffer import get_b... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
f8219b95718b-1 | def input_variables(self) -> List[str]:
"""Input variables for this prompt template."""
return [self.variable_name]
MessagePromptTemplateT = TypeVar(
"MessagePromptTemplateT", bound="BaseStringMessagePromptTemplate"
)
class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC):
prompt:... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
f8219b95718b-2 | def format(self, **kwargs: Any) -> BaseMessage:
text = self.prompt.format(**kwargs)
return HumanMessage(content=text, additional_kwargs=self.additional_kwargs)
class AIMessagePromptTemplate(BaseStringMessagePromptTemplate):
def format(self, **kwargs: Any) -> BaseMessage:
text = self.prompt.f... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
f8219b95718b-3 | def from_template(cls, template: str, **kwargs: Any) -> ChatPromptTemplate:
prompt_template = PromptTemplate.from_template(template, **kwargs)
message = HumanMessagePromptTemplate(prompt=prompt_template)
return cls.from_messages([message])
@classmethod
def from_role_strings(
cls,... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
f8219b95718b-4 | if isinstance(message_template, BaseMessage):
result.extend([message_template])
elif isinstance(message_template, BaseMessagePromptTemplate):
rel_params = {
k: v
for k, v in kwargs.items()
if k in message_template.in... | https://python.langchain.com/en/latest/_modules/langchain/prompts/chat.html |
df8ec58f996a-0 | Source code for langchain.prompts.loading
"""Load prompts from disk."""
import importlib
import json
import logging
from pathlib import Path
from typing import Union
import yaml
from langchain.output_parsers.regex import RegexParser
from langchain.prompts.base import BasePromptTemplate
from langchain.prompts.few_shot i... | https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
df8ec58f996a-1 | if template_path.suffix == ".txt":
with open(template_path) as f:
template = f.read()
else:
raise ValueError
# Set the template variable to the extracted variable.
config[var_name] = template
return config
def _load_examples(config: dict) -> dict:
... | https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
df8ec58f996a-2 | config = _load_template("prefix", config)
# Load the example prompt.
if "example_prompt_path" in config:
if "example_prompt" in config:
raise ValueError(
"Only one of example_prompt and example_prompt_path should "
"be specified."
)
config[... | https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
df8ec58f996a-3 | with open(file_path) as f:
config = json.load(f)
elif file_path.suffix == ".yaml":
with open(file_path, "r") as f:
config = yaml.safe_load(f)
elif file_path.suffix == ".py":
spec = importlib.util.spec_from_loader(
"prompt", loader=None, origin=str(file_path)
... | https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html |
e1604d77210c-0 | Source code for langchain.prompts.example_selector.length_based
"""Select examples based on length."""
import re
from typing import Callable, Dict, List
from pydantic import BaseModel, validator
from langchain.prompts.example_selector.base import BaseExampleSelector
from langchain.prompts.prompt import PromptTemplate
d... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
e1604d77210c-1 | get_text_length = values["get_text_length"]
string_examples = [example_prompt.format(**eg) for eg in values["examples"]]
return [get_text_length(eg) for eg in string_examples]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use base... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html |
2cc619722f14-0 | Source code for langchain.prompts.example_selector.semantic_similarity
"""Example selector that selects examples based on SemanticSimilarity."""
from __future__ import annotations
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Extra
from langchain.embeddings.base import Embeddings
fr... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
2cc619722f14-1 | return ids[0]
[docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]:
"""Select which examples to use based on semantic similarity."""
# Get the docs with the highest similarity.
if self.input_keys:
input_variables = {key: input_variables[key] for key in s... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
2cc619722f14-2 | instead of all variables.
vectorstore_cls_kwargs: optional kwargs containing url for vector store
Returns:
The ExampleSelector instantiated, backed by a vector store.
"""
if input_keys:
string_examples = [
" ".join(sorted_values({k: eg[k] for k... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
2cc619722f14-3 | examples = [dict(e.metadata) for e in example_docs]
# If example keys are provided, filter examples to those keys.
if self.example_keys:
examples = [{k: eg[k] for k in self.example_keys} for eg in examples]
return examples
[docs] @classmethod
def from_examples(
cls,
... | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
2cc619722f14-4 | string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs
)
return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html |
40040ac3e3cb-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
40040ac3e3cb-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
40040ac3e3cb-2 | "Please upgrade the unstructured package and try again."
)
if is_doc:
from unstructured.partition.doc import partition_doc
return partition_doc(filename=self.file_path, **self.unstructured_kwargs)
else:
from unstructured.partition.docx import partition_doc... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
5d4ba52650d9-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html |
5d4ba52650d9-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html |
5d4ba52650d9-2 | metadata = self._metadata_func(sample, metadata)
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 ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html |
40206397d2c3-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/epub.html |
b17fef0ba8f6-0 | Source code for langchain.document_loaders.srt
"""Loader for .srt (subtitle) files."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class SRTLoader(BaseLoader):
"""Loader for .srt (subtitle) files."""
def __init__(self, fil... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/srt.html |
a998e02a61cb-0 | Source code for langchain.document_loaders.docugami
"""Loader that loads processed documents from Docugami."""
import io
import logging
import os
import re
from pathlib import Path
from typing import Any, Dict, List, Mapping, Optional, Sequence, Union
import requests
from pydantic import BaseModel, root_validator
from ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
a998e02a61cb-1 | if values.get("file_paths") and values.get("docset_id"):
raise ValueError("Cannot specify both file_paths and remote API docset_id")
if not values.get("file_paths") and not values.get("docset_id"):
raise ValueError("Must specify either file_paths or remote API docset_id")
if valu... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
a998e02a61cb-2 | ancestor_chain = chunk.xpath("ancestor-or-self::*")
return "/" + "/".join(_xpath_qname_for_chunk(x) for x in ancestor_chain)
def _structure_value(node: Any) -> str:
"""Get the structure value for a node."""
structure = (
"table"
if node.tag == ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
a998e02a61cb-3 | """Create a Document from a node and text."""
metadata = {
XPATH_KEY: _xpath_for_chunk(node),
DOCUMENT_ID_KEY: document["id"],
DOCUMENT_NAME_KEY: document["name"],
STRUCTURE_KEY: node.attrib.get("structure", ""),
TAG_KEY: re.sub... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
a998e02a61cb-4 | while url:
response = requests.get(
url,
headers={"Authorization": f"Bearer {self.access_token}"},
)
if response.ok:
data = response.json()
all_documents.extend(data["documents"])
url = data.get("next", N... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
a998e02a61cb-5 | data={},
)
if response.ok:
data = response.json()
all_artifacts.extend(data["artifacts"])
url = data.get("next", None)
else:
raise Exception(
f"Failed to download {url} (status: {response.status_code}... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
a998e02a61cb-6 | per_file_metadata[doc_id] = metadata
else:
raise Exception(
f"Failed to download {artifact_url}/content "
+ "(status: {response.status_code})"
)
return per_file_metadata
def _load_chunks_for_document(
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
a998e02a61cb-7 | for project in _project_details:
metadata = self._metadata_for_project(project)
combined_project_metadata.update(metadata)
for doc in _document_details:
doc_metadata = combined_project_metadata.get(doc["id"])
chunks += self._load_chunks... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/docugami.html |
41295d2af60d-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
41295d2af60d-1 | return partition_pptx(filename=self.file_path, **self.unstructured_kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
47f79e84ed4d-0 | Source code for langchain.document_loaders.url_playwright
"""Loader that uses Playwright to load a page, then uses unstructured to load the html.
"""
import logging
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html |
47f79e84ed4d-1 | [docs] def load(self) -> List[Document]:
"""Load the specified URLs using Playwright and create Document instances.
Returns:
List[Document]: A list of Document instances with loaded content.
"""
from playwright.sync_api import sync_playwright
from unstructured.part... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html |
708d6c11ba78-0 | Source code for langchain.document_loaders.gcs_file
"""Loading logic for loading documents from a GCS 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 Uns... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_file.html |
8f514528499f-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html |
8f514528499f-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html |
8ad7d6fb0f2e-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html |
8ad7d6fb0f2e-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html |
8ad7d6fb0f2e-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html |
e19dfc7c0356-0 | Source code for langchain.document_loaders.dataframe
"""Load from Dataframe object"""
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class DataFrameLoader(BaseLoader):
"""Load Pandas DataFrames."""
def __init__(self, dat... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/dataframe.html |
30d7f162858d-0 | Source code for langchain.document_loaders.gcs_directory
"""Loading logic for loading documents from an GCS directory."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.gcs_file import GCSFileLoader
[docs]cl... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html |
c3d1f00a146d-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
c3d1f00a146d-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
c3d1f00a146d-2 | executor.map(lambda i: self.load_file(i, p, docs, pbar), items)
else:
for i in items:
self.load_file(i, p, docs, pbar)
if pbar:
pbar.close()
return docs
#
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
8d8679716569-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
8d8679716569-1 | if values.get("folder_id") and (
values.get("document_ids") or values.get("file_ids")
):
raise ValueError(
"Cannot specify both folder_id and document_ids nor "
"folder_id and file_ids"
)
if (
not values.get("folder_id")
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
8d8679716569-2 | return type_mapping[x] if x in type_mapping else x
values["file_types"] = [full_form(file_type) for file_type in file_types]
return values
@validator("credentials_path")
def validate_credentials_path(cls, v: Any, **kwargs: Any) -> Any:
"""Validate that credentials_path exists."""
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
8d8679716569-3 | with open(self.token_path, "w") as token:
token.write(creds.to_json())
return creds
def _load_sheet_from_id(self, id: str) -> List[Document]:
"""Load a sheet and all tabs from an ID."""
from googleapiclient.discovery import build
creds = self._load_credentials()
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
8d8679716569-4 | """Load a document from an ID."""
from io import BytesIO
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload
creds = self._load_credentials()
service = build("drive", "v3", credentia... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
8d8679716569-5 | if file_types:
_files = [f for f in files if f["mimeType"] in file_types] # type: ignore
else:
_files = files
returns = []
for file in files:
if file["trashed"] and not self.load_trashed_files:
continue
elif file["mimeType"] == "ap... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
8d8679716569-6 | else:
returns.append(file)
return returns
def _load_documents_from_ids(self) -> List[Document]:
"""Load documents from a list of IDs."""
if not self.document_ids:
raise ValueError("document_ids must be set")
return [self._load_document_from_id(doc_id) for ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
8d8679716569-7 | raise ValueError("file_ids must be set")
docs = []
for file_id in self.file_ids:
docs.extend(self._load_file_from_id(file_id))
return docs
[docs] def load(self) -> List[Document]:
"""Load documents."""
if self.folder_id:
return self._load_documents_from... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
01800f6c7086-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... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
01800f6c7086-1 | import fitz
parent_dir = Path(self.file_path).parent
# regex is useful for Zotero flavor bibtex files
file_names = self.file_regex.findall(entry.get("file", ""))
if not file_names:
return None
texts: List[str] = []
for file_name in file_names:
try:... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
01800f6c7086-2 | yield doc
[docs] def load(self) -> List[Document]:
"""Load bibtex file documents from the given bibtex file path.
See https://bibtexparser.readthedocs.io/en/master/
Args:
file_path: the path to the bibtex file
Returns:
a list of documents with the document.page... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
b5a482a970bc-0 | Source code for langchain.document_loaders.unstructured
"""Loader that uses unstructured to load files."""
import collections
from abc import ABC, abstractmethod
from typing import IO, Any, List, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
b5a482a970bc-1 | import unstructured # noqa:F401
except ImportError:
raise ValueError(
"unstructured package not found, please install it with "
"`pip install unstructured`"
)
_valid_modes = {"single", "elements"}
if mode not in _valid_modes:
r... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
b5a482a970bc-2 | docs = [Document(page_content=text, metadata=metadata)]
else:
raise ValueError(f"mode of {self.mode} not supported.")
return docs
[docs]class UnstructuredFileLoader(UnstructuredBaseLoader):
"""Loader that uses unstructured to load files."""
def __init__(
self,
file_pa... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
b5a482a970bc-3 | elements.extend(_elements)
return elements
else:
from unstructured.partition.api import partition_via_api
return partition_via_api(
filename=file_path,
file=file,
api_key=api_key,
api_url=api_url,
**unstructured_kwargs,
)
[d... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
b5a482a970bc-4 | file: Union[IO, Sequence[IO]],
mode: str = "single",
**unstructured_kwargs: Any,
):
"""Initialize with file path."""
self.file = file
super().__init__(mode=mode, **unstructured_kwargs)
def _get_elements(self) -> List:
from unstructured.partition.auto import partit... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html |
4032dd26e093-0 | Source code for langchain.document_loaders.azure_blob_storage_container
"""Loading logic for loading documents from an Azure Blob Storage container."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.azure_blob_storage_file import (
AzureBlobStorageFileLoader... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_container.html |
e2807c8d5fdb-0 | Source code for langchain.document_loaders.apify_dataset
"""Logic for loading documents from Apify datasets."""
from typing import Any, Callable, Dict, List
from pydantic import BaseModel, root_validator
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html |
e2807c8d5fdb-1 | )
return values
[docs] def load(self) -> List[Document]:
"""Load documents."""
dataset_items = self.apify_client.dataset(self.dataset_id).list_items().items
return list(map(self.dataset_mapping_function, dataset_items))
By Harrison Chase
© Copyright 2023, Harrison Chase.
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html |
e15cc9f869d2-0 | Source code for langchain.document_loaders.web_base
"""Web base loader class."""
import asyncio
import logging
import warnings
from typing import Any, List, Optional, Union
import aiohttp
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = log... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
e15cc9f869d2-1 | ):
"""Initialize with webpage path."""
# TODO: Deprecate web_path in favor of web_paths, and remove this
# left like this because there are a number of loaders that expect single
# urls
if isinstance(web_path, str):
self.web_paths = [web_path]
elif isinstance(... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
e15cc9f869d2-2 | return await response.text()
except aiohttp.ClientConnectionError as e:
if i == retries - 1:
raise
else:
logger.warning(
f"Error fetching {url} with attempt "
f... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
e15cc9f869d2-3 | )
[docs] def scrape_all(self, urls: List[str], parser: Union[str, None] = None) -> List[Any]:
"""Fetch all urls, then return soups for all results."""
from bs4 import BeautifulSoup
results = asyncio.run(self.fetch_all(urls))
final_results = []
for i, result in enumerate(result... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
e15cc9f869d2-4 | docs.append(Document(page_content=text, metadata=metadata))
return docs
[docs] def aload(self) -> List[Document]:
"""Load text from the urls in web_path async into Documents."""
results = self.scrape_all(self.web_paths)
docs = []
for i in range(len(results)):
soup ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
5b19f82d185f-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html |
5b19f82d185f-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html |
492c874320d4-0 | Source code for langchain.document_loaders.text
import logging
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.helpers import detect_file_encodings
logger = logging.getLogger(__name__)
[docs]class T... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html |
492c874320d4-1 | except Exception as e:
raise RuntimeError(f"Error loading {self.file_path}") from e
metadata = {"source": self.file_path}
return [Document(page_content=text, metadata=metadata)]
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html |
245e48105859-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html |
91ed3ad8fdc8-0 | Source code for langchain.document_loaders.telegram
"""Loader that loads Telegram chat json dump."""
from __future__ import annotations
import asyncio
import json
from pathlib import Path
from typing import TYPE_CHECKING, Dict, List, Optional, Union
from langchain.docstore.document import Document
from langchain.docume... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
91ed3ad8fdc8-1 | if isinstance(text, str):
# Take a single string as one page
text = [text]
page_docs = [Document(page_content=page) for page in text]
# Add page numbers as metadata
for i, doc in enumerate(page_docs):
doc.metadata["page"] = i + 1
# Split pages into chunks
doc_chunks = []
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
91ed3ad8fdc8-2 | [docs] async def fetch_data_from_telegram(self) -> None:
"""Fetch data from Telegram API and save it as a JSON file."""
from telethon.sync import TelegramClient
data = []
async with TelegramClient(self.username, self.api_id, self.api_hash) as client:
async for message in c... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
91ed3ad8fdc8-3 | Args:
parent_id (int): The parent message ID.
reply_data (pd.DataFrame): A DataFrame containing reply messages.
Returns:
list: A list of message IDs that are replies to the parent message ID.
"""
# Find direct replies to the parent mess... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
91ed3ad8fdc8-4 | Args:
message_threads (dict): A dictionary where the key is the parent message \
ID and the value is a list of message IDs in ascending order.
data (pd.DataFrame): A DataFrame containing the conversation data:
- message.sender_id
- text
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
91ed3ad8fdc8-5 | please install with `pip install pandas`
"""
)
normalized_messages = pd.json_normalize(d)
df = pd.DataFrame(normalized_messages)
message_threads = self._get_message_threads(df)
combined_texts = self._combine_message_texts(message_threads, df)
return te... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html |
9d11c7fbc301-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://python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
9d11c7fbc301-1 | title = ""
metadata: Dict[str, Union[str, None]] = {
"source": self.file_path,
"title": title,
}
return [Document(page_content=text, metadata=metadata)]
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.