id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
7456cbc6e938-0
Source code for langchain.retrievers.document_compressors.chain_filter """Filter that uses an LLM to drop documents that aren't relevant to the query.""" from typing import Any, Callable, Dict, Optional, Sequence from langchain import BasePromptTemplate, LLMChain, PromptTemplate from langchain.base_language import Base...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html
7456cbc6e938-1
include_doc = self.llm_chain.predict_and_parse(**_input) if include_doc: filtered_docs.append(doc) return filtered_docs [docs] async def acompress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Filter down documents.""" ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html
70778b12a261-0
Source code for langchain.retrievers.document_compressors.cohere_rerank from __future__ import annotations from typing import TYPE_CHECKING, Dict, Sequence from pydantic import Extra, root_validator from langchain.retrievers.document_compressors.base import BaseDocumentCompressor from langchain.schema import Document f...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
70778b12a261-1
) -> Sequence[Document]: doc_list = list(documents) _docs = [d.page_content for d in doc_list] results = self.client.rerank( model=self.model, query=query, documents=_docs, top_n=self.top_n ) final_results = [] for r in results: doc = doc_list[r.in...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
eb7ebb370af0-0
Source code for langchain.retrievers.document_compressors.chain_extract """DocumentFilter that uses an LLM chain to extract the relevant parts of documents.""" from __future__ import annotations import asyncio from typing import Any, Callable, Dict, Optional, Sequence from langchain import LLMChain, PromptTemplate from...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
eb7ebb370af0-1
[docs] def compress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Compress page content of raw documents.""" compressed_docs = [] for doc in documents: _input = self.get_input(query, doc) output = self.llm_chain.pred...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
eb7ebb370af0-2
_get_input = get_input if get_input is not None else default_get_input llm_chain = LLMChain(llm=llm, prompt=_prompt, **(llm_chain_kwargs or {})) return cls(llm_chain=llm_chain, get_input=_get_input) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
36c948be9070-0
Source code for langchain.retrievers.self_query.base """Retriever that generates and executes structured queries over its own data source.""" from typing import Any, Dict, List, Optional, Type, cast from pydantic import BaseModel, Field, root_validator from langchain import LLMChain from langchain.base_language import ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
36c948be9070-1
vectorstore: VectorStore """The underlying vector store from which documents will be retrieved.""" llm_chain: LLMChain """The LLMChain for generating the vector store queries.""" search_type: str = "similarity" """The search type to perform on the vector store.""" search_kwargs: dict = Field(def...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
36c948be9070-2
if structured_query.limit is not None: new_kwargs["k"] = structured_query.limit search_kwargs = {**self.search_kwargs, **new_kwargs} docs = self.vectorstore.search(new_query, self.search_type, **search_kwargs) return docs [docs] async def aget_relevant_documents(self, query: str) ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
36c948be9070-3
**kwargs, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
b5ba877206da-0
Source code for langchain.tools.base """Base implementation for tools or skills.""" from __future__ import annotations import warnings from abc import ABC, abstractmethod from inspect import signature from typing import Any, Awaitable, Callable, Dict, Optional, Tuple, Type, Union from pydantic import ( BaseModel, ...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-1
... args_schema: Type[BaseModel] = SchemaClass ...""" raise SchemaAnnotationError( f"Tool definition for {name} must include valid type annotations" f" for argument 'args_schema' to behave as expected.\n" f"Expected annotation of 'Type[...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-2
model_name: str, func: Callable, ) -> Type[BaseModel]: """Create a pydantic schema from a function's signature.""" validated = validate_arguments(func, config=_SchemaConfig) # type: ignore inferred_model = validated.model # type: ignore if "run_manager" in inferred_model.__fields__: del in...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-3
"""Deprecated. Please use callbacks instead.""" class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def is_single_input(self) -> bool: """Whether the tool only accepts a single input.""" keys = {k f...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-4
values["callbacks"] = values.pop("callback_manager", None) return values @abstractmethod def _run( self, *args: Any, **kwargs: Any, ) -> Any: """Use the tool. Add run_manager: Optional[CallbackManagerForToolRun] = None to child implementations to enabl...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-5
) # TODO: maybe also pass through run_manager is _run supports kwargs new_arg_supported = signature(self._run).parameters.get("run_manager") run_manager = callback_manager.on_tool_start( {"name": self.name, "description": self.description}, tool_input if isinstance(tool_i...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-6
run_manager = await callback_manager.on_tool_start( {"name": self.name, "description": self.description}, tool_input if isinstance(tool_input, str) else str(tool_input), color=start_color, **kwargs, ) try: # We then call the tool on the tool in...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-7
return {"tool_input": {"type": "string"}} def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]: """Convert tool input to pydantic model.""" args, kwargs = super()._to_args_and_kwargs(tool_input) # For backwards compatibility. The tool must be run with a single in...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-8
**kwargs, ) if new_argument_supported else await self.coroutine(*args, **kwargs) ) raise NotImplementedError("Tool does not support async") # TODO: this is for backwards compatibility, remove in future def __init__( self, name: str, fun...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-9
return self.args_schema.schema()["properties"] def _run( self, *args: Any, run_manager: Optional[CallbackManagerForToolRun] = None, **kwargs: Any, ) -> Any: """Use the tool.""" new_argument_supported = signature(self.func).parameters.get("callbacks") retur...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-10
) -> StructuredTool: name = name or func.__name__ description = description or func.__doc__ assert ( description is not None ), "Function must have a docstring if description not provided." # Description example: # search_api(query: str) - Searches the API for...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-11
# Searches the API for the query. return @tool("search", return_direct=True) def search_api(query: str) -> str: # Searches the API for the query. return """ def _make_with_name(tool_name: str) -> Callable: def _make_tool(func: Calla...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
b5ba877206da-12
# Example usage: @tool(return_direct=True) def _partial(func: Callable[[str], str]) -> BaseTool: return _make_with_name(func.__name__)(func) return _partial else: raise ValueError("Too many arguments for tool decorator") By Harrison Chase © Copyright 2023, Harrison Cha...
https://python.langchain.com/en/latest/_modules/langchain/tools/base.html
c4030203a3a3-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://python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
c4030203a3a3-1
plugin = AIPlugin.from_url(url) description = ( f"Call this tool to get the OpenAPI spec (and usage guide) " f"for interacting with the {plugin.name_for_human} API. " f"You should only call this ONCE! What is the " f"{plugin.name_for_human} API useful for? " ...
https://python.langchain.com/en/latest/_modules/langchain/tools/plugin.html
94ea951bc237-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://python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
94ea951bc237-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 ( AsyncCallbackMa...
https://python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html
04dd8e4daccd-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 WikipediaAPIWrap...
https://python.langchain.com/en/latest/_modules/langchain/tools/wikipedia/tool.html
a1be3a113671-0
Source code for langchain.tools.shell.tool import asyncio import platform import warnings from typing import List, Optional, Type, Union from pydantic import BaseModel, Field, root_validator from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.too...
https://python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html
a1be3a113671-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]], r...
https://python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html
d9777a65934e-0
Source code for langchain.tools.zapier.tool """## Zapier Natural Language Actions API \ Full docs here: https://nla.zapier.com/api/v1/docs **Zapier Natural Language Actions** gives you access to the 5k+ apps, 20k+ actions on Zapier's platform through a natural language API interface. NLA supports apps like Gmail, Sales...
https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
d9777a65934e-1
2. Use LLMChain to generate a draft reply to (1) 3. Use NLA to send the draft reply (2) to someone in Slack via direct message In code, below: ```python import os # get from https://platform.openai.com/ os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "") # get from https://nla.zapier.com/demo/provid...
https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
d9777a65934e-2
agent = initialize_agent( toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) agent.run(("Summarize the last email I received regarding Silicon Valley Bank. " "Send the summary to the #test-zapier channel in slack.")) ``` """ from typing import Any, Dict, Optional f...
https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
d9777a65934e-3
name = "" description = "" @root_validator def set_name_description(cls, values: Dict[str, Any]) -> Dict[str, Any]: zapier_description = values["zapier_description"] params_schema = values["params_schema"] if "instructions" in params_schema: del params_schema["instruction...
https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
d9777a65934e-4
) # other useful actions [docs]class ZapierNLAListActions(BaseTool): """ Args: None """ name = "Zapier NLA: List Actions" description = BASE_ZAPIER_TOOL_PROMPT + ( "This tool returns a list of the user's exposed actions." ) api_wrapper: ZapierNLAWrapper = Field(default_factor...
https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html
c2593ab8077a-0
Source code for langchain.tools.google_places.tool """Tool for the Google search API.""" from typing import Optional from pydantic import BaseModel, Field from langchain.callbacks.manager import ( AsyncCallbackManagerForToolRun, CallbackManagerForToolRun, ) from langchain.tools.base import BaseTool from langcha...
https://python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html
f1d2f9f9c732-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 langcha...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
f1d2f9f9c732-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.ImageAnalysis...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
f1d2f9f9c732-2
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) ...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
f1d2f9f9c732-3
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( s...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html
efbdab169c9d-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 ...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
efbdab169c9d-1
values, "azure_cogs_key", "AZURE_COGS_KEY" ) 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 AzureKeyC...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
efbdab169c9d-2
with open(document_path, "rb") as document: poller = self.doc_analysis_client.begin_analyze_document( "prebuilt-document", document ) elif document_src_type == "remote": poller = self.doc_analysis_client.begin_analyze_document_from_url( ...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
efbdab169c9d-3
run_manager: Optional[CallbackManagerForToolRun] = None, ) -> 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._...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html
85a48619d000-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, ) fro...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html
85a48619d000-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( ...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html
85a48619d000-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": ...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html
d71174ca4e74-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, )...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html
d71174ca4e74-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-cognitiveservi...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html
d71174ca4e74-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 Run...
https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html
262422d1789b-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...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html
262422d1789b-1
# TODO: Add aiofiles method raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html
8636214e2e7f-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 langc...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html
8636214e2e7f-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_pat...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html
87414318cb86-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_ma...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html
87414318cb86-1
raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html
5bc7c750cc7d-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.util...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html
5bc7c750cc7d-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 NotImplementedErr...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html
5e8d0c76609c-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_ma...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html
5e8d0c76609c-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 By Harrison C...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html
26a9697b1b43-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_ma...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html
26a9697b1b43-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) async def _arun( self, source_path: str, destination_path: str, run_manager: ...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html
58d6062901cb-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_mana...
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html
58d6062901cb-1
raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html
bc9d0ffe10bf-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://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
bc9d0ffe10bf-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" By Harri...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html
ef3777772f51-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://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
ef3777772f51-1
response = await page.goto(url) status = response.status if response else "unknown" return f"Navigating to {url} returned status code {status}" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
ff485a7e9ea2-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://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
ff485a7e9ea2-1
# 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 an...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html
4eb2a0ee93a6-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://python.langchain.com/en/latest/_modules/langchain/tools/playwright/current_page.html
90aa01754edb-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://python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
90aa01754edb-1
page = await aget_current_page(self.async_browser) # Navigate to the desired webpage before using this tool try: await page.click(selector) return f"Clicked element '{selector}'" except Exception as e: return f"Error '{e}'" By Harrison Chase © Copyr...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
a09b8c00c1ce-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://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
a09b8c00c1ce-1
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 f...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html
07c46d806fdc-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://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
07c46d806fdc-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://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
07c46d806fdc-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) By H...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html
b2a2500952cc-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://python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html
b2a2500952cc-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 NotI...
https://python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html
10fa34c23765-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 pydant...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-1
+ f"Valid values are {[loc.value for loc in SUPPORTED_LOCATIONS]}" ) SCHEMA_TYPE = Union[str, Type, tuple, None, Enum] 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 ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-2
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"{p...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-3
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(...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-4
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=param...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-5
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 @classmeth...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-6
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 typ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-7
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 isinst...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-8
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...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-9
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_...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-10
# 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_, ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
10fa34c23765-11
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_...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html
7ee1fe62702e-0
Source code for langchain.tools.openapi.utils.openapi_utils """Utility functions for parsing an OpenAPI spec.""" import copy import json import logging import re from enum import Enum from pathlib import Path from typing import Dict, List, Optional, Union import requests import yaml from openapi_schema_pydantic import ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
7ee1fe62702e-1
return path_item @property def _components_strict(self) -> Components: """Get components or err.""" if self.components is None: raise ValueError("No components found in spec. ") return self.components @property def _parameters_strict(self) -> Dict[str, Union[Parameter...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
7ee1fe62702e-2
parameter = self._get_referenced_parameter(ref) while isinstance(parameter, Reference): parameter = self._get_referenced_parameter(parameter) return parameter [docs] def get_referenced_schema(self, ref: Reference) -> Schema: """Get a schema (or nested reference) or err.""" ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
7ee1fe62702e-3
"""Alert if the spec is not supported.""" warning_message = ( " This may result in degraded performance." + " Convert your OpenAPI spec to 3.1.* spec" + " for better support." ) swagger_version = obj.get("swagger") openapi_version = obj.get("openapi") ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
7ee1fe62702e-4
def from_spec_dict(cls, spec_dict: dict) -> "OpenAPISpec": """Get an OpenAPI spec from a dict.""" return cls.parse_obj(spec_dict) [docs] @classmethod def from_text(cls, text: str) -> "OpenAPISpec": """Get an OpenAPI spec from a text.""" try: spec_dict = json.loads(text...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
7ee1fe62702e-5
if isinstance(operation, Operation): results.append(method.value) return results [docs] def get_operation(self, path: str, method: str) -> Operation: """Get the operation object for a given path and HTTP method.""" path_item = self._get_path_strict(path) operation_obj ...
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html
7ee1fe62702e-6
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html