id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
c125cfb3b5c4-12 | if e.args:
observation = e.args[0]
else:
observation = "Tool execution error"
elif isinstance(self.handle_tool_error, str):
observation = self.handle_tool_error
elif callable(self.handle_tool_error):
observat... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-13 | )
return observation
[docs] async def arun(
self,
tool_input: Union[str, Dict],
verbose: Optional[bool] = None,
start_color: Optional[str] = "green",
color: Optional[str] = "green",
callbacks: Callbacks = None,
**kwargs: Any,
) -> Any:
"... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-14 | {"name": self.name, "description": self.description},
tool_input if isinstance(tool_input, str) else str(tool_input),
color=start_color,
**kwargs,
)
try:
# We then call the tool on the tool input to get an observation
tool_args, tool_kwargs = s... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-15 | else:
observation = "Tool execution error"
elif isinstance(self.handle_tool_error, str):
observation = self.handle_tool_error
elif callable(self.handle_tool_error):
observation = self.handle_tool_error(e)
else:
raise... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-16 | )
return observation
def __call__(self, tool_input: str, callbacks: Callbacks = None) -> str:
"""Make tool callable."""
return self.run(tool_input, callbacks=callbacks)
[docs]class Tool(BaseTool):
"""Tool that takes in function or coroutine directly."""
description: str = ""
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-17 | return {"tool_input": {"type": "string"}}
def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]:
"""Convert tool input to pydantic model."""
args, kwargs = super()._to_args_and_kwargs(tool_input)
# For backwards compatibility. The tool must be run with a single in... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-18 | ) -> Any:
"""Use the tool."""
new_argument_supported = signature(self.func).parameters.get("callbacks")
return (
self.func(
*args,
callbacks=run_manager.get_child() if run_manager else None,
**kwargs,
)
if new_ar... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-19 | *args,
callbacks=run_manager.get_child() if run_manager else None,
**kwargs,
)
if new_argument_supported
else await self.coroutine(*args, **kwargs)
)
raise NotImplementedError("Tool does not support async")
#... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-20 | return_direct: bool = False,
args_schema: Optional[Type[BaseModel]] = None,
**kwargs: Any,
) -> Tool:
"""Initialize tool from a function."""
return cls(
name=name,
func=func,
description=description,
return_direct=return_direct,
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-21 | """The asynchronous version of the function."""
@property
def args(self) -> dict:
"""The tool's input arguments."""
return self.args_schema.schema()["properties"]
def _run(
self,
*args: Any,
run_manager: Optional[CallbackManagerForToolRun] = None,
**kwargs: An... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-22 | *args: Any,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
**kwargs: Any,
) -> str:
"""Use the tool asynchronously."""
if self.coroutine:
new_argument_supported = signature(self.coroutine).parameters.get(
"callbacks"
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-23 | return_direct: bool = False,
args_schema: Optional[Type[BaseModel]] = None,
infer_schema: bool = True,
**kwargs: Any,
) -> StructuredTool:
"""Create tool from a given function.
A classmethod that helps to create a tool from a function.
Args:
func: The func... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-24 | ... code-block:: python
def add(a: int, b: int) -> int:
\"\"\"Add two numbers\"\"\"
return a + b
tool = StructuredTool.from_function(add)
tool.run(1, 2) # 3
"""
name = name or func.__name__
description = desc... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-25 | return cls(
name=name,
func=func,
args_schema=_args_schema,
description=description,
return_direct=return_direct,
**kwargs,
)
[docs]def tool(
*args: Union[str, Callable],
return_direct: bool = False,
args_schema: Optional[Type[B... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-26 | accept a dictionary input to its `run()` function.
Requires:
- Function must be of type (str) -> str
- Function must have a docstring
Examples:
.. code-block:: python
@tool
def search_api(query: str) -> str:
# Searches the API for the query.
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-27 | args_schema=args_schema,
infer_schema=infer_schema,
)
# If someone doesn't want a schema applied, we must treat it as
# a simple string->string function
assert func.__doc__ is not None, "Function must have a docstring"
return Tool(
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
c125cfb3b5c4-28 | # if the argument is a function, then we use the function name as the tool name
# Example usage: @tool
return _make_with_name(args[0].__name__)(args[0])
elif len(args) == 0:
# if there are no arguments, then we use the function name as the tool name
# Example usage: @tool(return_dire... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
ba0bb6ac6577-0 | Source code for langchain.tools.convert_to_openai
from typing import TypedDict
from langchain.tools import BaseTool, StructuredTool
class FunctionDescription(TypedDict):
"""Representation of a callable function to the OpenAI API."""
name: str
"""The name of the function."""
description: str
"""A des... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/convert_to_openai.html |
ba0bb6ac6577-1 | "parameters": {
"type": "object",
"properties": schema_["properties"],
"required": required,
},
}
else:
if tool.args_schema:
parameters = tool.args_schema.schema()
else:
parameters = {
# This ... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/convert_to_openai.html |
ba0bb6ac6577-2 | "parameters": parameters,
} | https://api.python.langchain.com/en/latest/_modules/langchain/tools/convert_to_openai.html |
d8e44a9ae989-0 | Source code for langchain.tools.plugin
from __future__ import annotations
import json
from typing import Optional, Type
import requests
import yaml
from pydantic import BaseModel
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base impo... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html |
d8e44a9ae989-1 | @classmethod
def from_url(cls, url: str) -> AIPlugin:
"""Instantiate AIPlugin from a URL."""
response = requests.get(url).json()
return cls(**response)
def marshal_spec(txt: str) -> dict:
"""Convert the yaml or json serialized spec to a dict.
Args:
txt: The yaml or json seria... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html |
d8e44a9ae989-2 | [docs] @classmethod
def from_plugin_url(cls, url: str) -> AIPluginTool:
plugin = AIPlugin.from_url(url)
description = (
f"Call this tool to get the OpenAPI spec (and usage guide) "
f"for interacting with the {plugin.name_for_human} API. "
f"You should only call... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html |
d8e44a9ae989-3 | description=description,
plugin=plugin,
api_spec=api_spec,
)
def _run(
self,
tool_input: Optional[str] = "",
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the tool."""
return self.api_spec
async def _arun(
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html |
7ab58456bdb7-0 | Source code for langchain.tools.ifttt
"""From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services.
# Creating a webhook
- Go to https://ifttt.com/create
# Configuring the "If This"
- Click on the "If This" button in the IFTTT interface.
- Search for "Webhooks" in the search bar.
- Choose the first... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html |
7ab58456bdb7-1 | # Configuring the "Then That"
- Tap on the "Then That" button in the IFTTT interface.
- Search for the service you want to connect, such as Spotify.
- Choose an action from the service, such as "Add track to a playlist".
- Configure the action by specifying the necessary details, such as the playlist name,
e.g., "Songs... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html |
7ab58456bdb7-2 | # Finishing up
- To get your webhook URL go to https://ifttt.com/maker_webhooks/settings
- Copy the IFTTT key value from there. The URL is of the form
https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value.
"""
from typing import Optional
import requests
from langchain.callbacks.manager import (
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html |
7ab58456bdb7-3 | tool_input: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
body = {"this": tool_input}
response = requests.post(self.url, data=body)
return response.text
async def _arun(
self,
tool_input: str,
run_manager: Optional[AsyncCallbackMa... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html |
db4931c34b9e-0 | Source code for langchain.tools.openweathermap.tool
"""Tool for the OpenWeatherMap API."""
from typing import Optional
from pydantic import Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilit... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/openweathermap/tool.html |
db4931c34b9e-1 | )
def _run(
self, location: str, run_manager: Optional[CallbackManagerForToolRun] = None
) -> str:
"""Use the OpenWeatherMap tool."""
return self.api_wrapper.run(location)
async def _arun(
self,
location: str,
run_manager: Optional[AsyncCallbackManagerForToolR... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/openweathermap/tool.html |
b48da2aec938-0 | Source code for langchain.tools.sleep.tool
"""Tool for agent to sleep."""
from asyncio import sleep as asleep
from time import sleep
from typing import Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/sleep/tool.html |
b48da2aec938-1 | sleep_time: int,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the Sleep tool."""
sleep(sleep_time)
return f"Agent slept for {sleep_time} seconds."
async def _arun(
self,
sleep_time: int,
run_manager: Optional[AsyncCallbackManag... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/sleep/tool.html |
f7c058dd588d-0 | Source code for langchain.tools.youtube.search
"""
Adapted from https://github.com/venuv/langchain_yt_tools
CustomYTSearchTool searches YouTube videos related to a person
and returns a specified number of video URLs.
Input to this tool should be a comma separated list,
- the first part contains a person name
- and th... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html |
f7c058dd588d-1 | "the first part contains a person name and the second a "
"number that is the maximum number of video results "
"to return aka num_results. the second part is optional"
)
def _search(self, person: str, num_results: int) -> str:
from youtube_search import YoutubeSearch
results = Y... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html |
f7c058dd588d-2 | if len(values) > 1:
num_results = int(values[1])
else:
num_results = 2
return self._search(person, num_results)
async def _arun(
self,
query: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Use the tool async... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html |
a1124f69d4bf-0 | Source code for langchain.tools.arxiv.tool
"""Tool for the Arxiv API."""
from typing import Optional
from pydantic import Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilities.arxiv import A... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/arxiv/tool.html |
a1124f69d4bf-1 | )
api_wrapper: ArxivAPIWrapper = Field(default_factory=ArxivAPIWrapper)
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the Arxiv tool."""
return self.api_wrapper.run(query)
async def _arun(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/arxiv/tool.html |
028ab949362b-0 | Source code for langchain.tools.python.tool
"""A tool for running python code in a REPL."""
import ast
import re
import sys
from contextlib import redirect_stdout
from io import StringIO
from typing import Any, Dict, Optional
from pydantic import Field, root_validator
from langchain.callbacks.manager import (
Async... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/python/tool.html |
028ab949362b-1 | str: The sanitized query
"""
# Removes `, whitespace & python from start
query = re.sub(r"^(\s|`)*(?i:python)?\s*", "", query)
# Removes whitespace & ` from end
query = re.sub(r"(\s|`)*$", "", query)
return query
[docs]class PythonREPLTool(BaseTool):
"""A tool for running python code in a RE... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/python/tool.html |
028ab949362b-2 | sanitize_input: bool = True
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> Any:
"""Use the tool."""
if self.sanitize_input:
query = sanitize_input(query)
return self.python_repl.run(query)
async def _arun(... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/python/tool.html |
028ab949362b-3 | "Input should be a valid python command. "
"When using this tool, sometimes output is abbreviated - "
"make sure it does not look abbreviated before using it in your answer."
)
globals: Optional[Dict] = Field(default_factory=dict)
locals: Optional[Dict] = Field(default_factory=dict)
sani... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/python/tool.html |
028ab949362b-4 | self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the tool."""
try:
if self.sanitize_input:
query = sanitize_input(query)
tree = ast.parse(query)
module = ast.Module(tree.body[:-1], type_ign... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/python/tool.html |
028ab949362b-5 | else:
return ret
except Exception:
with redirect_stdout(io_buffer):
exec(module_end_str, self.globals, self.locals)
return io_buffer.getvalue()
except Exception as e:
return "{}: {}".format(type(e).__name__, str(... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/python/tool.html |
fe27832d68dd-0 | Source code for langchain.tools.google_places.tool
"""Tool for the Google search API."""
from typing import Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html |
fe27832d68dd-1 | )
api_wrapper: GooglePlacesAPIWrapper = Field(default_factory=GooglePlacesAPIWrapper)
args_schema: Type[BaseModel] = GooglePlacesSchema
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the tool."""
return self.a... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html |
914d82279898-0 | Source code for langchain.tools.wolfram_alpha.tool
"""Tool for the Wolfram Alpha API."""
from typing import Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilities.wolfram_alpha import Wolf... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/wolfram_alpha/tool.html |
914d82279898-1 | def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the WolframAlpha tool."""
return self.api_wrapper.run(query)
async def _arun(
self,
query: str,
run_manager: Optional[AsyncCallbackManagerForToolR... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/wolfram_alpha/tool.html |
1410a84d2e51-0 | Source code for langchain.tools.powerbi.tool
"""Tools for interacting with a Power BI dataset."""
import logging
from typing import Any, Dict, Optional, Tuple
from pydantic import Field, validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-1 | description = """
Input to this tool is a detailed question about the dataset, output is a result from the dataset. It will try to answer the question using the dataset, and if it cannot, it will ask for clarification.
Example Input: "How many rows are in table1?"
""" # noqa: E501
llm_chain: LLMChain
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-2 | @validator("llm_chain")
def validate_llm_chain_input_variables( # pylint: disable=E0213
cls, llm_chain: LLMChain
) -> LLMChain:
"""Make sure the LLM chain has the correct input variables."""
if llm_chain.prompt.input_variables != [
"tool_input",
"tables",
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-3 | If the value is a bad request, overwrite with the escalated version,
if not present return None."""
if tool_input not in self.session_cache:
return None
return self.session_cache[tool_input]
def _run(
self,
tool_input: str,
run_manager: Optional[CallbackMa... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-4 | tables=self.powerbi.get_table_names(),
schemas=self.powerbi.get_schemas(),
examples=self.examples,
)
except Exception as exc: # pylint: disable=broad-except
self.session_cache[tool_input] = f"Error on call to LLM: {exc}"
return self.session_ca... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-5 | return self.session_cache[tool_input]
iterations = kwargs.get("iterations", 0)
if error and iterations < self.max_iterations:
return self._run(
tool_input=RETRY_RESPONSE.format(
tool_input=tool_input, query=query, error=error
),
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-6 | if cache := self._check_cache(tool_input):
logger.debug("Found cached result for %s: %s", tool_input, cache)
return cache
try:
logger.info("Running PBI Query Tool with input: %s", tool_input)
query = await self.llm_chain.apredict(
tool_input=tool_i... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-7 | pbi_result = await self.powerbi.arun(command=query)
result, error = self._parse_output(pbi_result)
if error is not None and "TokenExpired" in error:
self.session_cache[
tool_input
] = "Authentication token expired or invalid, please try reauthenticate."
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-8 | return self.session_cache[tool_input]
def _parse_output(
self, pbi_result: Dict[str, Any]
) -> Tuple[Optional[str], Optional[str]]:
"""Parse the output of the query to a markdown table."""
if "results" in pbi_result:
return json_to_md(pbi_result["results"][0]["tables"][0]["ro... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-9 | """Tool for getting metadata about a PowerBI Dataset."""
name = "schema_powerbi"
description = """
Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.
Be sure that the tables actually exist by calling list_tables_powerbi first!
Example Input... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-10 | async def _arun(
self,
tool_input: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
return await self.powerbi.aget_table_info(tool_input.split(", "))
[docs]class ListPowerBITool(BaseTool):
"""Tool for getting tables names."""
name = "list_tables_po... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
1410a84d2e51-11 | ) -> str:
"""Get the names of the tables."""
return ", ".join(self.powerbi.get_table_names())
async def _arun(
self,
tool_input: Optional[str] = None,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Get the names of the tables."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/powerbi/tool.html |
2a4ca7baabb1-0 | Source code for langchain.tools.metaphor_search.tool
"""Tool for the Metaphor search API."""
from typing import Dict, List, Optional, Union
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilities.me... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html |
2a4ca7baabb1-1 | def _run(
self,
query: str,
num_results: int,
include_domains: Optional[List[str]] = None,
exclude_domains: Optional[List[str]] = None,
start_crawl_date: Optional[str] = None,
end_crawl_date: Optional[str] = None,
start_published_date: Optional[str] = None... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html |
2a4ca7baabb1-2 | )
except Exception as e:
return repr(e)
async def _arun(
self,
query: str,
num_results: int,
include_domains: Optional[List[str]] = None,
exclude_domains: Optional[List[str]] = None,
start_crawl_date: Optional[str] = None,
end_crawl_date: O... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html |
2a4ca7baabb1-3 | end_crawl_date,
start_published_date,
end_published_date,
)
except Exception as e:
return repr(e) | https://api.python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html |
4da70e6ba431-0 | Source code for langchain.tools.json.tool
# flake8: noqa
"""Tools for working with JSON specs."""
from __future__ import annotations
import json
import re
from pathlib import Path
from typing import Dict, List, Optional, Union
from pydantic import BaseModel
from langchain.callbacks.manager import (
AsyncCallbackMan... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html |
4da70e6ba431-1 | res = [int(i) if i.isdigit() else i for i in res]
return res
class JsonSpec(BaseModel):
"""Base class for JSON spec."""
dict_: Dict
max_value_length: int = 200
@classmethod
def from_file(cls, path: Path) -> JsonSpec:
"""Create a JsonSpec from a file."""
if not path.exists():
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html |
4da70e6ba431-2 | items = _parse_input(text)
val = self.dict_
for i in items:
if i:
val = val[i]
if not isinstance(val, dict):
raise ValueError(
f"Value at path `{text}` is not a dict, get the value directly."
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html |
4da70e6ba431-3 | val = val[i]
if isinstance(val, dict) and len(str(val)) > self.max_value_length:
return "Value is a large dictionary, should explore its keys directly"
str_val = str(val)
if len(str_val) > self.max_value_length:
str_val = str_val[: self.max_value_lengt... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html |
4da70e6ba431-4 | """
spec: JsonSpec
def _run(
self,
tool_input: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
return self.spec.keys(tool_input)
async def _arun(
self,
tool_input: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] =... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html |
4da70e6ba431-5 | The input is a text representation of the path to the dict in Python syntax (e.g. data["key1"][0]["key2"]).
"""
spec: JsonSpec
def _run(
self,
tool_input: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
return self.spec.value(tool_input)
async ... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html |
f90330fd94d0-0 | Source code for langchain.tools.shell.tool
import asyncio
import platform
import warnings
from typing import List, Optional, Type, Union
from pydantic import BaseModel, Field, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.too... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html |
f90330fd94d0-1 | if not isinstance(commands, list):
values["commands"] = [commands]
# Warn that the bash tool is not safe
warnings.warn(
"The shell tool has no safeguards by default. Use at your own risk."
)
return values
def _get_default_bash_processs() -> BashProcess:
"""Get... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html |
f90330fd94d0-2 | """Name of tool."""
description: str = f"Run shell commands on this {_get_platform()} machine."
"""Description of tool."""
args_schema: Type[BaseModel] = ShellInput
"""Schema for input arguments."""
def _run(
self,
commands: Union[str, List[str]],
run_manager: Optional[Callba... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html |
24c40bc3f9d9-0 | Source code for langchain.tools.bing_search.tool
"""Tool for the Bing search API."""
from typing import Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.base import BaseTool
from langchain.utilities.bing_search import BingSearch... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html |
24c40bc3f9d9-1 | ) -> str:
"""Use the tool."""
return self.api_wrapper.run(query)
async def _arun(
self,
query: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Use the tool asynchronously."""
raise NotImplementedError("BingSearchRun does not... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html |
24c40bc3f9d9-2 | api_wrapper: BingSearchAPIWrapper
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the tool."""
return str(self.api_wrapper.results(query, self.num_results))
async def _arun(
self,
query: str,
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/bing_search/tool.html |
d6cf2af9a6e8-0 | Source code for langchain.tools.gmail.create_draft
import base64
from email.message import EmailMessage
from typing import List, Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.gmail.... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html |
d6cf2af9a6e8-1 | None,
description="The list of BCC recipients.",
)
[docs]class GmailCreateDraft(GmailBaseTool):
name: str = "create_gmail_draft"
description: str = (
"Use this tool to create a draft email with the provided message fields."
)
args_schema: Type[CreateDraftSchema] = CreateDraftSchema
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html |
d6cf2af9a6e8-2 | if cc is not None:
draft_message["Cc"] = ", ".join(cc)
if bcc is not None:
draft_message["Bcc"] = ", ".join(bcc)
encoded_message = base64.urlsafe_b64encode(draft_message.as_bytes()).decode()
return {"message": {"raw": encoded_message}}
def _run(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html |
d6cf2af9a6e8-3 | .drafts()
.create(userId="me", body=create_message)
.execute()
)
output = f'Draft created. Draft Id: {draft["id"]}'
return output
except Exception as e:
raise Exception(f"An error occurred: {e}")
async def _arun(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html |
7af3e034b960-0 | Source code for langchain.tools.gmail.search
import base64
import email
from enum import Enum
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.gmail... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html |
7af3e034b960-1 | " in:folder, is:important|read|starred, after:year/mo/date, "
"before:year/mo/date, label:label_name"
' "exact phrase".'
" Search newer/older than using d (day), m (month), and y (year): "
"newer_than:2d, older_than:1y."
" Attachments with extension example: filename:pdf. Multipl... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html |
7af3e034b960-2 | name: str = "search_gmail"
description: str = (
"Use this tool to search for email messages or threads."
" The input must be a valid Gmail query."
" The output is a JSON list of the requested resource."
)
args_schema: Type[SearchArgsSchema] = SearchArgsSchema
def _parse_threads(s... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html |
7af3e034b960-3 | for message in messages:
snippet = message["snippet"]
thread["messages"].append({"snippet": snippet, "id": message["id"]})
results.append(thread)
return results
def _parse_messages(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
results = []... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html |
7af3e034b960-4 | message_body = email_msg.get_payload()
body = clean_email_body(message_body)
results.append(
{
"id": message["id"],
"threadId": message_data["threadId"],
"snippet": message_data["snippet"],
"body": bo... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html |
7af3e034b960-5 | .execute()
.get(resource.value, [])
)
if resource == Resource.THREADS:
return self._parse_threads(results)
elif resource == Resource.MESSAGES:
return self._parse_messages(results)
else:
raise NotImplementedError(f"Resource of type {resource... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/search.html |
4575880223ec-0 | Source code for langchain.tools.gmail.get_thread
from typing import Dict, Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.gmail.base import GmailBaseTool
class GetThreadSchema(BaseMod... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html |
4575880223ec-1 | def _run(
self,
thread_id: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> Dict:
"""Run the tool."""
query = self.api_resource.users().threads().get(userId="me", id=thread_id)
thread_data = query.execute()
if not isinstance(thread_data, dict... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html |
4575880223ec-2 | self,
thread_id: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> Dict:
"""Run the tool."""
raise NotImplementedError | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html |
a43c10fd21b4-0 | Source code for langchain.tools.gmail.send_message
"""Send Gmail messages."""
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCal... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html |
a43c10fd21b4-1 | None,
description="The list of CC recipients.",
)
bcc: Optional[Union[str, List[str]]] = Field(
None,
description="The list of BCC recipients.",
)
[docs]class GmailSendMessage(GmailBaseTool):
name: str = "send_gmail_message"
description: str = (
"Use this tool to send... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html |
a43c10fd21b4-2 | """Create a message for an email."""
mime_message = MIMEMultipart()
mime_message.attach(MIMEText(message, "html"))
mime_message["To"] = ", ".join(to if isinstance(to, list) else [to])
mime_message["Subject"] = subject
if cc is not None:
mime_message["Cc"] = ", ".join(... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html |
a43c10fd21b4-3 | subject: str,
cc: Optional[Union[str, List[str]]] = None,
bcc: Optional[Union[str, List[str]]] = None,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Run the tool."""
try:
create_message = self._prepare_message(message, to, subject, cc=cc, b... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html |
a43c10fd21b4-4 | self,
message: str,
to: Union[str, List[str]],
subject: str,
cc: Optional[Union[str, List[str]]] = None,
bcc: Optional[Union[str, List[str]]] = None,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Run the tool asynchronously."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html |
b9a0a89368a0-0 | Source code for langchain.tools.gmail.get_message
import base64
import email
from typing import Dict, Optional, Type
from pydantic import BaseModel, Field
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.gmail.base import GmailBaseTool
f... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html |
b9a0a89368a0-1 | )
args_schema: Type[SearchArgsSchema] = SearchArgsSchema
def _run(
self,
message_id: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> Dict:
"""Run the tool."""
query = (
self.api_resource.users()
.messages()
.get(u... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html |
b9a0a89368a0-2 | "snippet": message_data["snippet"],
"body": body,
"subject": subject,
"sender": sender,
}
async def _arun(
self,
message_id: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> Dict:
"""Run the tool."""
raise... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html |
210b10c26422-0 | Source code for langchain.tools.vectorstore.tool
"""Tools for interacting with vectorstores."""
import json
from typing import Any, Dict, Optional
from pydantic import BaseModel, Field
from langchain.base_language import BaseLanguageModel
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html |
210b10c26422-1 | arbitrary_types_allowed = True
def _create_description_from_template(values: Dict[str, Any]) -> Dict[str, Any]:
values["description"] = values["template"].format(name=values["name"])
return values
[docs]class VectorStoreQATool(BaseVectorStoreTool, BaseTool):
"""Tool for the VectorDBQA chain. To be initializ... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html |
210b10c26422-2 | self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
"""Use the tool."""
chain = RetrievalQA.from_chain_type(
self.llm, retriever=self.vectorstore.as_retriever()
)
return chain.run(query)
async def _arun(
self,
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html |
210b10c26422-3 | template: str = (
"Useful for when you need to answer questions about {name} and the sources "
"used to construct the answer. "
"Whenever you need information about {description} "
"you should ALWAYS use this. "
" Input should be a fully formed question. "
... | https://api.python.langchain.com/en/latest/_modules/langchain/tools/vectorstore/tool.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.