id
stringlengths
14
15
text
stringlengths
35
2.51k
source
stringlengths
61
154
1a735b9a8632-1
) return thread_data async def _arun( self, thread_id: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> Dict: """Run the tool.""" raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_thread.html
cecf4ce8f514-0
Source code for langchain.tools.gmail.get_message import base64 import email from typing import Dict, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.gmail.base import GmailBaseTool from langchain.tools.gmail.utils import clean_email_body [docs]class SearchArgsSchema(BaseModel): message_id: str = Field( ..., description="The unique ID of the email message, retrieved from a search.", ) [docs]class GmailGetMessage(GmailBaseTool): name: str = "get_gmail_message" description: str = ( "Use this tool to fetch an email by message ID." " Returns the thread ID, snipet, body, subject, and sender." ) args_schema: Type[SearchArgsSchema] = SearchArgsSchema def _run( self, message_id: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> Dict: """Run the tool.""" query = ( self.api_resource.users() .messages() .get(userId="me", format="raw", id=message_id) ) message_data = query.execute() raw_message = base64.urlsafe_b64decode(message_data["raw"]) email_msg = email.message_from_bytes(raw_message) subject = email_msg["Subject"] sender = email_msg["From"] message_body = email_msg.get_payload() body = clean_email_body(message_body) return { "id": message_id, "threadId": message_data["threadId"], "snippet": message_data["snippet"],
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html
cecf4ce8f514-1
"snippet": message_data["snippet"], "body": body, "subject": subject, "sender": sender, } async def _arun( self, message_id: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> Dict: """Run the tool.""" raise NotImplementedError
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/get_message.html
7d2e0e49621c-0
Source code for langchain.tools.gmail.create_draft import base64 from email.message import EmailMessage from typing import List, Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.gmail.base import GmailBaseTool [docs]class CreateDraftSchema(BaseModel): message: str = Field( ..., description="The message 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 GmailCreateDraft(GmailBaseTool): name: str = "create_gmail_draft" description: str = ( "Use this tool to create a draft email with the provided message fields." ) args_schema: Type[CreateDraftSchema] = CreateDraftSchema def _prepare_draft_message( self, message: str, to: List[str], subject: str, cc: Optional[List[str]] = None, bcc: Optional[List[str]] = None, ) -> dict: draft_message = EmailMessage() draft_message.set_content(message) draft_message["To"] = ", ".join(to) draft_message["Subject"] = subject if cc is not None:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/create_draft.html
7d2e0e49621c-1
draft_message["Subject"] = subject if cc is not None: draft_message["Cc"] = ", ".join(cc) if bcc is not None: draft_message["Bcc"] = ", ".join(bcc) encoded_message = base64.urlsafe_b64encode(draft_message.as_bytes()).decode() return {"message": {"raw": encoded_message}} def _run( self, message: str, to: List[str], subject: str, cc: Optional[List[str]] = None, bcc: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: try: create_message = self._prepare_draft_message(message, to, subject, cc, bcc) draft = ( self.api_resource.users() .drafts() .create(userId="me", body=create_message) .execute() ) output = f'Draft created. Draft Id: {draft["id"]}' return output except Exception as e: raise Exception(f"An error occurred: {e}") async def _arun( self, 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/gmail/create_draft.html
b32f87b91635-0
Source code for langchain.tools.gmail.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.gmail.utils import build_resource_service if TYPE_CHECKING: # This is for linting and IDE typehints from googleapiclient.discovery import Resource else: try: # We do this so pydantic can resolve the types when instantiating from googleapiclient.discovery import Resource except ImportError: pass [docs]class GmailBaseTool(BaseTool): api_resource: Resource = Field(default_factory=build_resource_service) [docs] @classmethod def from_api_resource(cls, api_resource: Resource) -> "GmailBaseTool": return cls(service=api_resource)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/base.html
e6fc3ca16c57-0
Source code for langchain.tools.gmail.send_message """Send Gmail messages.""" import base64 from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from typing import Any, Dict, List, Optional, Union from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.gmail.base import GmailBaseTool [docs]class SendMessageSchema(BaseModel): message: str = Field( ..., description="The message to send.", ) to: Union[str, List[str]] = Field( ..., description="The list of recipients.", ) subject: str = Field( ..., description="The subject of the message.", ) cc: Optional[Union[str, List[str]]] = Field( None, description="The list of CC recipients.", ) bcc: Optional[Union[str, List[str]]] = Field( None, description="The list of BCC recipients.", ) [docs]class GmailSendMessage(GmailBaseTool): name: str = "send_gmail_message" description: str = ( "Use this tool to send email messages." " The input is the message, recipents" ) def _prepare_message( self, message: str, to: Union[str, List[str]], subject: str, cc: Optional[Union[str, List[str]]] = None, bcc: Optional[Union[str, List[str]]] = None, ) -> Dict[str, Any]: """Create a message for an email.""" mime_message = MIMEMultipart()
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html
e6fc3ca16c57-1
"""Create a message for an email.""" mime_message = MIMEMultipart() mime_message.attach(MIMEText(message, "html")) mime_message["To"] = ", ".join(to if isinstance(to, list) else [to]) mime_message["Subject"] = subject if cc is not None: mime_message["Cc"] = ", ".join(cc if isinstance(cc, list) else [cc]) if bcc is not None: mime_message["Bcc"] = ", ".join(bcc if isinstance(bcc, list) else [bcc]) encoded_message = base64.urlsafe_b64encode(mime_message.as_bytes()).decode() return {"raw": encoded_message} def _run( self, message: str, to: Union[str, List[str]], subject: str, cc: Optional[Union[str, List[str]]] = None, bcc: Optional[Union[str, List[str]]] = None, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Run the tool.""" try: create_message = self._prepare_message(message, to, subject, cc=cc, bcc=bcc) send_message = ( self.api_resource.users() .messages() .send(userId="me", body=create_message) ) sent_message = send_message.execute() return f'Message sent. Message Id: {sent_message["id"]}' except Exception as error: raise Exception(f"An error occurred: {error}") async def _arun( self, message: str, to: Union[str, List[str]], subject: str,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html
e6fc3ca16c57-2
to: Union[str, List[str]], subject: str, cc: Optional[Union[str, List[str]]] = None, bcc: Optional[Union[str, List[str]]] = None, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" raise NotImplementedError(f"The tool {self.name} does not support async yet.")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/gmail/send_message.html
124b4ab75105-0
Source code for langchain.tools.graphql.tool import json from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.graphql import GraphQLAPIWrapper [docs]class BaseGraphQLTool(BaseTool): """Base tool for querying a GraphQL API.""" graphql_wrapper: GraphQLAPIWrapper name = "query_graphql" description = """\ Input to this tool is a detailed and correct GraphQL query, output is a result from the API. If the query is not correct, an error message will be returned. If an error is returned with 'Bad request' in it, rewrite the query and try again. If an error is returned with 'Unauthorized' in it, do not try again, but tell the user to change their authentication. Example Input: query {{ allUsers {{ id, name, email }} }}\ """ # noqa: E501 [docs] class Config: """Configuration for this pydantic object.""" arbitrary_types_allowed = True def _run( self, tool_input: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: result = self.graphql_wrapper.run(tool_input) return json.dumps(result, indent=2) async def _arun( self, tool_input: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the Graphql tool asynchronously.""" raise NotImplementedError("GraphQLAPIWrapper does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/graphql/tool.html
bfe5f55efde3-0
Source code for langchain.tools.spark_sql.tool # flake8: noqa """Tools for interacting with Spark SQL.""" from typing import Any, Dict, Optional from pydantic import BaseModel, Extra, Field, root_validator from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.chains.llm import LLMChain from langchain.prompts import PromptTemplate from langchain.utilities.spark_sql import SparkSQL from langchain.tools.base import BaseTool from langchain.tools.spark_sql.prompt import QUERY_CHECKER [docs]class BaseSparkSQLTool(BaseModel): """Base tool for interacting with Spark SQL.""" db: SparkSQL = 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 QuerySparkSQLTool(BaseSparkSQLTool, BaseTool): """Tool for querying a Spark SQL.""" name = "query_sql_db" description = """ Input to this tool is a detailed and correct SQL query, output is a result from the Spark SQL. 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/spark_sql/tool.html
bfe5f55efde3-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 InfoSparkSQLTool(BaseSparkSQLTool, BaseTool): """Tool for getting metadata about a Spark SQL.""" name = "schema_sql_db" description = """ Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables. Be sure that the tables actually exist by calling list_tables_sql_db first! 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 ListSparkSQLTool(BaseSparkSQLTool, BaseTool): """Tool for getting tables names.""" name = "list_tables_sql_db" description = "Input is an empty string, output is a comma separated list of tables in the Spark SQL." def _run( self, tool_input: str = "",
https://api.python.langchain.com/en/latest/_modules/langchain/tools/spark_sql/tool.html
bfe5f55efde3-2
def _run( self, tool_input: str = "", run_manager: Optional[CallbackManagerForToolRun] = None, ) -> 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 QueryCheckerTool(BaseSparkSQLTool, 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 = "query_checker_sql_db" 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"] ), ) if values["llm_chain"].prompt.input_variables != ["query"]: raise ValueError(
https://api.python.langchain.com/en/latest/_modules/langchain/tools/spark_sql/tool.html
bfe5f55efde3-3
raise ValueError( "LLM chain for QueryCheckerTool need to use ['query'] as input_variables " "for the embedded prompt" ) 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) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: return await self.llm_chain.apredict(query=query)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/spark_sql/tool.html
6bb2a9417ea7-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
6bb2a9417ea7-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
5dbf9c91ce12-0
Source code for langchain.tools.google_places.tool """Tool for the Google search API.""" from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.google_places_api import GooglePlacesAPIWrapper [docs]class GooglePlacesSchema(BaseModel): query: str = Field(..., description="Query for google maps") [docs]class GooglePlacesTool(BaseTool): """Tool that adds the capability to query the Google places API.""" name = "google_places" description = ( "A wrapper around Google Places. " "Useful for when you need to validate or " "discover addressed from ambiguous text. " "Input should be a search query." ) api_wrapper: GooglePlacesAPIWrapper = Field(default_factory=GooglePlacesAPIWrapper) args_schema: Type[BaseModel] = GooglePlacesSchema def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return self.api_wrapper.run(query) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("GooglePlacesRun does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html
ef3721a08bf7-0
Source code for langchain.tools.searx_search.tool """Tool for the SearxNG search API.""" from typing import Optional from pydantic import Extra from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool, Field from langchain.utilities.searx_search import SearxSearchWrapper [docs]class SearxSearchRun(BaseTool): """Tool that adds the capability to query a Searx instance.""" name = "searx_search" description = ( "A meta search engine." "Useful for when you need to answer questions about current events." "Input should be a search query." ) wrapper: SearxSearchWrapper kwargs: dict = Field(default_factory=dict) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return self.wrapper.run(query, **self.kwargs) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" return await self.wrapper.arun(query, **self.kwargs) [docs]class SearxSearchResults(BaseTool): """Tool that has the capability to query a Searx instance and get back json.""" name = "Searx Search Results" description = ( "A meta search engine." "Useful for when you need to answer questions about current events."
https://api.python.langchain.com/en/latest/_modules/langchain/tools/searx_search/tool.html
ef3721a08bf7-1
"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" ) wrapper: SearxSearchWrapper num_results: int = 4 kwargs: dict = Field(default_factory=dict) [docs] class Config: """Pydantic config.""" extra = Extra.allow def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" return str(self.wrapper.results(query, self.num_results, **self.kwargs)) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" return ( await self.wrapper.aresults(query, self.num_results, **self.kwargs) ).__str__()
https://api.python.langchain.com/en/latest/_modules/langchain/tools/searx_search/tool.html
8c0629ab0ac8-0
Source code for langchain.tools.json.tool # flake8: noqa """Tools for working with JSON specs.""" from __future__ import annotations import json import re from pathlib import Path from typing import Dict, List, Optional, Union from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool def _parse_input(text: str) -> List[Union[str, int]]: """Parse input of the form data["key1"][0]["key2"] into a list of keys.""" _res = re.findall(r"\[.*?]", text) # strip the brackets and quotes, convert to int if possible res = [i[1:-1].replace('"', "") for i in _res] res = [int(i) if i.isdigit() else i for i in res] return res [docs]class JsonSpec(BaseModel): """Base class for JSON spec.""" dict_: Dict max_value_length: int = 200 [docs] @classmethod def from_file(cls, path: Path) -> JsonSpec: """Create a JsonSpec from a file.""" if not path.exists(): raise FileNotFoundError(f"File not found: {path}") dict_ = json.loads(path.read_text()) return cls(dict_=dict_) [docs] def keys(self, text: str) -> str: """Return the keys of the dict at the given path. Args: text: Python representation of the path to the dict (e.g. data["key1"][0]["key2"]). """ try: items = _parse_input(text) val = self.dict_
https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html
8c0629ab0ac8-1
try: items = _parse_input(text) val = self.dict_ for i in items: if i: val = val[i] if not isinstance(val, dict): raise ValueError( f"Value at path `{text}` is not a dict, get the value directly." ) return str(list(val.keys())) except Exception as e: return repr(e) [docs] def value(self, text: str) -> str: """Return the value of the dict at the given path. Args: text: Python representation of the path to the dict (e.g. data["key1"][0]["key2"]). """ try: items = _parse_input(text) val = self.dict_ for i in items: val = val[i] if isinstance(val, dict) and len(str(val)) > self.max_value_length: return "Value is a large dictionary, should explore its keys directly" str_val = str(val) if len(str_val) > self.max_value_length: str_val = str_val[: self.max_value_length] + "..." return str_val except Exception as e: return repr(e) [docs]class JsonListKeysTool(BaseTool): """Tool for listing keys in a JSON spec.""" name = "json_spec_list_keys" description = """ Can be used to list all keys at a given path. Before calling this you should be SURE that the path to this exists. The input is a text representation of the path to the dict in Python syntax (e.g. data["key1"][0]["key2"]). """ spec: JsonSpec
https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html
8c0629ab0ac8-2
""" spec: JsonSpec def _run( self, tool_input: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: return self.spec.keys(tool_input) async def _arun( self, tool_input: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: return self._run(tool_input) [docs]class JsonGetValueTool(BaseTool): """Tool for getting a value in a JSON spec.""" name = "json_spec_get_value" description = """ Can be used to see value in string format at a given path. Before calling this you should be SURE that the path to this exists. The input is a text representation of the path to the dict in Python syntax (e.g. data["key1"][0]["key2"]). """ spec: JsonSpec def _run( self, tool_input: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: return self.spec.value(tool_input) async def _arun( self, tool_input: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: return self._run(tool_input)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/json/tool.html
11de45472249-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
7a6e51a3ec42-0
Source code for langchain.tools.ddg_search.tool """Tool for the DuckDuckGo search API.""" import warnings from typing import Any, Optional from pydantic import Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper [docs]class DuckDuckGoSearchRun(BaseTool): """Tool that adds the capability to query the DuckDuckGo search API.""" name = "duckduckgo_search" description = ( "A wrapper around DuckDuckGo Search. " "Useful for when you need to answer questions about current events. " "Input should be a search query." ) api_wrapper: DuckDuckGoSearchAPIWrapper = Field( default_factory=DuckDuckGoSearchAPIWrapper ) 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("DuckDuckGoSearch does not support async") [docs]class DuckDuckGoSearchResults(BaseTool): """Tool that queries the Duck Duck Go Search API and get back json.""" name = "DuckDuckGo Results JSON" description = ( "A wrapper around Duck Duck Go Search. "
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html
7a6e51a3ec42-1
description = ( "A wrapper around Duck Duck Go 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: DuckDuckGoSearchAPIWrapper = Field( default_factory=DuckDuckGoSearchAPIWrapper ) 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("DuckDuckGoSearchResults does not support async") [docs]def DuckDuckGoSearchTool(*args: Any, **kwargs: Any) -> DuckDuckGoSearchRun: """ Deprecated. Use DuckDuckGoSearchRun instead. Args: *args: **kwargs: Returns: DuckDuckGoSearchRun """ warnings.warn( "DuckDuckGoSearchTool will be deprecated in the future. " "Please use DuckDuckGoSearchRun instead.", DeprecationWarning, ) return DuckDuckGoSearchRun(*args, **kwargs)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html
e2075c2e12d4-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
452998a9f00e-0
Source code for langchain.tools.interaction.tool """Tools for interacting with the user.""" import warnings from typing import Any from langchain.tools.human.tool import HumanInputRun [docs]def StdInInquireTool(*args: Any, **kwargs: Any) -> HumanInputRun: """Tool for asking the user for input.""" warnings.warn( "StdInInquireTool will be deprecated in the future. " "Please use HumanInputRun instead.", DeprecationWarning, ) return HumanInputRun(*args, **kwargs)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/interaction/tool.html
391fa322fbd9-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
391fa322fbd9-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
9499f6ad6036-0
Source code for langchain.tools.wikipedia.tool """Tool for the Wikipedia API.""" from typing import Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.wikipedia import WikipediaAPIWrapper [docs]class WikipediaQueryRun(BaseTool): """Tool that adds the capability to search using the Wikipedia API.""" name = "Wikipedia" description = ( "A wrapper around Wikipedia. " "Useful for when you need to answer general questions about " "people, places, companies, facts, historical events, or other subjects. " "Input should be a search query." ) api_wrapper: WikipediaAPIWrapper def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the Wikipedia tool.""" return self.api_wrapper.run(query) async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the Wikipedia tool asynchronously.""" raise NotImplementedError("WikipediaQueryRun does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/wikipedia/tool.html
8d812c1ddf58-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
8d812c1ddf58-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
ab76686547b3-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
d7d2faaf24e3-0
Source code for langchain.tools.azure_cognitive_services.utils import os import tempfile from urllib.parse import urlparse import requests [docs]def detect_file_src_type(file_path: str) -> str: """Detect if the file is local or remote.""" if os.path.isfile(file_path): return "local" parsed_url = urlparse(file_path) if parsed_url.scheme and parsed_url.netloc: return "remote" return "invalid" [docs]def download_audio_from_url(audio_url: str) -> str: """Download audio from url to local.""" ext = audio_url.split(".")[-1] response = requests.get(audio_url, stream=True) response.raise_for_status() with tempfile.NamedTemporaryFile(mode="wb", suffix=f".{ext}", delete=False) as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) return f.name
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/utils.html
4028e2425f09-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
4028e2425f09-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
4028e2425f09-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
4028e2425f09-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
e62e2a0eeedc-0
Source code for langchain.tools.azure_cognitive_services.text2speech from __future__ import annotations import logging import tempfile from typing import Any, Dict, Optional from pydantic import root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [docs]class AzureCogsText2SpeechTool(BaseTool): """Tool that queries the Azure Cognitive Services Text2Speech API. In order to set this up, follow instructions at: https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-text-to-speech?pivots=programming-language-python """ azure_cogs_key: str = "" #: :meta private: azure_cogs_region: str = "" #: :meta private: speech_language: str = "en-US" #: :meta private: speech_config: Any #: :meta private: name = "azure_cognitive_services_text2speech" description = ( "A wrapper around Azure Cognitive Services Text2Speech. " "Useful for when you need to convert text to speech. " ) [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_region = get_from_dict_or_env( values, "azure_cogs_region", "AZURE_COGS_REGION" ) try:
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html
e62e2a0eeedc-1
) try: import azure.cognitiveservices.speech as speechsdk values["speech_config"] = speechsdk.SpeechConfig( subscription=azure_cogs_key, region=azure_cogs_region ) except ImportError: raise ImportError( "azure-cognitiveservices-speech is not installed. " "Run `pip install azure-cognitiveservices-speech` to install." ) return values def _text2speech(self, text: str, speech_language: str) -> str: try: import azure.cognitiveservices.speech as speechsdk except ImportError: pass self.speech_config.speech_synthesis_language = speech_language speech_synthesizer = speechsdk.SpeechSynthesizer( speech_config=self.speech_config, audio_config=None ) result = speech_synthesizer.speak_text(text) if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted: stream = speechsdk.AudioDataStream(result) with tempfile.NamedTemporaryFile( mode="wb", suffix=".wav", delete=False ) as f: stream.save_to_wav_file(f.name) return f.name elif result.reason == speechsdk.ResultReason.Canceled: cancellation_details = result.cancellation_details logger.debug(f"Speech synthesis canceled: {cancellation_details.reason}") if cancellation_details.reason == speechsdk.CancellationReason.Error: raise RuntimeError( f"Speech synthesis error: {cancellation_details.error_details}" ) return "Speech synthesis canceled." else: return f"Speech synthesis failed: {result.reason}" def _run( self, query: str,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html
e62e2a0eeedc-2
def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" try: speech_file = self._text2speech(query, self.speech_language) return speech_file except Exception as e: raise RuntimeError(f"Error while running AzureCogsText2SpeechTool: {e}") async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("AzureCogsText2SpeechTool does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html
dc1cfbb25756-0
Source code for langchain.tools.azure_cognitive_services.speech2text from __future__ import annotations import logging import time 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, download_audio_from_url, ) from langchain.tools.base import BaseTool from langchain.utils import get_from_dict_or_env logger = logging.getLogger(__name__) [docs]class AzureCogsSpeech2TextTool(BaseTool): """Tool that queries the Azure Cognitive Services Speech2Text API. In order to set this up, follow instructions at: https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/get-started-speech-to-text?pivots=programming-language-python """ azure_cogs_key: str = "" #: :meta private: azure_cogs_region: str = "" #: :meta private: speech_language: str = "en-US" #: :meta private: speech_config: Any #: :meta private: name = "azure_cognitive_services_speech2text" description = ( "A wrapper around Azure Cognitive Services Speech2Text. " "Useful for when you need to transcribe audio to text. " "Input should be a url to an audio file." ) [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/speech2text.html
dc1cfbb25756-1
values, "azure_cogs_key", "AZURE_COGS_KEY" ) azure_cogs_region = get_from_dict_or_env( values, "azure_cogs_region", "AZURE_COGS_REGION" ) try: import azure.cognitiveservices.speech as speechsdk values["speech_config"] = speechsdk.SpeechConfig( subscription=azure_cogs_key, region=azure_cogs_region ) except ImportError: raise ImportError( "azure-cognitiveservices-speech is not installed. " "Run `pip install azure-cognitiveservices-speech` to install." ) return values def _continuous_recognize(self, speech_recognizer: Any) -> str: done = False text = "" def stop_cb(evt: Any) -> None: """callback that stop continuous recognition""" speech_recognizer.stop_continuous_recognition_async() nonlocal done done = True def retrieve_cb(evt: Any) -> None: """callback that retrieves the intermediate recognition results""" nonlocal text text += evt.result.text # retrieve text on recognized events speech_recognizer.recognized.connect(retrieve_cb) # stop continuous recognition on either session stopped or canceled events speech_recognizer.session_stopped.connect(stop_cb) speech_recognizer.canceled.connect(stop_cb) # Start continuous speech recognition speech_recognizer.start_continuous_recognition_async() while not done: time.sleep(0.5) return text def _speech2text(self, audio_path: str, speech_language: str) -> str: try: import azure.cognitiveservices.speech as speechsdk
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html
dc1cfbb25756-2
try: import azure.cognitiveservices.speech as speechsdk except ImportError: pass audio_src_type = detect_file_src_type(audio_path) if audio_src_type == "local": audio_config = speechsdk.AudioConfig(filename=audio_path) elif audio_src_type == "remote": tmp_audio_path = download_audio_from_url(audio_path) audio_config = speechsdk.AudioConfig(filename=tmp_audio_path) else: raise ValueError(f"Invalid audio path: {audio_path}") self.speech_config.speech_recognition_language = speech_language speech_recognizer = speechsdk.SpeechRecognizer(self.speech_config, audio_config) return self._continuous_recognize(speech_recognizer) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" try: text = self._speech2text(query, self.speech_language) return text except Exception as e: raise RuntimeError(f"Error while running AzureCogsSpeech2TextTool: {e}") async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("AzureCogsSpeech2TextTool does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html
fe89b7dad17b-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
fe89b7dad17b-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
fe89b7dad17b-2
res_dict["objects"] = [obj.name for obj in result.objects] if result.tags is not None: res_dict["tags"] = [tag.name for tag in result.tags] if result.text is not None: res_dict["text"] = [line.content for line in result.text.lines] else: error_details = sdk.ImageAnalysisErrorDetails.from_result(result) raise RuntimeError( f"Image analysis failed.\n" f"Reason: {error_details.reason}\n" f"Details: {error_details.message}" ) return res_dict def _format_image_analysis_result(self, image_analysis_result: Dict) -> str: formatted_result = [] if "caption" in image_analysis_result: formatted_result.append("Caption: " + image_analysis_result["caption"]) if ( "objects" in image_analysis_result and len(image_analysis_result["objects"]) > 0 ): formatted_result.append( "Objects: " + ", ".join(image_analysis_result["objects"]) ) if "tags" in image_analysis_result and len(image_analysis_result["tags"]) > 0: formatted_result.append("Tags: " + ", ".join(image_analysis_result["tags"])) if "text" in image_analysis_result and len(image_analysis_result["text"]) > 0: formatted_result.append("Text: " + ", ".join(image_analysis_result["text"])) return "\n".join(formatted_result) def _run( self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Use the tool.""" try: image_analysis_result = self._image_analysis(query)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
fe89b7dad17b-3
try: image_analysis_result = self._image_analysis(query) if not image_analysis_result: return "No good image analysis result was found" return self._format_image_analysis_result(image_analysis_result) except Exception as e: raise RuntimeError(f"Error while running AzureCogsImageAnalysisTool: {e}") async def _arun( self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Use the tool asynchronously.""" raise NotImplementedError("AzureCogsImageAnalysisTool does not support async")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
9fd5f2a4f3d3-0
Source code for langchain.tools.openapi.utils.api_models """Pydantic models for parsing an OpenAPI spec.""" import logging from enum import Enum from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union from openapi_schema_pydantic import MediaType, Parameter, Reference, RequestBody, Schema from pydantic import BaseModel, Field from langchain.tools.openapi.utils.openapi_utils import HTTPVerb, OpenAPISpec logger = logging.getLogger(__name__) PRIMITIVE_TYPES = { "integer": int, "number": float, "string": str, "boolean": bool, "array": List, "object": Dict, "null": None, } # See https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterIn # for more info. [docs]class APIPropertyLocation(Enum): """The location of the property.""" QUERY = "query" PATH = "path" HEADER = "header" COOKIE = "cookie" # Not yet supported [docs] @classmethod def from_str(cls, location: str) -> "APIPropertyLocation": """Parse an APIPropertyLocation.""" try: return cls(location) except ValueError: raise ValueError( f"Invalid APIPropertyLocation. Valid values are {cls.__members__}" ) _SUPPORTED_MEDIA_TYPES = ("application/json",) SUPPORTED_LOCATIONS = { APIPropertyLocation.QUERY, APIPropertyLocation.PATH, } INVALID_LOCATION_TEMPL = ( 'Unsupported APIPropertyLocation "{location}"' " for parameter {name}. "
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-1
'Unsupported APIPropertyLocation "{location}"' " for parameter {name}. " + f"Valid values are {[loc.value for loc in SUPPORTED_LOCATIONS]}" ) SCHEMA_TYPE = Union[str, Type, tuple, None, Enum] [docs]class APIPropertyBase(BaseModel): """Base model for an API property.""" # The name of the parameter is required and is case-sensitive. # If "in" is "path", the "name" field must correspond to a template expression # within the path field in the Paths Object. # If "in" is "header" and the "name" field is "Accept", "Content-Type", # or "Authorization", the parameter definition is ignored. # For all other cases, the "name" corresponds to the parameter # name used by the "in" property. name: str = Field(alias="name") """The name of the property.""" required: bool = Field(alias="required") """Whether the property is required.""" type: SCHEMA_TYPE = Field(alias="type") """The type of the property. Either a primitive type, a component/parameter type, or an array or 'object' (dict) of the above.""" default: Optional[Any] = Field(alias="default", default=None) """The default value of the property.""" description: Optional[str] = Field(alias="description", default=None) """The description of the property.""" [docs]class APIProperty(APIPropertyBase): """A model for a property in the query, path, header, or cookie params.""" location: APIPropertyLocation = Field(alias="location") """The path/how it's being passed to the endpoint.""" @staticmethod
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-2
"""The path/how it's being passed to the endpoint.""" @staticmethod def _cast_schema_list_type(schema: Schema) -> Optional[Union[str, Tuple[str, ...]]]: type_ = schema.type if not isinstance(type_, list): return type_ else: return tuple(type_) @staticmethod def _get_schema_type_for_enum(parameter: Parameter, schema: Schema) -> Enum: """Get the schema type when the parameter is an enum.""" param_name = f"{parameter.name}Enum" return Enum(param_name, {str(v): v for v in schema.enum}) @staticmethod def _get_schema_type_for_array( schema: Schema, ) -> Optional[Union[str, Tuple[str, ...]]]: items = schema.items if isinstance(items, Schema): schema_type = APIProperty._cast_schema_list_type(items) elif isinstance(items, Reference): ref_name = items.ref.split("/")[-1] schema_type = ref_name # TODO: Add ref definitions to make his valid else: raise ValueError(f"Unsupported array items: {items}") if isinstance(schema_type, str): # TODO: recurse schema_type = (schema_type,) return schema_type @staticmethod def _get_schema_type(parameter: Parameter, schema: Optional[Schema]) -> SCHEMA_TYPE: if schema is None: return None schema_type: SCHEMA_TYPE = APIProperty._cast_schema_list_type(schema) if schema_type == "array": schema_type = APIProperty._get_schema_type_for_array(schema) elif schema_type == "object": # TODO: Resolve array and object types to components. raise NotImplementedError("Objects not yet supported")
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-3
raise NotImplementedError("Objects not yet supported") elif schema_type in PRIMITIVE_TYPES: if schema.enum: schema_type = APIProperty._get_schema_type_for_enum(parameter, schema) else: # Directly use the primitive type pass else: raise NotImplementedError(f"Unsupported type: {schema_type}") return schema_type @staticmethod def _validate_location(location: APIPropertyLocation, name: str) -> None: if location not in SUPPORTED_LOCATIONS: raise NotImplementedError( INVALID_LOCATION_TEMPL.format(location=location, name=name) ) @staticmethod def _validate_content(content: Optional[Dict[str, MediaType]]) -> None: if content: raise ValueError( "API Properties with media content not supported. " "Media content only supported within APIRequestBodyProperty's" ) @staticmethod def _get_schema(parameter: Parameter, spec: OpenAPISpec) -> Optional[Schema]: schema = parameter.param_schema if isinstance(schema, Reference): schema = spec.get_referenced_schema(schema) elif schema is None: return None elif not isinstance(schema, Schema): raise ValueError(f"Error dereferencing schema: {schema}") return schema [docs] @staticmethod def is_supported_location(location: str) -> bool: """Return whether the provided location is supported.""" try: return APIPropertyLocation.from_str(location) in SUPPORTED_LOCATIONS except ValueError: return False [docs] @classmethod def from_parameter(cls, parameter: Parameter, spec: OpenAPISpec) -> "APIProperty": """Instantiate from an OpenAPI Parameter.""" location = APIPropertyLocation.from_str(parameter.param_in)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-4
location = APIPropertyLocation.from_str(parameter.param_in) cls._validate_location( location, parameter.name, ) cls._validate_content(parameter.content) schema = cls._get_schema(parameter, spec) schema_type = cls._get_schema_type(parameter, schema) default_val = schema.default if schema is not None else None return cls( name=parameter.name, location=location, default=default_val, description=parameter.description, required=parameter.required, type=schema_type, ) [docs]class APIRequestBodyProperty(APIPropertyBase): """A model for a request body property.""" properties: List["APIRequestBodyProperty"] = Field(alias="properties") """The sub-properties of the property.""" # This is useful for handling nested property cycles. # We can define separate types in that case. references_used: List[str] = Field(alias="references_used") """The references used by the property.""" @classmethod def _process_object_schema( cls, schema: Schema, spec: OpenAPISpec, references_used: List[str] ) -> Tuple[Union[str, List[str], None], List["APIRequestBodyProperty"]]: properties = [] required_props = schema.required or [] if schema.properties is None: raise ValueError( f"No properties found when processing object schema: {schema}" ) for prop_name, prop_schema in schema.properties.items(): if isinstance(prop_schema, Reference): ref_name = prop_schema.ref.split("/")[-1] if ref_name not in references_used: references_used.append(ref_name) prop_schema = spec.get_referenced_schema(prop_schema) else: continue
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-5
prop_schema = spec.get_referenced_schema(prop_schema) else: continue properties.append( cls.from_schema( schema=prop_schema, name=prop_name, required=prop_name in required_props, spec=spec, references_used=references_used, ) ) return schema.type, properties @classmethod def _process_array_schema( cls, schema: Schema, name: str, spec: OpenAPISpec, references_used: List[str] ) -> str: items = schema.items if items is not None: if isinstance(items, Reference): ref_name = items.ref.split("/")[-1] if ref_name not in references_used: references_used.append(ref_name) items = spec.get_referenced_schema(items) else: pass return f"Array<{ref_name}>" else: pass if isinstance(items, Schema): array_type = cls.from_schema( schema=items, name=f"{name}Item", required=True, # TODO: Add required spec=spec, references_used=references_used, ) return f"Array<{array_type.type}>" return "array" [docs] @classmethod def from_schema( cls, schema: Schema, name: str, required: bool, spec: OpenAPISpec, references_used: Optional[List[str]] = None, ) -> "APIRequestBodyProperty": """Recursively populate from an OpenAPI Schema.""" if references_used is None: references_used = [] schema_type = schema.type
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-6
references_used = [] schema_type = schema.type properties: List[APIRequestBodyProperty] = [] if schema_type == "object" and schema.properties: schema_type, properties = cls._process_object_schema( schema, spec, references_used ) elif schema_type == "array": schema_type = cls._process_array_schema(schema, name, spec, references_used) elif schema_type in PRIMITIVE_TYPES: # Use the primitive type directly pass elif schema_type is None: # No typing specified/parsed. WIll map to 'any' pass else: raise ValueError(f"Unsupported type: {schema_type}") return cls( name=name, required=required, type=schema_type, default=schema.default, description=schema.description, properties=properties, references_used=references_used, ) [docs]class APIRequestBody(BaseModel): """A model for a request body.""" description: Optional[str] = Field(alias="description") """The description of the request body.""" properties: List[APIRequestBodyProperty] = Field(alias="properties") # E.g., application/json - we only support JSON at the moment. media_type: str = Field(alias="media_type") """The media type of the request body.""" @classmethod def _process_supported_media_type( cls, media_type_obj: MediaType, spec: OpenAPISpec, ) -> List[APIRequestBodyProperty]: """Process the media type of the request body.""" references_used = [] schema = media_type_obj.media_type_schema if isinstance(schema, Reference):
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-7
schema = media_type_obj.media_type_schema if isinstance(schema, Reference): references_used.append(schema.ref.split("/")[-1]) schema = spec.get_referenced_schema(schema) if schema is None: raise ValueError( f"Could not resolve schema for media type: {media_type_obj}" ) api_request_body_properties = [] required_properties = schema.required or [] if schema.type == "object" and schema.properties: for prop_name, prop_schema in schema.properties.items(): if isinstance(prop_schema, Reference): prop_schema = spec.get_referenced_schema(prop_schema) api_request_body_properties.append( APIRequestBodyProperty.from_schema( schema=prop_schema, name=prop_name, required=prop_name in required_properties, spec=spec, ) ) else: api_request_body_properties.append( APIRequestBodyProperty( name="body", required=True, type=schema.type, default=schema.default, description=schema.description, properties=[], references_used=references_used, ) ) return api_request_body_properties [docs] @classmethod def from_request_body( cls, request_body: RequestBody, spec: OpenAPISpec ) -> "APIRequestBody": """Instantiate from an OpenAPI RequestBody.""" properties = [] for media_type, media_type_obj in request_body.content.items(): if media_type not in _SUPPORTED_MEDIA_TYPES: continue api_request_body_properties = cls._process_supported_media_type( media_type_obj, spec, ) properties.extend(api_request_body_properties) return cls( description=request_body.description,
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-8
return cls( description=request_body.description, properties=properties, media_type=media_type, ) [docs]class APIOperation(BaseModel): """A model for a single API operation.""" operation_id: str = Field(alias="operation_id") """The unique identifier of the operation.""" description: Optional[str] = Field(alias="description") """The description of the operation.""" base_url: str = Field(alias="base_url") """The base URL of the operation.""" path: str = Field(alias="path") """The path of the operation.""" method: HTTPVerb = Field(alias="method") """The HTTP method of the operation.""" properties: Sequence[APIProperty] = Field(alias="properties") # TODO: Add parse in used components to be able to specify what type of # referenced object it is. # """The properties of the operation.""" # components: Dict[str, BaseModel] = Field(alias="components") request_body: Optional[APIRequestBody] = Field(alias="request_body") """The request body of the operation.""" @staticmethod def _get_properties_from_parameters( parameters: List[Parameter], spec: OpenAPISpec ) -> List[APIProperty]: """Get the properties of the operation.""" properties = [] for param in parameters: if APIProperty.is_supported_location(param.param_in): properties.append(APIProperty.from_parameter(param, spec)) elif param.required: raise ValueError( INVALID_LOCATION_TEMPL.format( location=param.param_in, name=param.name ) ) else: logger.warning( INVALID_LOCATION_TEMPL.format(
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-9
) else: logger.warning( INVALID_LOCATION_TEMPL.format( location=param.param_in, name=param.name ) + " Ignoring optional parameter" ) pass return properties [docs] @classmethod def from_openapi_url( cls, spec_url: str, path: str, method: str, ) -> "APIOperation": """Create an APIOperation from an OpenAPI URL.""" spec = OpenAPISpec.from_url(spec_url) return cls.from_openapi_spec(spec, path, method) [docs] @classmethod def from_openapi_spec( cls, spec: OpenAPISpec, path: str, method: str, ) -> "APIOperation": """Create an APIOperation from an OpenAPI spec.""" operation = spec.get_operation(path, method) parameters = spec.get_parameters_for_operation(operation) properties = cls._get_properties_from_parameters(parameters, spec) operation_id = OpenAPISpec.get_cleaned_operation_id(operation, path, method) request_body = spec.get_request_body_for_operation(operation) api_request_body = ( APIRequestBody.from_request_body(request_body, spec) if request_body is not None else None ) description = operation.description or operation.summary if not description and spec.paths is not None: description = spec.paths[path].description or spec.paths[path].summary return cls( operation_id=operation_id, description=description, base_url=spec.base_url, path=path, method=method, properties=properties, request_body=api_request_body, )
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-10
properties=properties, request_body=api_request_body, ) [docs] @staticmethod def ts_type_from_python(type_: SCHEMA_TYPE) -> str: if type_ is None: # TODO: Handle Nones better. These often result when # parsing specs that are < v3 return "any" elif isinstance(type_, str): return { "str": "string", "integer": "number", "float": "number", "date-time": "string", }.get(type_, type_) elif isinstance(type_, tuple): return f"Array<{APIOperation.ts_type_from_python(type_[0])}>" elif isinstance(type_, type) and issubclass(type_, Enum): return " | ".join([f"'{e.value}'" for e in type_]) else: return str(type_) def _format_nested_properties( self, properties: List[APIRequestBodyProperty], indent: int = 2 ) -> str: """Format nested properties.""" formatted_props = [] for prop in properties: prop_name = prop.name prop_type = self.ts_type_from_python(prop.type) prop_required = "" if prop.required else "?" prop_desc = f"/* {prop.description} */" if prop.description else "" if prop.properties: nested_props = self._format_nested_properties( prop.properties, indent + 2 ) prop_type = f"{{\n{nested_props}\n{' ' * indent}}}" formatted_props.append( f"{prop_desc}\n{' ' * indent}{prop_name}{prop_required}: {prop_type}," ) return "\n".join(formatted_props)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
9fd5f2a4f3d3-11
) return "\n".join(formatted_props) [docs] def to_typescript(self) -> str: """Get typescript string representation of the operation.""" operation_name = self.operation_id params = [] if self.request_body: formatted_request_body_props = self._format_nested_properties( self.request_body.properties ) params.append(formatted_request_body_props) for prop in self.properties: prop_name = prop.name prop_type = self.ts_type_from_python(prop.type) prop_required = "" if prop.required else "?" prop_desc = f"/* {prop.description} */" if prop.description else "" params.append(f"{prop_desc}\n\t\t{prop_name}{prop_required}: {prop_type},") formatted_params = "\n".join(params).strip() description_str = f"/* {self.description} */" if self.description else "" typescript_definition = f""" {description_str} type {operation_name} = (_: {{ {formatted_params} }}) => any; """ return typescript_definition.strip() @property def query_params(self) -> List[str]: return [ property.name for property in self.properties if property.location == APIPropertyLocation.QUERY ] @property def path_params(self) -> List[str]: return [ property.name for property in self.properties if property.location == APIPropertyLocation.PATH ] @property def body_params(self) -> List[str]: if self.request_body is None: return [] return [prop.name for prop in self.request_body.properties]
https://api.python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
28a8b85d3ce3-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
28a8b85d3ce3-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
6918288cb21d-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
6918288cb21d-1
return context.pages[-1] [docs]def create_async_playwright_browser(headless: bool = True) -> AsyncBrowser: """ Create a 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: """ 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
46488152fb9d-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
46488152fb9d-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
9ab7688ab9e7-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
9ab7688ab9e7-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
1a3569fbdb7a-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
1a3569fbdb7a-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
9be64c2b81e2-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
9be64c2b81e2-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
9be64c2b81e2-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
58c85248a116-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
58c85248a116-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
f9c66e8653f3-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
2cc0da41cdcb-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
2cc0da41cdcb-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
c198df582014-0
Source code for langchain.tools.shell.tool import asyncio import platform import warnings from typing import List, Optional, Type, Union from pydantic import BaseModel, Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.bash import BashProcess [docs]class ShellInput(BaseModel): """Commands for the Bash Shell tool.""" commands: Union[str, List[str]] = Field( ..., description="List of shell commands to run. Deserialized using json.loads", ) """List of shell commands to run.""" @root_validator def _validate_commands(cls, values: dict) -> dict: """Validate commands.""" # TODO: Add real validators commands = values.get("commands") if not isinstance(commands, list): values["commands"] = [commands] # Warn that the bash tool is not safe warnings.warn( "The shell tool has no safeguards by default. Use at your own risk." ) return values def _get_default_bash_processs() -> BashProcess: """Get file path from string.""" return BashProcess(return_err_output=True) def _get_platform() -> str: """Get platform.""" system = platform.system() if system == "Darwin": return "MacOS" return system [docs]class ShellTool(BaseTool): """Tool to run shell commands.""" process: BashProcess = Field(default_factory=_get_default_bash_processs) """Bash process to run commands.""" name: str = "terminal" """Name of tool."""
https://api.python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html
c198df582014-1
name: str = "terminal" """Name of tool.""" description: str = f"Run shell commands on this {_get_platform()} machine." """Description of tool.""" args_schema: Type[BaseModel] = ShellInput """Schema for input arguments.""" def _run( self, commands: Union[str, List[str]], run_manager: Optional[CallbackManagerForToolRun] = None, ) -> str: """Run commands and return final output.""" return self.process.run(commands) async def _arun( self, commands: Union[str, List[str]], run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run commands asynchronously and return final output.""" return await asyncio.get_event_loop().run_in_executor( None, self.process.run, commands )
https://api.python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html
93cf69b51c00-0
Source code for langchain.tools.metaphor_search.tool """Tool for the Metaphor search API.""" from typing import Dict, List, Optional, Union from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.metaphor_search import MetaphorSearchAPIWrapper [docs]class MetaphorSearchResults(BaseTool): """Tool that has capability to query the Metaphor Search API and get back json.""" name = "metaphor_search_results_json" description = ( "A wrapper around Metaphor Search. " "Input should be a Metaphor-optimized query. " "Output is a JSON array of the query results" ) api_wrapper: MetaphorSearchAPIWrapper def _run( self, query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None, run_manager: Optional[CallbackManagerForToolRun] = None, ) -> Union[List[Dict], str]: """Use the tool.""" try: return self.api_wrapper.results( query, num_results, include_domains, exclude_domains, start_crawl_date, end_crawl_date, start_published_date, end_published_date, ) except Exception as e: return repr(e) async def _arun(
https://api.python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html
93cf69b51c00-1
return repr(e) async def _arun( self, query: str, num_results: int, include_domains: Optional[List[str]] = None, exclude_domains: Optional[List[str]] = None, start_crawl_date: Optional[str] = None, end_crawl_date: Optional[str] = None, start_published_date: Optional[str] = None, end_published_date: Optional[str] = None, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> Union[List[Dict], str]: """Use the tool asynchronously.""" try: return await self.api_wrapper.results_async( query, num_results, include_domains, exclude_domains, start_crawl_date, end_crawl_date, start_published_date, end_published_date, ) except Exception as e: return repr(e)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html
5df74d70d560-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
8dd6ed266abc-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
8dd6ed266abc-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
a3da68b1acc7-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
fe89cc7ff80f-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
fe89cc7ff80f-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
f4c48d19e1c0-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
b6baef693c51-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
b6baef693c51-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
c3cb3b6bf9bd-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
c3cb3b6bf9bd-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
8bc6fda779eb-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
7e77a6af34f5-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
7e77a6af34f5-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
1d81dac07857-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
1d81dac07857-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
1d81dac07857-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
1d81dac07857-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