id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
00d48d5791df-0
Source code for langchain.document_loaders.evernote """Load documents from Evernote. https://gist.github.com/foxmask/7b29c43a161e001ff04afdb2f181e31c """ import hashlib import logging from base64 import b64decode from time import strptime from typing import Any, Dict, Iterator, List, Optional from langchain.docstore.do...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
00d48d5791df-1
self.file_path = file_path self.load_single_document = load_single_document [docs] def load(self) -> List[Document]: """Load documents from EverNote export file.""" documents = [ Document( page_content=note["content"], metadata={ ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
00d48d5791df-2
rsc_dict["hash"] = hashlib.md5(rsc_dict[elem.tag]).hexdigest() else: rsc_dict[elem.tag] = elem.text return rsc_dict @staticmethod def _parse_note(note: List, prefix: Optional[str] = None) -> dict: note_dict: Dict[str, Any] = {} resources = [] def add_p...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
00d48d5791df-3
# Without huge_tree set to True, parser may complain about huge text node # Try to recover, because there may be " ", which will cause # "XMLSyntaxError: Entity 'nbsp' not defined" try: from lxml import etree except ImportError as e: logging.error( ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
501394452f8b-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
501394452f8b-1
title = "" metadata: Dict[str, Union[str, None]] = { "source": self.file_path, "title": title, } return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html
7f73a32534b5-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
7f73a32534b5-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
c3410e78ad83-0
Source code for langchain.document_loaders.azure_blob_storage_file """Loading logic for loading documents from an Azure Blob Storage 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_...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_file.html
f68d52594afe-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
f68d52594afe-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
86280d2cad9c-0
Source code for langchain.document_loaders.word_document """Loader that loads word documents.""" import os import tempfile from abc import ABC from typing import List from urllib.parse import urlparse import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html
86280d2cad9c-1
if hasattr(self, "temp_file"): self.temp_file.close() [docs] def load(self) -> List[Document]: """Load given path as single page.""" import docx2txt return [ Document( page_content=docx2txt.process(self.file_path), metadata={"source": se...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html
86280d2cad9c-2
"Please upgrade the unstructured package and try again." ) if is_doc: from unstructured.partition.doc import partition_doc return partition_doc(filename=self.file_path, **self.unstructured_kwargs) else: from unstructured.partition.docx import partition_doc...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html
1940d2a51d1e-0
Source code for langchain.document_loaders.sitemap """Loader that fetches a sitemap and loads those URLs.""" import itertools import re from typing import Any, Callable, Generator, Iterable, List, Optional from langchain.document_loaders.web_base import WebBaseLoader from langchain.schema import Document def _default_p...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
1940d2a51d1e-1
meta_function: Function to parse bs4.Soup output for metadata remember when setting this method to also copy metadata["loc"] to metadata["source"] if you are using this field is_local: whether the sitemap is a local file """ if blocksize is not None and blocks...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
1940d2a51d1e-2
} ) for sitemap in soup.find_all("sitemap"): loc = sitemap.find("loc") if not loc: continue soup_child = self.scrape_all([loc.text], "xml")[0] els.extend(self.parse_sitemap(soup_child)) return els [docs] def load(self) -> Lis...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
6c4e9e2faac2-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
6c4e9e2faac2-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
6c4e9e2faac2-2
return type_mapping[x] if x in type_mapping else x values["file_types"] = [full_form(file_type) for file_type in file_types] return values @validator("credentials_path") def validate_credentials_path(cls, v: Any, **kwargs: Any) -> Any: """Validate that credentials_path exists.""" ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html
6c4e9e2faac2-3
with open(self.token_path, "w") as token: token.write(creds.to_json()) return creds def _load_sheet_from_id(self, id: str) -> List[Document]: """Load a sheet and all tabs from an ID.""" from googleapiclient.discovery import build creds = self._load_credentials() ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html
6c4e9e2faac2-4
"""Load a document from an ID.""" from io import BytesIO from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaIoBaseDownload creds = self._load_credentials() service = build("drive", "v3", credentia...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html
6c4e9e2faac2-5
if file_types: _files = [f for f in files if f["mimeType"] in file_types] # type: ignore else: _files = files returns = [] for file in files: if file["trashed"] and not self.load_trashed_files: continue elif file["mimeType"] == "ap...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html
6c4e9e2faac2-6
else: returns.append(file) return returns def _load_documents_from_ids(self) -> List[Document]: """Load documents from a list of IDs.""" if not self.document_ids: raise ValueError("document_ids must be set") return [self._load_document_from_id(doc_id) for ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html
6c4e9e2faac2-7
raise ValueError("file_ids must be set") docs = [] for file_id in self.file_ids: docs.extend(self._load_file_from_id(file_id)) return docs [docs] def load(self) -> List[Document]: """Load documents.""" if self.folder_id: return self._load_documents_from...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html
0e11c257bf3a-0
Source code for langchain.document_loaders.json_loader """Loader that loads data from JSON.""" import json from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class JSONLoader...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html
0e11c257bf3a-1
""" try: import jq # noqa:F401 except ImportError: raise ImportError( "jq package not found, please install it with `pip install jq`" ) self.file_path = Path(file_path).resolve() self._jq_schema = jq.compile(jq_schema) self._co...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html
0e11c257bf3a-2
metadata = self._metadata_func(sample, metadata) else: content = sample if self._text_content and not isinstance(content, str): raise ValueError( f"Expected page_content is string, got {type(content)} instead. \ Set `text_content=False` if the ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/json_loader.html
80fb1469e416-0
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...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/arxiv.html
b8a0818d9450-0
Source code for langchain.document_loaders.blackboard """Loader that loads all documents from a blackboard course.""" import contextlib import re from pathlib import Path from typing import Any, List, Optional, Tuple from urllib.parse import unquote from langchain.docstore.document import Document from langchain.docume...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
b8a0818d9450-1
): """Initialize with blackboard course url. The BbRouter cookie is required for most blackboard courses. Args: blackboard_course_url: Blackboard course url. bbrouter: BbRouter cookie. load_all_recursively: If True, load all documents recursively. ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
b8a0818d9450-2
"""Load data into document objects. Returns: List of documents. """ if self.load_all_recursively: soup_info = self.scrape() self.folder_path = self._get_folder_path(soup_info) relative_paths = self._get_paths(soup_info) documents = [] ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
b8a0818d9450-3
) # Get the folder path folder_path = Path(".") / course_name_clean return str(folder_path) def _get_documents(self, soup: Any) -> List[Document]: """Fetch content from page and return Documents. Args: soup: BeautifulSoup4 soup object. Returns: ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
b8a0818d9450-4
Path(self.folder_path).mkdir(parents=True, exist_ok=True) # Download all attachments for attachment in attachments: self.download(attachment) def _load_documents(self) -> List[Document]: """Load all documents in the folder. Returns: List of documents. ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
b8a0818d9450-5
"""Parse the filename from a url. Args: url: Url to parse the filename from. Returns: The filename. """ if (url_path := Path(url)) and url_path.suffix == ".pdf": return url_path.name else: return self._parse_filename_from_url(url) ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
b8a0818d9450-6
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
996c6459381d-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
996c6459381d-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
7e17bbb6e1cf-0
Source code for langchain.document_loaders.python import tokenize from langchain.document_loaders.text import TextLoader [docs]class PythonLoader(TextLoader): """ Load Python files, respecting any non-default encoding if specified. """ def __init__(self, file_path: str): with open(file_path, "rb...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/python.html
3df7f12ee88c-0
Source code for langchain.document_loaders.airbyte_json """Loader that loads local airbyte json files.""" import json from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.utils import stringify_dict [docs]class AirbyteJSONLoader(B...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte_json.html
ba7ef36f2d84-0
Source code for langchain.document_loaders.notiondb """Notion DB loader for langchain""" from typing import Any, Dict, List, Optional import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader NOTION_BASE_URL = "https://api.notion.com/v1" DATABASE_URL = NOTIO...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html
ba7ef36f2d84-1
Returns: List[Document]: List of documents. """ page_ids = self._retrieve_page_ids() return list(self.load_page(page_id) for page_id in page_ids) def _retrieve_page_ids( self, query_dict: Dict[str, Any] = {"page_size": 100} ) -> List[str]: """Get all the pages...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html
ba7ef36f2d84-2
value = ( [item["name"] for item in prop_data["multi_select"]] if prop_data["multi_select"] else [] ) elif prop_type == "url": value = prop_data["url"] else: value = None metad...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html
ba7ef36f2d84-3
) -> Any: res = requests.request( method, url, headers=self.headers, json=query_dict, timeout=self.request_timeout_sec, ) res.raise_for_status() return res.json() By Harrison Chase © Copyright 2023, Harrison Chase. ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notiondb.html
360bc80247ad-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
a88f46461310-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
a65a143a0955-0
Source code for langchain.document_loaders.text import logging from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.helpers import detect_file_encodings logger = logging.getLogger(__name__) [docs]class T...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html
a65a143a0955-1
except Exception as e: raise RuntimeError(f"Error loading {self.file_path}") from e metadata = {"source": self.file_path} return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html
9bcd6a66de1e-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
9bcd6a66de1e-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
9bcd6a66de1e-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
07a108179143-0
Source code for langchain.document_loaders.wikipedia from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.utilities.wikipedia import WikipediaAPIWrapper [docs]class WikipediaLoader(BaseLoader): """Loads a query resul...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/wikipedia.html
9ecafac1c215-0
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...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html
9ecafac1c215-1
text = stringify_dict(json_data) metadata = {"source": url} 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...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html
d7f88d75371a-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
d7f88d75371a-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
d7f88d75371a-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
d7f88d75371a-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
d7f88d75371a-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
17d5b757d27f-0
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...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html
17d5b757d27f-1
for i, row in enumerate(csv_reader): 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.fi...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/csv_loader.html
90e77fc66c37-0
Source code for langchain.document_loaders.gcs_file """Loading logic for loading documents from a GCS file.""" import os import tempfile from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.unstructured import Uns...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_file.html
76c1a897d7bd-0
Source code for langchain.document_loaders.toml import json from pathlib import Path from typing import Iterator, List, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class TomlLoader(BaseLoader): """ A TOML document loader that inherits from ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/toml.html
76c1a897d7bd-1
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/toml.html
ef578debfa4c-0
Source code for langchain.document_loaders.telegram """Loader that loads Telegram chat json dump.""" from __future__ import annotations import asyncio import json from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Union from langchain.docstore.document import Document from langchain.docume...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
ef578debfa4c-1
if isinstance(text, str): # Take a single string as one page text = [text] page_docs = [Document(page_content=page) for page in text] # Add page numbers as metadata for i, doc in enumerate(page_docs): doc.metadata["page"] = i + 1 # Split pages into chunks doc_chunks = [] ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
ef578debfa4c-2
[docs] async def fetch_data_from_telegram(self) -> None: """Fetch data from Telegram API and save it as a JSON file.""" from telethon.sync import TelegramClient data = [] async with TelegramClient(self.username, self.api_id, self.api_hash) as client: async for message in c...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
ef578debfa4c-3
Args: parent_id (int): The parent message ID. reply_data (pd.DataFrame): A DataFrame containing reply messages. Returns: list: A list of message IDs that are replies to the parent message ID. """ # Find direct replies to the parent mess...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
ef578debfa4c-4
Args: message_threads (dict): A dictionary where the key is the parent message \ ID and the value is a list of message IDs in ascending order. data (pd.DataFrame): A DataFrame containing the conversation data: - message.sender_id - text ...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
ef578debfa4c-5
please install with `pip install pandas` """ ) normalized_messages = pd.json_normalize(d) df = pd.DataFrame(normalized_messages) message_threads = self._get_message_threads(df) combined_texts = self._combine_message_texts(message_threads, df) return te...
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
a17606966641-0
Source code for langchain.chat_models.google_palm """Wrapper around Google's PaLM Chat API.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional from pydantic import BaseModel, root_validator from tenacity import ( before_sleep_log, ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
a17606966641-1
raise ChatGooglePalmError("ChatResponse must have at least one candidate.") generations: List[ChatGeneration] = [] for candidate in response.candidates: author = candidate.get("author") if author is None: raise ChatGooglePalmError(f"ChatResponse must have an author: {candidate}") ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
a17606966641-2
raise ChatGooglePalmError("System message must be first input message.") context = input_message.content elif isinstance(input_message, HumanMessage) and input_message.example: if messages: raise ChatGooglePalmError( "Message examples must come before ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
a17606966641-3
return genai.types.MessagePromptDict( context=context, examples=examples, messages=messages, ) def _create_retry_decorator() -> Callable[[Any], Any]: """Returns a tenacity retry decorator, preconfigured to handle PaLM exceptions""" import google.api_core.exceptions multiplier = 2...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
a17606966641-4
return await llm.client.chat_async(**kwargs) return await _achat_with_retry(**kwargs) [docs]class ChatGooglePalm(BaseChatModel, BaseModel): """Wrapper around Google's PaLM Chat API. To use you must have the google.generativeai Python package installed and either: 1. The ``GOOGLE_API_KEY``` envir...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
a17606966641-5
"""Validate api key, python package exists, temperature, top_p, and top_k.""" google_api_key = get_from_dict_or_env( values, "google_api_key", "GOOGLE_API_KEY" ) try: import google.generativeai as genai genai.configure(api_key=google_api_key) except Im...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
a17606966641-6
candidate_count=self.n, ) return _response_to_result(response, stop) async def _agenerate( self, messages: List[BaseMessage], stop: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, ) -> ChatResult: prompt = _messages...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/google_palm.html
c6ea77d826ca-0
Source code for langchain.chat_models.azure_openai """Azure OpenAI chat wrapper.""" from __future__ import annotations import logging from typing import Any, Dict, Mapping from pydantic import root_validator from langchain.chat_models.openai import ChatOpenAI from langchain.schema import ChatResult from langchain.utils...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
c6ea77d826ca-1
openai_api_base: str = "" openai_api_version: str = "" openai_api_key: str = "" openai_organization: str = "" openai_proxy: str = "" @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" openai...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
c6ea77d826ca-2
openai.organization = openai_organization if openai_proxy: openai.proxy = {"http": openai_proxy, "https": openai_proxy} # type: ignore[assignment] # noqa: E501 except ImportError: raise ImportError( "Could not import openai python package. " ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
c6ea77d826ca-3
if res.get("finish_reason", None) == "content_filter": raise ValueError( "Azure has not provided the response due to a content" " filter being triggered" ) return super()._create_chat_result(response) By Harrison Chase © Copyrigh...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/azure_openai.html
c5793726a8e7-0
Source code for langchain.chat_models.vertexai """Wrapper around Google VertexAI chat-based models.""" from dataclasses import dataclass, field from typing import Dict, List, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForL...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
c5793726a8e7-1
""" if not history: return _ChatHistory() first_message = history[0] system_message = first_message if isinstance(first_message, SystemMessage) else None chat_history = _ChatHistory(system_message=system_message) messages_left = history[1:] if system_message else history if len(messages_...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
c5793726a8e7-2
) -> ChatResult: """Generate next turn in the conversation. Args: messages: The history of the conversation as a list of messages. stop: The list of stop words (optional). run_manager: The Callbackmanager for LLM run, it's not used at the moment. Returns: ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
c5793726a8e7-3
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/chat_models/vertexai.html
abe24beb4b5f-0
Source code for langchain.chat_models.promptlayer_openai """PromptLayer wrapper.""" import datetime from typing import Any, List, Mapping, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.chat_models import ChatOpenAI from langchain.sch...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
abe24beb4b5f-1
) -> ChatResult: """Call ChatOpenAI generate and then call PromptLayer API to log the request.""" from promptlayer.utils import get_api_key, promptlayer_api_request request_start_time = datetime.datetime.now().timestamp() generated_responses = super()._generate(messages, stop, run_manage...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
abe24beb4b5f-2
generated_responses = await super()._agenerate(messages, stop, run_manager) request_end_time = datetime.datetime.now().timestamp() message_dicts, params = super()._create_message_dicts(messages, stop) for i, generation in enumerate(generated_responses.generations): response_dict, par...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/promptlayer_openai.html
7a49ad8a6fba-0
Source code for langchain.chat_models.anthropic from typing import Any, Dict, List, Optional from pydantic import Extra from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun, ) from langchain.chat_models.base import BaseChatModel from langchain.llms.anthropic import _...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
7a49ad8a6fba-1
elif isinstance(message, AIMessage): message_text = f"{self.AI_PROMPT} {message.content}" elif isinstance(message, SystemMessage): message_text = f"{self.HUMAN_PROMPT} <admin>{message.content}</admin>" else: raise ValueError(f"Got unknown type {message}") retu...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
7a49ad8a6fba-2
) -> ChatResult: prompt = self._convert_messages_to_prompt(messages) params: Dict[str, Any] = {"prompt": prompt, **self._default_params} if stop: params["stop_sequences"] = stop if self.streaming: completion = "" stream_resp = self.client.completion_st...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
7a49ad8a6fba-3
completion = response["completion"] message = AIMessage(content=completion) return ChatResult(generations=[ChatGeneration(message=message)]) [docs] def get_num_tokens(self, text: str) -> int: """Calculate number of tokens.""" if not self.count_tokens: raise NameError("Plea...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/anthropic.html
76e596cfdd32-0
Source code for langchain.chat_models.openai """OpenAI chat wrapper.""" from __future__ import annotations import logging import sys from typing import ( TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Union, ) from pydantic import Extra, Field, root_validator fro...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
76e596cfdd32-1
return retry( reraise=True, stop=stop_after_attempt(llm.max_retries), wait=wait_exponential(multiplier=1, min=min_seconds, max=max_seconds), retry=( retry_if_exception_type(openai.error.Timeout) | retry_if_exception_type(openai.error.APIError) | retry_...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
76e596cfdd32-2
elif isinstance(message, HumanMessage): message_dict = {"role": "user", "content": message.content} elif isinstance(message, AIMessage): message_dict = {"role": "assistant", "content": message.content} elif isinstance(message, SystemMessage): message_dict = {"role": "system", "content": ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
76e596cfdd32-3
leave blank if not using a proxy or service emulator.""" openai_api_base: Optional[str] = None openai_organization: Optional[str] = None # to support explicit proxy for OpenAI openai_proxy: Optional[str] = None request_timeout: Optional[Union[float, Tuple[float, float]]] = None """Timeout for re...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
76e596cfdd32-4
invalid_model_kwargs = all_required_field_names.intersection(extra.keys()) if invalid_model_kwargs: raise ValueError( f"Parameters {invalid_model_kwargs} should be specified explicitly. " f"Instead they were passed in as part of `model_kwargs` parameter." ...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
76e596cfdd32-5
try: values["client"] = openai.ChatCompletion except AttributeError: raise ValueError( "`openai` has no `ChatCompletion` attribute, this is likely " "due to an old version of the openai package. Try upgrading it " "with `pip install --upgra...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
76e596cfdd32-6
| retry_if_exception_type(openai.error.APIConnectionError) | retry_if_exception_type(openai.error.RateLimitError) | retry_if_exception_type(openai.error.ServiceUnavailableError) ), before_sleep=before_sleep_log(logger, logging.WARNING), ) [docs] def com...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html
76e596cfdd32-7
messages=message_dicts, **params ): role = stream_resp["choices"][0]["delta"].get("role", role) token = stream_resp["choices"][0]["delta"].get("content", "") inner_completion += token if run_manager: run_manager.on_llm_new_t...
https://python.langchain.com/en/latest/_modules/langchain/chat_models/openai.html