id stringlengths 14 16 | source stringlengths 49 117 | text stringlengths 16 2.73k |
|---|---|---|
39cb87b1200b-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html | 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:
wit... |
39cb87b1200b-2 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html | """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_content in text format
"""
return list(self.l... |
c24691be44c8-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html | Source code for langchain.document_loaders.image_captions
"""
Loader that loads image captions
By default, the loader utilizes the pre-trained BLIP image captioning model.
https://huggingface.co/Salesforce/blip-image-captioning-base
"""
from typing import Any, List, Tuple, Union
import requests
from langchain.docstore.... |
c24691be44c8-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html | doc = Document(page_content=caption, metadata=metadata)
results.append(doc)
return results
def _get_captions_and_metadata(
self, model: Any, processor: Any, path_image: str
) -> Tuple[str, dict]:
"""
Helper function for getting the captions and metadata of an image
... |
8e3feae567a0-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html | Source code for langchain.document_loaders.csv_loader
import csv
from typing import Dict, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class CSVLoader(BaseLoader):
"""Loads a CSV file into a list of documents.
Each document represen... |
8e3feae567a0-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html | content = "\n".join(f"{k.strip()}: {v.strip()}" for k, v in row.items())
try:
source = (
row[self.source_column]
if self.source_column is not None
else self.file_path
)
except ... |
530ca3f4803c-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_file.html | 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... |
613425a6a57d-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html | 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... |
613425a6a57d-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html | 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")
and not values.get("document_ids")
... |
613425a6a57d-2 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html | 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."""
if not v.exists():
raise ValueError(f"credenti... |
613425a6a57d-3 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html | 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()
sheets_service = build("sheets", "v4", credentials=creds)
spreadsheet = sheets_service.spreadsheets()... |
613425a6a57d-4 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html | from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload
creds = self._load_credentials()
service = build("drive", "v3", credentials=creds)
file = service.files().get(fileId=id, supportsAllDrives=True).execute()
request = service.files().e... |
613425a6a57d-5 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html | returns = []
for file in files:
if file["trashed"] and not self.load_trashed_files:
continue
elif file["mimeType"] == "application/vnd.google-apps.document":
returns.append(self._load_document_from_id(file["id"])) # type: ignore
elif file["mim... |
613425a6a57d-6 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html | return [self._load_document_from_id(doc_id) for doc_id in self.document_ids]
def _load_file_from_id(self, id: str) -> List[Document]:
"""Load a file from an ID."""
from io import BytesIO
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
... |
613425a6a57d-7 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html | return self._load_documents_from_folder(
self.folder_id, file_types=self.file_types
)
elif self.document_ids:
return self._load_documents_from_ids()
else:
return self._load_file_from_ids()
By Harrison Chase
© Copyright 2023, Harrison Chase.
... |
dfe740a96200-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/markdown.html | Source code for langchain.document_loaders.markdown
"""Loader that loads Markdown files."""
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredMarkdownLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to load markdown files."""
... |
e5a6ca771ca5-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html | 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 ... |
e5a6ca771ca5-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html | [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.
Last updated on J... |
b58c9e613a7b-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/mediawikidump.html | Source code for langchain.document_loaders.mediawikidump
"""Load Data from a MediaWiki dump xml."""
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class MWDumpLoader(BaseLoader):
"""
Load MediaWiki dump from XML fil... |
b58c9e613a7b-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/mediawikidump.html | docs.append(Document(page_content=text, metadata=metadata))
return docs
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
57f59e1b4a8e-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/facebook_chat.html | 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) -... |
c9c96205b539-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html | 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):
... |
c9c96205b539-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gitbook.html | """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 = urljoin(self.base_url, path)
print(f"Fetch... |
86fc62079112-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html | Source code for langchain.document_loaders.blockchain
import os
import re
import time
from enum import Enum
from typing import List, Optional
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
class BlockchainType(Enum):
ETH_MAINNET = "eth-mainnet... |
86fc62079112-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html | blockchainType: BlockchainType = BlockchainType.ETH_MAINNET,
api_key: str = "docs-demo",
startToken: str = "",
get_all_tokens: bool = False,
max_execution_time: Optional[int] = None,
):
self.contract_address = contract_address
self.blockchainType = blockchainType.valu... |
86fc62079112-2 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html | "tokenId": tokenId,
}
result.append(Document(page_content=content, metadata=metadata))
# exit after the first API call if get_all_tokens is False
if not self.get_all_tokens:
break
# get the start token for the next API call from the las... |
86fc62079112-3 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html | def _detect_value_type(tokenId: str) -> str:
if isinstance(tokenId, int):
return "int"
elif tokenId.startswith("0x"):
return "hex_0x"
elif tokenId.startswith("0xbf"):
return "hex_0xbf"
else:
return "hex_0xbf"
By Harrison Chase
© ... |
7dfab82497b9-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html | Source code for langchain.document_loaders.spreedly
"""Loader that fetches data from Spreedly API."""
import json
import urllib.request
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import stringify_dict
SPREEDLY_ENDP... |
7dfab82497b9-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html | return [Document(page_content=text, metadata=metadata)]
def _get_resource(self) -> List[Document]:
endpoint = SPREEDLY_ENDPOINTS.get(self.resource)
if endpoint is None:
return []
return self._make_request(endpoint)
[docs] def load(self) -> List[Document]:
return self._... |
0f425d7ed3aa-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/discord.html | Source code for langchain.document_loaders.discord
"""Load from Discord chat dump"""
from __future__ import annotations
from typing import TYPE_CHECKING, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHECKING:
import pandas as pd
[docs]class Dis... |
a7ae9f8c19e8-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/rtf.html | Source code for langchain.document_loaders.rtf
"""Loader that loads rich text files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
satisfies_min_unstructured_version,
)
[docs]class UnstructuredRTFLoader(UnstructuredFileLoader):
"""Loader that u... |
d70a6c46b1ec-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_directory.html | Source code for langchain.document_loaders.s3_directory
"""Loading logic for loading documents from an s3 directory."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.s3_file import S3FileLoader
[docs]class ... |
6cea27b55c9a-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html | 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... |
6cea27b55c9a-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html | 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_titles = json.loads(result.content)["body"]
... |
8f13a38e8819-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/arxiv.html | Source code for langchain.document_loaders.arxiv
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utilities.arxiv import ArxivAPIWrapper
[docs]class ArxivLoader(BaseLoader):
"""Loads a query result from arxiv.org... |
7f0dc8eb31df-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/onedrive_file.html | Source code for langchain.document_loaders.onedrive_file
from __future__ import annotations
import tempfile
from typing import TYPE_CHECKING, List
from pydantic import BaseModel, Field
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders... |
caf46924cec2-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html | 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 ... |
e7cafdeb4aff-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/college_confidential.html | 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... |
0e1dcfa8ac07-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/whatsapp_chat.html | Source code for langchain.document_loaders.whatsapp_chat
import re
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(date: str, sender: str, text: str) -> str:
"""Combine message information i... |
0e1dcfa8ac07-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/whatsapp_chat.html | metadata = {"source": str(p)}
return [Document(page_content=text_content, metadata=metadata)]
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
b96026bb96f2-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/stripe.html | Source code for langchain.document_loaders.stripe
"""Loader that fetches data from Stripe"""
import json
import urllib.request
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import get_from_env, stringify_dic... |
b96026bb96f2-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/stripe.html | [docs] def load(self) -> List[Document]:
return self._get_resource()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
c75bebb119f4-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/conllu.html | 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... |
e3932ad5c8af-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/max_compute.html | Source code for langchain.document_loaders.max_compute
from __future__ import annotations
from typing import Any, Iterator, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utilities.max_compute import MaxComputeAPIWrapper
[d... |
e3932ad5c8af-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/max_compute.html | endpoint: MaxCompute endpoint.
project: A project is a basic organizational unit of MaxCompute, which is
similar to a database.
access_id: MaxCompute access ID. Should be passed in directly or set as the
environment variable `MAX_COMPUTE_ACCESS_ID`.
se... |
d723dd7421c8-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/roam.html | Source code for langchain.document_loaders.roam
"""Loader that loads Roam directory dump."""
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class RoamLoader(BaseLoader):
"""Loader that loads Roam files fr... |
2fbb030228fc-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_file.html | 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... |
56041dbb9950-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/excel.html | Source code for langchain.document_loaders.excel
"""Loader that loads Microsoft Excel files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructured_version,
)
[docs]class UnstructuredExcelLoader(UnstructuredFileLoader):
"""Loader t... |
085a50365fca-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/azlyrics.html | 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] ... |
104761ebcdf2-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html | 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 =... |
104761ebcdf2-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html | 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 load(self) -> List[Document]:
if self.page_type == ... |
104761ebcdf2-2 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html | 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.select_one(".post-content .post-text").text.strip())
answersHeader ... |
104761ebcdf2-3 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html | if key in data
]
).strip()
metadata = {"source": self.web_path, "title": data["title"]}
documents.append(Document(page_content=text, metadata=metadata))
if include_guides:
"""Load and return documents for each guide linked to from the device"""
guide_u... |
104761ebcdf2-4 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/ifixit.html | row["title"]
if row["title"] != ""
else "Step {}".format(row["orderby"])
)
)
for line in row["lines"]:
doc_parts.append(line["text_raw"])
doc_parts.append(data["conclusion_raw"])
text = "\n".join(doc_parts)
... |
b821acbb6407-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_container.html | 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... |
88f4ed2aef35-0 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html | 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 ... |
88f4ed2aef35-1 | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html | 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_content_columns
if self.metadata_columns is None:
metadata_columns = []
... |
369e7b6c442d-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html | Source code for langchain.llms.databricks
import os
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional
import requests
from pydantic import BaseModel, Extra, Field, PrivateAttr, root_validator, validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langch... |
369e7b6c442d-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html | # See https://docs.databricks.com/machine-learning/model-serving/score-model-serving-endpoints.html
wrapped_request = {"dataframe_records": [request]}
response = self.post_raw(wrapped_request)["predictions"]
# For a single-record query, the result is not a list.
if isinstance(response, l... |
369e7b6c442d-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html | host = os.getenv("DATABRICKS_HOST")
if not host:
try:
host = get_repl_context().browserHostName
if not host:
raise ValueError("context doesn't contain browserHostName.")
except Exception as e:
raise ValueError(
"host was not set and... |
369e7b6c442d-3 | https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html | Set ``endpoint_name`` accordingly and do not set ``cluster_id`` and
``cluster_driver_port``.
The expected model signature is:
* inputs::
[{"name": "prompt", "type": "string"},
{"name": "stop", "type": "list[string]"}]
* outputs: ``[{"type": "string"}]``
* **Cluster drive... |
369e7b6c442d-4 | https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html | If not provided, the default value is determined by
* the ``DATABRICKS_HOST`` environment variable if present, or
* the hostname of the current Databricks workspace if running inside
a Databricks notebook attached to an interactive cluster in "single user"
or "no isolation shared" mode.
"""
... |
369e7b6c442d-5 | https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html | We recommend the server using a port number between ``[3000, 8000]``.
"""
model_kwargs: Optional[Dict[str, Any]] = None
"""Extra parameters to pass to the endpoint."""
transform_input_fn: Optional[Callable] = None
"""A function that transforms ``{prompt, stop, **kwargs}`` into a JSON-compatible
... |
369e7b6c442d-6 | https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html | raise ValueError("Cannot set both endpoint_name and cluster_driver_port.")
elif values["endpoint_name"]:
return None
elif v is None:
raise ValueError(
"Must set cluster_driver_port to connect to a cluster driver."
)
elif int(v) <= 0:
... |
369e7b6c442d-7 | https://python.langchain.com/en/latest/_modules/langchain/llms/databricks.html | run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""Queries the LLM endpoint with the given prompt and stop sequence."""
# TODO: support callbacks
request = {"prompt": prompt, "stop": stop}
if self.model_kwargs:
request.update(self.model_kwargs)
i... |
70e40758fede-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html | Source code for langchain.llms.huggingface_hub
"""Wrapper around HuggingFace APIs."""
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enf... |
70e40758fede-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html | @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"
)
try:
... |
70e40758fede-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html | """Call out to HuggingFace Hub's inference endpoint.
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
... |
07f61111ffc2-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html | Source code for langchain.llms.bedrock
import json
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
class LLMInputOutp... |
07f61111ffc2-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html | To authenticate, the AWS client uses the following methods to
automatically load credentials:
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
If a specific credential profile should be used, you must pass
the name of the profile from the ~/.aws/credentials file that is to ... |
07f61111ffc2-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html | """Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that AWS credentials to and python package exists in environment."""
# Skip creating new client if passed in constructor
if values... |
07f61111ffc2-3 | https://python.langchain.com/en/latest/_modules/langchain/llms/bedrock.html | run_manager: Optional[CallbackManagerForLLMRun] = None,
) -> str:
"""Call out to Bedrock service model.
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.
... |
be0fec3a0075-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html | Source code for langchain.llms.self_hosted
"""Run model inference on self-hosted remote hardware."""
import importlib.util
import logging
import pickle
from typing import Any, Callable, List, Mapping, Optional
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llm... |
be0fec3a0075-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html | logger.warning(
"Device has %d GPUs available. "
"Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 for CPU and "
"can be a positive integer associated with CUDA device id.",
cuda_device_coun... |
be0fec3a0075-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html | )
Example for <2GB model (can be serialized and sent directly to the server):
.. code-block:: python
from langchain.llms import SelfHostedPipeline
import runhouse as rh
gpu = rh.cluster(name="rh-a10x", instance_type="A100:1")
my_model = ...
llm = S... |
be0fec3a0075-3 | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html | """Configuration for this pydantic object."""
extra = Extra.forbid
def __init__(self, **kwargs: Any):
"""Init the pipeline with an auxiliary function.
The load function must be in global scope to be imported
and run on the server, i.e. in a module and not a REPL or closure.
T... |
be0fec3a0075-4 | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html | load_fn_kwargs = {"pipeline": pipeline, "device": device}
return cls(
load_fn_kwargs=load_fn_kwargs,
model_load_fn=_send_pipeline_to_device,
hardware=hardware,
model_reqs=["transformers", "torch"] + (model_reqs or []),
**kwargs,
)
@property... |
55f6653bf6eb-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html | Source code for langchain.llms.mosaicml
"""Wrapper around MosaicML APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils impo... |
55f6653bf6eb-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html | "https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict"
)
"""Endpoint URL to use."""
inject_instruction_format: bool = False
"""Whether to inject the instruction format into the prompt."""
model_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model."""
retry... |
55f6653bf6eb-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html | prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
is_retry: bool = False,
) -> str:
"""Call out to a MosaicML LLM inference endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional l... |
55f6653bf6eb-3 | https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html | f"Error raised by inference API, no key data: {parsed_response}"
)
generated_text = parsed_response["data"]
except requests.exceptions.JSONDecodeError as e:
raise ValueError(
f"Error raised by inference API: {e}.\nResponse: {response.text}"
)
... |
63ed32933add-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html | Source code for langchain.llms.huggingface_text_gen_inference
"""Wrapper around Huggingface text generation inference API."""
from functools import partial
from typing import Any, Dict, List, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from... |
63ed32933add-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html | max_new_tokens = 512,
top_k = 10,
top_p = 0.95,
typical_p = 0.95,
temperature = 0.01,
repetition_penalty = 1.03,
)
print(llm("What is Deep Learning?"))
# Streaming response example
... |
63ed32933add-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html | values["client"] = text_generation.Client(
values["inference_server_url"], timeout=values["timeout"]
)
except ImportError:
raise ImportError(
"Could not import text_generation python package. "
"Please install it with `pip install text_gene... |
63ed32933add-3 | https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_text_gen_inference.html | "top_k": self.top_k,
"top_p": self.top_p,
"typical_p": self.typical_p,
"temperature": self.temperature,
"repetition_penalty": self.repetition_penalty,
"seed": self.seed,
}
text = ""
for res in self.client... |
932ce7e190b2-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html | Source code for langchain.llms.writer
"""Wrapper around Writer APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import e... |
932ce7e190b2-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html | """Whether to return log probabilities."""
n: Optional[int] = None
"""How many completions to generate."""
writer_api_key: Optional[str] = None
"""Writer API key."""
base_url: Optional[str] = None
"""Base url to use, if None decides based on model name."""
class Config:
"""Configurat... |
932ce7e190b2-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html | **{"model_id": self.model_id, "writer_org_id": self.writer_org_id},
**self._default_params,
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "writer"
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
ru... |
932ce7e190b2-3 | https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html | Last updated on Jun 04, 2023. |
8d99de6ba11a-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html | Source code for langchain.llms.beam
"""Wrapper around Beam API."""
import base64
import json
import logging
import subprocess
import textwrap
import time
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import Callba... |
8d99de6ba11a-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html | call_result = llm._call(input)
"""
model_name: str = ""
name: str = ""
cpu: str = ""
memory: str = ""
gpu: str = ""
python_version: str = ""
python_packages: List[str] = []
max_length: str = ""
url: str = ""
"""model endpoint to use"""
model_kwargs: Dict[str, Any] = Field... |
8d99de6ba11a-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html | beam_client_id = get_from_dict_or_env(
values, "beam_client_id", "BEAM_CLIENT_ID"
)
beam_client_secret = get_from_dict_or_env(
values, "beam_client_secret", "BEAM_CLIENT_SECRET"
)
values["beam_client_id"] = beam_client_id
values["beam_client_secret"] = bea... |
8d99de6ba11a-3 | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html | )
script_name = "app.py"
with open(script_name, "w") as file:
file.write(
script.format(
name=self.name,
cpu=self.cpu,
memory=self.memory,
gpu=self.gpu,
python_version=self.pyt... |
8d99de6ba11a-4 | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html | "https://raw.githubusercontent.com/slai-labs"
"/get-beam/main/get-beam.sh -sSfL | sh`."
)
self.app_creation()
self.run_creation()
process = subprocess.run(
"beam deploy app.py", shell=True, capture_output=True, text=True
)
if process.return... |
8d99de6ba11a-5 | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html | "Accept-Encoding": "gzip, deflate",
"Authorization": "Basic " + self.authorization,
"Connection": "keep-alive",
"Content-Type": "application/json",
}
for _ in range(DEFAULT_NUM_TRIES):
request = requests.post(url, headers=headers, data=json.dumps(payload))... |
e10c8c970323-0 | https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html | Source code for langchain.llms.gpt4all
"""Wrapper for the GPT4All model."""
from functools import partial
from typing import Any, Dict, List, Mapping, Optional, Set
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from... |
e10c8c970323-1 | https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html | """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_mlock")
"""Force system to keep model in RAM."""
embedding: bool = Field(False, alias="embedding")
... |
e10c8c970323-2 | https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html | """If model does not exist in ~/.cache/gpt4all/, download it."""
client: Any = None #: :meta private:
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@staticmethod
def _model_param_names() -> Set[str]:
return {
"n_ctx",
"n... |
e10c8c970323-3 | https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html | model_type=values["backend"],
allow_download=values["allow_download"],
)
if values["n_threads"] is not None:
# set n_threads
values["client"].model.set_thread_count(values["n_threads"])
values["backend"] = values["client"].model_type
return values
... |
e10c8c970323-4 | https://python.langchain.com/en/latest/_modules/langchain/llms/gpt4all.html | text += token
if stop is not None:
text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.