id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
ea8b0f74f895-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 |
ea8b0f74f895-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 |
ea8b0f74f895-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 |
ea8b0f74f895-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 |
ea8b0f74f895-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 |
ea8b0f74f895-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 |
ea8b0f74f895-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 |
639d9d383789-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 |
639d9d383789-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 |
639d9d383789-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 |
c2ebc90769b4-0 | Source code for langchain.document_loaders.weather
"""Simple reader that reads weather data from OpenWeatherMap API"""
from __future__ import annotations
from datetime import datetime
from typing import Iterator, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.b... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/weather.html |
c2ebc90769b4-1 | return list(self.lazy_load())
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/weather.html |
f3d44c4c304e-0 | Source code for langchain.document_loaders.confluence
"""Load Data from a Confluence Space"""
import logging
from io import BytesIO
from typing import Any, Callable, List, Optional, Union
from tenacity import (
before_sleep_log,
retry,
stop_after_attempt,
wait_exponential,
)
from langchain.docstore.docu... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
f3d44c4c304e-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 |
f3d44c4c304e-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 |
f3d44c4c304e-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 |
f3d44c4c304e-4 | :type include_restricted_content: bool, optional
:param include_archived_content: Whether to include archived content,
defaults to False
:type include_archived_content: bool, optional
:param include_attachments: defaults to False
:type include_att... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
f3d44c4c304e-5 | )
ids_by_label = [page["id"] for page in pages]
if page_ids:
page_ids = list(set(page_ids + ids_by_label))
else:
page_ids = list(set(ids_by_label))
if cql:
pages = self.paginate_request(
self.confluence.cql,
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
f3d44c4c304e-6 | Unfortunately, due to page size, sometimes the Confluence API
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... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
f3d44c4c304e-7 | break
docs.extend(batch)
return docs[:max_pages]
[docs] def is_public_page(self, page: dict) -> bool:
"""Check if a page is publicly accessible."""
restrictions = self.confluence.get_all_restrictions_for_content(page["id"])
return (
page["status"] == "current"
... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
f3d44c4c304e-8 | ).get_text() + "".join(attachment_texts)
if include_comments:
comments = self.confluence.get_page_comments(
page["id"], expand="body.view.value", depth="all"
)["results"]
comment_texts = [
BeautifulSoup(comment["body"]["view"]["value"], "lxml")... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
f3d44c4c304e-9 | elif (
media_type == "application/vnd.openxmlformats-officedocument"
".wordprocessingml.document"
):
text = title + self.process_doc(absolute_url)
elif media_type == "application/vnd.ms-excel":
text = title + self.process_xls(absolu... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
f3d44c4c304e-10 | "`pytesseract` or `Pillow` package not found, "
"please run `pip install pytesseract Pillow`"
)
response = self.confluence.request(path=link, absolute=True)
text = ""
if (
response.status_code != 200
or response.content == b""
or re... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
f3d44c4c304e-11 | ):
return text
workbook = xlrd.open_workbook(file_contents=response.content)
for sheet in workbook.sheets():
text += f"{sheet.name}:\n"
for row in range(sheet.nrows):
for col in range(sheet.ncols):
text += f"{sheet.cell_value(row, c... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html |
eabd5f6790b8-0 | Source code for langchain.document_loaders.hugging_face_dataset
"""Loader that loads HuggingFace datasets."""
from typing import Iterator, List, Mapping, Optional, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class HuggingFaceDatasetLoader... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
eabd5f6790b8-1 | self.page_content_column = page_content_column
self.name = name
self.data_dir = data_dir
self.data_files = data_files
self.cache_dir = cache_dir
self.keep_in_memory = keep_in_memory
self.save_infos = save_infos
self.use_auth_token = use_auth_token
self.num... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
80b161add499-0 | Source code for langchain.document_loaders.pdf
"""Loader that loads PDF files."""
import json
import logging
import os
import tempfile
import time
from abc import ABC
from io import StringIO
from pathlib import Path
from typing import Any, Iterator, List, Mapping, Optional
from urllib.parse import urlparse
import reque... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
80b161add499-1 | # If the file is a web path, download it to a temporary file, and use that
if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path):
r = requests.get(self.file_path)
if r.status_code != 200:
raise ValueError(
"Check the url of your ... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
80b161add499-2 | """Initialize with file path."""
try:
import pypdf # noqa:F401
except ImportError:
raise ImportError(
"pypdf package not found, please install it with " "`pip install pypdf`"
)
self.parser = PyPDFParser()
super().__init__(file_path)
[d... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
80b161add499-3 | silent_errors: bool = False,
load_hidden: bool = False,
recursive: bool = False,
):
self.path = path
self.glob = glob
self.load_hidden = load_hidden
self.recursive = recursive
self.silent_errors = silent_errors
@staticmethod
def _is_visible(path: Path)... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
80b161add499-4 | [docs] def load(self) -> List[Document]:
"""Eagerly load the content."""
return list(self.lazy_load())
[docs] def lazy_load(
self,
) -> Iterator[Document]:
"""Lazily lod documents."""
blob = Blob.from_path(self.file_path)
yield from self.parser.parse(blob)
[docs... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
80b161add499-5 | """Initialize with file path."""
try:
import fitz # noqa:F401
except ImportError:
raise ImportError(
"`PyMuPDF` package not found, please install it with "
"`pip install pymupdf`"
)
super().__init__(file_path)
[docs] def loa... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
80b161add499-6 | @property
def url(self) -> str:
return "https://api.mathpix.com/v3/pdf"
@property
def data(self) -> dict:
options = {"conversion_formats": {self.processed_file_format: True}}
return {"options_json": json.dumps(options)}
[docs] def send_pdf(self) -> str:
with open(self.file... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
80b161add499-7 | return response.content.decode("utf-8")
[docs] def clean_pdf(self, contents: str) -> str:
contents = "\n".join(
[line for line in contents.split("\n") if not line.startswith("![]")]
)
# replace \section{Title} with # Title
contents = contents.replace("\\section{", "# ").re... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
80b161add499-8 | [docs] def load(self) -> List[Document]:
"""Load file."""
parser = PDFPlumberParser(text_kwargs=self.text_kwargs)
blob = Blob.from_path(self.file_path)
return parser.parse(blob)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
8153ddde4853-0 | Source code for langchain.document_loaders.url_selenium
"""Loader that uses Selenium to load a page, then uses unstructured to load the html.
"""
import logging
from typing import TYPE_CHECKING, List, Literal, Optional, Union
if TYPE_CHECKING:
from selenium.webdriver import Chrome, Firefox
from langchain.docstore.d... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html |
8153ddde4853-1 | raise ImportError(
"selenium package not found, please install it with "
"`pip install selenium`"
)
try:
import unstructured # noqa:F401
except ImportError:
raise ImportError(
"unstructured package not found, please ins... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html |
8153ddde4853-2 | for arg in self.arguments:
firefox_options.add_argument(arg)
if self.headless:
firefox_options.add_argument("--headless")
if self.binary_location is not None:
firefox_options.binary_location = self.binary_location
if self.executable_pat... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html |
79a905bf4a28-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 |
c9e85e1799ee-0 | Source code for langchain.document_loaders.image
"""Loader that loads image files."""
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredImageLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to load image files, such as PNGs and... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/image.html |
e3aeffbd3009-0 | Source code for langchain.document_loaders.facebook_chat
"""Loader that loads Facebook chat json dump."""
import datetime
import json
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(row: dict) -... | https://python.langchain.com/en/latest/_modules/langchain/document_loaders/facebook_chat.html |
639e771225b1-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 |
639e771225b1-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 |
b1682da5b172-0 | Source code for langchain.utilities.apify
from typing import Any, Callable, Dict, Optional
from pydantic import BaseModel, root_validator
from langchain.document_loaders import ApifyDatasetLoader
from langchain.document_loaders.base import Document
from langchain.utils import get_from_dict_or_env
[docs]class ApifyWrapp... | https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
b1682da5b172-1 | *,
build: Optional[str] = None,
memory_mbytes: Optional[int] = None,
timeout_secs: Optional[int] = None,
) -> ApifyDatasetLoader:
"""Run an Actor on the Apify platform and wait for results to be ready.
Args:
actor_id (str): The ID or name of the Actor on the Apify... | https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
b1682da5b172-2 | memory_mbytes: Optional[int] = None,
timeout_secs: Optional[int] = None,
) -> ApifyDatasetLoader:
"""Run an Actor on the Apify platform and wait for results to be ready.
Args:
actor_id (str): The ID or name of the Actor on the Apify platform.
run_input (Dict): The inp... | https://python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
103ece6d9f47-0 | Source code for langchain.utilities.metaphor_search
"""Util that calls Metaphor Search API.
In order to set this up, follow instructions at:
"""
import json
from typing import Dict, List
import aiohttp
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env... | https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
103ece6d9f47-1 | """Run query through Metaphor Search and return metadata.
Args:
query: The query to search for.
num_results: The number of results to return.
Returns:
A list of dictionaries with the following keys:
title - The title of the
url - The ur... | https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
103ece6d9f47-2 | for result in raw_search_results:
cleaned_results.append(
{
"title": result["title"],
"url": result["url"],
"author": result["author"],
"date_created": result["dateCreated"],
}
)
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
a8da2d59af68-0 | Source code for langchain.utilities.google_search
"""Util that calls Google Search."""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class GoogleSearchAPIWrapper(BaseModel):
"""Wrapper for Google Search API.
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
a8da2d59af68-1 | - Under Search engine ID you’ll find the search-engine-ID.
4. Enable the Custom Search API
- Navigate to the APIs & Services→Dashboard panel in Cloud Console.
- Click Enable APIs and Services.
- Search for Custom Search API and click on it.
- Click Enable.
URL for it: https://console.cloud.googl... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
a8da2d59af68-2 | from googleapiclient.discovery import build
except ImportError:
raise ImportError(
"google-api-python-client is not installed. "
"Please install it with `pip install google-api-python-client`"
)
service = build("customsearch", "v1", developerKey=go... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
a8da2d59af68-3 | if "snippet" in result:
metadata_result["snippet"] = result["snippet"]
metadata_results.append(metadata_result)
return metadata_results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
af8d3019d5b5-0 | Source code for langchain.utilities.google_places_api
"""Chain that calls Google Places API.
"""
import logging
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class GooglePlacesAPIWrapper(BaseModel):
"""Wrapper arou... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
af8d3019d5b5-1 | except ImportError:
raise ImportError(
"Could not import googlemaps python package. "
"Please install it with `pip install googlemaps`."
)
return values
[docs] def run(self, query: str) -> str:
"""Run Places search and get k number of places tha... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
af8d3019d5b5-2 | "formatted_address", "Unknown"
)
phone_number = place_details.get("result", {}).get(
"formatted_phone_number", "Unknown"
)
website = place_details.get("result", {}).get("website", "Unknown")
formatted_details = (
f"{name}\nAddre... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
1636c4b7ec9f-0 | Source code for langchain.utilities.duckduckgo_search
"""Util that calls DuckDuckGo Search.
No setup required. Free.
https://pypi.org/project/duckduckgo-search/
"""
from typing import Dict, List, Optional
from pydantic import BaseModel, Extra
from pydantic.class_validators import root_validator
[docs]class DuckDuckGoSe... | https://python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html |
1636c4b7ec9f-1 | )
if results is None or len(results) == 0:
return ["No good DuckDuckGo Search Result was found"]
snippets = [result["body"] for result in results]
return snippets
[docs] def run(self, query: str) -> str:
snippets = self.get_snippets(query)
return " ".join(snippets)... | https://python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html |
7aad9adb5ccf-0 | Source code for langchain.utilities.google_serper
"""Util that calls Google Search using the Serper.dev API."""
from typing import Any, Dict, List, Optional
import aiohttp
import requests
from pydantic.class_validators import root_validator
from pydantic.main import BaseModel
from typing_extensions import Literal
from ... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
7aad9adb5ccf-1 | arbitrary_types_allowed = True
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key exists in environment."""
serper_api_key = get_from_dict_or_env(
values, "serper_api_key", "SERPER_API_KEY"
)
values["serper_api_key"] = serp... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
7aad9adb5ccf-2 | """Run query through GoogleSearch and parse result async."""
results = await self._async_google_serper_search_results(
query,
gl=self.gl,
hl=self.hl,
num=self.k,
search_type=self.type,
tbs=self.tbs,
**kwargs,
)
r... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
7aad9adb5ccf-3 | return snippets
def _parse_results(self, results: dict) -> str:
return " ".join(self._parse_snippets(results))
def _google_serper_api_results(
self, search_term: str, search_type: str = "search", **kwargs: Any
) -> dict:
headers = {
"X-API-KEY": self.serper_api_key or "",... | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
7aad9adb5ccf-4 | url, params=params, headers=headers, raise_for_status=True
) as response:
search_results = await response.json()
return search_results
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
a0a5a162e2d0-0 | Source code for langchain.utilities.awslambda
"""Util that calls Lambda."""
import json
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
[docs]class LambdaWrapper(BaseModel):
"""Wrapper for AWS Lambda SDK.
Docs for using:
1. pip install boto3
2. Create a lambd... | https://python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
a0a5a162e2d0-1 | answer = json.loads(payload_string)["body"]
except StopIteration:
return "Failed to parse response from Lambda"
if answer is None or answer == "":
# We don't want to return the assumption alone if answer is empty
return "Request failed."
else:
retu... | https://python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
1c4c31f121f2-0 | Source code for langchain.utilities.arxiv
"""Util that calls Arxiv."""
import logging
import os
from typing import Any, Dict, List
from pydantic import BaseModel, Extra, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name__)
[docs]class ArxivAPIWrapper(BaseModel):
"""Wrapper aroun... | https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
1c4c31f121f2-1 | class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that the python package exists in environment."""
try:
import arxiv
values["arxiv_search"] =... | https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
1c4c31f121f2-2 | for result in results
]
if docs:
return "\n\n".join(docs)[: self.doc_content_chars_max]
else:
return "No good Arxiv Result was found"
[docs] def load(self, query: str) -> List[Document]:
"""
Run Arxiv search and get the article texts plus the article me... | https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
1c4c31f121f2-3 | "doi": result.doi,
"primary_category": result.primary_category,
"categories": result.categories,
"links": [link.href for link in result.links],
}
else:
extra_metadata = {}
metadata = {
"Pu... | https://python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
48df19567545-0 | Source code for langchain.utilities.twilio
"""Util that calls Twilio."""
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class TwilioAPIWrapper(BaseModel):
"""Sms Client using Twilio.
To use, you should have the ... | https://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
48df19567545-1 | that is enabled for the type of message you want to send. Phone numbers or
[short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from
Twilio also work here. You cannot, for example, spoof messages from a private
cell phone number. If you are using `messaging_service_sid`, th... | https://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
48df19567545-2 | characters in length.
to: The destination phone number in
[E.164](https://www.twilio.com/docs/glossary/what-e164) format for
SMS/MMS or
[Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses)
for other 3rd-party chann... | https://python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
c53721627d0b-0 | Source code for langchain.utilities.graphql
import json
from typing import Any, Callable, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
[docs]class GraphQLAPIWrapper(BaseModel):
"""Wrapper around GraphQL API.
To use, you should have the ``gql`` python package installed.
This wrapper w... | https://python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html |
c53721627d0b-1 | result = self._execute_query(query)
return json.dumps(result, indent=2)
def _execute_query(self, query: str) -> Dict[str, Any]:
"""Execute a GraphQL query and return the results."""
document_node = self.gql_function(query)
result = self.gql_client.execute(document_node)
retur... | https://python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html |
891637ca1f20-0 | Source code for langchain.utilities.wolfram_alpha
"""Util that calls WolframAlpha."""
from typing import Any, Dict, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class WolframAlphaAPIWrapper(BaseModel):
"""Wrapper for Wolfram Alpha.
Docs fo... | https://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html |
891637ca1f20-1 | res = self.wolfram_client.query(query)
try:
assumption = next(res.pods).text
answer = next(res.results).text
except StopIteration:
return "Wolfram Alpha wasn't able to answer it"
if answer is None or answer == "":
# We don't want to return the assu... | https://python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html |
7ba70aa913f4-0 | Source code for langchain.utilities.spark_sql
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Iterable, List, Optional
if TYPE_CHECKING:
from pyspark.sql import DataFrame, Row, SparkSession
[docs]class SparkSQL:
def __init__(
self,
spark_session: Optional[SparkSession] ... | https://python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
7ba70aa913f4-1 | f"ignore_tables {missing_tables} not found in database"
)
usable_tables = self.get_usable_table_names()
self._usable_tables = set(usable_tables) if usable_tables else self._all_tables
if not isinstance(sample_rows_in_table_info, int):
raise TypeError("sample_rows_in_t... | https://python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
7ba70aa913f4-2 | )
# Ignore the data source provider and options to reduce the number of tokens.
using_clause_index = statement.find("USING")
return statement[:using_clause_index] + ";"
[docs] def get_table_info(self, table_names: Optional[List[str]] = None) -> str:
all_table_names = self.get_usable_t... | https://python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
7ba70aa913f4-3 | f"{self._sample_rows_in_table_info} rows from {table} table:\n"
f"{columns_str}\n"
f"{sample_rows_str}"
)
def _convert_row_as_tuple(self, row: Row) -> tuple:
return tuple(map(str, row.asDict().values()))
def _get_dataframe_results(self, df: DataFrame) -> list:
ret... | https://python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
7ba70aa913f4-4 | If the statement throws an error, the error message is returned.
"""
try:
from pyspark.errors import PySparkException
except ImportError:
raise ValueError(
"pyspark is not installed. Please install it with `pip install pyspark`"
)
try:
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
05a213dd6508-0 | Source code for langchain.utilities.python
import sys
from io import StringIO
from typing import Dict, Optional
from pydantic import BaseModel, Field
[docs]class PythonREPL(BaseModel):
"""Simulates a standalone Python REPL."""
globals: Optional[Dict] = Field(default_factory=dict, alias="_globals")
locals: O... | https://python.langchain.com/en/latest/_modules/langchain/utilities/python.html |
ebd68c5e1c26-0 | Source code for langchain.utilities.openweathermap
"""Util that calls OpenWeatherMap using PyOWM."""
from typing import Any, Dict, Optional
from pydantic import Extra, root_validator
from langchain.tools.base import BaseModel
from langchain.utils import get_from_dict_or_env
[docs]class OpenWeatherMapAPIWrapper(BaseMode... | https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
ebd68c5e1c26-1 | heat_index = w.heat_index
clouds = w.clouds
return (
f"In {location}, the current weather is as follows:\n"
f"Detailed status: {detailed_status}\n"
f"Wind speed: {wind['speed']} m/s, direction: {wind['deg']}°\n"
f"Humidity: {humidity}%\n"
f"Tem... | https://python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
407fe0331038-0 | Source code for langchain.utilities.searx_search
"""Utility for using SearxNG meta search API.
SearxNG is a privacy-friendly free metasearch engine that aggregates results from
`multiple search engines
<https://docs.searxng.org/admin/engines/configured_engines.html>`_ and databases and
supports the `OpenSearch
<https:... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
407fe0331038-1 | Other methods are are available for convenience.
:class:`SearxResults` is a convenience wrapper around the raw json result.
Example usage of the ``run`` method to make a search:
.. code-block:: python
s.run(query="what is the best search engine?")
Engine Parameters
-----------------
You can pass any `accept... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
407fe0331038-2 | .. code-block:: python
# select the github engine and pass the search suffix
s = SearchWrapper("langchain library", query_suffix="!gh")
s = SearchWrapper("langchain library")
# select github the conventional google search syntax
s.run("large language models", query_suffix="site:g... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
407fe0331038-3 | return {"language": "en", "format": "json"}
[docs]class SearxResults(dict):
"""Dict like wrapper around search api results."""
_data = ""
def __init__(self, data: str):
"""Take a raw result from Searx and make it into a dict like object."""
json_data = json.loads(data)
super().__init... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
407fe0331038-4 | .. code-block:: python
from langchain.utilities import SearxSearchWrapper
# note the unsecure parameter is not needed if you pass the url scheme as
# http
searx = SearxSearchWrapper(searx_host="http://localhost:8888",
un... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
407fe0331038-5 | if categories:
values["params"]["categories"] = ",".join(categories)
searx_host = get_from_dict_or_env(values, "searx_host", "SEARX_HOST")
if not searx_host.startswith("http"):
print(
f"Warning: missing the url scheme on host \
! assuming secure ht... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
407fe0331038-6 | ) as response:
if not response.ok:
raise ValueError("Searx API returned an error: ", response.text)
result = SearxResults(await response.text())
self._result = result
else:
async with self.aiosession.get(
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
407fe0331038-7 | searx.run("what is the weather in France ?", engine="qwant")
# the same result can be achieved using the `!` syntax of searx
# to select the engine using `query_suffix`
searx.run("what is the weather in France ?", query_suffix="!qwant")
"""
_params = {
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
407fe0331038-8 | ) -> str:
"""Asynchronously version of `run`."""
_params = {
"q": query,
}
params = {**self.params, **_params, **kwargs}
if self.query_suffix and len(self.query_suffix) > 0:
params["q"] += " " + self.query_suffix
if isinstance(query_suffix, str) an... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
407fe0331038-9 | categories: List of categories to use for the query.
**kwargs: extra parameters to pass to the searx API.
Returns:
Dict with the following keys:
{
snippet: The description of the result.
title: The title of the result.
link: T... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
407fe0331038-10 | self,
query: str,
num_results: int,
engines: Optional[List[str]] = None,
query_suffix: Optional[str] = "",
**kwargs: Any,
) -> List[Dict]:
"""Asynchronously query with json results.
Uses aiohttp. See `results` for more info.
"""
_params = {
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
f131fe42b9e5-0 | Source code for langchain.utilities.powerbi
"""Wrapper around a Power BI endpoint."""
from __future__ import annotations
import asyncio
import logging
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union
import aiohttp
import requests
from aiohttp import ServerTimeoutError
from pydanti... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
f131fe42b9e5-1 | """Fix the table names."""
return [fix_table_name(table) for table in table_names]
@root_validator(pre=True, allow_reuse=True)
def token_or_credential_present(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that at least one of token and credentials is present."""
if "token" ... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
f131fe42b9e5-2 | "Could not get a token from the supplied credentials."
) from exc
raise ClientAuthenticationError("No credential or token supplied.")
[docs] def get_table_names(self) -> Iterable[str]:
"""Get names of tables available."""
return self.table_names
[docs] def get_schemas(self)... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
f131fe42b9e5-3 | if table_names not in self.table_names:
_LOGGER.warning("Table %s not found in dataset.", table_names)
return None
return [fix_table_name(table_names)]
return self.table_names
def _get_tables_todo(self, tables_todo: List[str]) -> List[str]:
"""... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
f131fe42b9e5-4 | await asyncio.gather(*[self._aget_schema(table) for table in tables_todo])
return self._get_schema_for_tables(tables_requested)
def _get_schema(self, table: str) -> None:
"""Get the schema for a table."""
try:
result = self.run(
f"EVALUATE TOPN({self.sample_rows_i... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.