id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
43a0c102b9ba-1
return values [docs] def compress_documents( self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Filter documents based on similarity of their embeddings to the query.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embed...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html
ace4e9e3ab75-0
Source code for langchain.retrievers.document_compressors.base """Interface for retrieved document compressors.""" from abc import ABC, abstractmethod from typing import List, Sequence, Union from pydantic import BaseModel from langchain.schema import BaseDocumentTransformer, Document class BaseDocumentCompressor(BaseM...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
ace4e9e3ab75-1
self, documents: Sequence[Document], query: str ) -> Sequence[Document]: """Compress retrieved documents given the query context.""" for _transformer in self.transformers: if isinstance(_transformer, BaseDocumentCompressor): documents = await _transformer.acompress_docume...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html
7f211cdb8959-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
7f211cdb8959-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
d321729d141d-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
d321729d141d-1
return [] 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.index] ...
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html
8f6153d82a93-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
8f6153d82a93-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
8f6153d82a93-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 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html
ee1793b4691c-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
ee1793b4691c-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
ee1793b4691c-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
ee1793b4691c-3
**kwargs, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
9ceb96d60ac2-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
330adb61837c-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
330adb61837c-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
f9c670adeca4-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
f9c670adeca4-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
3ddde9079b6e-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
8af3e3efb5cc-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
8af3e3efb5cc-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
51db1c733e70-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
51db1c733e70-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
51db1c733e70-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
51db1c733e70-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
51db1c733e70-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
c646ad0b9fa5-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
76b92547fcbf-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
76b92547fcbf-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
76b92547fcbf-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
76b92547fcbf-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
65ddd3c1b66c-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
65ddd3c1b66c-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
65ddd3c1b66c-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
65ddd3c1b66c-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
c3014c1a4b2b-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
c3014c1a4b2b-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
c3014c1a4b2b-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
e70c41afbe39-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
e70c41afbe39-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
e70c41afbe39-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
1b6b3d751132-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
1b6b3d751132-1
# TODO: Add aiofiles method raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html
40d792e6a15d-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
40d792e6a15d-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
2701baa9e85a-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
2701baa9e85a-1
raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html
91ec62a5f730-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
91ec62a5f730-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
0fd49865cac1-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
0fd49865cac1-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
f20d76a0b713-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
f20d76a0b713-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
d5e6dab9034b-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
d5e6dab9034b-1
raise NotImplementedError By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html
c1dd2e4cc55c-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
c1dd2e4cc55c-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
09bc1050c547-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
09bc1050c547-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 28, 2023.
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html
437ff1f04829-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
437ff1f04829-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
8f10b404113c-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
3f54552d22bc-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
3f54552d22bc-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...
https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html
a989598aa7a6-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
a989598aa7a6-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
c947f4210ceb-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
c947f4210ceb-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
c947f4210ceb-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
3a584bd2f335-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
3a584bd2f335-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
11bbba842a4f-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
11bbba842a4f-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
11bbba842a4f-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
11bbba842a4f-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
11bbba842a4f-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
11bbba842a4f-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
11bbba842a4f-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
11bbba842a4f-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
11bbba842a4f-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
11bbba842a4f-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
11bbba842a4f-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
11bbba842a4f-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
93568b333c3a-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
93568b333c3a-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
93568b333c3a-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
93568b333c3a-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