id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
f03dfd4a71c9-0 | Source code for langchain.utilities.alpha_vantage
"""Util that calls AlphaVantage for Currency Exchange Rate."""
from typing import Any, Dict, List, Optional
import requests
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class AlphaVantageAPIWra... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/alpha_vantage.html |
f03dfd4a71c9-1 | data = response.json()
if "Error Message" in data:
raise ValueError(f"API Error: {data['Error Message']}")
return data
@property
def standard_currencies(self) -> List[str]:
return ["USD", "EUR", "GBP", "JPY", "CHF", "CAD", "AUD", "NZD"]
[docs] def run(self, from_currency: ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/alpha_vantage.html |
fd7cde9647e4-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 typing_extensions import Literal
from langchain.pydantic_v1 import BaseModel, root_validator
from langchain.utils import get_fr... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
fd7cde9647e4-1 | @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"] = serper_api_key
return values
[d... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
fd7cde9647e4-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
fd7cde9647e4-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
fd7cde9647e4-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 | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_serper.html |
e99c382ce3ba-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 langchain.pydantic_v1 import BaseModel, Extra, root_validator
[docs]class DuckDuckGoSearchAPIWrapper(BaseModel... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html |
e99c382ce3ba-1 | 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(snippets) == self.max_results:
break
return snippets
[d... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html |
e99c382ce3ba-2 | "link": result["url"],
}
return {
"snippet": result["body"],
"title": result["title"],
"link": result["href"],
}
formatted_results = []
for i, res in enumerate(results, 1):
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/duckduckgo_search.html |
9bc167c2f835-0 | Source code for langchain.utilities.google_search
"""Util that calls Google Search."""
from typing import Any, Dict, List, Optional
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class GoogleSearchAPIWrapper(BaseModel):
"""Wrapper for Google... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
9bc167c2f835-1 | - Create a custom search engine here: https://programmablesearchengine.google.com/.
- In `What to search` to search, pick the `Search the entire Web` option.
After search engine is created, you can click on it and find `Search engine ID`
on the Overview page.
"""
search_engine: Any #: :meta priva... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
9bc167c2f835-2 | raise ImportError(
"google-api-python-client is not installed. "
"Please install it with `pip install google-api-python-client"
">=2.100.0`"
)
service = build("customsearch", "v1", developerKey=google_api_key)
values["search_engine"] = service
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
9bc167c2f835-3 | for result in results:
metadata_result = {
"title": result["title"],
"link": result["link"],
}
if "snippet" in result:
metadata_result["snippet"] = result["snippet"]
metadata_results.append(metadata_result)
return me... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_search.html |
f4feb469b5ad-0 | Source code for langchain.utilities.redis
from __future__ import annotations
import logging
import re
from typing import TYPE_CHECKING, Any, List, Optional, Pattern
from urllib.parse import urlparse
import numpy as np
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from redis.client import Redis as RedisType... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html |
f4feb469b5ad-1 | """Check if the correct Redis modules are installed."""
installed_modules = client.module_list()
installed_modules = {
module[b"name"].decode("utf-8"): module for module in installed_modules
}
for module in required_modules:
if module["name"] in installed_modules and int(
ins... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html |
f4feb469b5ad-2 | needed holding the name of the redis service within the sentinels to get the
correct redis server connection. The default service name is "mymaster". The
optional second part of the path is the redis db number to connect to.
An optional username or password is used for booth connections to the rediserver
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html |
f4feb469b5ad-3 | if _check_for_cluster(redis_client):
redis_client.close()
redis_client = _redis_cluster_client(redis_url, **kwargs)
return redis_client
def _redis_sentinel_client(redis_url: str, **kwargs: Any) -> RedisType:
"""helper method to parse an (un-official) redis+sentinel url
and create a S... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html |
f4feb469b5ad-4 | # add client_name also
for arg in kwargs:
if arg.startswith("ssl") or arg == "client_name":
sentinel_args[arg] = kwargs[arg]
# sentinel user/pass is part of sentinel_kwargs, user/pass for redis server
# connection as direct parameter in kwargs
sentinel_client = redis.sentinel.Sentine... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html |
c94171f45ccd-0 | Source code for langchain.utilities.wikipedia
"""Util that calls Wikipedia."""
import logging
from typing import Any, Dict, List, Optional
from langchain.pydantic_v1 import BaseModel, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name__)
WIKIPEDIA_MAX_QUERY_LENGTH = 300
[docs]class W... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
c94171f45ccd-1 | 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 Wikipedia Search Result was found"
return "\n\n".join(summaries)[: self.doc_content... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
c94171f45ccd-2 | 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
Returns: a list of documents.
"""
page_titles = sel... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
442f754921fd-0 | Source code for langchain.utilities.tensorflow_datasets
import logging
from typing import Any, Callable, Dict, Iterator, List, Optional
from langchain.pydantic_v1 import BaseModel, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name__)
[docs]class TensorflowDatasets(BaseModel):
""... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html |
442f754921fd-1 | },
)
tsds_client = TensorflowDatasets(
dataset_name="mlqa/en",
split_name="train",
load_max_docs=MAX_DOCS,
sample_to_document_function=mlqaen_example_to_document,
)
"""
dataset_name: str =... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html |
442f754921fd-2 | for s in self.dataset.take(self.load_max_docs)
if self.sample_to_document_function is not None
)
[docs] def load(self) -> List[Document]:
"""Download a selected dataset.
Returns: a list of Documents.
"""
return list(self.lazy_load()) | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html |
f802ea56149f-0 | Source code for langchain.utilities.brave_search
import json
from typing import List
import requests
from langchain.pydantic_v1 import BaseModel, Field
from langchain.schema import Document
[docs]class BraveSearchWrapper(BaseModel):
"""Wrapper around the Brave search engine."""
api_key: str
"""The API key t... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/brave_search.html |
f802ea56149f-1 | )
for item in results
]
def _search_request(self, query: str) -> List[dict]:
headers = {
"X-Subscription-Token": self.api_key,
"Accept": "application/json",
}
req = requests.PreparedRequest()
params = {**self.search_kwargs, **{"q": query}}
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/brave_search.html |
b73d66fc7f66-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:/... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
b73d66fc7f66-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
b73d66fc7f66-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
b73d66fc7f66-3 | validator,
)
from langchain.utils import get_from_dict_or_env
def _get_default_params() -> dict:
return {"language": "en", "format": "json"}
[docs]class SearxResults(dict):
"""Dict like wrapper around search api results."""
_data: str = ""
[docs] def __init__(self, data: str):
"""Take a raw resul... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
b73d66fc7f66-4 | Example with SSL disabled:
.. 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",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
b73d66fc7f66-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
b73d66fc7f66-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(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
b73d66fc7f66-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 = {
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
b73d66fc7f66-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
b73d66fc7f66-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.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
b73d66fc7f66-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searx_search.html |
70cfe72b8029-0 | Source code for langchain.utilities.dataforseo_api_search
import base64
from typing import Dict, Optional
from urllib.parse import quote
import aiohttp
import requests
from langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class DataForSeoAPIWrap... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html |
70cfe72b8029-1 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that login and password exists in environment."""
login = get_from_dict_or_env(values, "api_login", "DATAFORSEO_LOGIN")
password = get_from_dict_or_env(values, "api_password", "DATAFORSEO_PASSWORD")
va... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html |
70cfe72b8029-2 | obj = {"keyword": quote(keyword)}
obj = {**obj, **self.default_params, **self.params}
data = [obj]
_url = (
f"https://api.dataforseo.com/v3/serp/{obj['se_name']}"
f"/{obj['se_type']}/live/advanced"
)
return {
"url": _url,
"headers":... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html |
70cfe72b8029-3 | ) as response:
res = await response.json()
else:
async with self.aiosession.post(
request_details["url"],
headers=request_details["headers"],
json=request_details["data"],
) as response:
res = await respo... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html |
70cfe72b8029-4 | if isinstance(v, dict):
self._cleanup_unnecessary_items(v)
return d
def _process_response(self, res: dict) -> str:
"""Process response from DataForSEO SERP API."""
toret = "No good search result found"
for task in res.get("tasks", []):
for result in task.g... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html |
4f8c7646bf42-0 | Source code for langchain.utilities.pubmed
import json
import logging
import time
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Dict, Iterator, List
from langchain.pydantic_v1 import BaseModel, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html |
4f8c7646bf42-1 | doc_content_chars_max: int = 2000
email: str = "your_email@example.com"
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that the python package exists in environment."""
try:
import xmltodict
values["parse"] = xmltodict.parse
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html |
4f8c7646bf42-2 | Return an iterator of dictionaries containing the document metadata.
"""
url = (
self.base_url_esearch
+ "db=pubmed&term="
+ str({urllib.parse.quote(query)})
+ f"&retmode=json&retmax={self.top_k_results}&usehistory=y"
)
result = urllib.requ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html |
4f8c7646bf42-3 | )
retry = 0
while True:
try:
result = urllib.request.urlopen(url)
break
except urllib.error.HTTPError as e:
if e.code == 429 and retry < self.max_retry:
# Too Many Requests errors
# wait for a... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html |
4f8c7646bf42-4 | else "No abstract available"
)
)
)
a_d = ar.get("ArticleDate", {})
pub_date = "-".join(
[a_d.get("Year", ""), a_d.get("Month", ""), a_d.get("Day", "")]
)
return {
"uid": uid,
"Title": ar.get("ArticleTitle", ""),
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/pubmed.html |
533035748d32-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 request... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
533035748d32-1 | def fix_table_names(cls, table_names: List[str]) -> List[str]:
"""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 a... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
533035748d32-2 | raise ClientAuthenticationError(
"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."""
re... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
533035748d32-3 | if isinstance(table_names, str) and table_names != "":
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 _g... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
533035748d32-4 | tables_todo = self._get_tables_todo(tables_requested)
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 =... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
533035748d32-5 | self.schemas[table] = "unknown"
def _create_json_content(self, command: str) -> dict[str, Any]:
"""Create the json content for the request."""
return {
"queries": [{"query": rf"{command}"}],
"impersonatedUserName": self.impersonated_user_name,
"serializerSettings"... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
533035748d32-6 | async with session.post(
self.request_url,
headers=self.headers,
json=self._create_json_content(command),
timeout=10,
) as response:
if response.status == 403:
return "TokenError: Could not login to PowerBI, ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
056f559c9987-0 | Source code for langchain.utilities.google_places_api
"""Chain that calls Google Places API.
"""
import logging
from typing import Any, Dict, Optional
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class GooglePlacesAPIWrapper(BaseModel):
""... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
056f559c9987-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
056f559c9987-2 | "formatted_address", "Unknown"
)
phone_number = place_details.get("result", {}).get(
"formatted_phone_number", "Unknown"
)
website = place_details.get("result", {}).get("website", "Unknown")
place_id = place_details.get("result", {}).get("place... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_places_api.html |
8aa1440ed5a1-0 | Source code for langchain.utilities.golden_query
"""Util that calls Golden."""
import json
from typing import Dict, Optional
import requests
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
GOLDEN_BASE_URL = "https://golden.com"
GOLDEN_TIMEOUT = 5000
[d... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/golden_query.html |
8aa1440ed5a1-1 | content = json.loads(response.content)
query_id = content["id"]
response = requests.get(
(
f"{GOLDEN_BASE_URL}/api/v2/public/queries/{query_id}/results/"
"?pageSize=10"
),
headers=headers,
timeout=GOLDEN_TIMEOUT,
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/golden_query.html |
66de919a3475-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 langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.utils impo... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
66de919a3475-1 | "endPublishedDate": end_published_date,
"useAutoprompt": use_autoprompt,
}
response = requests.post(
# type: ignore
f"{METAPHOR_API_URL}/search",
headers=headers,
json=params,
)
response.raise_for_status()
search_results... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
66de919a3475-2 | start_crawl_date: If specified, only pages we crawled after start_crawl_date will be returned.
end_crawl_date: If specified, only pages we crawled before end_crawl_date will be returned.
start_published_date: If specified, only pages published after start_published_date will be returned.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
66de919a3475-3 | end_published_date: Optional[str] = None,
use_autoprompt: Optional[bool] = None,
) -> List[Dict]:
"""Get results from the Metaphor Search API asynchronously."""
# Function to perform the API call
async def fetch() -> str:
headers = {"X-Api-Key": self.metaphor_api_key}
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
66de919a3475-4 | "author": result.get("author", "Unknown Author"),
"published_date": result.get("publishedDate", "Unknown Date"),
}
)
return cleaned_results | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
7b9bc0a5a7aa-0 | Source code for langchain.utilities.sql_database
"""SQLAlchemy wrapper around a database."""
from __future__ import annotations
import warnings
from typing import Any, Dict, Iterable, List, Literal, Optional, Sequence, Union
import sqlalchemy
from sqlalchemy import MetaData, Table, create_engine, inspect, select, text
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-1 | view_support: bool = False,
max_string_length: int = 300,
):
"""Create engine from database URI."""
self._engine = engine
self._schema = schema
if include_tables and ignore_tables:
raise ValueError("Cannot specify both include_tables and ignore_tables")
se... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-2 | self._custom_table_info = custom_table_info
if self._custom_table_info:
if not isinstance(self._custom_table_info, dict):
raise TypeError(
"table_info must be a dictionary with table names as keys and the "
"desired table info as values"
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-3 | **kwargs: Any,
) -> SQLDatabase:
"""
Class method to create an SQLDatabase instance from a Databricks connection.
This method requires the 'databricks-sql-connector' package. If not installed,
it can be added using `pip install databricks-sql-connector`.
Args:
cat... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-4 | cluster the notebook is attached to. Defaults to None.
engine_args (Optional[dict]): The arguments to be used when connecting
Databricks. Defaults to None.
**kwargs (Any): Additional keyword arguments for the `from_uri` method.
Returns:
SQLDatabase: An instanc... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-5 | "Need to provide either 'warehouse_id' or 'cluster_id'."
)
if warehouse_id and cluster_id:
raise ValueError("Can't have both 'warehouse_id' or 'cluster_id'.")
if warehouse_id:
http_path = f"/sql/1.0/warehouses/{warehouse_id}"
else:
http_path = ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-6 | with a default value of "".
tenant (str): The name of the tenant used to connect to the CnosDB service,
with a default value of "cnosdb".
database (str): The name of the database in the CnosDB tenant.
Returns:
SQLDatabase: An instance of SQLDatabase configured... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-7 | """Get information about specified tables.
Follows best practices as specified in: Rajkumar et al, 2022
(https://arxiv.org/abs/2204.00498)
If `sample_rows_in_table_info`, the specified number of sample rows will be
appended to each table description. This can increase performance as
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-8 | table_info += f"\n{self._get_table_indexes(table)}\n"
if self._sample_rows_in_table_info:
table_info += f"\n{self._get_sample_rows(table)}\n"
if has_extra_info:
table_info += "*/"
tables.append(table_info)
tables.sort()
final_str = "\n\... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-9 | f"{columns_str}\n"
f"{sample_rows_str}"
)
def _execute(
self,
command: str,
fetch: Union[Literal["all"], Literal["one"]] = "all",
) -> Sequence[Dict[str, Any]]:
"""
Executes SQL command through underlying engine.
If the statement returns no row... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-10 | elif fetch == "one":
first_result = cursor.fetchone()
result = [] if first_result is None else [first_result._asdict()]
else:
raise ValueError("Fetch parameter must be either 'one' or 'all'")
return result
return []
[doc... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
7b9bc0a5a7aa-11 | """Format the error message"""
return f"Error: {e}"
[docs] def run_no_throw(
self,
command: str,
fetch: Union[Literal["all"], Literal["one"]] = "all",
) -> str:
"""Execute a SQL command and return a string representing the results.
If the statement returns rows... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
e7a6d896cdfc-0 | Source code for langchain.utilities.bing_search
"""Util that calls Bing Search.
In order to set this up, follow instructions at:
https://levelup.gitconnected.com/api-tutorial-how-to-use-bing-web-search-api-in-python-4165d5592a7e
"""
from typing import Dict, List
import requests
from langchain.pydantic_v1 import BaseMod... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
e7a6d896cdfc-1 | """Validate that api key and endpoint exists in environment."""
bing_subscription_key = get_from_dict_or_env(
values, "bing_subscription_key", "BING_SUBSCRIPTION_KEY"
)
values["bing_subscription_key"] = bing_subscription_key
bing_search_url = get_from_dict_or_env(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
e7a6d896cdfc-2 | metadata_result = {
"snippet": result["snippet"],
"title": result["name"],
"link": result["url"],
}
metadata_results.append(metadata_result)
return metadata_results | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
cccecba97338-0 | Source code for langchain.utilities.opaqueprompts
from typing import Dict, Union
[docs]def sanitize(
input: Union[str, Dict[str, str]]
) -> Dict[str, Union[str, Dict[str, str]]]:
"""
Sanitize input string or dict of strings by replacing sensitive data with
placeholders.
It returns the sanitized inpu... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/opaqueprompts.html |
cccecba97338-1 | sanitize_response: op.SanitizeResponse = op.sanitize([input])
return {
"sanitized_input": sanitize_response.sanitized_texts[0],
"secure_context": sanitize_response.secure_context,
}
if isinstance(input, dict):
# the input could be a dict[string, string], so we sanitiz... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/opaqueprompts.html |
cccecba97338-2 | sanitized_text, secure_context
)
return desanitize_response.desanitized_text | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/opaqueprompts.html |
cdd60b93d5f4-0 | Source code for langchain.utilities.dalle_image_generator
"""Utility that calls OpenAI's Dall-E Image Generator."""
from typing import Any, Dict, Optional
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class DallEAPIWrapper(BaseModel):
"""Wr... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dalle_image_generator.html |
cdd60b93d5f4-1 | "Please it install it with `pip install openai`."
) from e
return values
[docs] def run(self, query: str) -> str:
"""Run query through OpenAI and parse result."""
response = self.client.create(
prompt=query, n=self.n, size=self.size, model=self.model
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/dalle_image_generator.html |
a49541e7440f-0 | Source code for langchain.utilities.openapi
"""Utility functions for parsing an OpenAPI spec."""
from __future__ import annotations
import copy
import json
import logging
import re
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, Dict, List, Optional, Union
import requests
import yaml
fr... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
a49541e7440f-1 | raise ValueError("No paths found in spec")
return self.paths
def _get_path_strict(self, path: str) -> PathItem:
path_item = self._paths_strict.get(path)
if not path_item:
raise ValueError(f"No path found for {path}")
return path_item
@property
def _components_stri... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
a49541e7440f-2 | parameters = self._parameters_strict
if ref_name not in parameters:
raise ValueError(f"No parameter found for {ref_name}")
return parameters[ref_name]
def _get_root_referenced_parameter(self, ref: Reference) -> Parameter:
"""Get the root reference or err."""
from openapi_... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
a49541e7440f-3 | request_bodies = self._request_bodies_strict
if ref_name not in request_bodies:
raise ValueError(f"No request body found for {ref_name}")
return request_bodies[ref_name]
def _get_root_referenced_request_body(
self, ref: Reference
) -> Optional[RequestBody]:
"""Get the... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
a49541e7440f-4 | def parse_obj(cls, obj: dict) -> OpenAPISpec:
try:
cls._alert_unsupported_spec(obj)
return super().parse_obj(obj)
except ValidationError as e:
# We are handling possibly misconfigured specs and
# want to do a best-effort job to get a reasonable interface o... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
a49541e7440f-5 | def from_url(cls, url: str) -> OpenAPISpec:
"""Get an OpenAPI spec from a URL."""
response = requests.get(url)
return cls.from_text(response.text)
@property
def base_url(self) -> str:
"""Get the base url."""
return self.servers[0].url
[docs] def get_methods_for_path(se... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
a49541e7440f-6 | raise ValueError(f"No {method} method found for {path}")
return operation_obj
[docs] def get_parameters_for_operation(self, operation: Operation) -> List[Parameter]:
"""Get the components for a given operation."""
from openapi_pydantic import Reference
parameters = []
if opera... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
688049c407e2-0 | Source code for langchain.utilities.serpapi
"""Chain that calls SerpAPI.
Heavily borrowed from https://github.com/ofirpress/self-ask
"""
import os
import sys
from typing import Any, Dict, Optional, Tuple
import aiohttp
from langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator
from langchain.utils import... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
688049c407e2-1 | aiosession: Optional[aiohttp.ClientSession] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python packag... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
688049c407e2-2 | """Use aiohttp to run query through SerpAPI and return the results async."""
def construct_url_and_params() -> Tuple[str, Dict[str, str]]:
params = self.get_params(query)
params["source"] = "python"
if self.serpapi_api_key:
params["serp_api_key"] = self.serpap... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
688049c407e2-3 | if isinstance(answer_box, list):
answer_box = answer_box[0]
if "result" in answer_box.keys():
return answer_box["result"]
elif "answer" in answer_box.keys():
return answer_box["answer"]
elif "snippet" in answer_box.keys():
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
688049c407e2-4 | ):
return res["popular_destinations"]["destinations"]
elif "top_sights" in res.keys() and "sights" in res["top_sights"].keys():
return res["top_sights"]["sights"]
elif (
"images_results" in res.keys()
and "thumbnail" in res["images_results"][0].keys()
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
688049c407e2-5 | snippets.append(organic_result["link"])
if "buying_guide" in res.keys():
snippets.append(res["buying_guide"])
if "local_results" in res.keys() and "places" in res["local_results"].keys():
snippets.append(res["local_results"]["places"])
if len(snippets) > 0:
re... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
0526c91229e3-0 | Source code for langchain.utilities.tavily_search
"""Util that calls Tavily Search API.
In order to set this up, follow instructions at:
"""
import json
from typing import Dict, List, Optional
import aiohttp
import requests
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.utils import g... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tavily_search.html |
0526c91229e3-1 | "max_results": max_results,
"search_depth": search_depth,
"include_domains": include_domains,
"exclude_domains": exclude_domains,
"include_answer": include_answer,
"include_raw_content": include_raw_content,
"include_images": include_images,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/tavily_search.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.