id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
c21d0f36b346-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 |
a0fa599ab428-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 |
a0fa599ab428-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 |
a0fa599ab428-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 |
a0fa599ab428-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 |
a0fa599ab428-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 |
be255d72f791-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 |
be255d72f791-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 |
be255d72f791-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 |
be255d72f791-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 |
be255d72f791-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 |
be255d72f791-5 | 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": {"includeNulls": True},
}
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
be255d72f791-6 | ) -> str:
"""Converts a JSON object to a markdown table."""
output_md = ""
headers = json_contents[0].keys()
for header in headers:
header.replace("[", ".").replace("]", "")
if table_name:
header.replace(f"{table_name}.", "")
output_md += f"| {header} "
output_md ... | https://python.langchain.com/en/latest/_modules/langchain/utilities/powerbi.html |
5c28762831cd-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 |
5c28762831cd-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 |
5c28762831cd-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 |
5c28762831cd-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 |
5c28762831cd-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 |
5c28762831cd-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 |
5c28762831cd-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 |
5c28762831cd-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 |
5c28762831cd-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 |
5c28762831cd-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 |
5c28762831cd-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 |
58fb06fc60a8-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 |
58fb06fc60a8-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 |
58fb06fc60a8-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 |
c645d04d9d26-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 |
c645d04d9d26-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 |
c645d04d9d26-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 |
b1d34001e968-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 |
b1d34001e968-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 |
b1d34001e968-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 |
1bedde35eaf9-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 |
1bedde35eaf9-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 |
1bedde35eaf9-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 |
1bedde35eaf9-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 |
a1ccc132d2a4-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 |
a1ccc132d2a4-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 |
a1ccc132d2a4-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 |
a1ccc132d2a4-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 |
a1ccc132d2a4-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 |
c37dc4467471-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 |
c37dc4467471-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 |
749e6fe9332a-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 |
749e6fe9332a-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 |
749e6fe9332a-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 |
a0a92fc4ca3e-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 |
a0a92fc4ca3e-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 |
b6b1c9f4b01d-0 | Source code for langchain.utilities.bash
"""Wrapper around subprocess to run commands."""
from __future__ import annotations
import platform
import re
import subprocess
from typing import TYPE_CHECKING, List, Union
from uuid import uuid4
if TYPE_CHECKING:
import pexpect
def _lazy_import_pexpect() -> pexpect:
""... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
b6b1c9f4b01d-1 | # Set the custom prompt
process.sendline("PS1=" + prompt)
process.expect_exact(prompt, timeout=10)
return process
[docs] def run(self, commands: Union[str, List[str]]) -> str:
"""Run commands and return final output."""
if isinstance(commands, str):
commands = [com... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
b6b1c9f4b01d-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://python.langchain.com/en/latest/_modules/langchain/utilities/bash.html |
ea76fec10582-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 pydantic import BaseModel, Extra, Field, root_validator
from langchain.utils import get_from_dic... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
ea76fec10582-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... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
ea76fec10582-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... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
ea76fec10582-3 | toret = res["answer_box"]["snippet"]
elif (
"answer_box" in res.keys()
and "snippet_highlighted_words" in res["answer_box"].keys()
):
toret = res["answer_box"]["snippet_highlighted_words"][0]
elif (
"sports_results" in res.keys()
and "g... | https://python.langchain.com/en/latest/_modules/langchain/utilities/serpapi.html |
7a3fd405f1aa-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 |
7a3fd405f1aa-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 |
7a3fd405f1aa-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 |
7a3fd405f1aa-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 |
a4d83d80665c-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 |
8c4a82f2a876-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 pydantic import BaseModel, Extra, ro... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
8c4a82f2a876-1 | 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(
values,
"bing_search_url",
"BING_SEARCH_URL",
... | https://python.langchain.com/en/latest/_modules/langchain/utilities/bing_search.html |
8c4a82f2a876-2 | "snippet": result["snippet"],
"title": result["name"],
"link": result["url"],
}
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/bing_search.html |
d8862fac4172-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://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
d8862fac4172-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://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
d8862fac4172-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://python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
835b3ee82190-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 |
835b3ee82190-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 |
e83a7d1e4deb-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 |
e83a7d1e4deb-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 |
cab4ce13bbfd-0 | Source code for langchain.llms.rwkv
"""Wrapper for the RWKV model.
Based on https://github.com/saharNooby/rwkv.cpp/blob/master/rwkv/chat_with_bot.py
https://github.com/BlinkDL/ChatRWKV/blob/main/v2/chat.py
"""
from typing import Any, Dict, List, Mapping, Optional, Set
from pydantic import BaseModel, Extra, roo... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
cab4ce13bbfd-1 | """Positive values penalize new tokens based on their existing frequency
in the text so far, decreasing the model's likelihood to repeat the same
line verbatim.."""
penalty_alpha_presence: float = 0.4
"""Positive values penalize new tokens based on whether they appear
in the text so far, increasing ... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
cab4ce13bbfd-2 | """Validate that the python package exists in the environment."""
try:
import tokenizers
except ImportError:
raise ImportError(
"Could not import tokenizers python package. "
"Please install it with `pip install tokenizers`."
)
... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
cab4ce13bbfd-3 | AVOID_REPEAT_TOKENS = []
AVOID_REPEAT = ",:?!"
for i in AVOID_REPEAT:
dd = self.pipeline.encode(i)
assert len(dd) == 1
AVOID_REPEAT_TOKENS += dd
tokens = [int(x) for x in _tokens]
self.model_tokens += tokens
out: Any = None
while len(to... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
cab4ce13bbfd-4 | occurrence[token] += 1
logits = self.run_rnn([token])
xxx = self.tokenizer.decode(self.model_tokens[out_last:])
if "\ufffd" not in xxx: # avoid utf-8 display issues
decoded += xxx
out_last = begin + i + 1
if i >= self.max_tokens_per_ge... | https://python.langchain.com/en/latest/_modules/langchain/llms/rwkv.html |
83a329f01be1-0 | Source code for langchain.llms.anyscale
"""Wrapper around Anyscale"""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils import enf... | https://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html |
83a329f01be1-1 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
anyscale_service_url = get_from_dict_or_env(
values, "anyscale_service_url", "ANYSCALE_SERVICE_URL"
)
anyscale_service_route = get_... | https://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html |
83a329f01be1-2 | ) -> str:
"""Call out to Anyscale Service endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
... | https://python.langchain.com/en/latest/_modules/langchain/llms/anyscale.html |
ad4b66ca2685-0 | Source code for langchain.llms.mosaicml
"""Wrapper around MosaicML APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms.utils impo... | https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
ad4b66ca2685-1 | )
"""
endpoint_url: str = (
"https://models.hosted-on.mosaicml.hosting/mpt-7b-instruct/v1/predict"
)
"""Endpoint URL to use."""
inject_instruction_format: bool = False
"""Whether to inject the instruction format into the prompt."""
model_kwargs: Optional[dict] = None
"""Key word ... | https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
ad4b66ca2685-2 | instruction=prompt,
)
return prompt
def _call(
self,
prompt: str,
stop: Optional[List[str]] = None,
run_manager: Optional[CallbackManagerForLLMRun] = None,
is_retry: bool = False,
) -> str:
"""Call out to a MosaicML LLM inference endpoint.
... | https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
ad4b66ca2685-3 | raise ValueError(
f"Error raised by inference API: {parsed_response['error']}"
)
if "data" not in parsed_response:
raise ValueError(
f"Error raised by inference API, no key data: {parsed_response}"
)
generate... | https://python.langchain.com/en/latest/_modules/langchain/llms/mosaicml.html |
4a320b319427-0 | Source code for langchain.llms.beam
"""Wrapper around Beam API."""
import base64
import json
import logging
import subprocess
import textwrap
import time
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import Callba... | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
4a320b319427-1 | llm._deploy()
call_result = llm._call(input)
"""
model_name: str = ""
name: str = ""
cpu: str = ""
memory: str = ""
gpu: str = ""
python_version: str = ""
python_packages: List[str] = []
max_length: str = ""
url: str = ""
"""model endpoint to use"""
model_kwargs: ... | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
4a320b319427-2 | """Validate that api key and python package exists in environment."""
beam_client_id = get_from_dict_or_env(
values, "beam_client_id", "BEAM_CLIENT_ID"
)
beam_client_secret = get_from_dict_or_env(
values, "beam_client_secret", "BEAM_CLIENT_SECRET"
)
values... | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
4a320b319427-3 | outputs={{"text": beam.Types.String()}},
handler="run.py:beam_langchain",
)
"""
)
script_name = "app.py"
with open(script_name, "w") as file:
file.write(
script.format(
name=self.name,
cpu=self.cpu,
... | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
4a320b319427-4 | if beam.__path__ == "":
raise ImportError
except ImportError:
raise ImportError(
"Could not import beam python package. "
"Please install it with `curl "
"https://raw.githubusercontent.com/slai-labs"
"/get-beam/main/get-... | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
4a320b319427-5 | ) -> str:
"""Call to Beam."""
url = "https://apps.beam.cloud/" + self.app_id if self.app_id else self.url
payload = {"prompt": prompt, "max_length": self.max_length}
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Authorization": "Bas... | https://python.langchain.com/en/latest/_modules/langchain/llms/beam.html |
c0d1afdeff2e-0 | Source code for langchain.llms.gooseai
"""Wrapper around GooseAI API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.utils import... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
c0d1afdeff2e-1 | presence_penalty: float = 0
"""Penalizes repeated tokens."""
n: int = 1
"""How many completions to generate for each prompt."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not explicitly specified."""
logit_bias: Optional[Dict[... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
c0d1afdeff2e-2 | )
try:
import openai
openai.api_key = gooseai_api_key
openai.api_base = "https://api.goose.ai/v1"
values["client"] = openai.Completion
except ImportError:
raise ImportError(
"Could not import openai python package. "
... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
c0d1afdeff2e-3 | if stop is not None:
if "stop" in params:
raise ValueError("`stop` found in both the input and default params.")
params["stop"] = stop
response = self.client.create(engine=self.model_name, prompt=prompt, **params)
text = response.choices[0].text
return tex... | https://python.langchain.com/en/latest/_modules/langchain/llms/gooseai.html |
09556f006467-0 | Source code for langchain.llms.self_hosted
"""Run model inference on self-hosted remote hardware."""
import importlib.util
import logging
import pickle
from typing import Any, Callable, List, Mapping, Optional
from pydantic import Extra
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llm... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
09556f006467-1 | )
if device < 0 and cuda_device_count > 0:
logger.warning(
"Device has %d GPUs available. "
"Provide device={deviceId} to `from_model_id` to use available"
"GPUs for execution. deviceId is -1 for CPU and "
"can be a positive integer ass... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
09556f006467-2 | llm = SelfHostedPipeline(
model_load_fn=load_pipeline,
hardware=gpu,
model_reqs=model_reqs, inference_fn=inference_fn
)
Example for <2GB model (can be serialized and sent directly to the server):
.. code-block:: python
from langchain.ll... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
09556f006467-3 | load_fn_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model load function."""
model_reqs: List[str] = ["./", "torch"]
"""Requirements to install on hardware to inference the model."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
09556f006467-4 | if not isinstance(pipeline, str):
logger.warning(
"Serializing pipeline to send to remote hardware. "
"Note, it can be quite slow"
"to serialize and send large models with each execution. "
"Consider sending the pipeline"
"to th... | https://python.langchain.com/en/latest/_modules/langchain/llms/self_hosted.html |
3af31488ec12-0 | Source code for langchain.llms.cerebriumai
"""Wrapper around CerebriumAI API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.callbacks.manager import CallbackManagerForLLMRun
from langchain.llms.base import LLM
from langchain.llms... | https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
3af31488ec12-1 | all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if field_name in extra:
raise ValueError(f"Found {field_name... | https://python.langchain.com/en/latest/_modules/langchain/llms/cerebriumai.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.