id
stringlengths
14
16
text
stringlengths
44
2.73k
source
stringlengths
49
114
c3bc2f3fbb9c-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
e5589608af86-0
Source code for langchain.document_loaders.csv_loader from csv import DictReader 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 d...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html
e5589608af86-1
with open(self.file_path, newline="", encoding=self.encoding) as csvfile: csv = DictReader(csvfile, **self.csv_args) # type: ignore for i, row in enumerate(csv): content = "\n".join(f"{k.strip()}: {v.strip()}" for k, v in row.items()) if self.source_column is not...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html
3a5b2d04548d-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
3a5b2d04548d-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
3a5b2d04548d-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
0a901d8d090a-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
0a901d8d090a-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
0a901d8d090a-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
0a901d8d090a-3
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html
b0b61d1c6543-0
Source code for langchain.document_loaders.readthedocs """Loader that loads ReadTheDocs documentation directory dump.""" from pathlib import Path from typing import Any, List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class ReadTheDocsLoader(B...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html
b0b61d1c6543-1
text = text[0].get_text() else: text = "" return "\n".join([t for t in text.split("\n") if t]) docs = [] for p in Path(self.file_path).rglob("*"): if p.is_dir(): continue with open(p, encoding=self.encoding, errors=self.erro...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html
3edc009100e7-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
ef57e4e64ca9-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
ef57e4e64ca9-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
ef57e4e64ca9-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
ef57e4e64ca9-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
ef57e4e64ca9-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
ef57e4e64ca9-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
ef57e4e64ca9-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
614bc78f9dcb-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
614bc78f9dcb-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
b44ec3fdcb33-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
bc8d05ced339-0
Source code for langchain.document_loaders.text from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class TextLoader(BaseLoader): """Load text files.""" def __init__(self, file_path: str, encoding: Optional[str] = None):...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html
a2d5f7a5f039-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
a2d5f7a5f039-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
a2d5f7a5f039-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
a2d5f7a5f039-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
a2d5f7a5f039-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
073e1f990ca5-0
Source code for langchain.document_loaders.confluence """Load Data from a Confluence Space""" import logging from typing import Any, Callable, List, Optional, Union from tenacity import ( before_sleep_log, retry, stop_after_attempt, wait_exponential, ) from langchain.docstore.document import Document fr...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-1
:param url: _description_ :type url: str :param api_key: _description_, defaults to None :type api_key: str, optional :param username: _description_, defaults to None :type username: str, optional :param oauth2: _description_, defaults to {} :type oauth2: dict, optional :param cloud: _de...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-2
if errors: raise ValueError(f"Error(s) while validating input: {errors}") self.base_url = url self.number_of_retries = number_of_retries self.min_retry_seconds = min_retry_seconds self.max_retry_seconds = max_retry_seconds try: from atlassian import Conflu...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-3
"`username` and provide a value for `oauth2`" ) if oauth2 and oauth2.keys() != [ "access_token", "access_token_secret", "consumer_key", "key_cert", ]: errors.append( "You have either ommited require keys or added ext...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-4
:param include_comments: defaults to False :type include_comments: bool, optional :param limit: Maximum number of pages to retrieve per request, defaults to 50 :type limit: int, optional :param max_pages: Maximum number of pages to retrieve in total, defaults 1000 :type max_pages...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-5
max_pages=max_pages, expand="body.storage.value", ) for page in pages: doc = self.process_page( page, include_attachments, include_comments, text_maker ) docs.append(doc) if cql: pages = self....
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-6
doesn't match the limit value. If `limit` is >100 confluence seems to cap the response to 100. Also, due to the Atlassian Python package, we don't get the "next" values from the "_links" key because they only return the value from the results key. So here, the pagination starts from 0 a...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-7
return docs[:max_pages] [docs] def process_page( self, page: dict, include_attachments: bool, include_comments: bool, text_maker: Any, ) -> Document: if include_attachments: attachment_texts = self.process_attachment(page["id"]) else: ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-8
texts = [] for attachment in attachments: media_type = attachment["metadata"]["mediaType"] absolute_url = self.base_url + attachment["_links"]["download"] title = attachment["title"] if media_type == "application/pdf": text = title + self.process_p...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-9
or response.content == b"" or response.content is None ): return text try: images = convert_from_bytes(response.content) except ValueError: return text for i, image in enumerate(images): image_text = pytesseract.image_to_string(...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-10
text = "" if ( response.status_code != 200 or response.content == b"" or response.content is None ): return text file_data = BytesIO(response.content) return docx2txt.process(file_data) [docs] def process_xls(self, link: str) -> str: ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
073e1f990ca5-11
"`pytesseract`, `Pillow`, or `svglib` package not found," "please run `pip install pytesseract Pillow svglib`" ) response = self.confluence.request(path=link, absolute=True) text = "" if ( response.status_code != 200 or response.content == b"" ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
2291f40ef84b-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
2291f40ef84b-1
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html
3b4c55411188-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
3b4c55411188-1
documents.append(Document(page_content=text, metadata=metadata)) return documents By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html
3f466f1f3b76-0
Source code for langchain.document_loaders.html """Loader that uses unstructured to load HTML files.""" from typing import List from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredHTMLLoader(UnstructuredFileLoader): """Loader that uses unstructured to load HTML files."...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/html.html
f45709be2157-0
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...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/roam.html
81f0d772a7aa-0
Source code for langchain.document_loaders.evernote """Load documents from Evernote. https://gist.github.com/foxmask/7b29c43a161e001ff04afdb2f181e31c """ import hashlib from base64 import b64decode from time import strptime from typing import Any, Dict, List from langchain.docstore.document import Document from langcha...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
81f0d772a7aa-1
else: note_dict[elem.tag] = elem.text note_dict["resource"] = resources return note_dict def _parse_note_xml(xml_file: str) -> str: """Parse Evernote xml.""" # Without huge_tree set to True, parser may complain about huge text node # Try to recover, because there may be " ", which w...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
c64b22e034dc-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
c64b22e034dc-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
c64b22e034dc-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
c64b22e034dc-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
c64b22e034dc-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
a2bebfc28a5e-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
dddccd30eb77-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
dddccd30eb77-1
"source": self.file_path, "title": title, } return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html
8935ea941e75-0
Source code for langchain.document_loaders.imsdb """Loader that loads IMSDb.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.web_base import WebBaseLoader [docs]class IMSDbLoader(WebBaseLoader): """Loader that loads IMSDb webpages.""" [docs] def load(se...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/imsdb.html
6491fe68634a-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
cba7a2cf41a5-0
Source code for langchain.document_loaders.sitemap """Loader that fetches a sitemap and loads those URLs.""" import re from typing import Any, Callable, List, Optional from langchain.document_loaders.web_base import WebBaseLoader from langchain.schema import Document def _default_parsing_function(content: Any) -> str: ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
cba7a2cf41a5-1
re.match(r, loc.text) for r in self.filter_urls ): continue els.append( { tag: prop.text for tag in ["loc", "lastmod", "changefreq", "priority"] if (prop := url.find(tag)) } ) ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
744d4a904198-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
744d4a904198-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
744d4a904198-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
744d4a904198-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
744d4a904198-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
744d4a904198-5
return result["choices"][0]["text"] [docs] def stream( self, prompt: str, stop: Optional[List[str]] = None ) -> Generator[Dict, None, None]: """Yields results objects as they are generated in real time. BETA: this is a beta feature while we figure out the right abstraction: Once t...
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
744d4a904198-6
token=token, verbose=self.verbose, log_probs=log_probs ) yield chunk By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/llms/llamacpp.html
c01f71c0543f-0
Source code for langchain.llms.aleph_alpha """Wrapper around Aleph Alpha APIs.""" from typing import Any, Dict, List, Optional, Sequence from pydantic import Extra, root_validator from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.utils import get_from_dict_or_env [d...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
c01f71c0543f-1
presence_penalty: float = 0.0 """Penalizes repeated tokens.""" frequency_penalty: float = 0.0 """Penalizes repeated tokens according to frequency.""" repetition_penalties_include_prompt: Optional[bool] = False """Flag deciding whether presence penalty or frequency penalty are updated from the pr...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
c01f71c0543f-2
sequence_penalty: float = 0.0 sequence_penalty_min_length: int = 2 use_multiplicative_sequence_penalty: bool = False completion_bias_inclusion: Optional[Sequence[str]] = None completion_bias_inclusion_first_token_only: bool = False completion_bias_exclusion: Optional[Sequence[str]] = None comple...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
c01f71c0543f-3
values, "aleph_alpha_api_key", "ALEPH_ALPHA_API_KEY" ) try: import aleph_alpha_client values["client"] = aleph_alpha_client.Client(token=aleph_alpha_api_key) except ImportError: raise ValueError( "Could not import aleph_alpha_client python pack...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
c01f71c0543f-4
"sequence_penalty": self.sequence_penalty, "sequence_penalty_min_length": self.sequence_penalty_min_length, "use_multiplicative_sequence_penalty": self.use_multiplicative_sequence_penalty, # noqa: E501 "completion_bias_inclusion": self.completion_bias_inclusion, "complet...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
c01f71c0543f-5
from aleph_alpha_client import CompletionRequest, Prompt params = self._default_params if self.stop_sequences is not None and stop is not None: raise ValueError( "stop sequences found in both the input and default params." ) elif self.stop_sequences is not...
https://python.langchain.com/en/latest/_modules/langchain/llms/aleph_alpha.html
9022a96104ae-0
Source code for langchain.llms.predictionguard """Wrapper around Prediction Guard APIs.""" import logging from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.utils import get_from_...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
9022a96104ae-1
values["client"] = pg.Client(token=token) except ImportError: raise ValueError( "Could not import predictionguard python package. " "Please install it with `pip install predictionguard`." ) return values @property def _default_params(self) ...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
9022a96104ae-2
"temperature": params["temperature"], }, ) text = response["text"] # If stop tokens are provided, Prediction Guard's endpoint returns them. # In order to make this consistent with other endpoints, we strip them. if stop is not None or self.stop is not None: ...
https://python.langchain.com/en/latest/_modules/langchain/llms/predictionguard.html
a25311748176-0
Source code for langchain.llms.sagemaker_endpoint """Wrapper around Sagemaker InvokeEndpoint API.""" from abc import abstractmethod from typing import Any, Dict, Generic, List, Mapping, Optional, TypeVar, Union from pydantic import Extra, root_validator from langchain.llms.base import LLM from langchain.llms.utils impo...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
a25311748176-1
def transform_input(self, prompt: INPUT_TYPE, model_kwargs: Dict) -> bytes: """Transforms the input to a format that model can accept as the request Body. Should return bytes or seekable file like object in the format specified in the content_type request header. """ @abstrac...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
a25311748176-2
) se = SagemakerEndpoint( endpoint_name=endpoint_name, region_name=region_name, credentials_profile_name=credentials_profile_name ) """ client: Any #: :meta private: endpoint_name: str = "" """The name of the endpoint from the depl...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
a25311748176-3
response_json = json.loads(output.read().decode("utf-8")) return response_json[0]["generated_text"] """ model_kwargs: Optional[Dict] = None """Key word arguments to pass to the model.""" endpoint_kwargs: Optional[Dict] = None """Optional attributes passed to the invoke_endpoint ...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
a25311748176-4
"""Get the identifying parameters.""" _model_kwargs = self.model_kwargs or {} return { **{"endpoint_name": self.endpoint_name}, **{"model_kwargs": _model_kwargs}, } @property def _llm_type(self) -> str: """Return type of llm.""" return "sagemaker_e...
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
a25311748176-5
text = enforce_stop_tokens(text, stop) return text By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/llms/sagemaker_endpoint.html
81ade6317d2b-0
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.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.utils import get_from_dict_or_env...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
81ade6317d2b-1
@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: ...
https://python.langchain.com/en/latest/_modules/langchain/llms/huggingface_hub.html
81ade6317d2b-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_hub.html
01c44ee1d92e-0
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.llms.base import LLM from langchain.llms.utils import enforce_stop_tokens from langchain.utils import get_from_dict_or_e...
https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html
01c44ee1d92e-1
by fixing the random seed (assuming all other hyperparameters are also fixed)""" beam_search_diversity_rate: float = 1.0 """Only applies to beam search, i.e. when the beam width is >1. A higher value encourages beam search to return a more diverse set of candidates""" beam_width: Optional[int] =...
https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html
01c44ee1d92e-2
"temperature": self.temperature, "top_p": self.top_p, "top_k": self.top_k, "repetition_penalty": self.repetition_penalty, "random_seed": self.random_seed, "beam_search_diversity_rate": self.beam_search_diversity_rate, "beam_width": self.beam_width,...
https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html
01c44ee1d92e-3
}, json={"prompt": prompt, **self._default_params}, ) text = response.text if stop is not None: # I believe this is required since the stop tokens # are not enforced by the model parameters text = enforce_stop_tokens(text, stop) return text...
https://python.langchain.com/en/latest/_modules/langchain/llms/writer.html
5d4b6aa210f4-0
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.llms.base import LLM from langchain.llms.utils import enforce_stop_t...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
5d4b6aa210f4-1
if device < 0 and cuda_device_count > 0: 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 wi...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
5d4b6aa210f4-2
model_load_fn=load_pipeline, hardware=gpu, model_reqs=model_reqs, inference_fn=inference_fn ) Example for <2GB model (can be serialized and sent directly to the server): .. code-block:: python from langchain.llms import SelfHostedPipeline i...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
5d4b6aa210f4-3
"""Key word arguments to pass to the model load function.""" model_reqs: List[str] = ["./", "torch"] """Requirements to install on hardware to inference the model.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def __init__(self, **kwargs: Any): ...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
5d4b6aa210f4-4
logger.warning( "Serializing pipeline to send to remote hardware. " "Note, it can be quite slow" "to serialize and send large models with each execution. " "Consider sending the pipeline" "to the cluster and passing the path to the pipeline...
https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html
68fe0d53f106-0
Source code for langchain.llms.ai21 """Wrapper around AI21 APIs.""" from typing import Any, Dict, List, Optional import requests from pydantic import BaseModel, Extra, root_validator from langchain.llms.base import LLM from langchain.utils import get_from_dict_or_env class AI21PenaltyData(BaseModel): """Parameters ...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
68fe0d53f106-1
"""Penalizes repeated tokens according to count.""" frequencyPenalty: AI21PenaltyData = AI21PenaltyData() """Penalizes repeated tokens according to frequency.""" numResults: int = 1 """How many completions to generate for each prompt.""" logitBias: Optional[Dict[str, float]] = None """Adjust the...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
68fe0d53f106-2
@property def _identifying_params(self) -> Dict[str, Any]: """Get the identifying parameters.""" return {**{"model": self.model}, **self._default_params} @property def _llm_type(self) -> str: """Return type of llm.""" return "ai21" def _call(self, prompt: str, stop: Optio...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
68fe0d53f106-3
optional_detail = response.json().get("error") raise ValueError( f"AI21 /complete call failed with status code {response.status_code}." f" Details: {optional_detail}" ) response_json = response.json() return response_json["completions"][0]["data"][...
https://python.langchain.com/en/latest/_modules/langchain/llms/ai21.html
93469452885e-0
Source code for langchain.llms.replicate """Wrapper around Replicate API.""" import logging from typing import Any, Dict, List, Mapping, Optional from pydantic import Extra, Field, root_validator from langchain.llms.base import LLM from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [d...
https://python.langchain.com/en/latest/_modules/langchain/llms/replicate.html