id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
115d2a7a94a4-0 | Source code for langchain.utilities.portkey
import json
import os
from typing import Dict, Optional
[docs]class Portkey:
"""Portkey configuration.
Attributes:
base: The base URL for the Portkey API.
Default: "https://api.portkey.ai/v1/proxy"
"""
base = "https://api.portkey.ai/v1/proxy"... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/portkey.html |
115d2a7a94a4-1 | headers = {
"x-portkey-api-key": api_key,
"x-portkey-mode": "proxy openai",
}
if trace_id:
headers["x-portkey-trace-id"] = trace_id
if retry_count:
headers["x-portkey-retry-count"] = str(retry_count)
if cache:
headers["x-portkey... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/portkey.html |
afc07acaa362-0 | Source code for langchain.utilities.google_scholar
"""Util that calls Google Scholar Search."""
from typing import Dict, Optional
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class GoogleScholarAPIWrapper(BaseModel):
"""Wrapper for Google ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_scholar.html |
afc07acaa362-1 | google_scholar = GoogleScholarAPIWrapper()
google_scholar.run('langchain')
"""
top_k_results: int = 10
hl: str = "en"
lr: str = "lang_en"
serp_api_key: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validato... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_scholar.html |
afc07acaa362-2 | results = (
self.google_scholar_engine( # type: ignore
{
"q": query,
"start": page,
"hl": self.hl,
"num": min(
self.top_k_results, 20
)... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_scholar.html |
afc07acaa362-3 | f"Summary: {result.get('publication_info',{}).get('summary','')}\n"
f"Total-Citations: {result.get('inline_links',{}).get('cited_by',{}).get('total','')}" # noqa: E501
for result in total_results
]
return "\n\n".join(docs) | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/google_scholar.html |
aef74c6edd0d-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:
"""SparkSQL is a utility class for interacting with Spark SQL."""
[docs] ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
aef74c6edd0d-1 | )
if catalog is not None:
self._spark.catalog.setCurrentCatalog(catalog)
if schema is not None:
self._spark.catalog.setCurrentDatabase(schema)
self._all_tables = set(self._get_all_table_names())
self._include_tables = set(include_tables) if include_tables else set... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
aef74c6edd0d-2 | )
spark = SparkSession.builder.remote(database_uri).getOrCreate()
return cls(spark, **kwargs)
[docs] def get_usable_table_names(self) -> Iterable[str]:
"""Get names of tables available."""
if self._include_tables:
return self._include_tables
# sorting the result ca... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
aef74c6edd0d-3 | table_info += "*/"
tables.append(table_info)
final_str = "\n\n".join(tables)
return final_str
def _get_sample_spark_rows(self, table: str) -> str:
query = f"SELECT * FROM {table} LIMIT {self._sample_rows_in_table_info}"
df = self._spark.sql(query)
columns_str = "\... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
aef74c6edd0d-4 | 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
demonstrated in the paper.
"""
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/spark_sql.html |
7675721da6c7-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html |
7675721da6c7-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/bibtex.html |
c92ea5ae7da2-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
c92ea5ae7da2-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",... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
c92ea5ae7da2-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 =... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
c92ea5ae7da2-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
c92ea5ae7da2-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)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
c92ea5ae7da2-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:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
c92ea5ae7da2-6 | "commit_message": "Create " + file_path,
"actions": [
{
"action": "update",
"file_path": file_path,
"content": updated_file_content,
}
],
}
self.gitlab_... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
c92ea5ae7da2-7 | return self.delete_file(query)
else:
raise ValueError("Invalid mode" + mode) | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/gitlab.html |
400e031c6e54-0 | Source code for langchain.utilities.clickup
"""Util that calls clickup."""
import json
import warnings
from dataclasses import asdict, dataclass, fields
from typing import Any, Dict, List, Mapping, Optional, Tuple, Type, Union
import requests
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
from langc... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-1 | creator_username=data["creator"]["username"],
creator_email=data["creator"]["email"],
assignees=data["assignees"],
watchers=data["watchers"],
priority=priority,
due_date=data["due_date"],
start_date=data["start_date"],
points=data["poin... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-2 | initials=data["user"]["initials"],
)
[docs]@dataclass
class Team(Component):
"""Component class for a team."""
id: int
name: str
members: List[Member]
[docs] @classmethod
def from_data(cls, data: Dict) -> "Team":
members = [Member.from_data(member_data) for member_data in data["me... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-3 | except Exception as e:
if fault_tolerant:
warning_str = f"""Error encountered while trying to parse
{str(data)}: {str(e)}\n Falling back to returning input data."""
warnings.warn(warning_str)
return data
else:
raise e
[docs]def extract_dict_elements_from_c... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-4 | [docs]def fetch_first_id(data: dict, key: str) -> Optional[int]:
"""Fetch the first id from a dictionary."""
if key in data and len(data[key]) > 0:
if len(data[key]) > 1:
warnings.warn(f"Found multiple {key}: {data[key]}. Defaulting to first.")
return data[key][0]["id"]
return No... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-5 | return fetch_first_id(data, "folders")
[docs]def fetch_list_id(space_id: int, folder_id: int, access_token: str) -> Optional[int]:
"""Fetch the list id."""
if folder_id:
url = f"{DEFAULT_URL}/folder/{folder_id}/list"
else:
url = f"{DEFAULT_URL}/space/{space_id}/list"
data = fetch_data(ur... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-6 | """Get the access token."""
url = f"{DEFAULT_URL}/oauth/token"
params = {
"client_id": oauth_client_id,
"client_secret": oauth_client_secret,
"code": code,
}
response = requests.post(url, params=params)
data = response.json()
if "access... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-7 | """Parse appropriate content from the list of teams."""
parsed_teams: Dict[str, List[dict]] = {"teams": []}
for team in input_dict["teams"]:
try:
team = parse_dict_through_component(team, Team, fault_tolerant=False)
parsed_teams["teams"].append(team)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-8 | return {"response": response}
[docs] def get_task(self, query: str, fault_tolerant: bool = True) -> Dict:
"""
Retrieve a specific task.
"""
params, error = load_query(query, fault_tolerant=True)
if params is None:
return {"Error": error}
url = f"{DEFAULT_UR... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-9 | [docs] def get_spaces(self) -> Dict:
"""
Get all spaces for the team.
"""
url = f"{DEFAULT_URL}/team/{self.team_id}/space"
response = requests.get(
url, headers=self.get_headers(), params=self.get_default_params()
)
data = response.json()
pa... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-10 | }
headers = self.get_headers()
payload = {query_dict["attribute_name"]: query_dict["value"]}
response = requests.put(url, headers=headers, params=params, json=payload)
return {"response": response}
[docs] def update_task_assignees(self, query: str) -> Dict:
"""
Add or ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-11 | [docs] def create_task(self, query: str) -> Dict:
"""
Creates a new task.
"""
query_dict, error = load_query(query, fault_tolerant=True)
if query_dict is None:
return {"Error": error}
list_id = self.list_id
url = f"{DEFAULT_URL}/list/{list_id}/task"... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-12 | self.list_id = parsed_list["id"]
return parsed_list
[docs] def create_folder(self, query: str) -> Dict:
"""
Creates a new folder.
"""
query_dict, error = load_query(query, fault_tolerant=True)
if query_dict is None:
return {"Error": error}
space_id ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
400e031c6e54-13 | output = self.update_task(query)
elif mode == "update_task_assignees":
output = self.update_task_assignees(query)
else:
output = {"ModeError": f"Got unexpected mode {mode}."}
try:
return json.dumps(output)
except Exception:
return str(outpu... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/clickup.html |
8a8bf348b1c9-0 | Source code for langchain.utilities.vertexai
"""Utilities to init Vertex AI."""
from importlib import metadata
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
from google.api_core.gapic_v1.client_info import ClientInfo
from google.auth.credentials import Credentials
[docs]def raise_vertex_import_er... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/vertexai.html |
8a8bf348b1c9-1 | r"""Returns a custom user agent header.
Args:
module (Optional[str]):
Optional. The module for a custom user agent header.
Returns:
google.api_core.gapic_v1.client_info.ClientInfo
"""
try:
from google.api_core.gapic_v1.client_info import ClientInfo
except ImportEr... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/vertexai.html |
20f76d333997-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
20f76d333997-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:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
20f76d333997-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:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
20f76d333997-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:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
20f76d333997-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/apify.html |
4ba5c595deec-0 | Source code for langchain.utilities.scenexplain
"""Util that calls SceneXplain.
In order to set this up, you need API key for the SceneXplain API.
You can obtain a key by following the steps below.
- Sign up for a free account at https://scenex.jina.ai/.
- Navigate to the API Access page (https://scenex.jina.ai/api) an... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html |
4ba5c595deec-1 | "languages": ["en"],
}
]
}
response = requests.post(self.scenex_api_url, headers=headers, json=payload)
response.raise_for_status()
result = response.json().get("result", [])
img = result[0] if result else {}
return img.get("text", "")
@roo... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/scenexplain.html |
68f28c4f559e-0 | Source code for langchain.utilities.openweathermap
"""Util that calls OpenWeatherMap using PyOWM."""
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 OpenWeatherMapAPIWrapper(BaseModel):
"""Wrapper ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
68f28c4f559e-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/openweathermap.html |
fd9d6aca7567-0 | Source code for langchain.utilities.anthropic
from typing import Any, List
def _get_anthropic_client() -> Any:
try:
import anthropic
except ImportError:
raise ImportError(
"Could not import anthropic python package. "
"This is needed in order to accurately tokenize the te... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/anthropic.html |
d50f2d5f1ea0-0 | Source code for langchain.utilities.twilio
"""Util that calls Twilio."""
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 TwilioAPIWrapper(BaseModel):
"""Messaging Client using Twilio.
To use, y... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
d50f2d5f1ea0-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
d50f2d5f1ea0-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/twilio.html |
cc5493f88733-0 | Source code for langchain.utilities.requests
"""Lightweight wrapper around requests library, with async support."""
from contextlib import asynccontextmanager
from typing import Any, AsyncGenerator, Dict, Optional
import aiohttp
import requests
from langchain.pydantic_v1 import BaseModel, Extra
[docs]class Requests(Bas... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html |
cc5493f88733-1 | """PUT the URL and return the text."""
return requests.put(
url, json=data, headers=self.headers, auth=self.auth, **kwargs
)
[docs] def delete(self, url: str, **kwargs: Any) -> requests.Response:
"""DELETE the URL and return the text."""
return requests.delete(url, headers... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html |
cc5493f88733-2 | yield response
[docs] @asynccontextmanager
async def apatch(
self, url: str, data: Dict[str, Any], **kwargs: Any
) -> AsyncGenerator[aiohttp.ClientResponse, None]:
"""PATCH the URL and return the text asynchronously."""
async with self._arequest("PATCH", url, json=data, **kwargs) as r... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html |
cc5493f88733-3 | headers=self.headers, aiosession=self.aiosession, auth=self.auth
)
[docs] def get(self, url: str, **kwargs: Any) -> str:
"""GET the URL and return the text."""
return self.requests.get(url, **kwargs).text
[docs] def post(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html |
cc5493f88733-4 | return await response.text()
[docs] async def apatch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str:
"""PATCH the URL and return the text asynchronously."""
async with self.requests.apatch(url, data, **kwargs) as response:
return await response.text()
[docs] async def aput... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/requests.html |
c53f1c832fc0-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html |
c53f1c832fc0-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_... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/max_compute.html |
0097bd10ff7e-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:
"... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html |
0097bd10ff7e-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)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/python.html |
cfda5880b057-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
cfda5880b057-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
cfda5880b057-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
cfda5880b057-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
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
cfda5880b057-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
cfda5880b057-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:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
cfda5880b057-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(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/github.html |
0a09325f35a6-0 | Source code for langchain.utilities.graphql
import json
from typing import Any, Callable, Dict, Optional
from langchain.pydantic_v1 import BaseModel, Extra, root_validator
[docs]class GraphQLAPIWrapper(BaseModel):
"""Wrapper around GraphQL API.
To use, you should have the ``gql`` python package installed.
T... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html |
0a09325f35a6-1 | return json.dumps(result, indent=2)
def _execute_query(self, query: str) -> Dict[str, Any]:
"""Execute a GraphQL query and return the results."""
document_node = self.gql_function(query)
result = self.gql_client.execute(document_node)
return result | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/graphql.html |
eebf852543f6-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
eebf852543f6-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,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/awslambda.html |
7f0b4fc8029e-0 | Source code for langchain.utilities.searchapi
from typing import Any, Dict, Optional
import aiohttp
import requests
from langchain.pydantic_v1 import BaseModel, root_validator
from langchain.utils import get_from_dict_or_env
[docs]class SearchApiAPIWrapper(BaseModel):
"""
Wrapper around SearchApi API.
To us... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html |
7f0b4fc8029e-1 | results = await self.aresults(query, **kwargs)
return self._result_as_string(results)
[docs] def results(self, query: str, **kwargs: Any) -> dict:
results = self._search_api_results(query, **kwargs)
return results
[docs] async def aresults(self, query: str, **kwargs: Any) -> dict:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html |
7f0b4fc8029e-2 | url=request_details["url"],
headers=request_details["headers"],
params=request_details["params"],
raise_for_status=True,
) as response:
results = await response.json()
else:
async with self.aiosession.get... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html |
7f0b4fc8029e-3 | if "title" in r.keys()
]
toret = "\n".join(videos)
elif "images" in result.keys():
images = [
f"""Title: "{r["title"]}" Link: {r["original"]["link"]}"""
for r in result["images"]
if "original" in r.keys()
]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/searchapi.html |
708d7cb76c03-0 | Source code for langchain.utilities.zapier
"""Util that can interact with Zapier NLA.
Full docs here: https://nla.zapier.com/start/
Note: this wrapper currently only implemented the `api_key` auth method for testing
and server-side production use cases (using the developer's connected accounts on
Zapier.com)
For use-ca... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
708d7cb76c03-1 | your own provider and generate credentials.
"""
zapier_nla_api_key: str
zapier_nla_oauth_access_token: str
zapier_nla_api_base: str = "https://nla.zapier.com/api/v1/"
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
def _format_headers(self) -> Dic... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
708d7cb76c03-2 | {
"instructions": instructions,
}
)
if preview_only:
data.update({"preview_only": True})
return data
def _create_action_url(self, action_id: str) -> str:
"""Create a url for an action."""
return self.zapier_nla_api_base + f"exposed/{act... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
708d7cb76c03-3 | return values
[docs] async def alist(self) -> List[Dict]:
"""Returns a list of all exposed (enabled) actions associated with
current user (associated with the set api_key). Change your exposed
actions here: https://nla.zapier.com/demo/start/
The return list can be empty if no actions ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
708d7cb76c03-4 | """
session = self._get_session()
try:
response = session.get(self.zapier_nla_api_base + "exposed/")
response.raise_for_status()
except requests.HTTPError as http_err:
if response.status_code == 401:
if self.zapier_nla_oauth_access_token:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
708d7cb76c03-5 | ) -> Dict:
"""Executes an action that is identified by action_id, must be exposed
(enabled) by the current user (associated with the set api_key). Change
your exposed actions here: https://nla.zapier.com/demo/start/
The return JSON is guaranteed to be less than ~500 words (350
to... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
708d7cb76c03-6 | response = await self._arequest(
"POST",
self._create_action_url(action_id),
json=self._create_action_payload(instructions, params, preview_only=True),
)
return response["result"]
[docs] def run_as_str(self, *args, **kwargs) -> str: # type: ignore[no-untyped-def]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
708d7cb76c03-7 | """Same as list, but returns a stringified version of the JSON for
insertting back into an LLM."""
actions = self.list()
return json.dumps(actions)
[docs] async def alist_as_str(self) -> str: # type: ignore[no-untyped-def]
"""Same as list, but returns a stringified version of the JSO... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/zapier.html |
6671f8d4b603-0 | Source code for langchain.utilities.jira
"""Util that calls Jira."""
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
# TODO: think about error handling, more specific api specs, and jql/project limits
[docs]... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html |
6671f8d4b603-1 | )
jira = Jira(
url=jira_instance_url,
username=jira_username,
password=jira_api_token,
cloud=True,
)
confluence = Confluence(
url=jira_instance_url,
username=jira_username,
password=jira_api_token,
cl... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html |
6671f8d4b603-2 | parsed.append(
{
"key": key,
"summary": summary,
"created": created,
"assignee": assignee,
"priority": priority,
"status": status,
"related_issues": rel_issues,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html |
6671f8d4b603-3 | )
params = json.loads(query)
return self.jira.issue_create(fields=dict(params))
[docs] def page_create(self, query: str) -> str:
try:
import json
except ImportError:
raise ImportError(
"json is not installed. Please install it with `pip install ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/jira.html |
9299e646bb89-0 | Source code for langchain.utilities.arcee
# This module contains utility classes and functions for interacting with Arcee API.
# For more information and updates, refer to the Arcee utils page:
# [https://github.com/arcee-ai/arcee-python/blob/main/arcee/dalm.py]
from enum import Enum
from typing import Any, Dict, List,... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html |
9299e646bb89-1 | 'strict_search' means that the exact string must appear
in the provided field.
This is NOT an exact eq filter. ie a document with content
"the happy dog crossed the street" will match on a strict_search of
"dog" but won't match on "the dog".
Python equivalent ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html |
9299e646bb89-2 | "source_id": arcee_document.source.id,
# arcee document metadata
"index": arcee_document.index,
"id": arcee_document.id,
"score": arcee_document.score,
},
)
[docs]class ArceeWrapper:
"""Wrapper for Arcee API."""
[docs] def __init... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html |
9299e646bb89-3 | raise Exception(
f"Model {self.model_id} is not ready. "
"Please wait for training to complete."
)
def _make_request(
self,
method: Literal["post", "get"],
route: Union[ArceeRoute, str],
body: Optional[Mapping[str, Any]] = None,
par... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html |
9299e646bb89-4 | self, prompt: str, **kwargs: Mapping[str, Any]
) -> Mapping[str, Any]:
"""Make the request body for generate/retrieve models endpoint"""
_model_kwargs = self.model_kwargs or {}
_params = {**_model_kwargs, **kwargs}
filters = [DALMFilter(**f) for f in _params.get("filters", [])]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html |
9299e646bb89-5 | filters: Filters to apply to the context dataset.
"""
response = self._make_request(
method="post",
route=ArceeRoute.retrieve.value,
body=self._make_request_body_for_models(
prompt=query,
**kwargs,
),
)
retur... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arcee.html |
9e605f1161d2-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
9e605f1161d2-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,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
9e605f1161d2-2 | import arxiv
values["arxiv_search"] = arxiv.Search
values["arxiv_exceptions"] = (
arxiv.ArxivError,
arxiv.UnexpectedEmptyPageError,
arxiv.HTTPError,
)
values["arxiv_result"] = arxiv.Result
except ImportError:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
9e605f1161d2-3 | },
)
for result in results
]
return docs
[docs] def run(self, query: str) -> str:
"""
Performs an arxiv search and A single string
with the publish date, title, authors, and summary
for each article separated by two newlines.
If an error... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
9e605f1161d2-4 | """
Run Arxiv search and get the article texts plus the article meta information.
See https://lukasschwab.me/arxiv.py/index.html#Search
Returns: a list of documents with the document.page_content in text format
Performs an arxiv search, downloads the top k results as PDFs, loads
... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
9e605f1161d2-5 | logger.debug(f_ex)
continue
if self.load_all_available_meta:
extra_metadata = {
"entry_id": result.entry_id,
"published_first_time": str(result.published.date()),
"comment": result.comment,
"journ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/arxiv.html |
ed2de7655e3d-0 | Source code for langchain.utilities.wolfram_alpha
"""Util that calls WolframAlpha."""
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 WolframAlphaAPIWrapper(BaseModel):
"""Wrapper for Wolfram Alpha... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html |
ed2de7655e3d-1 | """Run query through WolframAlpha and parse result."""
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 ... | lang/api.python.langchain.com/en/latest/_modules/langchain/utilities/wolfram_alpha.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.