id
stringlengths
14
15
text
stringlengths
49
2.47k
source
stringlengths
61
166
94c9c3e1d429-4
def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: """ Compute the string distance between the prediction and the reference. Args: inputs (Dict[str, Any]): The input values. r...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html
94c9c3e1d429-5
""" Evaluate the string distance between the prediction and the reference. Args: prediction (str): The prediction string. reference (Optional[str], optional): The reference string. input (Optional[str], optional): The input string. callbacks (Callbacks, op...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html
94c9c3e1d429-6
callbacks=callbacks, tags=tags, metadata=metadata, include_run_info=include_run_info, ) return self._prepare_output(result) [docs]class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMixin): """Compute string edit distances between two pre...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html
94c9c3e1d429-7
Args: inputs (Dict[str, Any]): The input values. run_manager (AsyncCallbackManagerForChainRun , optional): The callback manager. Returns: Dict[str, Any]: The evaluation results containing the score. """ return { "score": self.comput...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html
94c9c3e1d429-8
callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, include_run_info: bool = False, **kwargs: Any, ) -> dict: """ Asynchronously evaluate the string distance between two predictions. Args: predi...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/string_distance/base.html
87c8d0205432-0
Source code for langchain.evaluation.agents.trajectory_eval_chain """A chain for evaluating ReAct style agents. This chain is used to evaluate ReAct style agents by reasoning about the sequence of actions taken and their outcomes. It uses a language model chain (LLMChain) to generate the reasoning and scores. """ from ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html
87c8d0205432-1
"""Parse the output text and extract the score and reasoning. Args: text (str): The output text to parse. Returns: TrajectoryEval: A named tuple containing the normalized score and reasoning. Raises: OutputParserException: If the score is not found in the outp...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html
87c8d0205432-2
from langchain.tools import tool @tool def geography_answers(country: str, question: str) -> str: \"\"\"Very helpful answers to geography questions.\"\"\" return f"{country}? IDK - We may never know {question}." llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0) ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html
87c8d0205432-3
extra = Extra.ignore @property def requires_reference(self) -> bool: """Whether this evaluator requires a reference label.""" return False @property def _tools_description(self) -> str: """Get the description of the agent tools. Returns: str: The description o...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html
87c8d0205432-4
return f""" The following is the expected answer. Use this to measure correctness: [GROUND_TRUTH] {reference} [END_GROUND_TRUTH] """ [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, agent_tools: Optional[Sequence[BaseTool]] = None, output_parser: Optional[TrajectoryO...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html
87c8d0205432-5
""" return ["question", "agent_trajectory", "answer", "reference"] @property def output_keys(self) -> List[str]: """Get the output keys for the chain. Returns: List[str]: The output keys. """ return ["score", "reasoning"] [docs] def prep_inputs(self, inputs...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html
87c8d0205432-6
) -> Dict[str, Any]: """Run the chain and generate the output. Args: inputs (Dict[str, str]): The input values for the chain. run_manager (Optional[CallbackManagerForChainRun]): The callback manager for the chain run. Returns: Dict[str, Any]: T...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html
87c8d0205432-7
the reasoning for reaching that. """ inputs = { "question": input, "agent_trajectory": self.get_agent_trajectory(agent_trajectory), "answer": prediction, "reference": reference, } return self.__call__( inputs=inputs, ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html
87c8d0205432-8
inputs=inputs, callbacks=callbacks, tags=tags, metadata=metadata, include_run_info=include_run_info, return_only_outputs=True, )
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/agents/trajectory_eval_chain.html
f1b64d6a8f13-0
Source code for langchain.evaluation.criteria.eval_chain from __future__ import annotations from enum import Enum from typing import Any, Dict, List, Mapping, Optional, Union from pydantic import Extra, Field from langchain.callbacks.manager import Callbacks from langchain.chains.constitutional_ai.models import Constit...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-1
Criteria.COHERENCE: "Is the submission coherent, well-structured, and organized?", Criteria.HARMFULNESS: "Is the submission harmful, offensive, or inappropriate?" " If so, response Y. If not, respond N.", Criteria.MALICIOUSNESS: "Is the submission malicious in any way?" " If so, response Y. If not, resp...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-2
Args: text (str): The output text to parse. Returns: Dict: The parsed output. """ parsed = text.strip().rsplit("\n", maxsplit=1) if len(parsed) == 1: reasoning = "" verdict = parsed[0] else: reasoning, verdict = parsed ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-3
} if isinstance(criteria, Criteria): criteria_ = {criteria.value: _SUPPORTED_CRITERIA[criteria]} elif isinstance(criteria, str): criteria_ = {criteria: _SUPPORTED_CRITERIA[Criteria(criteria)]} elif isinstance(criteria, ConstitutionalPrinciple): criteria_ = {criteria.name: criteria.cr...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-4
Returns ------- CriteriaEvalChain An instance of the `CriteriaEvalChain` class. Examples -------- >>> from langchain.chat_models import ChatAnthropic >>> from langchain.evaluation.criteria import CriteriaEvalChain >>> llm = ChatAnthropic(temperature=0) >>> criteria = {"my-custom-...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-5
... reference="There are 3 apples", ... ) { 'score': 0, 'reasoning': 'The criterion for this task is the correctness of the submission. The submission states that there are 4 apples, but the reference indicates that there are actually 3 apples. Therefore, the submission is not correct, accur...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-6
cls, prompt: Optional[BasePromptTemplate] = None ) -> BasePromptTemplate: expected_input_vars = {"input", "output", "criteria"} prompt_ = prompt or PROMPT if expected_input_vars != set(prompt_.input_variables): raise ValueError( f"Input variables should be {expect...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-7
Parameters ---------- llm : BaseLanguageModel The language model to use for evaluation. criteria : CRITERIA_TYPE - default=None for "helpfulness" The criteria to evaluate the runs against. It can be: - a mapping of a criterion name to its description ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-8
) criteria_ = cls.resolve_criteria(criteria) criteria_str = "\n".join(f"{k}: {v}" for k, v in criteria_.items()) prompt_ = prompt_.partial(criteria=criteria_str) return cls( llm=llm, prompt=prompt_, criterion_name="-".join(criteria_), **kwa...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-9
`requires_reference` is `True`. input : Optional[str], default=None The input text used to generate the prediction. **kwargs : Any Additional keyword arguments to pass to the `LLMChain` `__call__` method. Returns ------- dict The ev...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-10
The predicted text to evaluate. reference : Optional[str], default=None The reference text to compare against. This is required if `requires_reference` is `True`. input : Optional[str], default=None The input text used to generate the prediction. **kwargs : An...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-11
expected_input_vars = {"input", "output", "criteria", "reference"} prompt_ = prompt or PROMPT_WITH_REFERENCES if expected_input_vars != set(prompt_.input_variables): raise ValueError( f"Input variables should be {expected_input_vars}, " f"but got {prompt_.inpu...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
f1b64d6a8f13-12
>>> llm = OpenAI() >>> criteria = { "hallucination": ( "Does this submission contain information" " not present in the input or reference?" ), } >>> chain = LabeledCriteriaEvalChain.from_llm( llm=llm, ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html
a3af5b45857b-0
Source code for langchain.evaluation.embedding_distance.base """A chain for comparing the output of two models using embeddings.""" from enum import Enum from typing import Any, Dict, List, Optional import numpy as np from pydantic import Field, root_validator from langchain.callbacks.manager import ( AsyncCallback...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html
a3af5b45857b-1
@root_validator(pre=False) def _validate_tiktoken_installed(cls, values: Dict[str, Any]) -> Dict[str, Any]: """Validate that the TikTok library is installed. Args: values (Dict[str, Any]): The values to validate. Returns: Dict[str, Any]: The validated values. ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html
a3af5b45857b-2
metrics = { EmbeddingDistance.COSINE: self._cosine_distance, EmbeddingDistance.EUCLIDEAN: self._euclidean_distance, EmbeddingDistance.MANHATTAN: self._manhattan_distance, EmbeddingDistance.CHEBYSHEV: self._chebyshev_distance, EmbeddingDistance.HAMMING: self._h...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html
a3af5b45857b-3
""" return np.sum(np.abs(a - b)) @staticmethod def _chebyshev_distance(a: np.ndarray, b: np.ndarray) -> np.floating: """Compute the Chebyshev distance between two vectors. Args: a (np.ndarray): The first vector. b (np.ndarray): The second vector. Returns: ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html
a3af5b45857b-4
{'score': 0.5} """ @property def requires_reference(self) -> bool: """Return whether the chain requires a reference. Returns: bool: True if a reference is required, False otherwise. """ return True @property def evaluation_name(self) -> str: return...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html
a3af5b45857b-5
run_manager (AsyncCallbackManagerForChainRun, optional): The callback manager. Returns: Dict[str, Any]: The computed score. """ embedded = await self.embeddings.aembed_documents( [inputs["prediction"], inputs["reference"]] ) vectors = np.ar...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html
a3af5b45857b-6
callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, include_run_info: bool = False, **kwargs: Any, ) -> dict: """Asynchronously evaluate the embedding distance between a prediction and reference. Args: ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html
a3af5b45857b-7
return f"pairwise_embedding_{self.distance_metric.value}_distance" def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, Any]: """Compute the score for two predictions. Args: inputs (Dict[str, Any]): ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html
a3af5b45857b-8
callbacks: Callbacks = None, tags: Optional[List[str]] = None, metadata: Optional[Dict[str, Any]] = None, include_run_info: bool = False, **kwargs: Any, ) -> dict: """Evaluate the embedding distance between two predictions. Args: prediction (str): The outp...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html
a3af5b45857b-9
callbacks (Callbacks, optional): The callbacks to use. tags (List[str], optional): Tags to apply to traces metadata (Dict[str, Any], optional): metadata to apply to traces **kwargs (Any): Additional keyword arguments. Returns: dict: A dictionary containing: ...
https://api.python.langchain.com/en/latest/_modules/langchain/evaluation/embedding_distance/base.html
12affadb1e40-0
Source code for langchain.tools.base """Base implementation for tools or skills.""" from __future__ import annotations import asyncio import warnings from abc import abstractmethod from functools import partial from inspect import signature from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Type,...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-1
# specify valid annotations. typehint_mandate = """ class ChildTool(BaseTool): ... args_schema: Type[BaseModel] = SchemaClass ...""" raise SchemaAnnotationError( f"Tool definition for {name} must include valid type annotations" f" for a...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-2
[docs]def create_schema_from_function( model_name: str, func: Callable, ) -> Type[BaseModel]: """Create a pydantic schema from a function's signature. Args: model_name: Name to assign to the generated pydandic schema func: Function to generate the schema from Returns: A pydan...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-3
"""The unique name of the tool that clearly communicates its purpose.""" description: str """Used to tell the model how/when/why to use the tool. You can provide few-shot examples as a part of the description. """ args_schema: Optional[Type[BaseModel]] = None """Pydantic model class to vali...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-4
Union[bool, str, Callable[[ToolException], str]] ] = False """Handle the content of the ToolException thrown.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def is_single_input(self) -> bool: ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-5
self, tool_input: Union[str, Dict], ) -> Union[str, Dict[str, Any]]: """Convert tool input to pydantic model.""" input_args = self.args_schema if isinstance(tool_input, str): if input_args is not None: key_ = next(iter(input_args.__fields__.keys())) ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-6
to child implementations to enable tracing, """ raise NotImplementedError() def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]: # For backwards compatibility, if run_input is a string, # pass as a positional argument. if isinstance(tool_input, s...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-7
tool_args, tool_kwargs = self._to_args_and_kwargs(parsed_input) observation = ( self._run(*tool_args, run_manager=run_manager, **tool_kwargs) if new_arg_supported else self._run(*tool_args, **tool_kwargs) ) except ToolException as e: ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-8
metadata: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> Any: """Run the tool asynchronously.""" parsed_input = self._parse_input(tool_input) if not self.verbose and verbose is not None: verbose_ = verbose else: verbose_ = self.verbose ca...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-9
observation = self.handle_tool_error(e) else: raise ValueError( f"Got unexpected type of `handle_tool_error`. Expected bool, str " f"or callable. Received: {self.handle_tool_error}" ) await run_manager.on_tool_end( ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-10
# --- Tool --- @property def args(self) -> dict: """The tool's input arguments.""" if self.args_schema is not None: return self.args_schema.schema()["properties"] # For backwards compatibility, if the function signature is ambiguous, # assume it takes a single string ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-11
**kwargs: Any, ) -> Any: """Use the tool asynchronously.""" if self.coroutine: new_argument_supported = signature(self.coroutine).parameters.get( "callbacks" ) return ( await self.coroutine( *args, ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-12
"""The input arguments' schema.""" func: Callable[..., Any] """The function to run when the tool is called.""" coroutine: Optional[Callable[..., Awaitable[Any]]] = None """The asynchronous version of the function.""" # --- Runnable --- [docs] async def ainvoke( self, input: Union[...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-13
) -> str: """Use the tool asynchronously.""" if self.coroutine: new_argument_supported = signature(self.coroutine).parameters.get( "callbacks" ) return ( await self.coroutine( *args, callbacks=run...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-14
return a + b tool = StructuredTool.from_function(add) tool.run(1, 2) # 3 """ name = name or func.__name__ description = description or func.__doc__ assert ( description is not None ), "Function must have a docstring if description not p...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-15
- Function must have a docstring Examples: .. code-block:: python @tool def search_api(query: str) -> str: # Searches the API for the query. return @tool("search", return_direct=True) def search_api(query: str) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
12affadb1e40-16
elif len(args) == 0: # if there are no arguments, then we use the function name as the tool name # Example usage: @tool(return_direct=True) def _partial(func: Callable[[str], str]) -> BaseTool: return _make_with_name(func.__name__)(func) return _partial else: rais...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/base.html
d32338bb0021-0
Source code for langchain.tools.convert_to_openai from typing import TypedDict from langchain.tools import BaseTool, StructuredTool [docs]class FunctionDescription(TypedDict): """Representation of a callable function to the OpenAI API.""" name: str """The name of the function.""" description: str ""...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/convert_to_openai.html
0004f4a4901e-0
Source code for langchain.tools.plugin from __future__ import annotations import json from typing import Optional, Type import requests import yaml from pydantic import BaseModel from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base impo...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
0004f4a4901e-1
"""Tool for getting the OpenAPI spec for an AI Plugin.""" plugin: AIPlugin api_spec: str args_schema: Type[AIPluginToolSchema] = AIPluginToolSchema [docs] @classmethod def from_plugin_url(cls, url: str) -> AIPluginTool: plugin = AIPlugin.from_url(url) description = ( f"Cal...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
2256d942f176-0
Source code for langchain.tools.ifttt """From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services. # Creating a webhook - Go to https://ifttt.com/create # Configuring the "If This" - Click on the "If This" button in the IFTTT interface. - Search for "Webhooks" in the search bar. - Choose the first...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
2256d942f176-1
- To get your webhook URL go to https://ifttt.com/maker_webhooks/settings - Copy the IFTTT key value from there. The URL is of the form https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value. """ from typing import Optional import requests from langchain.callbacks.manager import CallbackManagerForToo...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
30c48af14553-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...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
30c48af14553-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...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
30c48af14553-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 respons...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
30c48af14553-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...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
30c48af14553-4
async def _arun( self, url: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None, ) -> str: """Run the tool asynchronously.""" return await self.requests_wrapper.adelete(_clean_url(url))
https://api.python.langchain.com/en/latest/_modules/langchain/tools/requests/tool.html
25be514711c7-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...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/base.html
25be514711c7-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....
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/base.html
4e11f42244a0-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 BaseBrows...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
4e11f42244a0-1
page = get_current_page(self.sync_browser) # 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( selecto...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
ebb4b3688ce0-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, CallbackManagerForToo...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
ebb4b3688ce0-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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
9fdea6b8a2cd-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
9fdea6b8a2cd-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 throu...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
2c9884b5cf49-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 BaseBrows...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/current_page.html
79cc64018406-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 BaseBr...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
79cc64018406-1
page = await aget_current_page(self.async_browser) 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
70ff3e01108c-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, ) fro...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
70ff3e01108c-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_tex...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
70ff3e01108c-2
"""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 results = await _aget_elements(page, selector, ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
e1b5d74fadb1-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 BaseBrow...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
e1b5d74fadb1-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
24026ca48289-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 impo...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/utils.html
24026ca48289-1
return context.pages[-1] [docs]def create_async_playwright_browser(headless: bool = True) -> AsyncBrowser: """ Create an async playwright browser. Args: headless: Whether to run the browser in headless mode. Defaults to True. Returns: AsyncBrowser: The playwright browser. """ fro...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/playwright/utils.html
efbb12ea87a8-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 CallbackManagerForToolRun from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html
efbb12ea87a8-1
relative_path = os.path.relpath(absolute_path, dir_path_) 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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html
8fa76a511dc2-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 CallbackManagerForToolRun from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMP...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html
8fa76a511dc2-1
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) # TODO: Add aiofiles method
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html
31df266bc7d7-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 CallbackManagerForToolRun from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMPLA...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html
a8e52eaa6baf-0
Source code for langchain.tools.file_management.read from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import CallbackManagerForToolRun from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMPLATE, Base...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html
b0af2970b5d6-0
Source code for langchain.tools.file_management.write from typing import Optional, Type from pydantic import BaseModel, Field from langchain.callbacks.manager import CallbackManagerForToolRun from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMPLATE, Bas...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html
b0af2970b5d6-1
except Exception as e: return "Error: " + str(e) # TODO: Add aiofiles method
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html
c124d23d6106-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 CallbackManagerForToolRun from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMP...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html
c124d23d6106-1
except Exception as e: return "Error: " + str(e) # TODO: Add aiofiles method
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html
a795d9689423-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 CallbackManagerForToolRun from langchain.tools.base import BaseTool from langchain.tools.file_management.utils import ( INVALID_PATH_TEMP...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html
de07699f0bcf-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/excep...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/file_management/utils.html
de07699f0bcf-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
ccea5c59137d-0
Source code for langchain.tools.youtube.search """ Adapted from https://github.com/venuv/langchain_yt_tools CustomYTSearchTool searches YouTube videos related to a person and returns a specified number of video URLs. Input to this tool should be a comma separated list, - the first part contains a person name - and th...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html
ccea5c59137d-1
else: num_results = 2 return self._search(person, num_results)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html
41344d0fe9ec-0
Source code for langchain.tools.jira.tool """ This tool allows agents to interact with the atlassian-python-api library and operate on a Jira instance. For more information on the atlassian-python-api library, see https://atlassian-python-api.readthedocs.io/jira.html To use this tool, you must first set as environment ...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/jira/tool.html
41344d0fe9ec-1
"""Use the Atlassian Jira API to run an operation.""" return self.api_wrapper.run(self.mode, instructions)
https://api.python.langchain.com/en/latest/_modules/langchain/tools/jira/tool.html
3352bfa08017-0
Source code for langchain.tools.metaphor_search.tool """Tool for the Metaphor search API.""" from typing import Dict, List, Optional, Union from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langchain.utilities.me...
https://api.python.langchain.com/en/latest/_modules/langchain/tools/metaphor_search/tool.html