id stringlengths 14 16 | text stringlengths 44 2.73k | source stringlengths 49 115 |
|---|---|---|
460e23266d9f-0 | Source code for langchain.document_loaders.notiondb
"""Notion DB loader for langchain"""
from typing import Any, Dict, List
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... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
460e23266d9f-1 | def _retrieve_page_ids(
self, query_dict: Dict[str, Any] = {"page_size": 100}
) -> List[str]:
"""Get all the pages from a Notion database."""
pages: List[Dict[str, Any]] = []
while True:
data = self._request(
DATABASE_URL.format(database_id=self.database_i... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
460e23266d9f-2 | metadata[prop_name.lower()] = value
metadata["id"] = page_id
return Document(page_content=self._load_blocks(page_id), metadata=metadata)
def _load_blocks(self, block_id: str, num_tabs: int = 0) -> str:
"""Read a block and its children."""
result_lines_arr: List[str] = []
cur_... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
460e23266d9f-3 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html |
a6c779fee4dc-0 | Source code for langchain.document_loaders.directory
"""Loading logic for loading documents from a directory."""
import logging
from pathlib import Path
from typing import List, Type, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_lo... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
a6c779fee4dc-1 | [docs] def load(self) -> List[Document]:
"""Load documents."""
p = Path(self.path)
docs = []
items = list(p.rglob(self.glob) if self.recursive else p.glob(self.glob))
pbar = None
if self.show_progress:
try:
from tqdm import tqdm
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html |
6dd107be477b-0 | Source code for langchain.document_loaders.word_document
"""Loader that loads word documents."""
import os
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredWordDocumentLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to load w... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
6dd107be477b-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
e44210fb6bb7-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 |
e44210fb6bb7-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 |
e44210fb6bb7-2 | if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
str(self.credentials_path), SCOPES
)
creds = f... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
e44210fb6bb7-3 | title = header[j].strip() if len(header) > j else ""
content.append(f"{title}: {v.strip()}")
page_content = "\n".join(content)
documents.append(Document(page_content=page_content, metadata=metadata))
return documents
def _load_document_from_id(self, id: st... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
e44210fb6bb7-4 | from googleapiclient.discovery import build
creds = self._load_credentials()
service = build("drive", "v3", credentials=creds)
files = self._fetch_files_recursive(service, folder_id)
returns = []
for file in files:
if file["mimeType"] == "application/vnd.google-apps.d... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
e44210fb6bb7-5 | 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 doc_id in self.document_ids]
def _load_file_fro... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
e44210fb6bb7-6 | 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_folder(self.folder_id)
elif self.documen... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
0d91528ce774-0 | Source code for langchain.document_loaders.bigquery
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class BigQueryLoader(BaseLoader):
"""Loads a query result from BigQuery into a list of documents.
Each document repr... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html |
0d91528ce774-1 | metadata_columns = []
for row in query_result:
page_content = "\n".join(
f"{k}: {v}" for k, v in row.items() if k in page_content_columns
)
metadata = {k: v for k, v in row.items() if k in metadata_columns}
doc = Document(page_content=page_content,... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html |
0dbe06141e66-0 | Source code for langchain.document_loaders.notebook
"""Loader that loads .ipynb notebook files."""
import json
from pathlib import Path
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_cells(
cell: dict, include_outp... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
0dbe06141e66-1 | return f"'{cell_type}' cell: '{source}'\n\n"
return ""
def remove_newlines(x: Any) -> Any:
"""Remove recursively newlines, no matter the data structure they are stored in."""
import pandas as pd
if isinstance(x, str):
return x.replace("\n", "")
elif isinstance(x, list):
return [remov... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
0dbe06141e66-2 | if self.remove_newline:
filtered_data = filtered_data.applymap(remove_newlines)
text = filtered_data.apply(
lambda x: concatenate_cells(
x, self.include_outputs, self.max_output_length, self.traceback
),
axis=1,
).str.cat(sep=" ")
m... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
38aed8cf6975-0 | Source code for langchain.document_loaders.slack_directory
"""Loader for documents from a Slack export."""
import json
import zipfile
from pathlib import Path
from typing import Dict, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class Slack... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html |
38aed8cf6975-1 | channel_name = Path(channel_path).parent.name
if not channel_name:
continue
if channel_path.endswith(".json"):
messages = self._read_json(zip_file, channel_path)
for message in messages:
document = self._... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html |
38aed8cf6975-2 | "timestamp": timestamp,
"user": user,
}
def _get_message_source(self, channel_name: str, user: str, timestamp: str) -> str:
"""
Get the message source as a string.
Args:
channel_name (str): The name of the channel the message belongs to.
user (str)... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html |
2d76eca8de2d-0 | Source code for langchain.document_loaders.ifixit
"""Loader that loads iFixit data."""
from typing import List, Optional
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.web_base import WebBaseLoader
IFIXIT_BASE_URL =... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html |
2d76eca8de2d-1 | """Teardowns are just guides by a different name"""
self.page_type = pieces[0] if pieces[0] != "Teardown" else "Guide"
if self.page_type == "Guide" or self.page_type == "Answers":
self.id = pieces[2]
else:
self.id = pieces[1]
self.web_path = web_path
[docs] def... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html |
2d76eca8de2d-2 | self, url_override: Optional[str] = None
) -> List[Document]:
loader = WebBaseLoader(self.web_path if url_override is None else url_override)
soup = loader.scrape()
output = []
title = soup.find("h1", "post-title").text
output.append("# " + title)
output.append(soup.s... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html |
2d76eca8de2d-3 | text = "\n".join(
[
data[key]
for key in ["title", "description", "contents_raw"]
if key in data
]
).strip()
metadata = {"source": self.web_path, "title": data["title"]}
documents.append(Document(page_content=text, metadata=... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html |
2d76eca8de2d-4 | doc_parts.append("\n - " + part["text"])
for row in data["steps"]:
doc_parts.append(
"\n\n## "
+ (
row["title"]
if row["title"] != ""
else "Step {}".format(row["orderby"])
)
)
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html |
8540fe7f2173-0 | Source code for langchain.document_loaders.bilibili
import json
import re
import warnings
from typing import List, Tuple
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class BiliBiliLoader(BaseLoader):
"""Loader that loads bilibili trans... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html |
8540fe7f2173-1 | video_info = sync(v.get_info())
video_info.update({"url": url})
# Get subtitle url
subtitle = video_info.pop("subtitle")
sub_list = subtitle["list"]
if sub_list:
sub_url = sub_list[0]["subtitle_url"]
result = requests.get(sub_url)
raw_sub_title... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html |
9b417e4a8582-0 | Source code for langchain.document_loaders.gutenberg
"""Loader that loads .txt web files."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class GutenbergLoader(BaseLoader):
"""Loader that uses urllib to load .txt web files."""
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gutenberg.html |
df8e0a11371a-0 | Source code for langchain.document_loaders.pdf
"""Loader that loads PDF files."""
import os
import tempfile
from abc import ABC
from io import StringIO
from typing import Any, List, Optional
from urllib.parse import urlparse
import requests
from langchain.docstore.document import Document
from langchain.document_loader... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
df8e0a11371a-1 | self.web_path = self.file_path
self.temp_file = tempfile.NamedTemporaryFile()
self.temp_file.write(r.content)
self.file_path = self.temp_file.name
elif not os.path.isfile(self.file_path):
raise ValueError("File path %s is not a valid file or url" % self.file_path)... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
df8e0a11371a-2 | return [
Document(
page_content=page.extract_text(),
metadata={"source": self.file_path, "page": i},
)
for i, page in enumerate(pdf_reader.pages)
]
[docs]class PDFMinerLoader(BasePDFLoader):
"""Loader that uses PDFMi... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
df8e0a11371a-3 | from pdfminer.layout import LAParams
from pdfminer.utils import open_filename
output_string = StringIO()
with open_filename(self.file_path, "rb") as fp:
extract_text_to_fp(
fp, # type: ignore[arg-type]
output_string,
codec="",
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
df8e0a11371a-4 | if type(doc.metadata[k]) in [str, int]
}
),
)
for page in doc
]
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
b37dfa840c41-0 | Source code for langchain.document_loaders.conllu
"""Load CoNLL-U files."""
import csv
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class CoNLLULoader(BaseLoader):
"""Load CoNLL-U files."""
def __init__(self, file_path: str... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/conllu.html |
ec48e4649b85-0 | Source code for langchain.document_loaders.gitbook
"""Loader that loads GitBook."""
from typing import Any, List, Optional
from urllib.parse import urljoin, urlparse
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class GitbookLoader(WebBaseLoader):
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
ec48e4649b85-1 | [docs] def load(self) -> List[Document]:
"""Fetch text from one single GitBook page."""
if self.load_all_paths:
soup_info = self.scrape()
relative_paths = self._get_paths(soup_info)
documents = []
for path in relative_paths:
url = urljoi... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html |
a5cf4904619d-0 | Source code for langchain.document_loaders.blockchain
import os
import re
from enum import Enum
from typing import List
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
class BlockchainType(Enum):
ETH_MAINNET = "eth-mainnet"
ETH_GOERLI = "et... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html |
a5cf4904619d-1 | raise ValueError(f"Invalid contract address {self.contract_address}")
[docs] def load(self) -> List[Document]:
url = (
f"https://{self.blockchainType}.g.alchemy.com/nft/v2/"
f"{self.api_key}/getNFTsForCollection?withMetadata="
f"True&contractAddress={self.contract_address}... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html |
74425117eee9-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 |
74425117eee9-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 |
ed87cdd056d7-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 |
ed87cdd056d7-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 Apr 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
81acb89cb3bb-0 | Source code for langchain.document_loaders.college_confidential
"""Loader that loads College Confidential."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class CollegeConfidentialLoader(WebBaseLoader):
"""Loader that lo... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/college_confidential.html |
b74be1108512-0 | Source code for langchain.document_loaders.twitter
"""Twitter document loader."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHEC... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html |
b74be1108512-1 | user = api.get_user(screen_name=username)
docs = self._format_tweets(tweets, user)
results.extend(docs)
return results
def _format_tweets(
self, tweets: List[Dict[str, Any]], user_info: dict
) -> Iterable[Document]:
"""Format tweets into a string."""
for t... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html |
b74be1108512-2 | access_token=access_token,
access_token_secret=access_token_secret,
consumer_key=consumer_key,
consumer_secret=consumer_secret,
)
return cls(
auth_handler=auth,
twitter_users=twitter_users,
number_tweets=number_tweets,
)
By ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html |
9a3b4dc326e8-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 |
fe926d877ed2-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 |
fe926d877ed2-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 |
4de6465c43e7-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 |
c8c227083f76-0 | Source code for langchain.document_loaders.chatgpt
"""Load conversations from ChatGPT data export"""
import datetime
import json
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(message: dict, title: str) -> str:
if ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html |
c8c227083f76-1 | documents.append(Document(page_content=text, metadata=metadata))
return documents
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html |
26751ce6f17c-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 |
26751ce6f17c-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 |
26751ce6f17c-2 | if i == retries - 1:
raise
else:
logger.warning(
f"Error fetching {url} with attempt "
f"{i + 1}/{retries}: {e}. Retrying..."
)
await asyncio.sleep(... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
26751ce6f17c-3 | """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(results):
url = urls[i]
if parser is None:
if url.endswith(".xml"):
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
26751ce6f17c-4 | results = self.scrape_all(self.web_paths)
docs = []
for i in range(len(results)):
soup = results[i]
text = soup.get_text()
metadata = _build_metadata(soup, self.web_paths[i])
docs.append(Document(page_content=text, metadata=metadata))
return docs
B... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
f1e297c05262-0 | Source code for langchain.document_loaders.hn
"""Loader that loads HN."""
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class HNLoader(WebBaseLoader):
"""Load Hacker News data from either main page results or the com... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html |
f1e297c05262-1 | title = lineItem.find("span", {"class": "titleline"}).text.strip()
metadata = {
"source": self.web_path,
"title": title,
"link": link,
"ranking": ranking,
}
documents.append(
Document(
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html |
5a214e75e4ad-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 |
b750721fd7bd-0 | Source code for langchain.document_loaders.s3_file
"""Loading logic for loading documents from an s3 file."""
import os
import tempfile
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import Unst... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_file.html |
31da3aeb3ac0-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 |
31da3aeb3ac0-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 |
614a3d591d7c-0 | Source code for langchain.document_loaders.youtube
"""Loader that loads YouTube transcript."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from pydantic.dataclasses import dataclass
from langchain.docstore.do... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
614a3d591d7c-1 | 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) -> Any:
"""Load credentials."""
# Adapted from https://developers.go... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
614a3d591d7c-2 | """Loader that loads Youtube transcripts."""
def __init__(
self,
video_id: str,
add_video_info: bool = False,
language: str = "en",
continue_on_failure: bool = False,
):
"""Initialize with YouTube video ID."""
self.video_id = video_id
self.add_vide... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
614a3d591d7c-3 | en_transcript = transcript_list.find_transcript(["en"])
transcript = en_transcript.translate(self.language)
transcript_pieces = transcript.fetch()
transcript = " ".join([t["text"].strip(" ") for t in transcript_pieces])
return [Document(page_content=transcript, metadata=metadata)]
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
614a3d591d7c-4 | .. code-block:: python
from langchain.document_loaders import GoogleApiClient
from langchain.document_loaders import GoogleApiYoutubeLoader
google_api_client = GoogleApiClient(
service_account_path=Path("path_to_your_sec_file.json")
)
loader = ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
614a3d591d7c-5 | if not values.get("channel_name") and not values.get("video_ids"):
raise ValueError("Must specify either channel_name or video_ids")
return values
def _get_transcripe_for_video_id(self, video_id: str) -> str:
from youtube_transcript_api import NoTranscriptFound, YouTubeTranscriptApi
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
614a3d591d7c-6 | channel_id = response["items"][0]["id"]["channelId"]
return channel_id
def _get_document_for_channel(self, channel: str, **kwargs: Any) -> List[Document]:
try:
from youtube_transcript_api import (
NoTranscriptFound,
TranscriptsDisabled,
)
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
614a3d591d7c-7 | )
else:
raise e
pass
request = self.youtube_client.search().list_next(request, response)
return video_ids
[docs] def load(self) -> List[Document]:
"""Load documents."""
document_list = []
if self.channel_name:... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
bb198b68e00c-0 | Source code for langchain.document_loaders.azlyrics
"""Loader that loads AZLyrics."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class AZLyricsLoader(WebBaseLoader):
"""Loader that loads AZLyrics webpages."""
[docs] ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/azlyrics.html |
de8e65f69020-0 | Source code for langchain.document_loaders.facebook_chat
"""Loader that loads Facebook chat json dump."""
import datetime
import json
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(row: dict) -... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/facebook_chat.html |
de8e65f69020-1 | df_filtered = df_filtered[["timestamp_ms", "content", "sender_name"]]
text = df_filtered.apply(concatenate_rows, axis=1).str.cat(sep="")
metadata = {"source": str(p)}
return [Document(page_content=text, metadata=metadata)]
By Harrison Chase
© Copyright 2023, Harrison Chase.
L... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/facebook_chat.html |
09c988d15e74-0 | Source code for langchain.document_loaders.hugging_face_dataset
"""Loader that loads HuggingFace datasets."""
from typing import List, Mapping, Optional, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class HuggingFaceDatasetLoader(BaseLoade... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
09c988d15e74-1 | self.page_content_column = page_content_column
self.name = name
self.data_dir = data_dir
self.data_files = data_files
self.cache_dir = cache_dir
self.keep_in_memory = keep_in_memory
self.save_infos = save_infos
self.use_auth_token = use_auth_token
self.num... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
fe89ec8fae28-0 | Source code for langchain.output_parsers.list
from __future__ import annotations
from abc import abstractmethod
from typing import List
from langchain.schema import BaseOutputParser
[docs]class ListOutputParser(BaseOutputParser):
"""Class to parse the output of an LLM call to a list."""
@property
def _type(... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html |
d8fa054def50-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):
"""Class to parse the output into a dictionary."""
regex_pattern: str = r"{}:\s?([^.'\n'... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html |
c6d10de1545c-0 | Source code for langchain.output_parsers.pydantic
import json
import re
from typing import Type, TypeVar
from pydantic import BaseModel, ValidationError
from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS
from langchain.schema import BaseOutputParser, OutputParserException
T = TypeVar(... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
c6d10de1545c-1 | @property
def _type(self) -> str:
return "pydantic"
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html |
513587d3d62d-0 | Source code for langchain.output_parsers.structured
from __future__ import annotations
import json
from typing import Any, List
from pydantic import BaseModel
from langchain.output_parsers.format_instructions import STRUCTURED_FORMAT_INSTRUCTIONS
from langchain.schema import BaseOutputParser, OutputParserException
line... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
513587d3d62d-1 | ) -> StructuredOutputParser:
return cls(response_schemas=response_schemas)
[docs] def get_format_instructions(self) -> str:
schema_str = "\n".join(
[_get_sub_string(schema) for schema in self.response_schemas]
)
return STRUCTURED_FORMAT_INSTRUCTIONS.format(format=schema_st... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html |
ca4affcb96c3-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):
"""Class to parse the output into a dictionary."""
regex: str
output_keys: List[str]
... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex.html |
20eeef642f35-0 | Source code for langchain.output_parsers.retry
from __future__ import annotations
from typing import TypeVar
from langchain.chains.llm import LLMChain
from langchain.prompts.base import BasePromptTemplate
from langchain.prompts.prompt import PromptTemplate
from langchain.schema import (
BaseLanguageModel,
BaseO... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
20eeef642f35-1 | 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:
try:
parsed_completion = self.parser.parse(completion)
except OutputParserException:
new_completio... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
20eeef642f35-2 | ) -> RetryWithErrorOutputParser[T]:
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:
try:
parsed_completion = self.parser.parse(completion)
except Outp... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html |
a59abe659aca-0 | Source code for langchain.output_parsers.fix
from __future__ import annotations
from typing import TypeVar
from langchain.chains.llm import LLMChain
from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT
from langchain.prompts.base import BasePromptTemplate
from langchain.schema import BaseLanguageModel, BaseOut... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html |
9042fcfacd92-0 | Source code for langchain.output_parsers.rail_parser
from __future__ import annotations
from typing import Any, Dict
from langchain.schema import BaseOutputParser
[docs]class GuardrailsOutputParser(BaseOutputParser):
guard: Any
@property
def _type(self) -> str:
return "guardrails"
[docs] @classme... | https://python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html |
145e1df8e24d-0 | Source code for langchain.llms.huggingface_endpoint
"""Wrapper around HuggingFace APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
145e1df8e24d-1 | extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
huggingfacehub_api_token = get_from_dict_or_env(
values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
145e1df8e24d-2 | Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
response = hf("Tell me a joke.")
"""
_mod... | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
145e1df8e24d-3 | # stop tokens when making calls to huggingface_hub.
text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
0ebce49197db-0 | Source code for langchain.llms.llamacpp
"""Wrapper around llama.cpp."""
import logging
from typing import Any, Dict, Generator, List, Optional
from pydantic import Field, root_validator
from langchain.llms.base import LLM
logger = logging.getLogger(__name__)
[docs]class LlamaCpp(LLM):
"""Wrapper around the llama.cp... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
0ebce49197db-1 | """Use half-precision for key/value cache."""
logits_all: bool = Field(False, alias="logits_all")
"""Return logits for all tokens, not just the last token."""
vocab_only: bool = Field(False, alias="vocab_only")
"""Only load the vocabulary, no weights."""
use_mlock: bool = Field(False, alias="use_mlo... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
0ebce49197db-2 | top_k: Optional[int] = 40
"""The top-k value to use for sampling."""
last_n_tokens_size: Optional[int] = 64
"""The number of tokens to look back when applying the repeat_penalty."""
use_mmap: Optional[bool] = True
"""Whether to keep the model loaded in RAM"""
streaming: bool = True
"""Whethe... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
0ebce49197db-3 | n_threads=n_threads,
n_batch=n_batch,
use_mmap=use_mmap,
last_n_tokens_size=last_n_tokens_size,
)
except ImportError:
raise ModuleNotFoundError(
"Could not import llama-cpp-python library. "
"Please install t... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
0ebce49197db-4 | Args:
stop (Optional[List[str]]): List of stop sequences for llama_cpp.
Returns:
Dictionary containing the combined parameters.
"""
# Raise error if stop sequences are in both input and default params
if self.stop and stop is not None:
raise ValueError... | https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.