id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
e97c5b29247c-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/redis.html |
41596348d971-0 | Source code for langchain.utilities.github
"""Util that calls GitHub."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
if TYPE_CHECKING:
fr... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
41596348d971-1 | )
try:
from github import Auth, GithubIntegration
except ImportError:
raise ImportError(
"PyGithub is not installed. "
"Please install it with `pip install PyGithub`"
)
with open(github_app_private_key, "r") as f:
pr... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
41596348d971-2 | and each issue's title and number.
"""
issues = self.github_repo_instance.get_issues(state="open")
if issues.totalCount > 0:
parsed_issues = self.parse_issues(issues)
parsed_issues_str = (
"Found " + str(len(parsed_issues)) + " issues:\n" + str(parsed_issu... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
41596348d971-3 | in the string, and the body are the rest of the string.
For example, "Updated README\nmade changes to add info"
Returns:
str: A success or failure message
"""
if self.github_base_branch == self.github_branch:
return """Cannot make a pull request because
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
41596348d971-4 | return "Unable to make comment due to error:\n" + str(e)
[docs] def create_file(self, file_query: str) -> str:
"""
Creates a new file on the Github repo
Parameters:
file_query(str): a string which contains the file path
and the file contents. The file path is the first... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
41596348d971-5 | """
Updates a file with new content.
Parameters:
file_query(str): Contains the file path and the file contents.
The old file contents is wrapped in OLD <<<< and >>>> OLD
The new file contents is wrapped in NEW <<<< and >>>> NEW
For example:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
41596348d971-6 | """
Deletes a file from the repo
Parameters:
file_path(str): Where the file is
Returns:
str: Success or failure message
"""
try:
file = self.github_repo_instance.get_contents(file_path)
self.github_repo_instance.delete_file(
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
25b87e7fbd4c-0 | Source code for langchain.utilities.sql_database
"""SQLAlchemy wrapper around a database."""
from __future__ import annotations
import warnings
from typing import Any, Iterable, List, Optional, Sequence
import sqlalchemy
from sqlalchemy import MetaData, Table, create_engine, inspect, select, text
from sqlalchemy.engine... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-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"
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-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 = ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-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
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-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\... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-9 | f"{columns_str}\n"
f"{sample_rows_str}"
)
def _execute(self, command: str, fetch: Optional[str] = "all") -> Sequence:
"""
Executes SQL command through underlying engine.
If the statement returns no rows, an empty list is returned.
"""
with self._engine.beg... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-10 | """
result = self._execute(command, fetch)
# Convert columns values to string to avoid issues with sqlalchemy
# truncating text
if not result:
return ""
elif isinstance(result, list):
res: Sequence = [
tuple(truncate_word(c, length=self._ma... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
25b87e7fbd4c-11 | except SQLAlchemyError as e:
"""Format the error message"""
return f"Error: {e}" | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/sql_database.html |
ceab941a5bf1-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
ceab941a5bf1-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
@prope... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
ceab941a5bf1-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."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
ceab941a5bf1-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[RequestB... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
ceab941a5bf1-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 ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
ceab941a5bf1-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] ... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
ceab941a5bf1-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_schema_pydantic import Reference
param... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/openapi.html |
d8e364ed665a-0 | Source code for langchain.utilities.bibtex
"""Util that calls bibtexparser."""
import logging
from typing import Any, Dict, List, Mapping
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
logger = logging.getLogger(__name__)
OPTIONAL_FIELDS = [
"annotate",
"booktitle",
"editor",
"howpub... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html |
d8e364ed665a-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 |
eec0dc207445-0 | Source code for langchain.utilities.python
import functools
import logging
import multiprocessing
import sys
from io import StringIO
from typing import Dict, Optional
from langchain.pydantic_v1 import BaseModel, Field
logger = logging.getLogger(__name__)
@functools.lru_cache(maxsize=None)
def warn_once() -> None:
"... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html |
eec0dc207445-1 | # create a Process
p = multiprocessing.Process(
target=self.worker, args=(command, self.globals, self.locals, queue)
)
# start it
p.start()
# wait for the process to finish or kill it after timeout seconds
p.join(timeout)
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html |
83a2ef3c8f5c-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):
""... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html |
83a2ef3c8f5c-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 =... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html |
83a2ef3c8f5c-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()) | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/tensorflow_datasets.html |
df1e1d2907e9-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html |
df1e1d2907e9-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html |
df1e1d2907e9-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":... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html |
df1e1d2907e9-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html |
df1e1d2907e9-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/dataforseo_api_search.html |
0466ed24cb20-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
0466ed24cb20-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
0466ed24cb20-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.
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
0466ed24cb20-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}
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
0466ed24cb20-4 | "author": result.get("author", "Unknown Author"),
"published_date": result.get("publishedDate", "Unknown Date"),
}
)
return cleaned_results | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/metaphor_search.html |
b381fe57e9af-0 | Source code for langchain.utilities.arxiv
"""Util that calls Arxiv."""
import logging
import os
import re
from typing import Any, Dict, List, Optional
from langchain.pydantic_v1 import BaseModel, root_validator
from langchain.schema import Document
logger = logging.getLogger(__name__)
[docs]class ArxivAPIWrapper(BaseMo... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
b381fe57e9af-1 | content
Example:
.. code-block:: python
from langchain.utilities.arxiv import ArxivAPIWrapper
arxiv = ArxivAPIWrapper(
top_k_results = 3,
ARXIV_MAX_QUERY_LENGTH = 300,
load_max_docs = 3,
load_all_available_meta = False,
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
b381fe57e9af-2 | import arxiv
values["arxiv_search"] = arxiv.Search
values["arxiv_exceptions"] = (
arxiv.ArxivError,
arxiv.UnexpectedEmptyPageError,
arxiv.HTTPError,
)
values["arxiv_result"] = arxiv.Result
except ImportError:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
b381fe57e9af-3 | 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 |
b381fe57e9af-4 | docs: List[Document] = []
for result in results:
try:
doc_file_name: str = result.download_pdf()
with fitz.open(doc_file_name) as doc_file:
text: str = "".join(page.get_text() for page in doc_file)
except (FileNotFoundError, fitz.fitz.F... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
83ea9f0456b6-0 | Source code for langchain.utilities.gitlab
"""Util that calls gitlab."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
if TYPE_CHECKING:
fr... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
83ea9f0456b6-1 | values, "gitlab_personal_access_token", "GITLAB_PERSONAL_ACCESS_TOKEN"
)
gitlab_branch = get_from_dict_or_env(
values, "gitlab_branch", "GITLAB_BRANCH", default="main"
)
gitlab_base_branch = get_from_dict_or_env(
values, "gitlab_base_branch", "GITLAB_BASE_BRANCH",... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
83ea9f0456b6-2 | """
Fetches all open issues from the repo
Returns:
str: A plaintext report containing the number of issues
and each issue's title and number.
"""
issues = self.gitlab_repo_instance.issues.list(state="opened")
if len(issues) > 0:
parsed_issues =... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
83ea9f0456b6-3 | """
Makes a pull request from the bot's branch to the base branch
Parameters:
pr_query(str): a string which contains the PR title
and the PR body. The title is the first line
in the string, and the body are the rest of the string.
For example, "Updated REA... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
83ea9f0456b6-4 | """
issue_number = int(comment_query.split("\n\n")[0])
comment = comment_query[len(str(issue_number)) + 2 :]
try:
issue = self.gitlab_repo_instance.issues.get(issue_number)
issue.notes.create({"body": comment})
return "Commented on issue " + str(issue_number)
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
83ea9f0456b6-5 | Parameters:
file_path(str): the file path
Returns:
str: The file decoded as a string
"""
file = self.gitlab_repo_instance.files.get(file_path, self.gitlab_branch)
return file.decode().decode("utf-8")
[docs] def update_file(self, file_query: str) -> str:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
83ea9f0456b6-6 | "commit_message": "Create " + file_path,
"actions": [
{
"action": "update",
"file_path": file_path,
"content": updated_file_content,
}
],
}
self.gitlab_... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
83ea9f0456b6-7 | return self.delete_file(query)
else:
raise ValueError("Invalid mode" + mode) | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
13f786eb76e8-0 | Source code for langchain.utilities.vertexai
"""Utilities to init Vertex AI."""
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from google.auth.credentials import Credentials
[docs]def raise_vertex_import_error(minimum_expected_version: str = "1.33.0") -> None:
"""Raise ImportError related to Vert... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/vertexai.html |
5bcf928abdd5-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 |
5bcf928abdd5-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 |
07b688a94f81-0 | Source code for langchain.utilities.apify
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional
from langchain.pydantic_v1 import BaseModel, root_validator
from langchain.schema.document import Document
from langchain.utils import get_from_dict_or_env
if TYPE_CHECKING:
from langchain.document_loaders impo... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
07b688a94f81-1 | dataset_mapping_function: Callable[[Dict], Document],
*,
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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
07b688a94f81-2 | dataset_mapping_function: Callable[[Dict], Document],
*,
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:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
07b688a94f81-3 | dataset_mapping_function: Callable[[Dict], Document],
*,
build: Optional[str] = None,
memory_mbytes: Optional[int] = None,
timeout_secs: Optional[int] = None,
) -> "ApifyDatasetLoader":
"""Run a saved Actor task on Apify and wait for results to be ready.
Args:
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
07b688a94f81-4 | self,
task_id: str,
task_input: Dict,
dataset_mapping_function: Callable[[Dict], Document],
*,
build: Optional[str] = None,
memory_mbytes: Optional[int] = None,
timeout_secs: Optional[int] = None,
) -> "ApifyDatasetLoader":
"""Run a saved Actor task on... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
50ec16c6f03b-0 | Source code for langchain.utilities.awslambda
"""Util that calls Lambda."""
import json
from typing import Any, Dict, Optional
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
[docs]class LambdaWrapper(BaseModel):
"""Wrapper for AWS Lambda SDK.
To use, you should have the ``boto3`` package ins... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
50ec16c6f03b-1 | Invokes the lambda function and returns the
result.
Args:
query: an input to passed to the lambda
function as the ``body`` of a JSON
object.
""" # noqa: E501
res = self.lambda_client.invoke(
FunctionName=self.function_name,
... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
9d7dcfd4052d-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
9d7dcfd4052d-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
9d7dcfd4052d-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... | https://api.python.langchain.com/en/latest/_modules/langchain/utilities/wikipedia.html |
43b9571766fa-0 | Source code for langchain.docstore.arbitrary_fn
from typing import Callable, Union
from langchain.docstore.base import Docstore
from langchain.schema import Document
[docs]class DocstoreFn(Docstore):
"""Langchain Docstore via arbitrary lookup function.
This is useful when:
* it's expensive to construct an ... | https://api.python.langchain.com/en/latest/_modules/langchain/docstore/arbitrary_fn.html |
b3ee01ec1527-0 | Source code for langchain.docstore.in_memory
"""Simple in memory docstore in the form of a dict."""
from typing import Dict, List, Optional, Union
from langchain.docstore.base import AddableMixin, Docstore
from langchain.docstore.document import Document
[docs]class InMemoryDocstore(Docstore, AddableMixin):
"""Simp... | https://api.python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html |
b3ee01ec1527-1 | """
if search not in self._dict:
return f"ID {search} not found."
else:
return self._dict[search] | https://api.python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html |
9c05b3ae67ef-0 | Source code for langchain.docstore.base
"""Interface to access to place that stores documents."""
from abc import ABC, abstractmethod
from typing import Dict, List, Union
from langchain.docstore.document import Document
[docs]class Docstore(ABC):
"""Interface to access to place that stores documents."""
[docs] @... | https://api.python.langchain.com/en/latest/_modules/langchain/docstore/base.html |
4181da336b42-0 | Source code for langchain.docstore.wikipedia
"""Wrapper around wikipedia API."""
from typing import Union
from langchain.docstore.base import Docstore
from langchain.docstore.document import Document
[docs]class Wikipedia(Docstore):
"""Wrapper around wikipedia API."""
[docs] def __init__(self) -> None:
"... | https://api.python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html |
cdbcd3b4241e-0 | Source code for langchain.agents.utils
from typing import Sequence
from langchain.tools.base import BaseTool
[docs]def validate_tools_single_input(class_name: str, tools: Sequence[BaseTool]) -> None:
"""Validate tools for single input."""
for tool in tools:
if not tool.is_single_input:
raise... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/utils.html |
28f83a08f340-0 | Source code for langchain.agents.tools
"""Interface for tools."""
from typing import List, Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool, Tool, tool
[docs]class InvalidTool(BaseTool):
"""Tool that is ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/tools.html |
f36440b0ee99-0 | Source code for langchain.agents.load_tools
# flake8: noqa
"""Load tools."""
import warnings
from typing import Any, Dict, List, Optional, Callable, Tuple
from mypy_extensions import Arg, KwArg
from langchain.agents.tools import Tool
from langchain.schema.language_model import BaseLanguageModel
from langchain.callbacks... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-1 | RequestsPatchTool,
RequestsPostTool,
RequestsPutTool,
)
from langchain.tools.eleven_labs.text2speech import ElevenLabsText2SpeechTool
from langchain.tools.scenexplain.tool import SceneXplainTool
from langchain.tools.searx_search.tool import SearxSearchResults, SearxSearchRun
from langchain.tools.shell.tool impo... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-2 | from langchain.utilities.openweathermap import OpenWeatherMapAPIWrapper
from langchain.utilities.dataforseo_api_search import DataForSeoAPIWrapper
def _get_python_repl() -> BaseTool:
return PythonREPLTool()
def _get_tools_requests_get() -> BaseTool:
return RequestsGetTool(requests_wrapper=TextRequestsWrapper())... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-3 | description="Useful for when you need to answer questions about math.",
func=LLMMathChain.from_llm(llm=llm).run,
coroutine=LLMMathChain.from_llm(llm=llm).arun,
)
def _get_open_meteo_api(llm: BaseLanguageModel) -> BaseTool:
chain = APIChain.from_llm_and_api_docs(llm, open_meteo_docs.OPEN_METEO_DO... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-4 | tmdb_bearer_token = kwargs["tmdb_bearer_token"]
chain = APIChain.from_llm_and_api_docs(
llm,
tmdb_docs.TMDB_DOCS,
headers={"Authorization": f"Bearer {tmdb_bearer_token}"},
)
return Tool(
name="TMDB API",
description="Useful for when you want to get information from Th... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-5 | def _get_wikipedia(**kwargs: Any) -> BaseTool:
return WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(**kwargs))
def _get_arxiv(**kwargs: Any) -> BaseTool:
return ArxivQueryRun(api_wrapper=ArxivAPIWrapper(**kwargs))
def _get_golden_query(**kwargs: Any) -> BaseTool:
return GoldenQueryRun(api_wrapper=Golden... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-6 | return Tool(
"Dall-E Image Generator",
DallEAPIWrapper(**kwargs).run,
"A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description.",
)
def _get_twilio(**kwargs: Any) -> BaseTool:
return Tool(
name=... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-7 | def _get_graphql_tool(**kwargs: Any) -> BaseTool:
graphql_endpoint = kwargs["graphql_endpoint"]
wrapper = GraphQLAPIWrapper(graphql_endpoint=graphql_endpoint)
return BaseGraphQLTool(graphql_wrapper=wrapper)
def _get_openweathermap(**kwargs: Any) -> BaseTool:
return OpenWeatherMapQueryRun(api_wrapper=Ope... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-8 | "google-search-results-json": (
_get_google_search_results_json,
["google_api_key", "google_cse_id", "num_results"],
),
"searx-search-results-json": (
_get_searx_search_results_json,
["searx_host", "engines", "num_results", "aiosession"],
),
"bing-search": (_get_bing_sear... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-9 | "arxiv": (
_get_arxiv,
["top_k_results", "load_max_docs", "load_all_available_meta"],
),
"golden-query": (_get_golden_query, ["golden_api_key"]),
"pubmed": (_get_pubmed, ["top_k_results"]),
"human": (_get_human_tool, ["prompt_func", "input_func"]),
"awslambda": (
_get_lambda_... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-10 | [docs]def load_huggingface_tool(
task_or_repo_id: str,
model_repo_id: Optional[str] = None,
token: Optional[str] = None,
remote: bool = False,
**kwargs: Any,
) -> BaseTool:
"""Loads a tool from the HuggingFace Hub.
Args:
task_or_repo_id: Task or model repo id.
model_repo_id: ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-11 | callbacks: Callbacks = None,
**kwargs: Any,
) -> List[BaseTool]:
"""Load tools based on their name.
Args:
tool_names: name of tools to load.
llm: An optional language model, may be needed to initialize certain tools.
callbacks: Optional callback manager or list of callback handlers.
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
f36440b0ee99-12 | missing_keys = set(extra_keys).difference(kwargs)
if missing_keys:
raise ValueError(
f"Tool {name} requires some parameters that were not "
f"provided: {missing_keys}"
)
sub_kwargs = {k: kwargs[k] for k in extra_keys}
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
e6d9fca7cb29-0 | Source code for langchain.agents.agent_iterator
from __future__ import annotations
import logging
import time
from abc import ABC, abstractmethod
from asyncio import CancelledError
from functools import wraps
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
NoReturn,
Optional,
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html |
e6d9fca7cb29-1 | self,
agent_executor: AgentExecutor,
inputs: Any,
callbacks: Callbacks = None,
*,
tags: Optional[list[str]] = None,
include_run_info: bool = False,
async_: bool = False,
):
"""
Initialize the AgentExecutorIterator with the given AgentExecutor,
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html |
e6d9fca7cb29-2 | return self._tags
@tags.setter
@rebuild_callback_manager_on_set
def tags(self, tags: Optional[List[str]]) -> None:
"""When tags are changed after __init__, rebuild callback mgr"""
self._tags = tags
@property
def agent_executor(self) -> AgentExecutor:
return self._agent_execut... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html |
e6d9fca7cb29-3 | )
[docs] def reset(self) -> None:
"""
Reset the iterator to its initial state, clearing intermediate steps,
iterations, and time elapsed.
"""
logger.debug("(Re)setting AgentExecutorIterator to fresh state")
self.intermediate_steps: list[tuple[AgentAction, str]] = []
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html |
e6d9fca7cb29-4 | return self._final_outputs
@final_outputs.setter
def final_outputs(self, outputs: Optional[Dict[str, Any]]) -> None:
# have access to intermediate steps by design in iterator,
# so return only outputs may as well always be true.
self._final_outputs = None
if outputs:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html |
e6d9fca7cb29-5 | """
pass
async def _on_first_async_step(self) -> None:
"""
Perform any necessary setup for the first step of the asynchronous iterator.
"""
# on first step, need to await callback manager and start async timeout ctxmgr
if self.iterations == 0:
assert isins... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html |
e6d9fca7cb29-6 | return await self._acall_next()
except StopAsyncIteration:
raise
except (TimeoutError, CancelledError):
await self.timeout_manager.__aexit__(None, None, None)
self.timeout_manager = None
return await self._astop()
except BaseException as e:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html |
e6d9fca7cb29-7 | run_manager: Optional[CallbackManagerForChainRun],
) -> Dict[str, Union[str, List[Tuple[AgentAction, str]]]]:
"""
Process the output of the next step,
handling AgentFinish and tool return cases.
"""
logger.debug("Processing output of Agent loop step")
if isinstance(ne... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html |
e6d9fca7cb29-8 | """
Process the output of the next async step,
handling AgentFinish and tool return cases.
"""
logger.debug("Processing output of async Agent loop step")
if isinstance(next_step_output, AgentFinish):
logger.debug(
"Hit AgentFinish: _areturn -> on_chain... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html |
e6d9fca7cb29-9 | self.intermediate_steps,
**self.inputs,
)
assert (
isinstance(self.run_manager, CallbackManagerForChainRun)
or self.run_manager is None
)
returned_output = self.agent_executor._return(
output, self.intermediate_steps, run_manager=self.run_m... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_iterator.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.