id
stringlengths
14
15
text
stringlengths
22
2.51k
source
stringlengths
61
154
ef31ddcf0c43-7
) return observation except (Exception, KeyboardInterrupt) as e: run_manager.on_tool_error(e) raise e else: run_manager.on_tool_end( str(observation), color=color, name=self.name, **kwargs ) 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, *, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> Any: """Run the tool asynchronously.""" parsed_input = self._parse_input(tool_input) if not self.verbose and verbose is not None: verbose_ = verbose else: verbose_ = self.verbose callback_manager = AsyncCallbackManager.configure( callbacks, self.callbacks, verbose_, tags, self.tags, metadata, self.metadata, ) new_arg_supported = signature(self._arun).parameters.get("run_manager") run_manager = await callback_manager.on_tool_start( {"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 = self._to_args_and_kwargs(parsed_input) observation = (
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
ef31ddcf0c43-8
observation = ( await self._arun(*tool_args, run_manager=run_manager, **tool_kwargs) if new_arg_supported else await self._arun(*tool_args, **tool_kwargs) ) except ToolException as e: if not self.handle_tool_error: await run_manager.on_tool_error(e) raise e elif isinstance(self.handle_tool_error, bool): 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): observation = self.handle_tool_error(e) else: raise ValueError( f"Got unexpected type of `handle_tool_error`. Expected bool, str " f"or callable. Received: {self.handle_tool_error}" ) await run_manager.on_tool_end( str(observation), color="red", name=self.name, **kwargs ) return observation except (Exception, KeyboardInterrupt) as e: await run_manager.on_tool_error(e) raise e else: await run_manager.on_tool_end( str(observation), color=color, name=self.name, **kwargs ) return observation [docs] 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 = "" func: Callable[..., str] """The function to run when the tool is called."""
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
ef31ddcf0c43-9
"""The function to run when the tool is called.""" coroutine: Optional[Callable[..., Awaitable[str]]] = None """The asynchronous version of the function.""" @property def args(self) -> dict: """The tool's input arguments.""" if self.args_schema is not None: return self.args_schema.schema()["properties"] # For backwards compatibility, if the function signature is ambiguous, # assume it takes a single string input. 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 input all_args = list(args) + list(kwargs.values()) if len(all_args) != 1: raise ToolException( f"Too many arguments to single-input tool {self.name}." f" Args: {all_args}" ) return tuple(all_args), {} def _run( self, *args: Any, run_manager: Optional[CallbackManagerForToolRun] = None, **kwargs: Any, ) -> 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_argument_supported else self.func(*args, **kwargs) ) async def _arun( self, *args: Any,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
ef31ddcf0c43-10
async def _arun( self, *args: Any, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, **kwargs: Any, ) -> Any: """Use the tool asynchronously.""" if self.coroutine: new_argument_supported = signature(self.coroutine).parameters.get( "callbacks" ) return ( await self.coroutine( *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") # TODO: this is for backwards compatibility, remove in future def __init__( self, name: str, func: Callable, description: str, **kwargs: Any ) -> None: """Initialize tool.""" super(Tool, self).__init__( name=name, func=func, description=description, **kwargs ) [docs] @classmethod def from_function( cls, func: Callable, name: str, # We keep these required to support backwards compatibility description: str, 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, args_schema=args_schema, **kwargs, ) [docs]class StructuredTool(BaseTool): """Tool that can operate on any number of inputs."""
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
ef31ddcf0c43-11
"""Tool that can operate on any number of inputs.""" description: str = "" args_schema: Type[BaseModel] = Field(..., description="The tool schema.") """The input arguments' schema.""" func: Callable[..., Any] """The function to run when the tool is called.""" coroutine: Optional[Callable[..., Awaitable[Any]]] = None """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: Any, ) -> 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_argument_supported else self.func(*args, **kwargs) ) async def _arun( self, *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" ) return ( await self.coroutine( *args, callbacks=run_manager.get_child() if run_manager else None, **kwargs, ) if new_argument_supported else await self.coroutine(*args, **kwargs) )
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
ef31ddcf0c43-12
else await self.coroutine(*args, **kwargs) ) raise NotImplementedError("Tool does not support async") [docs] @classmethod def from_function( cls, func: Callable, name: Optional[str] = None, description: Optional[str] = None, 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 function from which to create a tool name: The name of the tool. Defaults to the function name description: The description of the tool. Defaults to the function docstring return_direct: Whether to return the result directly or as a callback args_schema: The schema of the tool's input arguments infer_schema: Whether to infer the schema from the function's signature **kwargs: Additional arguments to pass to the tool Returns: The tool Examples: ... 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 = description or func.__doc__ assert ( description is not None ), "Function must have a docstring if description not provided." # Description example: # search_api(query: str) - Searches the API for the query.
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
ef31ddcf0c43-13
# search_api(query: str) - Searches the API for the query. description = f"{name}{signature(func)} - {description.strip()}" _args_schema = args_schema if _args_schema is None and infer_schema: _args_schema = create_schema_from_function(f"{name}Schema", func) 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[BaseModel]] = None, infer_schema: bool = True, ) -> Callable: """Make tools out of functions, can be used with or without arguments. Args: *args: The arguments to the tool. return_direct: Whether to return directly from the tool rather than continuing the agent loop. args_schema: optional argument schema for user to specify infer_schema: Whether to infer the schema of the arguments from the function's signature. This also makes the resultant tool 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. return @tool("search", return_direct=True) def search_api(query: str) -> str: # Searches the API for the query. return """ def _make_with_name(tool_name: str) -> Callable:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
ef31ddcf0c43-14
""" def _make_with_name(tool_name: str) -> Callable: def _make_tool(func: Callable) -> BaseTool: if infer_schema or args_schema is not None: return StructuredTool.from_function( func, name=tool_name, return_direct=return_direct, 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( name=tool_name, func=func, description=f"{tool_name} tool", return_direct=return_direct, ) return _make_tool if len(args) == 1 and isinstance(args[0], str): # if the argument is a string, then we use the string as the tool name # Example usage: @tool("search", return_direct=True) return _make_with_name(args[0]) elif len(args) == 1 and callable(args[0]): # 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_direct=True) def _partial(func: Callable[[str], str]) -> BaseTool: return _make_with_name(func.__name__)(func) return _partial else: raise ValueError("Too many arguments for tool decorator")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
885753ed14b9-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 option for "Receive a web request with a JSON payload." - Choose an Event Name that is specific to the service you plan to connect to. This will make it easier for you to manage the webhook URL. For example, if you're connecting to Spotify, you could use "Spotify" as your Event Name. - Click the "Create Trigger" button to save your settings and create your webhook. # 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 from AI". - Reference the JSON Payload received by the Webhook in your action. For the Spotify scenario, choose "{{JsonPayload}}" as your search query. - Tap the "Create Action" button to save your action settings. - Once you have finished configuring your action, click the "Finish" button to complete the setup. - Congratulations! You have successfully connected the Webhook to the desired service, and you're ready to start receiving data and triggering actions 🎉 # Finishing up - To get your webhook URL go to https://ifttt.com/maker_webhooks/settings
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
885753ed14b9-1
- 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 ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool [docs]class IFTTTWebhook(BaseTool): """IFTTT Webhook. Args: name: name of the tool description: description of the tool url: url to hit with the json event. """ url: str def _run( self, 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[AsyncCallbackManagerForToolRun] = None, ) -> str: raise NotImplementedError("Not implemented.")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
152f8632ffa0-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 import BaseTool [docs]class ApiConfig(BaseModel): type: str url: str has_user_authentication: Optional[bool] = False [docs]class AIPlugin(BaseModel): """AI Plugin Definition.""" schema_version: str name_for_model: str name_for_human: str description_for_model: str description_for_human: str auth: Optional[dict] = None api: ApiConfig logo_url: Optional[str] contact_email: Optional[str] legal_info_url: Optional[str] [docs] @classmethod def from_url(cls, url: str) -> AIPlugin: """Instantiate AIPlugin from a URL.""" response = requests.get(url).json() return cls(**response) [docs]def marshal_spec(txt: str) -> dict: """Convert the yaml or json serialized spec to a dict. Args: txt: The yaml or json serialized spec. Returns: dict: The spec as a dict. """ try: return json.loads(txt) except json.JSONDecodeError: return yaml.safe_load(txt) [docs]class AIPluginToolSchema(BaseModel): """AIPLuginToolSchema.""" tool_input: Optional[str] = "" [docs]class AIPluginTool(BaseTool): plugin: AIPlugin api_spec: str
https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
152f8632ffa0-1
plugin: AIPlugin api_spec: str args_schema: Type[AIPluginToolSchema] = AIPluginToolSchema [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 this ONCE! What is the " f"{plugin.name_for_human} API useful for? " ) + plugin.description_for_human open_api_spec_str = requests.get(plugin.api.url).text open_api_spec = marshal_spec(open_api_spec_str) api_spec = ( f"Usage Guide: {plugin.description_for_model}\n\n" f"OpenAPI Spec: {open_api_spec}" ) return cls( name=plugin.name_for_model, 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( self, tool_input: Optional[str] = None, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" return self.api_spec
https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
78ff1bad45d9-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 WolframAlphaAPIWrapper [docs]class WolframAlphaQueryRun(BaseTool): """Tool that adds the capability to query using the Wolfram Alpha SDK.""" name = "wolfram_alpha" description = ( "A wrapper around Wolfram Alpha. " "Useful for when you need to answer questions about Math, " "Science, Technology, Culture, Society and Everyday Life. " "Input should be a search query." ) api_wrapper: WolframAlphaAPIWrapper 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[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the WolframAlpha tool asynchronously.""" raise NotImplementedError("WolframAlphaQueryRun does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/wolfram_alpha/tool.html
ddfc7a8c5e50-0
Source code for langchain.tools.zapier.tool """## Zapier Natural Language Actions API \ Full docs here: https://nla.zapier.com/start/ **Zapier Natural Language Actions** gives you access to the 5k+ apps, 20k+ actions on Zapier's platform through a natural language API interface. NLA supports apps like Gmail, Salesforce, Trello, Slack, Asana, HubSpot, Google Sheets, Microsoft Teams, and thousands more apps: https://zapier.com/apps Zapier NLA handles ALL the underlying API auth and translation from natural language --> underlying API call --> return simplified output for LLMs The key idea is you, or your users, expose a set of actions via an oauth-like setup window, which you can then query and execute via a REST API. NLA offers both API Key and OAuth for signing NLA API requests. 1. Server-side (API Key): for quickly getting started, testing, and production scenarios where LangChain will only use actions exposed in the developer's Zapier account (and will use the developer's connected accounts on Zapier.com) 2. User-facing (Oauth): for production scenarios where you are deploying an end-user facing application and LangChain needs access to end-user's exposed actions and connected accounts on Zapier.com This quick start will focus on the server-side use case for brevity. Review [full docs](https://nla.zapier.com/start/) for user-facing oauth developer support. Typically, you'd use SequentialChain, here's a basic example: 1. Use NLA to find an email in Gmail 2. Use LLMChain to generate a draft reply to (1)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
ddfc7a8c5e50-1
2. Use LLMChain to generate a draft reply to (1) 3. Use NLA to send the draft reply (2) to someone in Slack via direct message In code, below: ```python import os # get from https://platform.openai.com/ os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "") # get from https://nla.zapier.com/docs/authentication/ os.environ["ZAPIER_NLA_API_KEY"] = os.environ.get("ZAPIER_NLA_API_KEY", "") from langchain.llms import OpenAI from langchain.agents import initialize_agent from langchain.agents.agent_toolkits import ZapierToolkit from langchain.utilities.zapier import ZapierNLAWrapper ## step 0. expose gmail 'find email' and slack 'send channel message' actions # first go here, log in, expose (enable) the two actions: # https://nla.zapier.com/demo/start # -- for this example, can leave all fields "Have AI guess" # in an oauth scenario, you'd get your own <provider> id (instead of 'demo') # which you route your users through first llm = OpenAI(temperature=0) zapier = ZapierNLAWrapper() ## To leverage OAuth you may pass the value `nla_oauth_access_token` to ## the ZapierNLAWrapper. If you do this there is no need to initialize ## the ZAPIER_NLA_API_KEY env variable # zapier = ZapierNLAWrapper(zapier_nla_oauth_access_token="TOKEN_HERE") toolkit = ZapierToolkit.from_zapier_nla_wrapper(zapier) agent = initialize_agent( toolkit.get_tools(), llm,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
ddfc7a8c5e50-2
agent = initialize_agent( toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) agent.run(("Summarize the last email I received regarding Silicon Valley Bank. " "Send the summary to the #test-zapier channel in slack.")) ``` """ from typing import Any, Dict, Optional from pydantic import Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.zapier.prompt import BASE_ZAPIER_TOOL_PROMPT from langchain.utilities.zapier import ZapierNLAWrapper [docs]class ZapierNLARunAction(BaseTool): """ Args: action_id: a specific action ID (from list actions) of the action to execute (the set api_key must be associated with the action owner) instructions: a natural language instruction string for using the action (eg. "get the latest email from Mike Knoop" for "Gmail: find email" action) params: a dict, optional. Any params provided will *override* AI guesses from `instructions` (see "understanding the AI guessing flow" here: https://nla.zapier.com/docs/using-the-api#ai-guessing) """ api_wrapper: ZapierNLAWrapper = Field(default_factory=ZapierNLAWrapper) action_id: str params: Optional[dict] = None base_prompt: str = BASE_ZAPIER_TOOL_PROMPT zapier_description: str params_schema: Dict[str, str] = Field(default_factory=dict) name = "" description = ""
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
ddfc7a8c5e50-3
name = "" description = "" [docs] @root_validator def set_name_description(cls, values: Dict[str, Any]) -> Dict[str, Any]: zapier_description = values["zapier_description"] params_schema = values["params_schema"] if "instructions" in params_schema: del params_schema["instructions"] # Ensure base prompt (if overrided) contains necessary input fields necessary_fields = {"{zapier_description}", "{params}"} if not all(field in values["base_prompt"] for field in necessary_fields): raise ValueError( "Your custom base Zapier prompt must contain input fields for " "{zapier_description} and {params}." ) values["name"] = zapier_description values["description"] = values["base_prompt"].format( zapier_description=zapier_description, params=str(list(params_schema.keys())), ) return values def _run( self, instructions: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> str: """Use the Zapier NLA tool to return a list of all exposed user actions.""" return self.api_wrapper.run_as_str(self.action_id, instructions, self.params) async def _arun( self, instructions: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the Zapier NLA tool to return a list of all exposed user actions.""" return await self.api_wrapper.arun_as_str( self.action_id, instructions, self.params, ) ZapierNLARunAction.__doc__ = (
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
ddfc7a8c5e50-4
) ZapierNLARunAction.__doc__ = ( ZapierNLAWrapper.run.__doc__ + ZapierNLARunAction.__doc__ # type: ignore ) # other useful actions [docs]class ZapierNLAListActions(BaseTool): """ Args: None """ name = "ZapierNLA_list_actions" description = BASE_ZAPIER_TOOL_PROMPT + ( "This tool returns a list of the user's exposed actions." ) api_wrapper: ZapierNLAWrapper = Field(default_factory=ZapierNLAWrapper) def _run( self, _: str = "", run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the Zapier NLA tool to return a list of all exposed user actions.""" return self.api_wrapper.list_as_str() async def _arun( self, _: str = "", run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the Zapier NLA tool to return a list of all exposed user actions.""" return await self.api_wrapper.alist_as_str() ZapierNLAListActions.__doc__ = ( ZapierNLAWrapper.list.__doc__ + ZapierNLAListActions.__doc__ # type: ignore )
https://api.python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
45e808e20a75-0
Source code for langchain.tools.requests.tool # flake8: noqa """Tools for making requests to an API endpoint.""" import json from typing import Any, Dict, Optional from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.requests import TextRequestsWrapper from langchain.tools.base import BaseTool def _parse_input(text: str) -> Dict[str, Any]: """Parse the json string into a dict.""" return json.loads(text) def _clean_url(url: str) -> str: """Strips quotes from the url.""" return url.strip("\"'") [docs]class BaseRequestsTool(BaseModel): """Base class for requests tools.""" requests_wrapper: TextRequestsWrapper [docs]class RequestsGetTool(BaseRequestsTool, BaseTool): """Tool for making a GET request to an API endpoint.""" name = "requests_get" description = "A portal to the internet. Use this when you need to get specific content from a website. Input should be a url (i.e. https://www.google.com). The output will be the text response of the GET request." def _run( self, url: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> str: """Run the tool.""" return self.requests_wrapper.get(_clean_url(url)) async def _arun( self, url: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" return await self.requests_wrapper.aget(_clean_url(url)) [docs]class RequestsPostTool(BaseRequestsTool, BaseTool):
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
45e808e20a75-1
[docs]class RequestsPostTool(BaseRequestsTool, BaseTool): """Tool for making a POST request to an API endpoint.""" name = "requests_post" description = """Use this when you want to POST to a website. Input should be a json string with two keys: "url" and "data". The value of "url" should be a string, and the value of "data" should be a dictionary of key-value pairs you want to POST to the url. Be careful to always use double quotes for strings in the json string The output will be the text response of the POST request. """ def _run( self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> str: """Run the tool.""" try: data = _parse_input(text) return self.requests_wrapper.post(_clean_url(data["url"]), data["data"]) except Exception as e: return repr(e) async def _arun( self, text: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" try: data = _parse_input(text) return await self.requests_wrapper.apost( _clean_url(data["url"]), data["data"] ) except Exception as e: return repr(e) [docs]class RequestsPatchTool(BaseRequestsTool, BaseTool): """Tool for making a PATCH request to an API endpoint.""" name = "requests_patch" description = """Use this when you want to PATCH to a website. Input should be a json string with two keys: "url" and "data".
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
45e808e20a75-2
Input should be a json string with two keys: "url" and "data". The value of "url" should be a string, and the value of "data" should be a dictionary of key-value pairs you want to PATCH to the url. Be careful to always use double quotes for strings in the json string The output will be the text response of the PATCH request. """ def _run( self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> str: """Run the tool.""" try: data = _parse_input(text) return self.requests_wrapper.patch(_clean_url(data["url"]), data["data"]) except Exception as e: return repr(e) async def _arun( self, text: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" try: data = _parse_input(text) return await self.requests_wrapper.apatch( _clean_url(data["url"]), data["data"] ) except Exception as e: return repr(e) [docs]class RequestsPutTool(BaseRequestsTool, BaseTool): """Tool for making a PUT request to an API endpoint.""" name = "requests_put" description = """Use this when you want to PUT to a website. Input should be a json string with two keys: "url" and "data". The value of "url" should be a string, and the value of "data" should be a dictionary of key-value pairs you want to PUT to the url.
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
45e808e20a75-3
key-value pairs you want to PUT to the url. Be careful to always use double quotes for strings in the json string. The output will be the text response of the PUT request. """ def _run( self, text: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> str: """Run the tool.""" try: data = _parse_input(text) return self.requests_wrapper.put(_clean_url(data["url"]), data["data"]) except Exception as e: return repr(e) async def _arun( self, text: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" try: data = _parse_input(text) return await self.requests_wrapper.aput( _clean_url(data["url"]), data["data"] ) except Exception as e: return repr(e) [docs]class RequestsDeleteTool(BaseRequestsTool, BaseTool): """Tool for making a DELETE request to an API endpoint.""" name = "requests_delete" description = "A portal to the internet. Use this when you need to make a DELETE request to a URL. Input should be a specific url, and the output will be the text response of the DELETE request." def _run( self, url: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Run the tool.""" return self.requests_wrapper.delete(_clean_url(url)) async def _arun( self, url: str,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
45e808e20a75-4
async def _arun( self, url: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" return await self.requests_wrapper.adelete(_clean_url(url))
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
af547b3491bd-0
Source code for langchain.tools.sql_database.tool # flake8: noqa """Tools for interacting with a SQL database.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, Field, root_validator from langchain.schema.language_model import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.chains.llm import LLMChain from langchain.prompts import PromptTemplate from langchain.sql_database import SQLDatabase from langchain.tools.base import BaseTool from langchain.tools.sql_database.prompt import QUERY_CHECKER [docs]class BaseSQLDatabaseTool(BaseModel): """Base tool for interacting with a SQL database.""" db: SQLDatabase = Field(exclude=True) # Override BaseTool.Config to appease mypy # See https://github.com/pydantic/pydantic/issues/4173 [docs] class Config(BaseTool.Config): """Configuration for this pydantic object.""" arbitrary_types_allowed = True extra = Extra.forbid [docs]class QuerySQLDataBaseTool(BaseSQLDatabaseTool, BaseTool): """Tool for querying a SQL database.""" name = "sql_db_query" description = """ Input to this tool is a detailed and correct SQL query, output is a result from the database. If the query is not correct, an error message will be returned. If an error is returned, rewrite the query, check the query, and try again. """ def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Execute the query, return the results or an error message."""
https://api.python.langchain.com/en/latest/_modules/langchain/tools/sql_database/tool.html
af547b3491bd-1
"""Execute the query, return the results or an error message.""" return self.db.run_no_throw(query) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: raise NotImplementedError("QuerySqlDbTool does not support async") [docs]class InfoSQLDatabaseTool(BaseSQLDatabaseTool, BaseTool): """Tool for getting metadata about a SQL database.""" name = "sql_db_schema" description = """ Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables. Example Input: "table1, table2, table3" """ def _run( self, table_names: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Get the schema for tables in a comma-separated list.""" return self.db.get_table_info_no_throw(table_names.split(", ")) async def _arun( self, table_name: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: raise NotImplementedError("SchemaSqlDbTool does not support async") [docs]class ListSQLDatabaseTool(BaseSQLDatabaseTool, BaseTool): """Tool for getting tables names.""" name = "sql_db_list_tables" description = "Input is an empty string, output is a comma separated list of tables in the database." def _run( self, tool_input: str = "", run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/sql_database/tool.html
af547b3491bd-2
) -> str: """Get the schema for a specific table.""" return ", ".join(self.db.get_usable_table_names()) async def _arun( self, tool_input: str = "", run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: raise NotImplementedError("ListTablesSqlDbTool does not support async") [docs]class QuerySQLCheckerTool(BaseSQLDatabaseTool, BaseTool): """Use an LLM to check if a query is correct. Adapted from https://www.patterns.app/blog/2023/01/18/crunchbot-sql-analyst-gpt/""" template: str = QUERY_CHECKER llm: BaseLanguageModel llm_chain: LLMChain = Field(init=False) name = "sql_db_query_checker" description = """ Use this tool to double check if your query is correct before executing it. Always use this tool before executing a query with query_sql_db! """ [docs] @root_validator(pre=True) def initialize_llm_chain(cls, values: Dict[str, Any]) -> Dict[str, Any]: if "llm_chain" not in values: values["llm_chain"] = LLMChain( llm=values.get("llm"), prompt=PromptTemplate( template=QUERY_CHECKER, input_variables=["query", "dialect"] ), ) if values["llm_chain"].prompt.input_variables != ["query", "dialect"]: raise ValueError( "LLM chain for QueryCheckerTool must have input variables ['query', 'dialect']" ) return values def _run( self,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/sql_database/tool.html
af547b3491bd-3
) return values def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the LLM to check the query.""" return self.llm_chain.predict(query=query, dialect=self.db.dialect) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: return await self.llm_chain.apredict(query=query, dialect=self.db.dialect)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/sql_database/tool.html
468e1d739536-0
Source code for langchain.tools.jira.tool """ This tool allows agents to interact with the atlassian-python-api library and operate on a Jira instance. For more information on the atlassian-python-api library, see https://atlassian-python-api.readthedocs.io/jira.html To use this tool, you must first set as environment variables: JIRA_API_TOKEN JIRA_USERNAME JIRA_INSTANCE_URL Below is a sample script that uses the Jira tool: ```python from langchain.agents import AgentType from langchain.agents import initialize_agent from langchain.agents.agent_toolkits.jira.toolkit import JiraToolkit from langchain.llms import OpenAI from langchain.utilities.jira import JiraAPIWrapper llm = OpenAI(temperature=0) jira = JiraAPIWrapper() toolkit = JiraToolkit.from_jira_api_wrapper(jira) agent = initialize_agent( toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) ``` """ from typing import Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.jira import JiraAPIWrapper [docs]class JiraAction(BaseTool): api_wrapper: JiraAPIWrapper = Field(default_factory=JiraAPIWrapper) mode: str name = "" description = "" def _run( self, instructions: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the Atlassian Jira API to run an operation."""
https://api.python.langchain.com/en/latest/_modules/langchain/tools/jira/tool.html
468e1d739536-1
"""Use the Atlassian Jira API to run an operation.""" return self.api_wrapper.run(self.mode, instructions) async def _arun( self, _: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the Atlassian Jira API to run an operation.""" raise NotImplementedError("JiraAction does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/jira/tool.html
d2693c525901-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 langchain.tools.base import BaseTool [docs]class SleepInput(BaseModel): """Input for CopyFileTool.""" sleep_time: int = Field(..., description="Time to sleep in seconds") [docs]class SleepTool(BaseTool): """Tool that adds the capability to sleep.""" name = "sleep" args_schema: Type[BaseModel] = SleepInput description = "Make agent sleep for a specified number of seconds." def _run( self, 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[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the sleep tool asynchronously.""" await asleep(sleep_time) return f"Agent slept for {sleep_time} seconds."
https://api.python.langchain.com/en/latest/_modules/langchain/tools/sleep/tool.html
87295774c631-0
Source code for langchain.tools.office365.create_draft_message from typing import List, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.office365.base import O365BaseTool [docs]class CreateDraftMessageSchema(BaseModel): body: str = Field( ..., description="The message body to include in the draft.", ) to: List[str] = Field( ..., description="The list of recipients.", ) subject: str = Field( ..., description="The subject of the message.", ) cc: Optional[List[str]] = Field( None, description="The list of CC recipients.", ) bcc: Optional[List[str]] = Field( None, description="The list of BCC recipients.", ) [docs]class O365CreateDraftMessage(O365BaseTool): name: str = "create_email_draft" description: str = ( "Use this tool to create a draft email with the provided message fields." ) args_schema: Type[CreateDraftMessageSchema] = CreateDraftMessageSchema def _run( self, body: str, to: List[str], subject: str, cc: Optional[List[str]] = None, bcc: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: # Get mailbox object mailbox = self.account.mailbox() message = mailbox.new_message() # Assign message values message.body = body message.subject = subject
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/create_draft_message.html
87295774c631-1
# Assign message values message.body = body message.subject = subject message.to.add(to) if cc is not None: message.cc.add(cc) if bcc is not None: message.bcc.add(cc) message.save_draft() output = "Draft created: " + str(message) return output async def _arun( self, message: str, to: List[str], subject: str, cc: Optional[List[str]] = None, bcc: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: raise NotImplementedError(f"The tool {self.name} does not support async yet.")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/create_draft_message.html
eb27da868b2c-0
Source code for langchain.tools.office365.messages_search """Util that Searches email messages in Office 365. Free, but setup is required. See link below. https://learn.microsoft.com/en-us/graph/auth/ """ from typing import Any, Dict, List, Optional, Type from pydantic import BaseModel, Extra, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.office365.base import O365BaseTool from langchain.tools.office365.utils import clean_body [docs]class SearchEmailsInput(BaseModel): """Input for SearchEmails Tool.""" """From https://learn.microsoft.com/en-us/graph/search-query-parameter""" folder: str = Field( default=None, description=( " If the user wants to search in only one folder, the name of the folder. " 'Default folders are "inbox", "drafts", "sent items", "deleted ttems", but ' "users can search custom folders as well." ), ) query: str = Field( description=( "The Microsoift Graph v1.0 $search query. Example filters include " "from:sender, from:sender, to:recipient, subject:subject, " "recipients:list_of_recipients, body:excitement, importance:high, " "received>2022-12-01, received<2021-12-01, sent>2022-12-01, " "sent<2021-12-01, hasAttachments:true attachment:api-catalog.md, " "cc:[email protected], bcc:[email protected], body:excitement date "
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/messages_search.html
eb27da868b2c-1
"range example: received:2023-06-08..2023-06-09 matching example: " "from:amy OR from:david." ) ) max_results: int = Field( default=10, description="The maximum number of results to return.", ) truncate: bool = Field( default=True, description=( "Whether the email body is trucated to meet token number limits. Set to " "False for searches that will retrieve very few results, otherwise, set to " "True" ), ) [docs]class O365SearchEmails(O365BaseTool): """Class for searching email messages in Office 365 Free, but setup is required """ name: str = "messages_search" args_schema: Type[BaseModel] = SearchEmailsInput description: str = ( "Use this tool to search for email messages." " The input must be a valid Microsoft Graph v1.0 $search query." " The output is a JSON list of the requested resource." ) [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _run( self, query: str, folder: str = "", max_results: int = 10, truncate: bool = True, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> List[Dict[str, Any]]: # Get mailbox object mailbox = self.account.mailbox() # Pull the folder if the user wants to search in a folder if folder != "":
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/messages_search.html
eb27da868b2c-2
if folder != "": mailbox = mailbox.get_folder(folder_name=folder) # Retrieve messages based on query query = mailbox.q().search(query) messages = mailbox.get_messages(limit=max_results, query=query) # Generate output dict output_messages = [] for message in messages: output_message = {} output_message["from"] = message.sender if truncate: output_message["body"] = message.body_preview else: output_message["body"] = clean_body(message.body) output_message["subject"] = message.subject output_message["date"] = message.modified.strftime("%Y-%m-%dT%H:%M:%S%z") output_message["to"] = [] for recipient in message.to._recipients: output_message["to"].append(str(recipient)) output_message["cc"] = [] for recipient in message.cc._recipients: output_message["cc"].append(str(recipient)) output_message["bcc"] = [] for recipient in message.bcc._recipients: output_message["bcc"].append(str(recipient)) output_messages.append(output_message) return output_messages async def _arun( self, query: str, max_results: int = 10, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> List[Dict[str, Any]]: """Run the tool.""" raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/messages_search.html
ab43493042ae-0
Source code for langchain.tools.office365.events_search """Util that Searches calendar events in Office 365. Free, but setup is required. See link below. https://learn.microsoft.com/en-us/graph/auth/ """ from datetime import datetime as dt from typing import Any, Dict, List, Optional, Type from pydantic import BaseModel, Extra, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.office365.base import O365BaseTool from langchain.tools.office365.utils import clean_body [docs]class SearchEventsInput(BaseModel): """Input for SearchEmails Tool.""" """From https://learn.microsoft.com/en-us/graph/search-query-parameter""" start_datetime: str = Field( description=( " The start datetime for the search query in the following format: " ' YYYY-MM-DDTHH:MM:SS±hh:mm, where "T" separates the date and time ' " components, and the time zone offset is specified as ±hh:mm. " ' For example: "2023-06-09T10:30:00+03:00" represents June 9th, ' " 2023, at 10:30 AM in a time zone with a positive offset of 3 " " hours from Coordinated Universal Time (UTC)." ) ) end_datetime: str = Field( description=( " The end datetime for the search query in the following format: " ' YYYY-MM-DDTHH:MM:SS±hh:mm, where "T" separates the date and time ' " components, and the time zone offset is specified as ±hh:mm. "
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html
ab43493042ae-1
" components, and the time zone offset is specified as ±hh:mm. " ' For example: "2023-06-09T10:30:00+03:00" represents June 9th, ' " 2023, at 10:30 AM in a time zone with a positive offset of 3 " " hours from Coordinated Universal Time (UTC)." ) ) max_results: int = Field( default=10, description="The maximum number of results to return.", ) truncate: bool = Field( default=True, description=( "Whether the event's body is trucated to meet token number limits. Set to " "False for searches that will retrieve very few results, otherwise, set to " "True." ), ) [docs]class O365SearchEvents(O365BaseTool): """Class for searching calendar events in Office 365 Free, but setup is required """ name: str = "events_search" args_schema: Type[BaseModel] = SearchEventsInput description: str = ( " Use this tool to search for the user's calendar events." " The input must be the start and end datetimes for the search query." " The output is a JSON list of all the events in the user's calendar" " between the start and end times. You can assume that the user can " " not schedule any meeting over existing meetings, and that the user " "is busy during meetings. Any times without events are free for the user. " ) [docs] class Config: """Configuration for this pydantic object.""" extra = Extra.forbid def _run(
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html
ab43493042ae-2
extra = Extra.forbid def _run( self, start_datetime: str, end_datetime: str, max_results: int = 10, truncate: bool = True, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> List[Dict[str, Any]]: TRUNCATE_LIMIT = 150 # Get calendar object schedule = self.account.schedule() calendar = schedule.get_default_calendar() # Process the date range parameters start_datetime_query = dt.strptime(start_datetime, "%Y-%m-%dT%H:%M:%S%z") end_datetime_query = dt.strptime(end_datetime, "%Y-%m-%dT%H:%M:%S%z") # Run the query q = calendar.new_query("start").greater_equal(start_datetime_query) q.chain("and").on_attribute("end").less_equal(end_datetime_query) events = calendar.get_events(query=q, include_recurring=True, limit=max_results) # Generate output dict output_events = [] for event in events: output_event = {} output_event["organizer"] = event.organizer output_event["subject"] = event.subject if truncate: output_event["body"] = clean_body(event.body)[:TRUNCATE_LIMIT] else: output_event["body"] = clean_body(event.body) # Get the time zone from the search parameters time_zone = start_datetime_query.tzinfo # Assign the datetimes in the search time zone output_event["start_datetime"] = event.start.astimezone(time_zone).strftime( "%Y-%m-%dT%H:%M:%S%z" )
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html
ab43493042ae-3
"%Y-%m-%dT%H:%M:%S%z" ) output_event["end_datetime"] = event.end.astimezone(time_zone).strftime( "%Y-%m-%dT%H:%M:%S%z" ) output_event["modified_date"] = event.modified.astimezone( time_zone ).strftime("%Y-%m-%dT%H:%M:%S%z") output_events.append(output_event) return output_events async def _arun( self, query: str, max_results: int = 10, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> List[Dict[str, Any]]: """Run the tool.""" raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/events_search.html
4ae64711c2d1-0
Source code for langchain.tools.office365.base """Base class for Gmail tools.""" from __future__ import annotations from typing import TYPE_CHECKING from pydantic import Field from langchain.tools.base import BaseTool from langchain.tools.office365.utils import authenticate if TYPE_CHECKING: from O365 import Account [docs]class O365BaseTool(BaseTool): account: Account = Field(default_factory=authenticate)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/base.html
164d904450a6-0
Source code for langchain.tools.office365.utils """O365 tool utils.""" from __future__ import annotations import logging import os from typing import TYPE_CHECKING if TYPE_CHECKING: from O365 import Account logger = logging.getLogger(__name__) [docs]def clean_body(body: str) -> str: """Clean body of a message or event.""" try: from bs4 import BeautifulSoup try: # Remove HTML soup = BeautifulSoup(str(body), "html.parser") body = soup.get_text() # Remove return characters body = "".join(body.splitlines()) # Remove extra spaces body = " ".join(body.split()) return str(body) except Exception: return str(body) except ImportError: return str(body) [docs]def authenticate() -> Account: """Authenticate using the Microsoft Grah API""" try: from O365 import Account except ImportError as e: raise ImportError( "Cannot import 0365. Please install the package with `pip install O365`." ) from e if "CLIENT_ID" in os.environ and "CLIENT_SECRET" in os.environ: client_id = os.environ["CLIENT_ID"] client_secret = os.environ["CLIENT_SECRET"] credentials = (client_id, client_secret) else: logger.error( "Error: The CLIENT_ID and CLIENT_SECRET environmental variables have not " "been set. Visit the following link on how to acquire these authorization " "tokens: https://learn.microsoft.com/en-us/graph/auth/" ) return None account = Account(credentials) if account.is_authenticated is False: if not account.authenticate( scopes=[
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/utils.html
164d904450a6-1
if account.is_authenticated is False: if not account.authenticate( scopes=[ "https://graph.microsoft.com/Mail.ReadWrite", "https://graph.microsoft.com/Mail.Send", "https://graph.microsoft.com/Calendars.ReadWrite", "https://graph.microsoft.com/MailboxSettings.ReadWrite", ] ): print("Error: Could not authenticate") return None else: return account else: return account
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/utils.html
dce37db5c9c8-0
Source code for langchain.tools.office365.send_event """Util that sends calendar events in Office 365. Free, but setup is required. See link below. https://learn.microsoft.com/en-us/graph/auth/ """ from datetime import datetime as dt from typing import List, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.office365.base import O365BaseTool [docs]class SendEventSchema(BaseModel): """Input for CreateEvent Tool.""" body: str = Field( ..., description="The message body to include in the event.", ) attendees: List[str] = Field( ..., description="The list of attendees for the event.", ) subject: str = Field( ..., description="The subject of the event.", ) start_datetime: str = Field( description=" The start datetime for the event in the following format: " ' YYYY-MM-DDTHH:MM:SS±hh:mm, where "T" separates the date and time ' " components, and the time zone offset is specified as ±hh:mm. " ' For example: "2023-06-09T10:30:00+03:00" represents June 9th, ' " 2023, at 10:30 AM in a time zone with a positive offset of 3 " " hours from Coordinated Universal Time (UTC).", ) end_datetime: str = Field( description=" The end datetime for the event in the following format: "
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_event.html
dce37db5c9c8-1
description=" The end datetime for the event in the following format: " ' YYYY-MM-DDTHH:MM:SS±hh:mm, where "T" separates the date and time ' " components, and the time zone offset is specified as ±hh:mm. " ' For example: "2023-06-09T10:30:00+03:00" represents June 9th, ' " 2023, at 10:30 AM in a time zone with a positive offset of 3 " " hours from Coordinated Universal Time (UTC).", ) [docs]class O365SendEvent(O365BaseTool): name: str = "send_event" description: str = ( "Use this tool to create and send an event with the provided event fields." ) args_schema: Type[SendEventSchema] = SendEventSchema def _run( self, body: str, attendees: List[str], subject: str, start_datetime: str, end_datetime: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: # Get calendar object schedule = self.account.schedule() calendar = schedule.get_default_calendar() event = calendar.new_event() event.body = body event.subject = subject event.start = dt.strptime(start_datetime, "%Y-%m-%dT%H:%M:%S%z") event.end = dt.strptime(end_datetime, "%Y-%m-%dT%H:%M:%S%z") for attendee in attendees: event.attendees.add(attendee) # TO-DO: Look into PytzUsageWarning event.save()
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_event.html
dce37db5c9c8-2
# TO-DO: Look into PytzUsageWarning event.save() output = "Event sent: " + str(event) return output async def _arun( self, message: str, to: List[str], subject: str, cc: Optional[List[str]] = None, bcc: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: raise NotImplementedError(f"The tool {self.name} does not support async yet.")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_event.html
0ba2e122165e-0
Source code for langchain.tools.office365.send_message from typing import List, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.office365.base import O365BaseTool [docs]class SendMessageSchema(BaseModel): body: str = Field( ..., description="The message body to be sent.", ) to: List[str] = Field( ..., description="The list of recipients.", ) subject: str = Field( ..., description="The subject of the message.", ) cc: Optional[List[str]] = Field( None, description="The list of CC recipients.", ) bcc: Optional[List[str]] = Field( None, description="The list of BCC recipients.", ) [docs]class O365SendMessage(O365BaseTool): name: str = "send_email" description: str = ( "Use this tool to send an email with the provided message fields." ) args_schema: Type[SendMessageSchema] = SendMessageSchema def _run( self, body: str, to: List[str], subject: str, cc: Optional[List[str]] = None, bcc: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: # Get mailbox object mailbox = self.account.mailbox() message = mailbox.new_message() # Assign message values message.body = body message.subject = subject message.to.add(to)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_message.html
0ba2e122165e-1
message.body = body message.subject = subject message.to.add(to) if cc is not None: message.cc.add(cc) if bcc is not None: message.bcc.add(cc) message.send() output = "Message sent: " + str(message) return output async def _arun( self, message: str, to: List[str], subject: str, cc: Optional[List[str]] = None, bcc: Optional[List[str]] = None, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: raise NotImplementedError(f"The tool {self.name} does not support async yet.")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/office365/send_message.html
8c9df3a4cb14-0
Source code for langchain.tools.steamship_image_generation.tool """This tool allows agents to generate images using Steamship. Steamship offers access to different third party image generation APIs using a single API key. Today the following models are supported: - Dall-E - Stable Diffusion To use this tool, you must first set as environment variables: STEAMSHIP_API_KEY ``` """ from __future__ import annotations from enum import Enum from typing import TYPE_CHECKING, Dict, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools import BaseTool from langchain.tools.steamship_image_generation.utils import make_image_public from langchain.utils import get_from_dict_or_env if TYPE_CHECKING: from steamship import Steamship [docs]class ModelName(str, Enum): """Supported Image Models for generation.""" DALL_E = "dall-e" STABLE_DIFFUSION = "stable-diffusion" SUPPORTED_IMAGE_SIZES = { ModelName.DALL_E: ("256x256", "512x512", "1024x1024"), ModelName.STABLE_DIFFUSION: ("512x512", "768x768"), } [docs]class SteamshipImageGenerationTool(BaseTool): """Tool used to generate images from a text-prompt.""" model_name: ModelName size: Optional[str] = "512x512" steamship: Steamship return_urls: Optional[bool] = False name = "GenerateImage" description = ( "Useful for when you need to generate an image." "Input: A detailed text-2-image prompt describing an image"
https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html
8c9df3a4cb14-1
"Input: A detailed text-2-image prompt describing an image" "Output: the UUID of a generated image" ) [docs] @root_validator(pre=True) def validate_size(cls, values: Dict) -> Dict: if "size" in values: size = values["size"] model_name = values["model_name"] if size not in SUPPORTED_IMAGE_SIZES[model_name]: raise RuntimeError(f"size {size} is not supported by {model_name}") return values [docs] @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" steamship_api_key = get_from_dict_or_env( values, "steamship_api_key", "STEAMSHIP_API_KEY" ) try: from steamship import Steamship except ImportError: raise ImportError( "steamship is not installed. " "Please install it with `pip install steamship`" ) steamship = Steamship( api_key=steamship_api_key, ) values["steamship"] = steamship if "steamship_api_key" in values: del values["steamship_api_key"] return values def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" image_generator = self.steamship.use_plugin( plugin_handle=self.model_name.value, config={"n": 1, "size": self.size} ) task = image_generator.generate(text=query, append_output_to_file=True) task.wait()
https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html
8c9df3a4cb14-2
task.wait() blocks = task.output.blocks if len(blocks) > 0: if self.return_urls: return make_image_public(self.steamship, blocks[0]) else: return blocks[0].id raise RuntimeError(f"[{self.name}] Tool unable to generate image!") async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("GenerateImageTool does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/tool.html
e77d9e85ce66-0
Source code for langchain.tools.steamship_image_generation.utils """Steamship Utils.""" from __future__ import annotations import uuid from typing import TYPE_CHECKING if TYPE_CHECKING: from steamship import Block, Steamship [docs]def make_image_public(client: Steamship, block: Block) -> str: """Upload a block to a signed URL and return the public URL.""" try: from steamship.data.workspace import SignedUrl from steamship.utils.signed_urls import upload_to_signed_url except ImportError: raise ValueError( "The make_image_public function requires the steamship" " package to be installed. Please install steamship" " with `pip install --upgrade steamship`" ) filepath = str(uuid.uuid4()) signed_url = ( client.get_workspace() .create_signed_url( SignedUrl.Request( bucket=SignedUrl.Bucket.PLUGIN_DATA, filepath=filepath, operation=SignedUrl.Operation.WRITE, ) ) .signed_url ) read_signed_url = ( client.get_workspace() .create_signed_url( SignedUrl.Request( bucket=SignedUrl.Bucket.PLUGIN_DATA, filepath=filepath, operation=SignedUrl.Operation.READ, ) ) .signed_url ) upload_to_signed_url(signed_url, block.raw()) return read_signed_url
https://api.python.langchain.com/en/latest/_modules/langchain/tools/steamship_image_generation/utils.html
de462fd751a8-0
Source code for langchain.tools.dataforseo_api_search.tool """Tool for the DataForSeo SERP API.""" from typing import Optional from pydantic.fields import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.dataforseo_api_search import DataForSeoAPIWrapper [docs]class DataForSeoAPISearchRun(BaseTool): """Tool that adds the capability to query the DataForSeo Google search API.""" name = "dataforseo_api_search" description = ( "A robust Google Search API provided by DataForSeo." "This tool is handy when you need information about trending topics " "or current events." ) api_wrapper: DataForSeoAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.run(query)) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" return (await self.api_wrapper.arun(query)).__str__() [docs]class DataForSeoAPISearchResults(BaseTool): """Tool that has capability to query the DataForSeo Google Search API and get back json.""" name = "DataForSeo Results JSON" description = ( "A comprehensive Google Search API provided by DataForSeo." "This tool is useful for obtaining real-time data on current events "
https://api.python.langchain.com/en/latest/_modules/langchain/tools/dataforseo_api_search/tool.html
de462fd751a8-1
"This tool is useful for obtaining real-time data on current events " "or popular searches." "The input should be a search query and the output is a JSON object " "of the query results." ) api_wrapper: DataForSeoAPIWrapper = Field(default_factory=DataForSeoAPIWrapper) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query)) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" return (await self.api_wrapper.aresults(query)).__str__()
https://api.python.langchain.com/en/latest/_modules/langchain/tools/dataforseo_api_search/tool.html
0c792c039cd2-0
Source code for langchain.tools.human.tool """Tool for asking human input.""" from typing import Callable, Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool def _print_func(text: str) -> None: print("\n") print(text) [docs]class HumanInputRun(BaseTool): """Tool that adds the capability to ask user for input.""" name = "human" description = ( "You can ask a human for guidance when you think you " "got stuck or you are not sure what to do next. " "The input should be a question for the human." ) prompt_func: Callable[[str], None] = Field(default_factory=lambda: _print_func) input_func: Callable = Field(default_factory=lambda: input) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the Human input tool.""" self.prompt_func(query) return self.input_func() async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the Human tool asynchronously.""" raise NotImplementedError("Human tool does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/human/tool.html
a8f4f374bac8-0
Source code for langchain.tools.scenexplain.tool """Tool for the SceneXplain API.""" from typing import Optional from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.scenexplain import SceneXplainAPIWrapper [docs]class SceneXplainInput(BaseModel): """Input for SceneXplain.""" query: str = Field(..., description="The link to the image to explain") [docs]class SceneXplainTool(BaseTool): """Tool that adds the capability to explain images.""" name = "image_explainer" description = ( "An Image Captioning Tool: Use this tool to generate a detailed caption " "for an image. The input can be an image file of any format, and " "the output will be a text description that covers every detail of the image." ) api_wrapper: SceneXplainAPIWrapper = Field(default_factory=SceneXplainAPIWrapper) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None ) -> 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("SceneXplainTool does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/scenexplain/tool.html
8bb124c04f38-0
Source code for langchain.tools.brave_search.tool from __future__ import annotations from typing import Any, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.brave_search import BraveSearchWrapper [docs]class BraveSearch(BaseTool): name = "brave_search" description = ( "a search engine. " "useful for when you need to answer questions about current events." " input should be a search query." ) search_wrapper: BraveSearchWrapper [docs] @classmethod def from_api_key( cls, api_key: str, search_kwargs: Optional[dict] = None, **kwargs: Any ) -> BraveSearch: wrapper = BraveSearchWrapper(api_key=api_key, search_kwargs=search_kwargs or {}) return cls(search_wrapper=wrapper, **kwargs) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return self.search_wrapper.run(query) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("BraveSearch does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/brave_search/tool.html
08b2c3cedba3-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 the second(optional) a number that is the maximum number of video results to return """ import json from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools import BaseTool [docs]class YouTubeSearchTool(BaseTool): name = "youtube_search" description = ( "search for youtube videos associated with a person. " "the input to this tool should be a comma separated list, " "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 = YoutubeSearch(person, num_results).to_json() data = json.loads(results) url_suffix_list = [video["url_suffix"] for video in data["videos"]] return str(url_suffix_list) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" values = query.split(",") person = values[0] if len(values) > 1: num_results = int(values[1]) else:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html
08b2c3cedba3-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 asynchronously.""" raise NotImplementedError("YouTubeSearchTool does not yet support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html
028e16b53092-0
Source code for langchain.tools.playwright.navigate from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import ( aget_current_page, get_current_page, ) [docs]class NavigateToolInput(BaseModel): """Input for NavigateToolInput.""" url: str = Field(..., description="url to navigate to") [docs]class NavigateTool(BaseBrowserTool): name: str = "navigate_browser" description: str = "Navigate a browser to the specified URL" args_schema: Type[BaseModel] = NavigateToolInput def _run( self, url: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) response = page.goto(url) status = response.status if response else "unknown" return f"Navigating to {url} returned status code {status}" async def _arun( self, url: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) response = await page.goto(url)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
028e16b53092-1
response = await page.goto(url) status = response.status if response else "unknown" return f"Navigating to {url} returned status code {status}"
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
91e396051b5e-0
Source code for langchain.tools.playwright.extract_hyperlinks from __future__ import annotations import json from typing import TYPE_CHECKING, Any, Optional, Type from pydantic import BaseModel, Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import aget_current_page, get_current_page if TYPE_CHECKING: pass [docs]class ExtractHyperlinksToolInput(BaseModel): """Input for ExtractHyperlinksTool.""" absolute_urls: bool = Field( default=False, description="Return absolute URLs instead of relative URLs", ) [docs]class ExtractHyperlinksTool(BaseBrowserTool): """Extract all hyperlinks on the page.""" name: str = "extract_hyperlinks" description: str = "Extract all hyperlinks on the current webpage" args_schema: Type[BaseModel] = ExtractHyperlinksToolInput [docs] @root_validator def check_bs_import(cls, values: dict) -> dict: """Check that the arguments are valid.""" try: from bs4 import BeautifulSoup # noqa: F401 except ImportError: raise ValueError( "The 'beautifulsoup4' package is required to use this tool." " Please install it with 'pip install beautifulsoup4'." ) return values [docs] @staticmethod def scrape_page(page: Any, html_content: str, absolute_urls: bool) -> str: from urllib.parse import urljoin from bs4 import BeautifulSoup # Parse the HTML content with BeautifulSoup soup = BeautifulSoup(html_content, "lxml")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
91e396051b5e-1
soup = BeautifulSoup(html_content, "lxml") # Find all the anchor elements and extract their href attributes anchors = soup.find_all("a") if absolute_urls: base_url = page.url links = [urljoin(base_url, anchor.get("href", "")) for anchor in anchors] else: links = [anchor.get("href", "") for anchor in anchors] # Return the list of links as a JSON string return json.dumps(links) def _run( self, absolute_urls: bool = False, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) html_content = page.content() return self.scrape_page(page, html_content, absolute_urls) async def _arun( self, absolute_urls: bool = False, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) html_content = await page.content() return self.scrape_page(page, html_content, absolute_urls)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
375419d2ff08-0
Source code for langchain.tools.playwright.extract_text from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import aget_current_page, get_current_page [docs]class ExtractTextTool(BaseBrowserTool): name: str = "extract_text" description: str = "Extract all the text on the current webpage" args_schema: Type[BaseModel] = BaseModel [docs] @root_validator def check_acheck_bs_importrgs(cls, values: dict) -> dict: """Check that the arguments are valid.""" try: from bs4 import BeautifulSoup # noqa: F401 except ImportError: raise ValueError( "The 'beautifulsoup4' package is required to use this tool." " Please install it with 'pip install beautifulsoup4'." ) return values def _run(self, run_manager: Optional[CallbackManagerForToolRun] = None) -> str: """Use the tool.""" # Use Beautiful Soup since it's faster than looping through the elements from bs4 import BeautifulSoup if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) html_content = page.content() # Parse the HTML content with BeautifulSoup soup = BeautifulSoup(html_content, "lxml") return " ".join(text for text in soup.stripped_strings) async def _arun(
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
375419d2ff08-1
async def _arun( self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") # Use Beautiful Soup since it's faster than looping through the elements from bs4 import BeautifulSoup page = await aget_current_page(self.async_browser) html_content = await page.content() # Parse the HTML content with BeautifulSoup soup = BeautifulSoup(html_content, "lxml") return " ".join(text for text in soup.stripped_strings)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
7ae7551bc188-0
Source code for langchain.tools.playwright.base from __future__ import annotations from typing import TYPE_CHECKING, Optional, Tuple, Type from pydantic import root_validator from langchain.tools.base import BaseTool if TYPE_CHECKING: from playwright.async_api import Browser as AsyncBrowser from playwright.sync_api import Browser as SyncBrowser else: try: # We do this so pydantic can resolve the types when instantiating from playwright.async_api import Browser as AsyncBrowser from playwright.sync_api import Browser as SyncBrowser except ImportError: pass [docs]def lazy_import_playwright_browsers() -> Tuple[Type[AsyncBrowser], Type[SyncBrowser]]: """ Lazy import playwright browsers. Returns: Tuple[Type[AsyncBrowser], Type[SyncBrowser]]: AsyncBrowser and SyncBrowser classes. """ try: from playwright.async_api import Browser as AsyncBrowser # noqa: F401 from playwright.sync_api import Browser as SyncBrowser # noqa: F401 except ImportError: raise ValueError( "The 'playwright' package is required to use the playwright tools." " Please install it with 'pip install playwright'." ) return AsyncBrowser, SyncBrowser [docs]class BaseBrowserTool(BaseTool): """Base class for browser tools.""" sync_browser: Optional["SyncBrowser"] = None async_browser: Optional["AsyncBrowser"] = None [docs] @root_validator def validate_browser_provided(cls, values: dict) -> dict: """Check that the arguments are valid.""" lazy_import_playwright_browsers() if values.get("async_browser") is None and values.get("sync_browser") is None:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/base.html
7ae7551bc188-1
raise ValueError("Either async_browser or sync_browser must be specified.") return values [docs] @classmethod def from_browser( cls, sync_browser: Optional[SyncBrowser] = None, async_browser: Optional[AsyncBrowser] = None, ) -> BaseBrowserTool: """Instantiate the tool.""" lazy_import_playwright_browsers() return cls(sync_browser=sync_browser, async_browser=async_browser)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/base.html
d76174037091-0
Source code for langchain.tools.playwright.utils """Utilities for the Playwright browser tools.""" from __future__ import annotations import asyncio from typing import TYPE_CHECKING, Any, Coroutine, TypeVar if TYPE_CHECKING: from playwright.async_api import Browser as AsyncBrowser from playwright.async_api import Page as AsyncPage from playwright.sync_api import Browser as SyncBrowser from playwright.sync_api import Page as SyncPage async def aget_current_page(browser: AsyncBrowser) -> AsyncPage: """ Asynchronously get the current page of the browser. Args: browser: The browser (AsyncBrowser) to get the current page from. Returns: AsyncPage: The current page. """ if not browser.contexts: context = await browser.new_context() return await context.new_page() context = browser.contexts[0] # Assuming you're using the default browser context if not context.pages: return await context.new_page() # Assuming the last page in the list is the active one return context.pages[-1] [docs]def get_current_page(browser: SyncBrowser) -> SyncPage: """ Get the current page of the browser. Args: browser: The browser to get the current page from. Returns: SyncPage: The current page. """ if not browser.contexts: context = browser.new_context() return context.new_page() context = browser.contexts[0] # Assuming you're using the default browser context if not context.pages: return context.new_page() # Assuming the last page in the list is the active one return context.pages[-1]
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/utils.html
d76174037091-1
return context.pages[-1] [docs]def create_async_playwright_browser(headless: bool = True) -> AsyncBrowser: """ Create an async playwright browser. Args: headless: Whether to run the browser in headless mode. Defaults to True. Returns: AsyncBrowser: The playwright browser. """ from playwright.async_api import async_playwright browser = run_async(async_playwright().start()) return run_async(browser.chromium.launch(headless=headless)) [docs]def create_sync_playwright_browser(headless: bool = True) -> SyncBrowser: """ Create a playwright browser. Args: headless: Whether to run the browser in headless mode. Defaults to True. Returns: SyncBrowser: The playwright browser. """ from playwright.sync_api import sync_playwright browser = sync_playwright().start() return browser.chromium.launch(headless=headless) T = TypeVar("T") [docs]def run_async(coro: Coroutine[Any, Any, T]) -> T: """Run an async coroutine. Args: coro: The coroutine to run. Coroutine[Any, Any, T] Returns: T: The result of the coroutine. """ event_loop = asyncio.get_event_loop() return event_loop.run_until_complete(coro)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/utils.html
49566e9684cd-0
Source code for langchain.tools.playwright.current_page from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import aget_current_page, get_current_page [docs]class CurrentWebPageTool(BaseBrowserTool): name: str = "current_webpage" description: str = "Returns the URL of the current page" args_schema: Type[BaseModel] = BaseModel def _run( self, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) return str(page.url) async def _arun( self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) return str(page.url)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/current_page.html
8bf504d7fb20-0
Source code for langchain.tools.playwright.get_elements from __future__ import annotations import json from typing import TYPE_CHECKING, List, Optional, Sequence, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import aget_current_page, get_current_page if TYPE_CHECKING: from playwright.async_api import Page as AsyncPage from playwright.sync_api import Page as SyncPage [docs]class GetElementsToolInput(BaseModel): """Input for GetElementsTool.""" selector: str = Field( ..., description="CSS selector, such as '*', 'div', 'p', 'a', #id, .classname", ) attributes: List[str] = Field( default_factory=lambda: ["innerText"], description="Set of attributes to retrieve for each element", ) async def _aget_elements( page: AsyncPage, selector: str, attributes: Sequence[str] ) -> List[dict]: """Get elements matching the given CSS selector.""" elements = await page.query_selector_all(selector) results = [] for element in elements: result = {} for attribute in attributes: if attribute == "innerText": val: Optional[str] = await element.inner_text() else: val = await element.get_attribute(attribute) if val is not None and val.strip() != "": result[attribute] = val if result: results.append(result) return results def _get_elements( page: SyncPage, selector: str, attributes: Sequence[str] ) -> List[dict]:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
8bf504d7fb20-1
) -> List[dict]: """Get elements matching the given CSS selector.""" elements = page.query_selector_all(selector) results = [] for element in elements: result = {} for attribute in attributes: if attribute == "innerText": val: Optional[str] = element.inner_text() else: val = element.get_attribute(attribute) if val is not None and val.strip() != "": result[attribute] = val if result: results.append(result) return results [docs]class GetElementsTool(BaseBrowserTool): name: str = "get_elements" description: str = ( "Retrieve elements in the current web page matching the given CSS selector" ) args_schema: Type[BaseModel] = GetElementsToolInput def _run( self, selector: str, attributes: Sequence[str] = ["innerText"], run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) # Navigate to the desired webpage before using this tool results = _get_elements(page, selector, attributes) return json.dumps(results, ensure_ascii=False) async def _arun( self, selector: str, attributes: Sequence[str] = ["innerText"], run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
8bf504d7fb20-2
raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) # Navigate to the desired webpage before using this tool results = await _aget_elements(page, selector, attributes) return json.dumps(results, ensure_ascii=False)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
04e80a56b7cd-0
Source code for langchain.tools.playwright.navigate_back from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import ( aget_current_page, get_current_page, ) [docs]class NavigateBackTool(BaseBrowserTool): """Navigate back to the previous page in the browser history.""" name: str = "previous_webpage" description: str = "Navigate back to the previous page in the browser history" args_schema: Type[BaseModel] = BaseModel def _run(self, run_manager: Optional[CallbackManagerForToolRun] = None) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) response = page.go_back() if response: return ( f"Navigated back to the previous page with URL '{response.url}'." f" Status code {response.status}" ) else: return "Unable to navigate back; no previous page in the history" async def _arun( self, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) response = await page.go_back() if response: return (
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
04e80a56b7cd-1
response = await page.go_back() if response: return ( f"Navigated back to the previous page with URL '{response.url}'." f" Status code {response.status}" ) else: return "Unable to navigate back; no previous page in the history"
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
87ef35a05564-0
Source code for langchain.tools.playwright.click from __future__ import annotations from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.playwright.base import BaseBrowserTool from langchain.tools.playwright.utils import ( aget_current_page, get_current_page, ) [docs]class ClickToolInput(BaseModel): """Input for ClickTool.""" selector: str = Field(..., description="CSS selector for the element to click") [docs]class ClickTool(BaseBrowserTool): name: str = "click_element" description: str = "Click on an element with the given CSS selector" args_schema: Type[BaseModel] = ClickToolInput visible_only: bool = True """Whether to consider only visible elements.""" playwright_strict: bool = False """Whether to employ Playwright's strict mode when clicking on elements.""" playwright_timeout: float = 1_000 """Timeout (in ms) for Playwright to wait for element to be ready.""" def _selector_effective(self, selector: str) -> str: if not self.visible_only: return selector return f"{selector} >> visible=1" def _run( self, selector: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.sync_browser is None: raise ValueError(f"Synchronous browser not provided to {self.name}") page = get_current_page(self.sync_browser) # Navigate to the desired webpage before using this tool
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
87ef35a05564-1
# Navigate to the desired webpage before using this tool selector_effective = self._selector_effective(selector=selector) from playwright.sync_api import TimeoutError as PlaywrightTimeoutError try: page.click( selector_effective, strict=self.playwright_strict, timeout=self.playwright_timeout, ) except PlaywrightTimeoutError: return f"Unable to click on element '{selector}'" return f"Clicked element '{selector}'" async def _arun( self, selector: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" if self.async_browser is None: raise ValueError(f"Asynchronous browser not provided to {self.name}") page = await aget_current_page(self.async_browser) # Navigate to the desired webpage before using this tool selector_effective = self._selector_effective(selector=selector) from playwright.async_api import TimeoutError as PlaywrightTimeoutError try: await page.click( selector_effective, strict=self.playwright_strict, timeout=self.playwright_timeout, ) except PlaywrightTimeoutError: return f"Unable to click on element '{selector}'" return f"Clicked element '{selector}'"
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
32d26f01ec5a-0
Source code for langchain.tools.google_search.tool """Tool for the Google search API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.google_search import GoogleSearchAPIWrapper [docs]class GoogleSearchRun(BaseTool): """Tool that adds the capability to query the Google search API.""" name = "google_search" description = ( "A wrapper around Google Search. " "Useful for when you need to answer questions about current events. " "Input should be a search query." ) api_wrapper: GoogleSearchAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> 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("GoogleSearchRun does not support async") [docs]class GoogleSearchResults(BaseTool): """Tool that has capability to query the Google Search API and get back json.""" name = "Google Search Results JSON" description = ( "A wrapper around Google Search. " "Useful for when you need to answer questions about current events. " "Input should be a search query. Output is a JSON array of the query results" ) num_results: int = 4 api_wrapper: GoogleSearchAPIWrapper def _run( self,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html
32d26f01ec5a-1
api_wrapper: GoogleSearchAPIWrapper 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, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("GoogleSearchRun does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_search/tool.html
70631432a19b-0
Source code for langchain.tools.file_management.read from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMPLATE, BaseFileToolMixin, FileValidationError, ) [docs]class ReadFileInput(BaseModel): """Input for ReadFileTool.""" file_path: str = Field(..., description="name of file") [docs]class ReadFileTool(BaseFileToolMixin, BaseTool): name: str = "read_file" args_schema: Type[BaseModel] = ReadFileInput description: str = "Read file from disk" def _run( self, file_path: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: try: read_path = self.get_relative_path(file_path) except FileValidationError: return INVALID_PATH_TEMPLATE.format(arg_name="file_path", value=file_path) if not read_path.exists(): return f"Error: no such file or directory: {file_path}" try: with read_path.open("r", encoding="utf-8") as f: content = f.read() return content except Exception as e: return "Error: " + str(e) async def _arun( self, file_path: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: # TODO: Add aiofiles method raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html
f6b5bdbf89f1-0
Source code for langchain.tools.file_management.list_dir import os from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMPLATE, BaseFileToolMixin, FileValidationError, ) [docs]class DirectoryListingInput(BaseModel): """Input for ListDirectoryTool.""" dir_path: str = Field(default=".", description="Subdirectory to list.") [docs]class ListDirectoryTool(BaseFileToolMixin, BaseTool): name: str = "list_directory" args_schema: Type[BaseModel] = DirectoryListingInput description: str = "List files and directories in a specified folder" def _run( self, dir_path: str = ".", run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: try: dir_path_ = self.get_relative_path(dir_path) except FileValidationError: return INVALID_PATH_TEMPLATE.format(arg_name="dir_path", value=dir_path) try: entries = os.listdir(dir_path_) if entries: return "\n".join(entries) else: return f"No files found in directory {dir_path}" except Exception as e: return "Error: " + str(e) async def _arun( self, dir_path: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: # TODO: Add aiofiles method raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html
5d1f7639f092-0
Source code for langchain.tools.file_management.delete import os from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMPLATE, BaseFileToolMixin, FileValidationError, ) [docs]class FileDeleteInput(BaseModel): """Input for DeleteFileTool.""" file_path: str = Field(..., description="Path of the file to delete") [docs]class DeleteFileTool(BaseFileToolMixin, BaseTool): name: str = "file_delete" args_schema: Type[BaseModel] = FileDeleteInput description: str = "Delete a file" def _run( self, file_path: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: try: file_path_ = self.get_relative_path(file_path) except FileValidationError: return INVALID_PATH_TEMPLATE.format(arg_name="file_path", value=file_path) if not file_path_.exists(): return f"Error: no such file or directory: {file_path}" try: os.remove(file_path_) return f"File deleted successfully: {file_path}." except Exception as e: return "Error: " + str(e) async def _arun( self, file_path: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: # TODO: Add aiofiles method raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html
87d11fb99d83-0
Source code for langchain.tools.file_management.move import shutil from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMPLATE, BaseFileToolMixin, FileValidationError, ) [docs]class FileMoveInput(BaseModel): """Input for MoveFileTool.""" source_path: str = Field(..., description="Path of the file to move") destination_path: str = Field(..., description="New path for the moved file") [docs]class MoveFileTool(BaseFileToolMixin, BaseTool): name: str = "move_file" args_schema: Type[BaseModel] = FileMoveInput description: str = "Move or rename a file from one location to another" def _run( self, source_path: str, destination_path: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: try: source_path_ = self.get_relative_path(source_path) except FileValidationError: return INVALID_PATH_TEMPLATE.format( arg_name="source_path", value=source_path ) try: destination_path_ = self.get_relative_path(destination_path) except FileValidationError: return INVALID_PATH_TEMPLATE.format( arg_name="destination_path_", value=destination_path_ ) if not source_path_.exists(): return f"Error: no such file or directory {source_path}" try: # shutil.move expects str args in 3.8
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html
87d11fb99d83-1
try: # shutil.move expects str args in 3.8 shutil.move(str(source_path_), destination_path_) return f"File moved successfully from {source_path} to {destination_path}." except Exception as e: return "Error: " + str(e) async def _arun( self, source_path: str, destination_path: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: # TODO: Add aiofiles method raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html
6eae2f7139dc-0
Source code for langchain.tools.file_management.utils import sys from pathlib import Path from typing import Optional from pydantic import BaseModel [docs]def is_relative_to(path: Path, root: Path) -> bool: """Check if path is relative to root.""" if sys.version_info >= (3, 9): # No need for a try/except block in Python 3.8+. return path.is_relative_to(root) try: path.relative_to(root) return True except ValueError: return False INVALID_PATH_TEMPLATE = ( "Error: Access denied to {arg_name}: {value}." " Permission granted exclusively to the current working directory" ) [docs]class FileValidationError(ValueError): """Error for paths outside the root directory.""" [docs]class BaseFileToolMixin(BaseModel): """Mixin for file system tools.""" root_dir: Optional[str] = None """The final path will be chosen relative to root_dir if specified.""" [docs] def get_relative_path(self, file_path: str) -> Path: """Get the relative path, returning an error if unsupported.""" if self.root_dir is None: return Path(file_path) return get_validated_relative_path(Path(self.root_dir), file_path) [docs]def get_validated_relative_path(root: Path, user_path: str) -> Path: """Resolve a relative path, raising an error if not within the root directory.""" # Note, this still permits symlinks from outside that point within the root. # Further validation would be needed if those are to be disallowed. root = root.resolve() full_path = (root / user_path).resolve() if not is_relative_to(full_path, root):
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/utils.html
6eae2f7139dc-1
if not is_relative_to(full_path, root): raise FileValidationError( f"Path {user_path} is outside of the allowed directory {root}" ) return full_path
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/utils.html
746085bb5320-0
Source code for langchain.tools.file_management.file_search import fnmatch import os from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMPLATE, BaseFileToolMixin, FileValidationError, ) [docs]class FileSearchInput(BaseModel): """Input for FileSearchTool.""" dir_path: str = Field( default=".", description="Subdirectory to search in.", ) pattern: str = Field( ..., description="Unix shell regex, where * matches everything.", ) [docs]class FileSearchTool(BaseFileToolMixin, BaseTool): name: str = "file_search" args_schema: Type[BaseModel] = FileSearchInput description: str = ( "Recursively search for files in a subdirectory that match the regex pattern" ) def _run( self, pattern: str, dir_path: str = ".", run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: try: dir_path_ = self.get_relative_path(dir_path) except FileValidationError: return INVALID_PATH_TEMPLATE.format(arg_name="dir_path", value=dir_path) matches = [] try: for root, _, filenames in os.walk(dir_path_): for filename in fnmatch.filter(filenames, pattern): absolute_path = os.path.join(root, filename) relative_path = os.path.relpath(absolute_path, dir_path_) matches.append(relative_path)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html
746085bb5320-1
matches.append(relative_path) if matches: return "\n".join(matches) else: return f"No files found for pattern {pattern} in directory {dir_path}" except Exception as e: return "Error: " + str(e) async def _arun( self, dir_path: str, pattern: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: # TODO: Add aiofiles method raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html
a097b7c66ceb-0
Source code for langchain.tools.file_management.write from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMPLATE, BaseFileToolMixin, FileValidationError, ) [docs]class WriteFileInput(BaseModel): """Input for WriteFileTool.""" file_path: str = Field(..., description="name of file") text: str = Field(..., description="text to write to file") append: bool = Field( default=False, description="Whether to append to an existing file." ) [docs]class WriteFileTool(BaseFileToolMixin, BaseTool): name: str = "write_file" args_schema: Type[BaseModel] = WriteFileInput description: str = "Write file to disk" def _run( self, file_path: str, text: str, append: bool = False, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: try: write_path = self.get_relative_path(file_path) except FileValidationError: return INVALID_PATH_TEMPLATE.format(arg_name="file_path", value=file_path) try: write_path.parent.mkdir(exist_ok=True, parents=False) mode = "a" if append else "w" with write_path.open(mode, encoding="utf-8") as f: f.write(text) return f"File written successfully to {file_path}." except Exception as e: return "Error: " + str(e)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html
a097b7c66ceb-1
except Exception as e: return "Error: " + str(e) async def _arun( self, file_path: str, text: str, append: bool = False, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: # TODO: Add aiofiles method raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html
4580d05fb5cc-0
Source code for langchain.tools.file_management.copy import shutil from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMPLATE, BaseFileToolMixin, FileValidationError, ) [docs]class FileCopyInput(BaseModel): """Input for CopyFileTool.""" source_path: str = Field(..., description="Path of the file to copy") destination_path: str = Field(..., description="Path to save the copied file") [docs]class CopyFileTool(BaseFileToolMixin, BaseTool): name: str = "copy_file" args_schema: Type[BaseModel] = FileCopyInput description: str = "Create a copy of a file in a specified location" def _run( self, source_path: str, destination_path: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: try: source_path_ = self.get_relative_path(source_path) except FileValidationError: return INVALID_PATH_TEMPLATE.format( arg_name="source_path", value=source_path ) try: destination_path_ = self.get_relative_path(destination_path) except FileValidationError: return INVALID_PATH_TEMPLATE.format( arg_name="destination_path", value=destination_path ) try: shutil.copy2(source_path_, destination_path_, follow_symlinks=False) return f"File copied successfully from {source_path} to {destination_path}." except Exception as e:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html
4580d05fb5cc-1
except Exception as e: return "Error: " + str(e) async def _arun( self, source_path: str, destination_path: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: # TODO: Add aiofiles method raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html
2600cf63389f-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.utilities import OpenWeatherMapAPIWrapper [docs]class OpenWeatherMapQueryRun(BaseTool): """Tool that adds the capability to query using the OpenWeatherMap API.""" api_wrapper: OpenWeatherMapAPIWrapper = Field( default_factory=OpenWeatherMapAPIWrapper ) name = "OpenWeatherMap" description = ( "A wrapper around OpenWeatherMap API. " "Useful for fetching current weather information for a specified location. " "Input should be a location string (e.g. London,GB)." ) 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[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the OpenWeatherMap tool asynchronously.""" raise NotImplementedError("OpenWeatherMapQueryRun does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openweathermap/tool.html
13cf92b9250a-0
Source code for langchain.tools.google_serper.tool """Tool for the Serper.dev Google Search API.""" from typing import Optional from pydantic.fields import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.google_serper import GoogleSerperAPIWrapper [docs]class GoogleSerperRun(BaseTool): """Tool that adds the capability to query the Serper.dev Google search API.""" name = "google_serper" description = ( "A low-cost Google Search API." "Useful for when you need to answer questions about current events." "Input should be a search query." ) api_wrapper: GoogleSerperAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.run(query)) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" return (await self.api_wrapper.arun(query)).__str__() [docs]class GoogleSerperResults(BaseTool): """Tool that has capability to query the Serper.dev Google Search API and get back json.""" name = "google_serrper_results_json" description = ( "A low-cost Google Search API." "Useful for when you need to answer questions about current events." "Input should be a search query. Output is a JSON object of the query results" )
https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html
13cf92b9250a-1
) api_wrapper: GoogleSerperAPIWrapper = Field(default_factory=GoogleSerperAPIWrapper) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.api_wrapper.results(query)) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" return (await self.api_wrapper.aresults(query)).__str__()
https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html
1be48111b07d-0
Source code for langchain.tools.azure_cognitive_services.form_recognizer from __future__ import annotations import logging from typing import Any, Dict, List, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.azure_cognitive_services.utils import detect_file_src_type from langchain.tools.base import BaseTool from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [docs]class AzureCogsFormRecognizerTool(BaseTool): """Tool that queries the Azure Cognitive Services Form Recognizer API. In order to set this up, follow instructions at: https://learn.microsoft.com/en-us/azure/applied-ai-services/form-recognizer/quickstarts/get-started-sdks-rest-api?view=form-recog-3.0.0&pivots=programming-language-python """ azure_cogs_key: str = "" #: :meta private: azure_cogs_endpoint: str = "" #: :meta private: doc_analysis_client: Any #: :meta private: name = "azure_cognitive_services_form_recognizer" description = ( "A wrapper around Azure Cognitive Services Form Recognizer. " "Useful for when you need to " "extract text, tables, and key-value pairs from documents. " "Input should be a url to a document." ) [docs] @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and endpoint exists in environment.""" azure_cogs_key = get_from_dict_or_env( values, "azure_cogs_key", "AZURE_COGS_KEY" )
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
1be48111b07d-1
) azure_cogs_endpoint = get_from_dict_or_env( values, "azure_cogs_endpoint", "AZURE_COGS_ENDPOINT" ) try: from azure.ai.formrecognizer import DocumentAnalysisClient from azure.core.credentials import AzureKeyCredential values["doc_analysis_client"] = DocumentAnalysisClient( endpoint=azure_cogs_endpoint, credential=AzureKeyCredential(azure_cogs_key), ) except ImportError: raise ImportError( "azure-ai-formrecognizer is not installed. " "Run `pip install azure-ai-formrecognizer` to install." ) return values def _parse_tables(self, tables: List[Any]) -> List[Any]: result = [] for table in tables: rc, cc = table.row_count, table.column_count _table = [["" for _ in range(cc)] for _ in range(rc)] for cell in table.cells: _table[cell.row_index][cell.column_index] = cell.content result.append(_table) return result def _parse_kv_pairs(self, kv_pairs: List[Any]) -> List[Any]: result = [] for kv_pair in kv_pairs: key = kv_pair.key.content if kv_pair.key else "" value = kv_pair.value.content if kv_pair.value else "" result.append((key, value)) return result def _document_analysis(self, document_path: str) -> Dict: document_src_type = detect_file_src_type(document_path) if document_src_type == "local": with open(document_path, "rb") as document: poller = self.doc_analysis_client.begin_analyze_document( "prebuilt-document", document )
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
1be48111b07d-2
"prebuilt-document", document ) elif document_src_type == "remote": poller = self.doc_analysis_client.begin_analyze_document_from_url( "prebuilt-document", document_path ) else: raise ValueError(f"Invalid document path: {document_path}") result = poller.result() res_dict = {} if result.content is not None: res_dict["content"] = result.content if result.tables is not None: res_dict["tables"] = self._parse_tables(result.tables) if result.key_value_pairs is not None: res_dict["key_value_pairs"] = self._parse_kv_pairs(result.key_value_pairs) return res_dict def _format_document_analysis_result(self, document_analysis_result: Dict) -> str: formatted_result = [] if "content" in document_analysis_result: formatted_result.append( f"Content: {document_analysis_result['content']}".replace("\n", " ") ) if "tables" in document_analysis_result: for i, table in enumerate(document_analysis_result["tables"]): formatted_result.append(f"Table {i}: {table}".replace("\n", " ")) if "key_value_pairs" in document_analysis_result: for kv_pair in document_analysis_result["key_value_pairs"]: formatted_result.append( f"{kv_pair[0]}: {kv_pair[1]}".replace("\n", " ") ) return "\n".join(formatted_result) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" try:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
1be48111b07d-3
) -> str: """Use the tool.""" try: document_analysis_result = self._document_analysis(query) if not document_analysis_result: return "No good document analysis result was found" return self._format_document_analysis_result(document_analysis_result) except Exception as e: raise RuntimeError(f"Error while running AzureCogsFormRecognizerTool: {e}") async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("AzureCogsFormRecognizerTool does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
928c20a1ad8b-0
Source code for langchain.tools.azure_cognitive_services.image_analysis from __future__ import annotations import logging from typing import Any, Dict, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.azure_cognitive_services.utils import detect_file_src_type from langchain.tools.base import BaseTool from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [docs]class AzureCogsImageAnalysisTool(BaseTool): """Tool that queries the Azure Cognitive Services Image Analysis API. In order to set this up, follow instructions at: https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts-sdk/image-analysis-client-library-40 """ azure_cogs_key: str = "" #: :meta private: azure_cogs_endpoint: str = "" #: :meta private: vision_service: Any #: :meta private: analysis_options: Any #: :meta private: name = "azure_cognitive_services_image_analysis" description = ( "A wrapper around Azure Cognitive Services Image Analysis. " "Useful for when you need to analyze images. " "Input should be a url to an image." ) [docs] @root_validator(pre=True) def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and endpoint exists in environment.""" azure_cogs_key = get_from_dict_or_env( values, "azure_cogs_key", "AZURE_COGS_KEY" ) azure_cogs_endpoint = get_from_dict_or_env( values, "azure_cogs_endpoint", "AZURE_COGS_ENDPOINT"
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
928c20a1ad8b-1
values, "azure_cogs_endpoint", "AZURE_COGS_ENDPOINT" ) try: import azure.ai.vision as sdk values["vision_service"] = sdk.VisionServiceOptions( endpoint=azure_cogs_endpoint, key=azure_cogs_key ) values["analysis_options"] = sdk.ImageAnalysisOptions() values["analysis_options"].features = ( sdk.ImageAnalysisFeature.CAPTION | sdk.ImageAnalysisFeature.OBJECTS | sdk.ImageAnalysisFeature.TAGS | sdk.ImageAnalysisFeature.TEXT ) except ImportError: raise ImportError( "azure-ai-vision is not installed. " "Run `pip install azure-ai-vision` to install." ) return values def _image_analysis(self, image_path: str) -> Dict: try: import azure.ai.vision as sdk except ImportError: pass image_src_type = detect_file_src_type(image_path) if image_src_type == "local": vision_source = sdk.VisionSource(filename=image_path) elif image_src_type == "remote": vision_source = sdk.VisionSource(url=image_path) else: raise ValueError(f"Invalid image path: {image_path}") image_analyzer = sdk.ImageAnalyzer( self.vision_service, vision_source, self.analysis_options ) result = image_analyzer.analyze() res_dict = {} if result.reason == sdk.ImageAnalysisResultReason.ANALYZED: if result.caption is not None: res_dict["caption"] = result.caption.content if result.objects is not None: res_dict["objects"] = [obj.name for obj in result.objects]
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html