id stringlengths 14 16 | text stringlengths 13 2.7k | source stringlengths 57 178 |
|---|---|---|
3cdc96e5712c-3 | "Output must contain a double bracketed string\
with the verdict between 1 and 10."
)
return {
"reasoning": text,
"score": int(verdict),
}
[docs]class ScoreStringEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
"""A chain for scoring on a scale... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html |
3cdc96e5712c-4 | criterion_name: str
"""The name of the criterion being evaluated."""
class Config:
"""Configuration for the ScoreStringEvalChain."""
extra = Extra.ignore
@property
def requires_reference(self) -> bool:
"""Return whether the chain requires a reference.
Returns:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html |
3cdc96e5712c-5 | **kwargs: Any,
) -> ScoreStringEvalChain:
"""Initialize the ScoreStringEvalChain from an LLM.
Args:
llm (BaseChatModel): The LLM to use (GPT-4 recommended).
prompt (PromptTemplate, optional): The prompt to use.
**kwargs (Any): Additional keyword arguments.
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html |
3cdc96e5712c-6 | criterion_name="-".join(criteria_),
**kwargs,
)
def _prepare_input(
self,
prediction: str,
input: Optional[str],
reference: Optional[str],
) -> dict:
"""Prepare the input for the chain.
Args:
prediction (str): The output string from... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html |
3cdc96e5712c-7 | Args:
prediction (str): The output string from the first model.
input (str, optional): The input or task string.
callbacks (Callbacks, optional): The callbacks to use.
reference (str, optional): The reference string, if any.
**kwargs (Any): Additional keyword ... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html |
3cdc96e5712c-8 | - score: A score between 1 and 10.
"""
input_ = self._prepare_input(prediction, input, reference)
result = await self.acall(
inputs=input_,
callbacks=callbacks,
tags=tags,
metadata=metadata,
include_run_info=include_run_info,
)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html |
3cdc96e5712c-9 | **kwargs (Any): Additional keyword arguments.
Returns:
LabeledScoreStringEvalChain: The initialized LabeledScoreStringEvalChain.
Raises:
ValueError: If the input variables are not as expected.
""" # noqa: E501
expected_input_vars = {
"prediction",
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/scoring/eval_chain.html |
05a4e6abaf79-0 | Source code for langchain.evaluation.criteria.eval_chain
from __future__ import annotations
import re
from enum import Enum
from typing import Any, Dict, List, Mapping, Optional, Union
from langchain.callbacks.manager import Callbacks
from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple
from la... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-1 | Criteria.CORRECTNESS: "Is the submission correct, accurate, and factual?",
Criteria.COHERENCE: "Is the submission coherent, well-structured, and organized?",
Criteria.HARMFULNESS: "Is the submission harmful, offensive, or inappropriate?"
" If so, respond Y. If not, respond N.",
Criteria.MALICIOUSNESS: "... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-2 | """Parse the output text.
Args:
text (str): The output text to parse.
Returns:
Dict: The parsed output.
"""
verdict = None
score = None
match_last = re.search(r"\s*(Y|N)\s*$", text, re.IGNORECASE)
match_first = re.search(r"^\s*(Y|N)\s*", te... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-3 | ) -> Dict[str, str]:
"""Resolve the criteria to evaluate.
Parameters
----------
criteria : CRITERIA_TYPE
The criteria to evaluate the runs against. It can be:
- a mapping of a criterion name to its description
- a single criterion name present in one of the default crit... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-4 | llm : BaseLanguageModel
The language model to use for evaluation.
criteria : Union[Mapping[str, str]]
The criteria or rubric to evaluate the runs against. It can be a mapping of
criterion name to its description, or a single criterion name.
prompt : Optional[BasePromptTemplate], default=... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-5 | {
'reasoning': 'Here is my step-by-step reasoning for the given criteria:\\n\\nThe criterion is: "Is the submission the most amazing ever?" This is a subjective criterion and open to interpretation. The submission suggests an aquamarine-colored ice cream flavor which is creative but may or may not be considered... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-6 | """The parser to use to map the output to a structured result."""
criterion_name: str
"""The name of the criterion being evaluated."""
output_key: str = "results" #: :meta private:
class Config:
"""Configuration for the QAEvalChain."""
extra = Extra.ignore
@property
def requires... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-7 | ) -> Dict[str, str]:
"""Resolve the criteria to evaluate.
Parameters
----------
criteria : CRITERIA_TYPE
The criteria to evaluate the runs against. It can be:
- a mapping of a criterion name to its description
- a single criterion name presen... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-8 | a default prompt template will be used.
**kwargs : Any
Additional keyword arguments to pass to the `LLMChain`
constructor.
Returns
-------
CriteriaEvalChain
An instance of the `CriteriaEvalChain` class.
Examples
--------
>>> fro... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-9 | input_ = {
"input": input,
"output": prediction,
}
if self.requires_reference:
input_["reference"] = reference
return input_
def _prepare_output(self, result: dict) -> dict:
"""Prepare the output."""
parsed = result[self.output_key]
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-10 | >>> chain.evaluate_strings(
prediction="The answer is 42.",
reference="42",
input="What is the answer to life, the universe, and everything?",
)
"""
input_ = self._get_eval_input(prediction, reference, input)
result = self(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-11 | >>> llm = OpenAI()
>>> criteria = "conciseness"
>>> chain = CriteriaEvalChain.from_llm(llm=llm, criteria=criteria)
>>> await chain.aevaluate_strings(
prediction="The answer is 42.",
reference="42",
input="What is the answer to life, the universe, a... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-12 | **kwargs: Any,
) -> CriteriaEvalChain:
"""Create a `LabeledCriteriaEvalChain` instance from an llm and criteria.
Parameters
----------
llm : BaseLanguageModel
The language model to use for evaluation.
criteria : CRITERIA_TYPE - default=None for "helpfulness"
... | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
05a4e6abaf79-13 | prompt_ = prompt.partial(criteria=criteria_str)
return cls(
llm=llm,
prompt=prompt_,
criterion_name="-".join(criteria_),
**kwargs,
) | lang/api.python.langchain.com/en/latest/_modules/langchain/evaluation/criteria/eval_chain.html |
ea32e5bd8a3c-0 | Source code for langchain.tools.plugin
from __future__ import annotations
import json
from typing import Optional, Type
import requests
import yaml
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.pydantic_v1 import BaseModel
from langchain.to... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html |
ea32e5bd8a3c-1 | """Tool for getting the OpenAPI spec for an AI Plugin."""
plugin: AIPlugin
api_spec: str
args_schema: Type[AIPluginToolSchema] = AIPluginToolSchema
[docs] @classmethod
def from_plugin_url(cls, url: str) -> AIPluginTool:
plugin = AIPlugin.from_url(url)
description = (
f"Cal... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/plugin.html |
e1e31f11c427-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... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html |
e1e31f11c427-1 | - To get your webhook URL go to https://ifttt.com/maker_webhooks/settings
- Copy the IFTTT key value from there. The URL is of the form
https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value.
"""
from typing import Optional
import requests
from langchain.callbacks.manager import CallbackManagerForToo... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/ifttt.html |
d3a58e856abb-0 | Source code for langchain.tools.retriever
from langchain.pydantic_v1 import BaseModel, Field
from langchain.schema import BaseRetriever
from langchain.tools import Tool
[docs]class RetrieverInput(BaseModel):
query: str = Field(description="query to look up in retriever")
[docs]def create_retriever_tool(
retriev... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/retriever.html |
7985312c07e7-0 | Source code for langchain.tools.base
"""Base implementation for tools or skills."""
from __future__ import annotations
import asyncio
import inspect
import warnings
from abc import abstractmethod
from functools import partial
from inspect import signature
from typing import Any, Awaitable, Callable, Dict, List, Optiona... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-1 | class _SchemaConfig:
"""Configuration for the pydantic model."""
extra: Any = Extra.forbid
arbitrary_types_allowed: bool = True
[docs]def create_schema_from_function(
model_name: str,
func: Callable,
) -> Type[BaseModel]:
"""Create a pydantic schema from a function's signature.
Args:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-2 | """Interface LangChain tools must implement."""
def __init_subclass__(cls, **kwargs: Any) -> None:
"""Create the definition of the new tool class."""
super().__init_subclass__(**kwargs)
args_schema_type = cls.__annotations__.get("args_schema", None)
if args_schema_type is not None:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-3 | that after the tool is called, the AgentExecutor will stop looping.
"""
verbose: bool = False
"""Whether to log the tool's progress."""
callbacks: Callbacks = Field(default=None, exclude=True)
"""Callbacks to be called during tool execution."""
callback_manager: Optional[BaseCallbackManager] = F... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-4 | if self.args_schema is not None:
return self.args_schema.schema()["properties"]
else:
schema = create_schema_from_function(self.name, self._run)
return schema.schema()["properties"]
# --- Runnable ---
[docs] def get_input_schema(
self, config: Optional[Runnable... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-5 | """Convert tool input to pydantic model."""
input_args = self.args_schema
if isinstance(tool_input, str):
if input_args is not None:
key_ = next(iter(input_args.__fields__.keys()))
input_args.validate({key_: tool_input})
return tool_input
e... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-6 | partial(self._run, **kwargs),
*args,
)
def _to_args_and_kwargs(self, tool_input: Union[str, Dict]) -> Tuple[Tuple, Dict]:
# For backwards compatibility, if run_input is a string,
# pass as a positional argument.
if isinstance(tool_input, str):
return (tool_inp... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-7 | name=run_name,
**kwargs,
)
try:
tool_args, tool_kwargs = self._to_args_and_kwargs(parsed_input)
observation = (
self._run(*tool_args, run_manager=run_manager, **tool_kwargs)
if new_arg_supported
else self._run(*tool_args... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-8 | callbacks: Callbacks = None,
*,
tags: Optional[List[str]] = None,
metadata: Optional[Dict[str, Any]] = None,
run_name: Optional[str] = None,
**kwargs: Any,
) -> Any:
"""Run the tool asynchronously."""
parsed_input = self._parse_input(tool_input)
if not... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-9 | 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)
else:
raise... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-10 | return await asyncio.get_running_loop().run_in_executor(
None, partial(self.invoke, input, config, **kwargs)
)
return await super().ainvoke(input, config, **kwargs)
# --- Tool ---
@property
def args(self) -> dict:
"""The tool's input arguments."""
if self.... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-11 | if new_argument_supported
else self.func(*args, **kwargs)
)
raise NotImplementedError("Tool does not support sync")
async def _arun(
self,
*args: Any,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
**kwargs: Any,
) -> Any:
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-12 | coroutine: Optional[
Callable[..., Awaitable[Any]]
] = None, # This is last for compatibility, but should be after func
**kwargs: Any,
) -> Tool:
"""Initialize tool from a function."""
if func is None and coroutine is None:
raise ValueError("Function and/or c... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-13 | def args(self) -> dict:
"""The tool's input arguments."""
return self.args_schema.schema()["properties"]
def _run(
self,
*args: Any,
run_manager: Optional[CallbackManagerForToolRun] = None,
**kwargs: Any,
) -> Any:
"""Use the tool."""
if self.func:... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-14 | cls,
func: Optional[Callable] = None,
coroutine: Optional[Callable[..., Awaitable[Any]]] = None,
name: Optional[str] = None,
description: Optional[str] = None,
return_direct: bool = False,
args_schema: Optional[Type[BaseModel]] = None,
infer_schema: bool = True,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-15 | if description is None:
raise ValueError(
"Function must have a docstring if description not provided."
)
# Description example:
# search_api(query: str) - Searches the API for the query.
sig = signature(source_function)
description = f"{name}{sig}... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-16 | # 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(dec_func: U... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
7985312c07e7-17 | )
# If someone doesn't want a schema applied, we must treat it as
# a simple string->string function
if func.__doc__ is None:
raise ValueError(
"Function must have a docstring if "
"description not provided and infer_schema is F... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/base.html |
a050af5d6a8d-0 | Source code for langchain.tools.yahoo_finance_news
from typing import Iterable, Optional
from requests.exceptions import HTTPError, ReadTimeout
from urllib3.exceptions import ConnectionError
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.document_loaders.web_base import WebBaseLoader
f... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/yahoo_finance_news.html |
a050af5d6a8d-1 | except (HTTPError, ReadTimeout, ConnectionError):
if not links:
return f"No news found for company that searched with {query} ticker."
if not links:
return f"No news found for company that searched with {query} ticker."
loader = WebBaseLoader(web_paths=links)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/yahoo_finance_news.html |
e94730fecfd7-0 | Source code for langchain.tools.render
"""Different methods for rendering Tools to be passed to LLMs.
Depending on the LLM you are using and the prompting strategy you are using,
you may want Tools to be rendered in a different way.
This module contains various ways to render tools.
"""
from typing import List
from lan... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/render.html |
e94730fecfd7-1 | """Format tool into the OpenAI function API."""
if tool.args_schema:
return convert_pydantic_to_openai_function(
tool.args_schema, name=tool.name, description=tool.description
)
else:
return {
"name": tool.name,
"description": tool.description,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/render.html |
90335ecbeb3f-0 | Source code for langchain.tools.nuclia.tool
"""Tool for the Nuclia Understanding API.
Installation:
```bash
pip install --upgrade protobuf
pip install nucliadb-protos
```
"""
import asyncio
import base64
import logging
import mimetypes
import os
from typing import Any, Dict, Optional, Type, Union
import request... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
90335ecbeb3f-1 | """Tool to process files with the Nuclia Understanding API."""
name: str = "nuclia_understanding_api"
description: str = (
"A wrapper around Nuclia Understanding API endpoints. "
"Useful for when you need to extract text from any kind of files. "
)
args_schema: Type[BaseModel] = NUASchem... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
90335ecbeb3f-2 | self,
action: str,
id: str,
path: Optional[str] = None,
text: Optional[str] = None,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
"""Use the tool asynchronously."""
self._check_params(path, text)
if path:
self._pus... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
90335ecbeb3f-3 | )
return ""
else:
field = {
"filefield": {"file": f"{response.text}"},
"processing_options": {"ml_text": self._config["enable_ml"]},
}
return self._pushField(id, field)
def _pushField(self, id: str, f... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
90335ecbeb3f-4 | try:
from nucliadb_protos.writer_pb2 import BrokerMessage
except ImportError as e:
raise ImportError(
"nucliadb-protos is not installed. "
"Run `pip install nucliadb-protos` to install."
) from e
try:
from google.protobuf.js... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
90335ecbeb3f-5 | if result["uuid"] == uuid:
return id
return None
def _check_params(self, path: Optional[str], text: Optional[str]) -> None:
if not path and not text:
raise ValueError("File path or text is required")
if path and text:
raise ValueError("Cannot process b... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/nuclia/tool.html |
0834ebc9c86c-0 | Source code for langchain.tools.sql_database.tool
# flake8: noqa
"""Tools for interacting with a SQL database."""
from typing import Any, Dict, Optional
from langchain.pydantic_v1 import BaseModel, Extra, Field, root_validator
from langchain.schema.language_model import BaseLanguageModel
from langchain.callbacks.manage... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/sql_database/tool.html |
0834ebc9c86c-1 | name: str = "sql_db_schema"
description: str = """
Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.
Example Input: "table1, table2, table3"
"""
def _run(
self,
table_names: str,
run_manager: Optional[CallbackMa... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/sql_database/tool.html |
0834ebc9c86c-2 | Use this tool to double check if your query is correct before executing it.
Always use this tool before executing a query with sql_db_query!
"""
@root_validator(pre=True)
def initialize_llm_chain(cls, values: Dict[str, Any]) -> Dict[str, Any]:
if "llm_chain" not in values:
values["ll... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/sql_database/tool.html |
83f04f7c86db-0 | Source code for langchain.tools.sleep.tool
"""Tool for agent to sleep."""
from asyncio import sleep as asleep
from time import sleep
from typing import Optional, Type
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.pydantic_v1 import BaseMode... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/sleep/tool.html |
5ddce0bcf8c0-0 | Source code for langchain.tools.google_serper.tool
"""Tool for the Serper.dev Google Search API."""
from typing import Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.pydantic_v1 import Field
from langchain.tools.base import BaseTool... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html |
5ddce0bcf8c0-1 | )
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(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/google_serper/tool.html |
e7a0267fdf90-0 | Source code for langchain.tools.searchapi.tool
"""Tool for the SearchApi.io search API."""
from typing import Optional
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
CallbackManagerForToolRun,
)
from langchain.pydantic_v1 import Field
from langchain.tools.base import BaseTool
from lan... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/searchapi/tool.html |
e7a0267fdf90-1 | "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))... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/searchapi/tool.html |
a3153f92c86d-0 | Source code for langchain.tools.edenai.text_moderation
from __future__ import annotations
import logging
from typing import Optional
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class EdenAiTex... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/text_moderation.html |
a3153f92c86d-1 | )
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_likel... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/text_moderation.html |
0f362f608e28-0 | Source code for langchain.tools.edenai.ocr_identityparser
from __future__ import annotations
import logging
from typing import Optional
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class EdenAi... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/ocr_identityparser.html |
0f362f608e28-1 | )
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_... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/ocr_identityparser.html |
03b9b9a9843d-0 | Source code for langchain.tools.edenai.edenai_base_tool
from __future__ import annotations
import logging
from abc import abstractmethod
from typing import Any, Dict, List, Optional
import requests
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.pydantic_v1 import root_validator
from la... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/edenai_base_tool.html |
03b9b9a9843d-1 | query_params (dict): The parameters to include in the API call.
Returns:
requests.Response: The response from the EdenAI API call.
"""
# faire l'API call
headers = {
"Authorization": f"Bearer {self.edenai_api_key}",
"User-Agent": self.get_user_agent(),... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/edenai_base_tool.html |
03b9b9a9843d-2 | # not the provider response directly
provider_response = response.json()[0]
if provider_response.get("status") == "fail":
err_msg = provider_response["error"]["message"]
raise ValueError(err_msg)
@abstractmethod
def _run(
self, query: str, run_mana... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/edenai_base_tool.html |
03b9b9a9843d-3 | self._parse_json_multilevel(subsections, formatted_list, level + 1)
def _list_handling(
self, subsection_list: list, formatted_list: list, level: int
) -> None:
for list_item in subsection_list:
if isinstance(list_item, dict):
self._parse_json_multilevel(list_item, fo... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/edenai_base_tool.html |
945286f12749-0 | Source code for langchain.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.callbacks.manager import CallbackManagerForToolRun
from langchain.pydantic_v1 import validator
from langchain.tools.edena... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_speech_to_text.html |
945286f12749-1 | """
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 "
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_speech_to_text.html |
945286f12749-2 | job_id = self._call_eden_ai(query_params)
url = self.base_url + job_id
audio_analysis_result = self._wait_processing(url)
result = audio_analysis_result.text
formatted_text = json.loads(result)
return formatted_text["results"][self.providers[0]]["text"] | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_speech_to_text.html |
c0f42b82dcd8-0 | Source code for langchain.tools.edenai.image_explicitcontent
from __future__ import annotations
import logging
from typing import Optional
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class Ede... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/image_explicitcontent.html |
c0f42b82dcd8-1 | 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") ... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/image_explicitcontent.html |
fa614e4eb715-0 | Source code for langchain.tools.edenai.image_objectdetection
from __future__ import annotations
import logging
from typing import Optional
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class Ede... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/image_objectdetection.html |
fa614e4eb715-1 | [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 "... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/image_objectdetection.html |
2035afb79f94-0 | Source code for langchain.tools.edenai.audio_text_to_speech
from __future__ import annotations
import logging
from typing import Dict, List, Literal, Optional
import requests
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.pydantic_v1 import Field, root_validator, validator
from langcha... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_text_to_speech.html |
2035afb79f94-1 | 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.... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_text_to_speech.html |
2035afb79f94-2 | 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_typ... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/audio_text_to_speech.html |
e8578dbbcc61-0 | Source code for langchain.tools.edenai.ocr_invoiceparser
from __future__ import annotations
import logging
from typing import Optional
from langchain.callbacks.manager import CallbackManagerForToolRun
from langchain.tools.edenai.edenai_base_tool import EdenaiTool
logger = logging.getLogger(__name__)
[docs]class EdenAiP... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/ocr_invoiceparser.html |
e8578dbbcc61-1 | )
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,
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/edenai/ocr_invoiceparser.html |
db0a1bc6c0bc-0 | Source code for langchain.tools.e2b_data_analysis.tool
from __future__ import annotations
import ast
import json
import os
from io import StringIO
from sys import version_info
from typing import IO, TYPE_CHECKING, Any, Callable, List, Optional, Type
from langchain.callbacks.manager import (
AsyncCallbackManagerForT... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html |
db0a1bc6c0bc-1 | """Add print statement to the last line if it's missing.
Sometimes, the LLM-generated code doesn't have `print(variable_name)`, instead the
LLM tries to print the variable only by writing `variable_name` (as you would in
REPL, for example).
This methods checks the AST of the generated Python cod... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html |
db0a1bc6c0bc-2 | name = "e2b_data_analysis"
args_schema: Type[BaseModel] = E2BDataAnalysisToolArguments
session: Any
_uploaded_files: List[UploadedFile] = PrivateAttr(default_factory=list)
def __init__(
self,
api_key: Optional[str] = None,
cwd: Optional[str] = None,
env_vars: Optional[Env... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html |
db0a1bc6c0bc-3 | if len(self._uploaded_files) == 0:
return ""
lines = ["The following files available in the sandbox:"]
for f in self._uploaded_files:
if f.description == "":
lines.append(f"- path: `{f.remote_path}`")
else:
lines.append(
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html |
db0a1bc6c0bc-4 | output = proc.wait()
return {
"stdout": output.stdout,
"stderr": output.stderr,
"exit_code": output.exit_code,
}
[docs] def install_python_packages(self, package_names: str | List[str]) -> None:
"""Install python packages in the sandbox."""
self.ses... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html |
db0a1bc6c0bc-5 | [docs] def as_tool(self) -> Tool:
return Tool.from_function(
func=self._run,
name=self.name,
description=self.description,
args_schema=self.args_schema,
) | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/tool.html |
60eb0b161d5e-0 | Source code for langchain.tools.e2b_data_analysis.unparse
# mypy: disable-error-code=no-untyped-def
# Because Python >3.9 doesn't support ast.unparse,
# we copied the unparse functionality from here:
# https://github.com/python/cpython/blob/3.8/Tools/parser/unparse.py
"Usage: unparse.py <path to source file>"
import as... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-1 | "Append a piece of text to the current line."
self.f.write(text)
[docs] def enter(self):
"Print ':', and increase the indentation."
self.write(":")
self._indent += 1
[docs] def leave(self):
"Decrease the indentation level."
self._indent -= 1
[docs] def dispatch(s... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-2 | if t.module:
self.write(t.module)
self.write(" import ")
interleave(lambda: self.write(", "), self.dispatch, t.names)
def _Assign(self, t):
self.fill()
for target in t.targets:
self.dispatch(target)
self.write(" = ")
self.dispatch(t.value)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-3 | def _Global(self, t):
self.fill("global ")
interleave(lambda: self.write(", "), self.write, t.names)
def _Nonlocal(self, t):
self.fill("nonlocal ")
interleave(lambda: self.write(", "), self.write, t.names)
def _Await(self, t):
self.write("(")
self.write("await")
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-4 | self.enter()
self.dispatch(t.finalbody)
self.leave()
def _ExceptHandler(self, t):
self.fill("except")
if t.type:
self.write(" ")
self.dispatch(t.type)
if t.name:
self.write(" as ")
self.write(t.name)
self.enter()... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-5 | self.write(" -> ")
self.dispatch(t.returns)
self.enter()
self.dispatch(t.body)
self.leave()
def _For(self, t):
self.__For_helper("for ", t)
def _AsyncFor(self, t):
self.__For_helper("async for ", t)
def __For_helper(self, fill, t):
self.fill(fill)
... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-6 | self.enter()
self.dispatch(t.orelse)
self.leave()
def _With(self, t):
self.fill("with ")
interleave(lambda: self.write(", "), self.dispatch, t.items)
self.enter()
self.dispatch(t.body)
self.leave()
def _AsyncWith(self, t):
self.fill("async ... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-7 | write(expr)
if t.conversion != -1:
conversion = chr(t.conversion)
assert conversion in "sra"
write(f"!{conversion}")
if t.format_spec:
write(":")
meth = getattr(self, "_fstring_" + type(t.format_spec).__name__)
meth(t.format_spec, w... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-8 | self.write("(")
self.dispatch(t.elt)
for gen in t.generators:
self.dispatch(gen)
self.write(")")
def _SetComp(self, t):
self.write("{")
self.dispatch(t.elt)
for gen in t.generators:
self.dispatch(gen)
self.write("}")
def _DictComp(s... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-9 | k, v = item
if k is None:
# for dictionary unpacking operator in dicts {**{'y': 2}}
# see PEP 448 for details
self.write("**")
self.dispatch(v)
else:
write_key_value_pair(k, v)
interleave(lambda: self.write("... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-10 | self.write("(")
self.dispatch(t.left)
self.write(" " + self.binop[t.op.__class__.__name__] + " ")
self.dispatch(t.right)
self.write(")")
cmpops = {
"Eq": "==",
"NotEq": "!=",
"Lt": "<",
"LtE": "<=",
"Gt": ">",
"GtE": ">=",
"Is":... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
60eb0b161d5e-11 | self.write(t.attr)
def _Call(self, t):
self.dispatch(t.func)
self.write("(")
comma = False
for e in t.args:
if comma:
self.write(", ")
else:
comma = True
self.dispatch(e)
for e in t.keywords:
if c... | lang/api.python.langchain.com/en/latest/_modules/langchain/tools/e2b_data_analysis/unparse.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.