id stringlengths 14 16 | source stringlengths 49 117 | text stringlengths 16 2.73k |
|---|---|---|
85ea5a22cf84-0 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/pupmed.html | Source code for langchain.retrievers.pupmed
from typing import List
from langchain.schema import BaseRetriever, Document
from langchain.utilities.pupmed import PubMedAPIWrapper
[docs]class PubMedRetriever(BaseRetriever, PubMedAPIWrapper):
"""
It is effectively a wrapper for PubMedAPIWrapper.
It wraps load()... |
5f7240409638-0 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/arxiv.html | Source code for langchain.retrievers.arxiv
from typing import List
from langchain.schema import BaseRetriever, Document
from langchain.utilities.arxiv import ArxivAPIWrapper
[docs]class ArxivRetriever(BaseRetriever, ArxivAPIWrapper):
"""
It is effectively a wrapper for ArxivAPIWrapper.
It wraps load() to ge... |
87c5aa1b4f2f-0 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/metal.html | Source code for langchain.retrievers.metal
from typing import Any, List, Optional
from langchain.schema import BaseRetriever, Document
[docs]class MetalRetriever(BaseRetriever):
def __init__(self, client: Any, params: Optional[dict] = None):
from metal_sdk.metal import Metal
if not isinstance(client... |
0b7752a6d233-0 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html | Source code for langchain.retrievers.document_compressors.embeddings_filter
"""Document compressor that uses embeddings to drop documents unrelated to the query."""
from typing import Callable, Dict, Optional, Sequence
import numpy as np
from pydantic import root_validator
from langchain.document_transformers import (
... |
0b7752a6d233-1 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/embeddings_filter.html | [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_embeddings_from_sta... |
b38c18542e9f-0 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html | 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... |
b38c18542e9f-1 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/base.html | ) -> Sequence[Document]:
"""Compress retrieved documents given the query context."""
for _transformer in self.transformers:
if isinstance(_transformer, BaseDocumentCompressor):
documents = await _transformer.acompress_documents(documents, query)
elif isinstance(_t... |
41c1f2aa5f56-0 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html | 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... |
41c1f2aa5f56-1 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_filter.html | 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."""
raise NotImplementedError
[docs] @classmethod
def from_... |
e0c8a17b4653-0 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html | 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... |
e0c8a17b4653-1 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/cohere_rerank.html | 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]
doc.metadata["re... |
20ad2b8f71ef-0 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html | 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... |
20ad2b8f71ef-1 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html | 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.predict_and_parse(**_input)
if len... |
20ad2b8f71ef-2 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/document_compressors/chain_extract.html | 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 Jun 04, 2023. |
1494a40ac0d8-0 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html | 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 ... |
1494a40ac0d8-1 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html | return BUILTIN_TRANSLATORS[vectorstore_cls]()
[docs]class SelfQueryRetriever(BaseRetriever, BaseModel):
"""Retriever that wraps around a vector store and uses an LLM to generate
the vector store queries."""
vectorstore: VectorStore
"""The underlying vector store from which documents will be retrieved.""... |
1494a40ac0d8-2 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html | new_query, new_kwargs = self.structured_query_translator.visit_structured_query(
structured_query
)
if structured_query.limit is not None:
new_kwargs["k"] = structured_query.limit
search_kwargs = {**self.search_kwargs, **new_kwargs}
docs = self.vectorstore.search(... |
1494a40ac0d8-3 | https://python.langchain.com/en/latest/_modules/langchain/retrievers/self_query/base.html | structured_query_translator=structured_query_translator,
**kwargs,
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
31600fbf13a0-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | 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,
... |
31600fbf13a0-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | 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[BaseModel]'"
f" but got '{args_schema_type}'.\n"
... |
31600fbf13a0-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | validated = validate_arguments(func, config=_SchemaConfig) # type: ignore
inferred_model = validated.model # type: ignore
if "run_manager" in inferred_model.__fields__:
del inferred_model.__fields__["run_manager"]
# Pydantic adds placeholder virtual fields we need to strip
filtered_args = get_... |
31600fbf13a0-3 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | """Callbacks to be called during tool execution."""
callback_manager: Optional[BaseCallbackManager] = Field(default=None, exclude=True)
"""Deprecated. Please use callbacks instead."""
handle_tool_error: Optional[
Union[bool, str, Callable[[ToolException], str]]
] = False
"""Handle the conten... |
31600fbf13a0-4 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | """Raise deprecation warning if callback_manager is used."""
if values.get("callback_manager") is not None:
warnings.warn(
"callback_manager is deprecated. Please use callbacks instead.",
DeprecationWarning,
)
values["callbacks"] = values.pop("... |
31600fbf13a0-5 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | verbose_ = verbose
else:
verbose_ = self.verbose
callback_manager = CallbackManager.configure(
callbacks, self.callbacks, verbose=verbose_
)
# TODO: maybe also pass through run_manager is _run supports kwargs
new_arg_supported = signature(self._run).parame... |
31600fbf13a0-6 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | raise e
else:
run_manager.on_tool_end(
str(observation), color=color, name=self.name, **kwargs
)
return observation
[docs] async def arun(
self,
tool_input: Union[str, Dict],
verbose: Optional[bool] = None,
start_color: Optio... |
31600fbf13a0-7 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | observation = e.args[0]
else:
observation = "Tool execution error"
elif isinstance(self.handle_tool_error, str):
observation = self.handle_tool_error
elif callable(self.handle_tool_error):
observation = self.handle_tool_error(e)... |
31600fbf13a0-8 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]:
"""Convert tool input to pydantic model."""
args, kwargs = super()._to_args_and_kwargs(tool_input)
# For backwards compatibility. The tool must be run with a single input
all_args = list(args) + list(kwarg... |
31600fbf13a0-9 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | else await self.coroutine(*args, **kwargs)
)
raise NotImplementedError("Tool does not support async")
# TODO: this is for backwards compatibility, remove in future
def __init__(
self, name: str, func: Callable, description: str, **kwargs: Any
) -> None:
"""Initialize tool... |
31600fbf13a0-10 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | run_manager: Optional[CallbackManagerForToolRun] = None,
**kwargs: Any,
) -> Any:
"""Use the tool."""
new_argument_supported = signature(self.func).parameters.get("callbacks")
return (
self.func(
*args,
callbacks=run_manager.get_child() if ... |
31600fbf13a0-11 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | ), "Function must have a docstring if description not provided."
# Description example:
# search_api(query: str) - Searches the API for the query.
description = f"{name}{signature(func)} - {description.strip()}"
_args_schema = args_schema
if _args_schema is None and infer_schema:... |
31600fbf13a0-12 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | return
"""
def _make_with_name(tool_name: str) -> Callable:
def _make_tool(func: Callable) -> BaseTool:
if infer_schema or args_schema is not None:
return StructuredTool.from_function(
func,
name=tool_name,
return_di... |
31600fbf13a0-13 | https://python.langchain.com/en/latest/_modules/langchain/tools/base.html | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
0f02d5e12ff2-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/plugin.html | 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... |
0f02d5e12ff2-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/plugin.html | f"Call this tool to get the OpenAPI spec (and usage guide) "
f"for interacting with the {plugin.name_for_human} API. "
f"You should only call this ONCE! What is the "
f"{plugin.name_for_human} API useful for? "
) + plugin.description_for_human
open_api_spec_str = requ... |
44adb980be83-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html | 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... |
44adb980be83-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html | - Copy the IFTTT key value from there. The URL is of the form
https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value.
"""
from typing import Optional
import requests
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.tools.bas... |
a004618372b6-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/wikipedia/tool.html | 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... |
59ca0a917a96-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html | 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... |
59ca0a917a96-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/shell/tool.html | description: str = f"Run shell commands on this {_get_platform()} machine."
"""Description of tool."""
args_schema: Type[BaseModel] = ShellInput
"""Schema for input arguments."""
def _run(
self,
commands: Union[str, List[str]],
run_manager: Optional[CallbackManagerForToolRun] = N... |
25aebc97572b-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html | 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... |
25aebc97572b-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html | 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/provider/debug
# (under User Information, after logging in)... |
25aebc97572b-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html | )
agent.run(("Summarize the last email I received regarding Silicon Valley Bank. "
"Send the summary to the #test-zapier channel in slack."))
```
"""
from typing import Any, Dict, Optional
from pydantic import Field, root_validator
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
Ca... |
25aebc97572b-3 | https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html | params_schema = values["params_schema"]
if "instructions" in params_schema:
del params_schema["instructions"]
# Ensure base prompt (if overrided) contains necessary input fields
necessary_fields = {"{zapier_description}", "{params}"}
if not all(field in values["base_prompt"] ... |
25aebc97572b-4 | https://python.langchain.com/en/latest/_modules/langchain/tools/zapier/tool.html | description = BASE_ZAPIER_TOOL_PROMPT + (
"This tool returns a list of the user's exposed actions."
)
api_wrapper: ZapierNLAWrapper = Field(default_factory=ZapierNLAWrapper)
def _run(
self,
_: str = "",
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
... |
fa2166511e04-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html | 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... |
d2ccf307509f-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html | 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... |
d2ccf307509f-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html | try:
import azure.ai.vision as sdk
values["vision_service"] = sdk.VisionServiceOptions(
endpoint=azure_cogs_endpoint, key=azure_cogs_key
)
values["analysis_options"] = sdk.ImageAnalysisOptions()
values["analysis_options"].features = (
... |
d2ccf307509f-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html | if result.text is not None:
res_dict["text"] = [line.content for line in result.text.lines]
else:
error_details = sdk.ImageAnalysisErrorDetails.from_result(result)
raise RuntimeError(
f"Image analysis failed.\n"
f"Reason: {error_details.rea... |
d2ccf307509f-3 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/image_analysis.html | raise RuntimeError(f"Error while running AzureCogsImageAnalysisTool: {e}")
async def _arun(
self,
query: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Use the tool asynchronously."""
raise NotImplementedError("AzureCogsImageAnalysisTool d... |
ff3957c2d5bc-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html | 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 ... |
ff3957c2d5bc-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html | azure_cogs_endpoint = get_from_dict_or_env(
values, "azure_cogs_endpoint", "AZURE_COGS_ENDPOINT"
)
try:
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential
values["doc_analysis_client"] = Documen... |
ff3957c2d5bc-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html | elif document_src_type == "remote":
poller = self.doc_analysis_client.begin_analyze_document_from_url(
"prebuilt-document", document_path
)
else:
raise ValueError(f"Invalid document path: {document_path}")
result = poller.result()
res_dict = {}... |
ff3957c2d5bc-3 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/form_recognizer.html | return "No good document analysis result was found"
return self._format_document_analysis_result(document_analysis_result)
except Exception as e:
raise RuntimeError(f"Error while running AzureCogsFormRecognizerTool: {e}")
async def _arun(
self,
query: str,
run... |
a7742ee10cab-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html | 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... |
a7742ee10cab-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html | azure_cogs_region = get_from_dict_or_env(
values, "azure_cogs_region", "AZURE_COGS_REGION"
)
try:
import azure.cognitiveservices.speech as speechsdk
values["speech_config"] = speechsdk.SpeechConfig(
subscription=azure_cogs_key, region=azure_cogs_region... |
a7742ee10cab-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/speech2text.html | if audio_src_type == "local":
audio_config = speechsdk.AudioConfig(filename=audio_path)
elif audio_src_type == "remote":
tmp_audio_path = download_audio_from_url(audio_path)
audio_config = speechsdk.AudioConfig(filename=tmp_audio_path)
else:
raise ValueErr... |
e8ad928a6dd3-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html | 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,
)... |
e8ad928a6dd3-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html | import azure.cognitiveservices.speech as speechsdk
values["speech_config"] = speechsdk.SpeechConfig(
subscription=azure_cogs_key, region=azure_cogs_region
)
except ImportError:
raise ImportError(
"azure-cognitiveservices-speech is not installed... |
e8ad928a6dd3-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/azure_cognitive_services/text2speech.html | ) -> str:
"""Use the tool."""
try:
speech_file = self._text2speech(query, self.speech_language)
return speech_file
except Exception as e:
raise RuntimeError(f"Error while running AzureCogsText2SpeechTool: {e}")
async def _arun(
self,
query:... |
d213221933e5-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html | 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... |
d213221933e5-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/read.html | © Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
555bbfc74448-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html | 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... |
555bbfc74448-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/file_search.html | return "\n".join(matches)
else:
return f"No files found for pattern {pattern} in directory {dir_path}"
except Exception as e:
return "Error: " + str(e)
async def _arun(
self,
dir_path: str,
pattern: str,
run_manager: Optional[AsyncCallb... |
10c3cad6a36d-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html | 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... |
10c3cad6a36d-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/list_dir.html | Last updated on Jun 04, 2023. |
c0a3a6f0cc28-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html | 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... |
c0a3a6f0cc28-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/write.html | async def _arun(
self,
file_path: str,
text: str,
append: bool = False,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
# TODO: Add aiofiles method
raise NotImplementedError
By Harrison Chase
© Copyright 2023, Harrison Chase.... |
71219ec1e8e0-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html | 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... |
71219ec1e8e0-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/copy.html | 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 Chase
© Copyright 2023, H... |
f6259141e8f4-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html | 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... |
f6259141e8f4-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/move.html | return f"File moved successfully from {source_path} to {destination_path}."
except Exception as e:
return "Error: " + str(e)
async def _arun(
self,
source_path: str,
destination_path: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:... |
886bef46ed20-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html | 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... |
886bef46ed20-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/file_management/delete.html | Last updated on Jun 04, 2023. |
a5ec6637b428-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html | 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... |
a5ec6637b428-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate_back.html | 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 Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 20... |
92e76d519017-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html | 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... |
92e76d519017-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/navigate.html | 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 Jun 04, 2023. |
4b9f1ee85256-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html | 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... |
4b9f1ee85256-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_hyperlinks.html | anchors = soup.find_all("a")
if absolute_urls:
base_url = page.url
links = [urljoin(base_url, anchor.get("href", "")) for anchor in anchors]
else:
links = [anchor.get("href", "") for anchor in anchors]
# Return the list of links as a JSON string
return... |
af6dcca24ee1-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/current_page.html | 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... |
068f1dc93717-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html | 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... |
068f1dc93717-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/click.html | selector_effective = self._selector_effective(selector=selector)
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
try:
page.click(
selector_effective,
strict=self.playwright_strict,
timeout=self.playwright_timeout,
... |
d681ecb151f1-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html | 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 ... |
d681ecb151f1-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/extract_text.html | ) -> str:
"""Use the tool."""
if self.async_browser is None:
raise ValueError(f"Asynchronous browser not provided to {self.name}")
# Use Beautiful Soup since it's faster than looping through the elements
from bs4 import BeautifulSoup
page = await aget_current_page(sel... |
46b63b3917de-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html | 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... |
46b63b3917de-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html | """Get elements matching the given CSS selector."""
elements = page.query_selector_all(selector)
results = []
for element in elements:
result = {}
for attribute in attributes:
if attribute == "innerText":
val: Optional[str] = element.inner_text()
else:... |
46b63b3917de-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/playwright/get_elements.html | 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 Harrison Chase
© Copyright 2023, Harrison Chase.
Last updat... |
d237881a9c21-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html | 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... |
d237881a9c21-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/youtube/search.html | num_results = 2
return self._search(person, num_results)
async def _arun(
self,
query: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Use the tool asynchronously."""
raise NotImplementedError("YouTubeSearchTool does not yet suppor... |
73a5efc7936d-0 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | 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... |
73a5efc7936d-1 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | 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 to a template expression
# within the path field in the Paths Obj... |
73a5efc7936d-2 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | else:
return tuple(type_)
@staticmethod
def _get_schema_type_for_enum(parameter: Parameter, schema: Schema) -> Enum:
"""Get the schema type when the parameter is an enum."""
param_name = f"{parameter.name}Enum"
return Enum(param_name, {str(v): v for v in schema.enum})
@st... |
73a5efc7936d-3 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | raise NotImplementedError(f"Unsupported type: {schema_type}")
return schema_type
@staticmethod
def _validate_location(location: APIPropertyLocation, name: str) -> None:
if location not in SUPPORTED_LOCATIONS:
raise NotImplementedError(
INVALID_LOCATION_TEMPL.format(lo... |
73a5efc7936d-4 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | return cls(
name=parameter.name,
location=location,
default=default_val,
description=parameter.description,
required=parameter.required,
type=schema_type,
)
class APIRequestBodyProperty(APIPropertyBase):
"""A model for a request body pr... |
73a5efc7936d-5 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | cls, schema: Schema, name: str, spec: OpenAPISpec, references_used: List[str]
) -> str:
items = schema.items
if items is not None:
if isinstance(items, Reference):
ref_name = items.ref.split("/")[-1]
if ref_name not in references_used:
... |
73a5efc7936d-6 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | # No typing specified/parsed. WIll map to 'any'
pass
else:
raise ValueError(f"Unsupported type: {schema_type}")
return cls(
name=name,
required=required,
type=schema_type,
default=schema.default,
description=schema.descr... |
73a5efc7936d-7 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | APIRequestBodyProperty.from_schema(
schema=prop_schema,
name=prop_name,
required=prop_name in required_properties,
spec=spec,
)
)
else:
api_request_body_properties.appe... |
73a5efc7936d-8 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | properties: Sequence[APIProperty] = Field(alias="properties")
# TODO: Add parse in used components to be able to specify what type of
# referenced object it is.
# """The properties of the operation."""
# components: Dict[str, BaseModel] = Field(alias="components")
request_body: Optional[APIRequestBo... |
73a5efc7936d-9 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | """Create an APIOperation from an OpenAPI spec."""
operation = spec.get_operation(path, method)
parameters = spec.get_parameters_for_operation(operation)
properties = cls._get_properties_from_parameters(parameters, spec)
operation_id = OpenAPISpec.get_cleaned_operation_id(operation, path... |
73a5efc7936d-10 | https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html | def _format_nested_properties(
self, properties: List[APIRequestBodyProperty], indent: int = 2
) -> str:
"""Format nested properties."""
formatted_props = []
for prop in properties:
prop_name = prop.name
prop_type = self.ts_type_from_python(prop.type)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.