id stringlengths 14 16 | text stringlengths 31 2.41k | source stringlengths 54 121 |
|---|---|---|
b0922af55c9f-2 | self.process.expect(self.prompt, timeout=10)
self.process.sendline("")
try:
self.process.expect([self.prompt, pexpect.EOF], timeout=10)
except pexpect.TIMEOUT:
return f"Timeout error while executing command {command}"
if self.process.after == pexpect.EOF:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
f6b80a4923bc-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
f6b80a4923bc-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
f6b80a4923bc-2 | 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=google_api_key)
values["search_engine"] = serv... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
f6b80a4923bc-3 | metadata_result["snippet"] = result["snippet"]
metadata_results.append(metadata_result)
return metadata_results | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
4dd023cda896-0 | Source code for langchain.utilities.max_compute
from __future__ import annotations
from typing import TYPE_CHECKING, Iterator, List, Optional
from langchain.utils import get_from_env
if TYPE_CHECKING:
from odps import ODPS
[docs]class MaxComputeAPIWrapper:
"""Interface for querying Alibaba Cloud MaxCompute tabl... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html |
4dd023cda896-1 | "https://pyodps.readthedocs.io/."
) from ex
access_id = access_id or get_from_env("access_id", "MAX_COMPUTE_ACCESS_ID")
secret_access_key = secret_access_key or get_from_env(
"secret_access_key", "MAX_COMPUTE_SECRET_ACCESS_KEY"
)
client = ODPS(
access_... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html |
00878a97fba7-0 | Source code for langchain.utilities.arxiv
"""Util that calls Arxiv."""
import logging
import os
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name__)
[docs]class ArxivAPIWrapper(BaseModel):
"""Wra... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
00878a97fba7-1 | doc_content_chars_max: Optional[int] = 4000
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:
i... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
00878a97fba7-2 | f"Summary: {result.summary}"
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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
00878a97fba7-3 | "journal_ref": result.journal_ref,
"doi": result.doi,
"primary_category": result.primary_category,
"categories": result.categories,
"links": [link.href for link in result.links],
}
else:
extra_met... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
56f2f573cb80-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html |
034d4562ab7f-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
034d4562ab7f-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
7e4e8c1b22e4-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, Optional
import aiohttp
import requests
from pydantic import BaseModel, Extra, root_validator
from langchain.utils import get_from_d... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
7e4e8c1b22e4-1 | # type: ignore
f"{METAPHOR_API_URL}/search",
headers=headers,
json=params,
)
response.raise_for_status()
search_results = response.json()
print(search_results)
return search_results["results"]
@root_validator(pre=True)
def validate_envi... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
7e4e8c1b22e4-2 | query,
num_results=num_results,
include_domains=include_domains,
exclude_domains=exclude_domains,
start_crawl_date=start_crawl_date,
end_crawl_date=end_crawl_date,
start_published_date=start_published_date,
end_published_date=end_publis... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
7e4e8c1b22e4-3 | data = await res.text()
return data
else:
raise Exception(f"Error {res.status}: {res.reason}")
results_json_str = await fetch()
results_json = json.loads(results_json_str)
return self._clean_results(results_json["results"])
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
83b26135df2a-0 | Source code for langchain.utilities.bibtex
"""Util that calls bibtexparser."""
import logging
from typing import Any, Dict, List, Mapping
from pydantic import BaseModel, Extra, root_validator
logger = logging.getLogger(__name__)
OPTIONAL_FIELDS = [
"annotate",
"booktitle",
"editor",
"howpublished",
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html |
83b26135df2a-1 | import bibtexparser
with open(path) as file:
entries = bibtexparser.load(file).entries
return entries
[docs] def get_metadata(
self, entry: Mapping[str, Any], load_extra: bool = False
) -> Dict[str, Any]:
"""Get metadata for the given entry."""
publication = en... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html |
4683d2608f43-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
4683d2608f43-1 | :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 `accepted searx search API
<https://docs.searxng.org/dev... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
4683d2608f43-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
4683d2608f43-3 | def _get_default_params() -> dict:
return {"language": "en", "format": "json"}
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.l... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
4683d2608f43-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
4683d2608f43-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
4683d2608f43-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
4683d2608f43-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
4683d2608f43-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
4683d2608f43-9 | engines: List of engines to use for the query.
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.
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
4683d2608f43-10 | ]
[docs] async def aresults(
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 i... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
eafa7d302d30-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html |
eafa7d302d30-1 | 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)
return result | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html |
b2e3b83db447-0 | Source code for langchain.utilities.brave_search
import json
import requests
from pydantic import BaseModel, Field
[docs]class BraveSearchWrapper(BaseModel):
api_key: str
search_kwargs: dict = Field(default_factory=dict)
[docs] def run(self, query: str) -> str:
headers = {
"X-Subscription... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/brave_search.html |
f7681c4934fb-0 | Source code for langchain.utilities.jira
"""Util that calls Jira."""
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.tools.jira.prompt import (
JIRA_CATCH_ALL_PROMPT,
JIRA_CONFLUENCE_PAGE_CREATE_PROMPT,
JIRA_GET_ALL_PROJECTS_PROMPT,
JIRA_... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html |
f7681c4934fb-1 | "mode": "create_page",
"name": "Create confluence page",
"description": JIRA_CONFLUENCE_PAGE_CREATE_PROMPT,
},
]
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
[docs] def list(self) -> List[Dict]:
return self.operations... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html |
f7681c4934fb-2 | values["jira"] = jira
values["confluence"] = confluence
return values
[docs] def parse_issues(self, issues: Dict) -> List[dict]:
parsed = []
for issue in issues["issues"]:
key = issue["key"]
summary = issue["fields"]["summary"]
created = issue["fiel... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html |
f7681c4934fb-3 | parsed = []
for project in projects:
id = project["id"]
key = project["key"]
name = project["name"]
type = project["projectTypeKey"]
style = project["style"]
parsed.append(
{"id": id, "key": key, "name": name, "type": type, ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html |
f7681c4934fb-4 | params = json.loads(query)
return self.confluence.create_page(**dict(params))
[docs] def other(self, query: str) -> str:
context = {"self": self}
exec(f"result = {query}", context)
result = context["result"]
return str(result)
[docs] def run(self, mode: str, query: str) -> ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html |
b229a1d2f9df-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
b229a1d2f9df-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
b229a1d2f9df-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
b229a1d2f9df-3 | 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:
return list(map(self._convert_row_as_tuple, df.collect()))
[docs] def run(se... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
b229a1d2f9df-4 | """
try:
from pyspark.errors import PySparkException
except ImportError:
raise ValueError(
"pyspark is not installed. Please install it with `pip install pyspark`"
)
try:
return self.run(command, fetch)
except PySparkExcepti... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
27b5539df1bf-0 | Source code for langchain.utilities.wikipedia
"""Util that calls Wikipedia."""
import logging
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name__)
WIKIPEDIA_MAX_QUERY_LENGTH = 300
[docs]class Wikiped... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
27b5539df1bf-1 | summaries = []
for page_title in page_titles[: self.top_k_results]:
if wiki_page := self._fetch_page(page_title):
if summary := self._formatted_page_summary(page_title, wiki_page):
summaries.append(summary)
if not summaries:
return "No good Wik... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
27b5539df1bf-2 | except (
self.wiki_client.exceptions.PageError,
self.wiki_client.exceptions.DisambiguationError,
):
return None
[docs] def load(self, query: str) -> List[Document]:
"""
Run Wikipedia search and get the article text plus the meta information.
See
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
57e635f45d05-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
57e635f45d05-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
57e635f45d05-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
36e824259f0a-0 | Source code for langchain.utilities.pupmed
import json
import logging
import time
import urllib.error
import urllib.request
from typing import List
from pydantic import BaseModel, Extra
from langchain.schema import Document
logger = logging.getLogger(__name__)
[docs]class PubMedAPIWrapper(BaseModel):
"""
Wrappe... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html |
36e824259f0a-1 | [docs] def run(self, query: str) -> str:
"""
Run PubMed search and get the article meta information.
See https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch
It uses only the most informative fields of article meta information.
"""
try:
# Retrieve ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html |
36e824259f0a-2 | article = self.retrieve_article(uid, webenv)
articles.append(article)
# Convert the list of articles to a JSON string
return articles
def _transform_doc(self, doc: dict) -> Document:
summary = doc.pop("summary")
return Document(page_content=summary, metadata=doc)
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html |
36e824259f0a-3 | end_tag = "</ArticleTitle>"
title = xml_text[
xml_text.index(start_tag) + len(start_tag) : xml_text.index(end_tag)
]
# Get abstract
abstract = ""
if "<AbstractText>" in xml_text and "</AbstractText>" in xml_text:
start_tag = "<AbstractText>"
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/pupmed.html |
4d5cc5ca11d3-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html |
4d5cc5ca11d3-1 | timelimit=self.time,
)
if results is None:
return ["No good DuckDuckGo Search Result was found"]
snippets = []
for i, res in enumerate(results, 1):
if res is not None:
snippets.append(res["body"])
if len(... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html |
4d5cc5ca11d3-2 | if res is not None:
formatted_results.append(to_metadata(res))
if len(formatted_results) == num_results:
break
return formatted_results | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html |
b6c78d96de66-0 | Source code for langchain.utilities.openapi
"""Utility functions for parsing an OpenAPI spec."""
import copy
import json
import logging
import re
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional, Union
import requests
import yaml
from openapi_schema_pydantic import (
Components... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
b6c78d96de66-1 | @property
def _components_strict(self) -> Components:
"""Get components or err."""
if self.components is None:
raise ValueError("No components found in spec. ")
return self.components
@property
def _parameters_strict(self) -> Dict[str, Union[Parameter, Reference]]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
b6c78d96de66-2 | parameter = self._get_referenced_parameter(ref)
while isinstance(parameter, Reference):
parameter = self._get_referenced_parameter(parameter)
return parameter
[docs] def get_referenced_schema(self, ref: Reference) -> Schema:
"""Get a schema (or nested reference) or err."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
b6c78d96de66-3 | while isinstance(request_body, Reference):
request_body = self._get_referenced_request_body(request_body)
return request_body
@staticmethod
def _alert_unsupported_spec(obj: dict) -> None:
"""Alert if the spec is not supported."""
warning_message = (
" This may res... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
b6c78d96de66-4 | for key in keys[:-1]:
item = item[key]
item.pop(keys[-1], None)
return cls.parse_obj(new_obj)
[docs] @classmethod
def from_spec_dict(cls, spec_dict: dict) -> "OpenAPISpec":
"""Get an OpenAPI spec from a dict."""
return cls.parse_obj(spec_dict)
[docs... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
b6c78d96de66-5 | path_item = self._get_path_strict(path)
results = []
for method in HTTPVerb:
operation = getattr(path_item, method.value, None)
if isinstance(operation, Operation):
results.append(method.value)
return results
[docs] def get_parameters_for_path(self, pat... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
b6c78d96de66-6 | return request_body
[docs] @staticmethod
def get_cleaned_operation_id(operation: Operation, path: str, method: str) -> str:
"""Get a cleaned operation id from an operation id."""
operation_id = operation.operationId
if operation_id is None:
# Replace all punctuation of any kin... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
c9f8540f095c-0 | Source code for langchain.utilities.zapier
"""Util that can interact with Zapier NLA.
Full docs here: https://nla.zapier.com/api/v1/docs
Note: this wrapper currently only implemented the `api_key` auth method for testing
and server-side production use cases (using the developer's connected accounts on
Zapier.com)
For u... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c9f8540f095c-1 | class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
def _get_session(self) -> Session:
session = requests.Session()
session.headers.update(
{
"Accept": "application/json",
"Content-Type": "application/json",
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c9f8540f095c-2 | zapier_nla_api_key = get_from_dict_or_env(
values,
"zapier_nla_api_key",
"ZAPIER_NLA_API_KEY",
zapier_nla_api_key_default,
)
values["zapier_nla_api_key"] = zapier_nla_api_key
return values
[docs] def list(self) -> List[Dict]:
"""Returns ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c9f8540f095c-3 | The return JSON is guaranteed to be less than ~500 words (350
tokens) making it safe to inject into the prompt of another LLM
call.
"""
session = self._get_session()
request = self._get_action_request(action_id, instructions, params)
response = session.send(session.prepar... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
c9f8540f095c-4 | data = self.preview(*args, **kwargs)
return json.dumps(data)
[docs] def list_as_str(self) -> str: # type: ignore[no-untyped-def]
"""Same as list, but returns a stringified version of the JSON for
insertting back into an LLM."""
actions = self.list()
return json.dumps(actions) | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
563046bb2716-0 | Source code for langchain.utilities.scenexplain
"""Util that calls SceneXplain.
In order to set this up, you need API key for the SceneXplain API.
You can obtain a key by following the steps below.
- Sign up for a free account at https://scenex.jina.ai/.
- Navigate to the API Access page (https://scenex.jina.ai/api) an... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html |
563046bb2716-1 | "languages": ["en"],
}
]
}
response = requests.post(self.scenex_api_url, headers=headers, json=payload)
response.raise_for_status()
result = response.json().get("result", [])
img = result[0] if result else {}
return img.get("text", "")
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html |
00d7fcb01817-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html |
00d7fcb01817-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html |
033080b16b17-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
033080b16b17-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
033080b16b17-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
033080b16b17-3 | return ["No good Google Search Result was found"]
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:
heade... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
033080b16b17-4 | else:
async with self.aiosession.post(
url, params=params, headers=headers, raise_for_status=True
) as response:
search_results = await response.json()
return search_results | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
3bfcfe8508d9-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):
"""Messaging Client using Twilio.
To use, you should hav... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
3bfcfe8508d9-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
3bfcfe8508d9-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
fc2fa914bae9-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
fc2fa914bae9-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
fc2fa914bae9-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://api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
5d67ee155530-0 | Source code for langchain.document_loaders.tomarkdown
"""Loader that loads HTML to markdown using 2markdown."""
from __future__ import annotations
from typing import Iterator, List
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class ToMarkd... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tomarkdown.html |
747698d8bf3f-0 | Source code for langchain.document_loaders.conllu
"""Load CoNLL-U files."""
import csv
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class CoNLLULoader(BaseLoader):
"""Load CoNLL-U files."""
def __init__(self, file_path: str... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/conllu.html |
4e7bd4e6a764-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/toml.html |
a93913bb9282-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html |
a93913bb9282-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html |
17d6c837a9de-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html |
eb2aea6e6db9-0 | Source code for langchain.document_loaders.joplin
import json
import urllib
from datetime import datetime
from typing import Iterator, List, Optional
from langchain.document_loaders.base import BaseLoader
from langchain.schema import Document
from langchain.utils import get_from_env
LINK_NOTE_TEMPLATE = "joplin://x-cal... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
eb2aea6e6db9-1 | )
self._get_tag_url = (
f"{base_url}/notes/{{id}}/tags?token={access_token}&fields=title"
)
def _get_notes(self) -> Iterator[Document]:
has_more = True
page = 1
while has_more:
req_note = urllib.request.Request(self._get_note_url.format(page=page))
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
eb2aea6e6db9-2 | def _convert_date(self, date: int) -> str:
return datetime.fromtimestamp(date / 1000).strftime("%Y-%m-%d %H:%M:%S")
[docs] def lazy_load(self) -> Iterator[Document]:
yield from self._get_notes()
[docs] def load(self) -> List[Document]:
return list(self.lazy_load()) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/joplin.html |
3880a5628382-0 | Source code for langchain.document_loaders.powerpoint
"""Loader that loads powerpoint files."""
import os
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredPowerPointLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to load powe... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
22748eb0f6f5-0 | Source code for langchain.document_loaders.snowflake_loader
from __future__ import annotations
from typing import Any, Dict, Iterator, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class SnowflakeLoader(BaseLoader):
"""Loads a que... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
22748eb0f6f5-1 | self.password = password
self.account = account
self.warehouse = warehouse
self.role = role
self.database = database
self.schema = schema
self.parameters = parameters
self.page_content_columns = (
page_content_columns if page_content_columns is not Non... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
22748eb0f6f5-2 | ) -> Tuple[List[str], List[str]]:
page_content_columns = (
self.page_content_columns if self.page_content_columns else []
)
metadata_columns = self.metadata_columns if self.metadata_columns else []
if page_content_columns is None and query_result:
page_content_col... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/snowflake_loader.html |
f6fdefc65945-0 | Source code for langchain.document_loaders.rtf
"""Loader that loads rich text files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
satisfies_min_unstructured_version,
)
[docs]class UnstructuredRTFLoader(UnstructuredFileLoader):
"""Loader that u... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rtf.html |
444f45e2bac4-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
444f45e2bac4-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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.