viruPVS/langchain-docs huggingface dataset:
Source code for langchain_community.tools.edenai.ocr_invoiceparser
from __future__ import annotations
import logging
from typing import Optional
from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class EdenAiParsingInvoiceTool(EdenaiTool):
    """Tool that queries the Eden AI Invoice parsing API.
    for api reference check edenai documentation:
    https://docs.edenai.co/reference/ocr_invoice_parser_create.
    To use, you should have
    the environment variable ``EDENAI_API_KEY`` set with your API token.
    You can find your token here: https://app.edenai.run/admin/account/settings
    """
    name = "edenai_invoice_parsing"
    description = (
        "A wrapper around edenai Services invoice parsing. "
        """Useful for when you have to extract information from 
        an image it enables to take invoices 
        in a variety of formats and returns the data in contains
        (items, prices, addresses, vendor name, etc.)
        in a structured format to automate the invoice processing """
        "Input should be the string url of the document to parse."
    )
    language: Optional[str] = None
    """
    language of the image passed to the model.
    """
    feature = "ocr"
    subfeature = "invoice_parser"
    def _parse_response(self, response: list) -> str:
        formatted_list: list = []
        if len(response) == 1:
            self._parse_json_multilevel(
                response[0]["extracted_data"][0], formatted_list
            )
        else:
            for entry in response:
)
        else:
            for entry in response:
                if entry.get("provider") == "eden-ai":
                    self._parse_json_multilevel(
                        entry["extracted_data"][0], formatted_list
                    )
        return "\n".join(formatted_list)
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        query_params = {
            "file_url": query,
            "language": self.language,
            "attributes_as_list": False,
        }
        return self._call_eden_ai(query_params)
Source code for langchain_community.tools.edenai.ocr_identityparser
from __future__ import annotations
import logging
from typing import Optional
from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class EdenAiParsingIDTool(EdenaiTool):
    """Tool that queries the Eden AI  Identity parsing API.
    for api reference check edenai documentation:
    https://docs.edenai.co/reference/ocr_identity_parser_create.
    To use, you should have
    the environment variable ``EDENAI_API_KEY`` set with your API token.
    You can find your token here: https://app.edenai.run/admin/account/settings
    """
    name = "edenai_identity_parsing"
    description = (
        "A wrapper around edenai Services Identity parsing. "
        "Useful for when you have to extract information from an ID Document "
        "Input should be the string url of the document to parse."
    )
    feature = "ocr"
    subfeature = "identity_parser"
    language: Optional[str] = None
    """
    language of the text passed to the model.
    """
    def _parse_response(self, response: list) -> str:
        formatted_list: list = []
        if len(response) == 1:
            self._parse_json_multilevel(
                response[0]["extracted_data"][0], formatted_list
            )
        else:
            for entry in response:
                if entry.get("provider") == "eden-ai":
                    self._parse_json_multilevel(
                        entry["extracted_data"][0], formatted_list
                    )
        return "\n".join(formatted_list)
)
        return "\n".join(formatted_list)
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        query_params = {
            "file_url": query,
            "language": self.language,
            "attributes_as_list": False,
        }
        return self._call_eden_ai(query_params)
Source code for langchain_community.tools.edenai.audio_speech_to_text
from __future__ import annotations
import json
import logging
import time
from typing import List, Optional
import requests
from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_core.pydantic_v1 import validator
from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class EdenAiSpeechToTextTool(EdenaiTool):
    """Tool that queries the Eden AI Speech To Text API.
    for api reference check edenai documentation:
    https://app.edenai.run/bricks/speech/asynchronous-speech-to-text.
    To use, you should have
    the environment variable ``EDENAI_API_KEY`` set with your API token.
    You can find your token here: https://app.edenai.run/admin/account/settings
    """
    edenai_api_key: Optional[str] = None
    name = "edenai_speech_to_text"
    description = (
        "A wrapper around edenai Services speech to text "
        "Useful for when you have to convert audio to text."
        "Input should be a url to an audio file."
    )
    is_async = True
    language: Optional[str] = "en"
    speakers: Optional[int]
    profanity_filter: bool = False
    custom_vocabulary: Optional[List[str]]
    feature: str = "audio"
    subfeature: str = "speech_to_text_async"
    base_url = "https://api.edenai.run/v2/audio/speech_to_text_async/"
    @validator("providers")
    def check_only_one_provider_selected(cls, v: List[str]) -> List[str]:
        """
"""
        This tool has no feature to combine providers results.
        Therefore we only allow one provider
        """
        if len(v) > 1:
            raise ValueError(
                "Please select only one provider. "
                "The feature to combine providers results is not available "
                "for this tool."
            )
        return v
    def _wait_processing(self, url: str) -> requests.Response:
        for _ in range(10):
            time.sleep(1)
            audio_analysis_result = self._get_edenai(url)
            temp = audio_analysis_result.json()
            if temp["status"] == "finished":
                if temp["results"][self.providers[0]]["error"] is not None:
                    raise Exception(
                        f"""EdenAI returned an unexpected response 
                        {temp['results'][self.providers[0]]['error']}"""
                    )
                else:
                    return audio_analysis_result
        raise Exception("Edenai speech to text job id processing Timed out")
    def _parse_response(self, response: dict) -> str:
        return response["public_id"]
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        all_params = {
            "file_url": query,
            "language": self.language,
            "speakers": self.speakers,
            "profanity_filter": self.profanity_filter,
            "custom_vocabulary": self.custom_vocabulary,
        }
        # filter so we don't send val to api when val is `None
        query_params = {k: v for k, v in all_params.items() if v is not None}
Source code for langchain_community.tools.edenai.image_objectdetection
from __future__ import annotations
import logging
from typing import Optional
from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class EdenAiObjectDetectionTool(EdenaiTool):
    """Tool that queries the Eden AI Object detection API.
    for api reference check edenai documentation:
    https://docs.edenai.co/reference/image_object_detection_create.
    To use, you should have
    the environment variable ``EDENAI_API_KEY`` set with your API token.
    You can find your token here: https://app.edenai.run/admin/account/settings
    """
    name = "edenai_object_detection"
    description = (
        "A wrapper around edenai Services Object Detection . "
        """Useful for when you have to do an  to identify and locate
        (with bounding boxes) objects in an image """
        "Input should be the string url of the image to identify."
    )
    show_positions: bool = False
    feature = "image"
    subfeature = "object_detection"
    def _parse_json(self, json_data: dict) -> str:
        result = []
        label_info = []
        for found_obj in json_data["items"]:
            label_str = f"{found_obj['label']} - Confidence {found_obj['confidence']}"
            x_min = found_obj.get("x_min")
            x_max = found_obj.get("x_max")
            y_min = found_obj.get("y_min")
            y_max = found_obj.get("y_max")
            if self.show_positions and all(
if self.show_positions and all(
                [x_min, x_max, y_min, y_max]
            ):  # some providers don't return positions
                label_str += f""",at the position x_min: {x_min}, x_max: {x_max}, 
                y_min: {y_min}, y_max: {y_max}"""
            label_info.append(label_str)
        result.append("\n".join(label_info))
        return "\n\n".join(result)
    def _parse_response(self, response: list) -> str:
        if len(response) == 1:
            result = self._parse_json(response[0])
        else:
            for entry in response:
                if entry.get("provider") == "eden-ai":
                    result = self._parse_json(entry)
        return result
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        query_params = {"file_url": query, "attributes_as_list": False}
        return self._call_eden_ai(query_params)
Source code for langchain_community.tools.edenai.text_moderation
from __future__ import annotations
import logging
from typing import Optional
from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class EdenAiTextModerationTool(EdenaiTool):
    """Tool that queries the Eden AI Explicit text detection.
    for api reference check edenai documentation:
    https://docs.edenai.co/reference/image_explicit_content_create.
    To use, you should have
    the environment variable ``EDENAI_API_KEY`` set with your API token.
    You can find your token here: https://app.edenai.run/admin/account/settings
    """
    name = "edenai_explicit_content_detection_text"
    description = (
        "A wrapper around edenai Services explicit content detection for text. "
        """Useful for when you have to scan text for offensive, 
        sexually explicit or suggestive content,
        it checks also if there is any content of self-harm,
        violence, racist or hate speech."""
        """the structure of the output is : 
        'the type of the explicit content : the likelihood of it being explicit'
        the likelihood is a number 
        between 1 and 5, 1 being the lowest and 5 the highest.
        something is explicit if the likelihood is equal or higher than 3.
        for example : 
        nsfw_likelihood: 1
        this is not explicit.
        for example : 
        nsfw_likelihood: 3
        this is explicit.
        """
        "Input should be a string."
    )
    language: str
    feature: str = "text"
)
    language: str
    feature: str = "text"
    subfeature: str = "moderation"
    def _parse_response(self, response: list) -> str:
        formatted_result = []
        for result in response:
            if "nsfw_likelihood" in result.keys():
                formatted_result.append(
                    "nsfw_likelihood: " + str(result["nsfw_likelihood"])
                )
            for label, likelihood in zip(result["label"], result["likelihood"]):
                formatted_result.append(f'"{label}": {str(likelihood)}')
        return "\n".join(formatted_result)
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        query_params = {"text": query, "language": self.language}
        return self._call_eden_ai(query_params)
Source code for langchain_community.tools.edenai.image_explicitcontent
from __future__ import annotations
import logging
from typing import Optional
from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class EdenAiExplicitImageTool(EdenaiTool):
    """Tool that queries the Eden AI Explicit image detection.
    for api reference check edenai documentation:
    https://docs.edenai.co/reference/image_explicit_content_create.
    To use, you should have
    the environment variable ``EDENAI_API_KEY`` set with your API token.
    You can find your token here: https://app.edenai.run/admin/account/settings
    """
    name = "edenai_image_explicit_content_detection"
    description = (
        "A wrapper around edenai Services Explicit image detection. "
        """Useful for when you have to extract Explicit Content from images.
        it detects adult only content in images, 
        that is generally inappropriate for people under
        the age of 18 and includes nudity, sexual activity,
        pornography, violence, gore content, etc."""
        "Input should be the string url of the image ."
    )
    combine_available = True
    feature = "image"
    subfeature = "explicit_content"
    def _parse_json(self, json_data: dict) -> str:
        result_str = f"nsfw_likelihood: {json_data['nsfw_likelihood']}\n"
        for idx, found_obj in enumerate(json_data["items"]):
            label = found_obj["label"].lower()
            likelihood = found_obj["likelihood"]
            result_str += f"{idx}: {label} likelihood {likelihood},\n"
result_str += f"{idx}: {label} likelihood {likelihood},\n"
        return result_str[:-2]
    def _parse_response(self, json_data: list) -> str:
        if len(json_data) == 1:
            result = self._parse_json(json_data[0])
        else:
            for entry in json_data:
                if entry.get("provider") == "eden-ai":
                    result = self._parse_json(entry)
        return result
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        query_params = {"file_url": query, "attributes_as_list": False}
        return self._call_eden_ai(query_params)
Source code for langchain_community.tools.edenai.audio_text_to_speech
from __future__ import annotations
import logging
from typing import Dict, List, Literal, Optional
import requests
from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_core.pydantic_v1 import Field, root_validator, validator
from langchain_community.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class EdenAiTextToSpeechTool(EdenaiTool):
    """Tool that queries the Eden AI Text to speech API.
    for api reference check edenai documentation:
    https://docs.edenai.co/reference/audio_text_to_speech_create.
    To use, you should have
    the environment variable ``EDENAI_API_KEY`` set with your API token.
    You can find your token here: https://app.edenai.run/admin/account/settings
    """
    name = "edenai_text_to_speech"
    description = (
        "A wrapper around edenai Services text to speech."
        "Useful for when you need to convert text to speech."
        """the output is a string representing the URL of the audio file,
        or the path to the downloaded wav file """
    )
    language: Optional[str] = "en"
    """
    language of the text passed to the model.
    """
    # optional params see api documentation for more info
    return_type: Literal["url", "wav"] = "url"
    rate: Optional[int]
    pitch: Optional[int]
    volume: Optional[int]
    audio_format: Optional[str]
    sampling_rate: Optional[int]
    voice_models: Dict[str, str] = Field(default_factory=dict)
    voice: Literal["MALE", "FEMALE"]
voice: Literal["MALE", "FEMALE"]
    """voice option : 'MALE' or 'FEMALE' """
    feature: str = "audio"
    subfeature: str = "text_to_speech"
    @validator("providers")
    def check_only_one_provider_selected(cls, v: List[str]) -> List[str]:
        """
        This tool has no feature to combine providers results.
        Therefore we only allow one provider
        """
        if len(v) > 1:
            raise ValueError(
                "Please select only one provider. "
                "The feature to combine providers results is not available "
                "for this tool."
            )
        return v
    @root_validator
    def check_voice_models_key_is_provider_name(cls, values: dict) -> dict:
        for key in values.get("voice_models", {}).keys():
            if key not in values.get("providers", []):
                raise ValueError(
                    "voice_model should be formatted like this "
                    "{<provider_name>: <its_voice_model>}"
                )
        return values
    def _download_wav(self, url: str, save_path: str) -> None:
        response = requests.get(url)
        if response.status_code == 200:
            with open(save_path, "wb") as f:
                f.write(response.content)
        else:
            raise ValueError("Error while downloading wav file")
    def _parse_response(self, response: list) -> str:
        result = response[0]
        if self.return_type == "url":
            return result["audio_resource_url"]
        else:
            self._download_wav(result["audio_resource_url"], "audio.wav")
            return "audio.wav"
    def _run(
        self,
return "audio.wav"
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        all_params = {
            "text": query,
            "language": self.language,
            "option": self.voice,
            "return_type": self.return_type,
            "rate": self.rate,
            "pitch": self.pitch,
            "volume": self.volume,
            "audio_format": self.audio_format,
            "sampling_rate": self.sampling_rate,
            "settings": self.voice_models,
        }
        # filter so we don't send val to api when val is `None
        query_params = {k: v for k, v in all_params.items() if v is not None}
        return self._call_eden_ai(query_params)
Source code for langchain_community.tools.google_serper.tool
"""Tool for the Serper.dev Google Search API."""
from typing import Optional
from langchain_core.callbacks import (
    AsyncCallbackManagerForToolRun,
    CallbackManagerForToolRun,
)
from langchain_core.pydantic_v1 import Field
from langchain_core.tools import BaseTool
from langchain_community.utilities.google_serper import GoogleSerperAPIWrapper
[docs]class GoogleSerperRun(BaseTool):
    """Tool that queries the Serper.dev Google search API."""
    name: str = "google_serper"
    description: str = (
        "A low-cost Google Search API."
        "Useful for when you need to answer questions about current events."
        "Input should be a search query."
    )
    api_wrapper: GoogleSerperAPIWrapper
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        return str(self.api_wrapper.run(query))
    async def _arun(
        self,
        query: str,
        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool asynchronously."""
        return (await self.api_wrapper.arun(query)).__str__()
[docs]class GoogleSerperResults(BaseTool):
    """Tool that queries the Serper.dev Google Search API
    and get back json."""
    name: str = "google_serper_results_json"
    description: str = (
        "A low-cost Google Search API."
        "Useful for when you need to answer questions about current events."
        "Input should be a search query. Output is a JSON object of the query results"
"Input should be a search query. Output is a JSON object of the query results"
    )
    api_wrapper: GoogleSerperAPIWrapper = Field(default_factory=GoogleSerperAPIWrapper)
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        return str(self.api_wrapper.results(query))
    async def _arun(
        self,
        query: str,
        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool asynchronously."""
        return (await self.api_wrapper.aresults(query)).__str__()
Source code for langchain_community.tools.searchapi.tool
"""Tool for the SearchApi.io search API."""
from typing import Optional
from langchain_core.callbacks import (
    AsyncCallbackManagerForToolRun,
    CallbackManagerForToolRun,
)
from langchain_core.pydantic_v1 import Field
from langchain_core.tools import BaseTool
from langchain_community.utilities.searchapi import SearchApiAPIWrapper
[docs]class SearchAPIRun(BaseTool):
    """Tool that queries the SearchApi.io search API."""
    name: str = "searchapi"
    description: str = (
        "Google search API provided by SearchApi.io."
        "This tool is handy when you need to answer questions about current events."
        "Input should be a search query."
    )
    api_wrapper: SearchApiAPIWrapper
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        return self.api_wrapper.run(query)
    async def _arun(
        self,
        query: str,
        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool asynchronously."""
        return await self.api_wrapper.arun(query)
[docs]class SearchAPIResults(BaseTool):
    """Tool that queries the SearchApi.io search API and returns JSON."""
    name: str = "searchapi_results_json"
    description: str = (
        "Google search API provided by SearchApi.io."
        "This tool is handy when you need to answer questions about current events."
        "The input should be a search query and the output is a JSON object "
        "with the query results."
    )
"with the query results."
    )
    api_wrapper: SearchApiAPIWrapper = Field(default_factory=SearchApiAPIWrapper)
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        return str(self.api_wrapper.results(query))
    async def _arun(
        self,
        query: str,
        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool asynchronously."""
        return (await self.api_wrapper.aresults(query)).__str__()
Source code for langchain_community.tools.google_scholar.tool
"""Tool for the Google Scholar"""
from typing import Optional
from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_core.tools import BaseTool
from langchain_community.utilities.google_scholar import GoogleScholarAPIWrapper
[docs]class GoogleScholarQueryRun(BaseTool):
    """Tool that queries the Google search API."""
    name: str = "google_scholar"
    description: str = (
        "A wrapper around Google Scholar Search. "
        "Useful for when you need to get information about"
        "research papers from Google Scholar"
        "Input should be a search query."
    )
    api_wrapper: GoogleScholarAPIWrapper
    def _run(
        self,
        query: str,
        run_manager: Optional[CallbackManagerForToolRun] = None,
    ) -> str:
        """Use the tool."""
        return self.api_wrapper.run(query)