id stringlengths 14 16 | text stringlengths 31 3.14k | source stringlengths 58 124 |
|---|---|---|
8daa9a81e3ca-0 | Source code for langchain.tools.plugin
from __future__ import annotations
import json
from typing import Optional
import requests
import yaml
from pydantic import BaseModel
from langchain.tools.base import BaseTool
class ApiConfig(BaseModel):
type: str
url: str
has_user_authentication: Optional[bool] = Fals... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/plugin.html |
8daa9a81e3ca-1 | plugin = AIPlugin.from_url(url)
description = (
f"Call this tool to get the OpenAPI spec (and usage guide) "
f"for interacting with the {plugin.name_for_human} API. "
f"You should only call this ONCE! What is the "
f"{plugin.name_for_human} API useful for? "
... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/plugin.html |
5a98b1d7ad61-0 | Source code for langchain.tools.base
"""Base implementation for tools or skills."""
from __future__ import annotations
from abc import ABC, abstractmethod
from inspect import signature
from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Type, Union
from pydantic import (
BaseModel,
Extra,
Fie... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
5a98b1d7ad61-1 | if schema_type is not None:
schema_annotations = dct.get("__annotations__", {})
args_schema_type = schema_annotations.get("args_schema", None)
if args_schema_type is None or args_schema_type == BaseModel:
# Throw errors for common mis-annotations.
# TO... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
5a98b1d7ad61-2 | )
for field_name in field_names
if field_name in model.__fields__
}
return create_model(name, **fields) # type: ignore
def get_filtered_args(inferred_model: Type[BaseModel], func: Callable) -> dict:
"""Get the arguments from a function's signature."""
schema = inferred_model.schema()["p... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
5a98b1d7ad61-3 | return_direct: bool = False
verbose: bool = False
callback_manager: BaseCallbackManager = Field(default_factory=get_callback_manager)
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
arbitrary_types_allowed = True
@property
def args(self) -> di... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
5a98b1d7ad61-4 | """If callback manager is None, set it.
This allows users to pass in None as callback manager, which is a nice UX.
"""
return callback_manager or get_callback_manager()
@abstractmethod
def _run(self, *args: Any, **kwargs: Any) -> str:
"""Use the tool."""
@abstractmethod
a... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
5a98b1d7ad61-5 | except (Exception, KeyboardInterrupt) as e:
self.callback_manager.on_tool_error(e, verbose=verbose_)
raise e
self.callback_manager.on_tool_end(
observation, verbose=verbose_, color=color, name=self.name, **kwargs
)
return observation
[docs] async def arun(
... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
5a98b1d7ad61-6 | )
try:
# We then call the tool on the tool input to get an observation
args, kwargs = _to_args_and_kwargs(tool_input)
observation = await self._arun(*args, **kwargs)
except (Exception, KeyboardInterrupt) as e:
if self.callback_manager.is_async:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/base.html |
0fa5c8230fed-0 | Source code for langchain.tools.openapi.utils.api_models
"""Pydantic models for parsing an OpenAPI spec."""
import logging
from enum import Enum
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type, Union
from openapi_schema_pydantic import MediaType, Parameter, Reference, RequestBody, Schema
from pydant... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-1 | )
_SUPPORTED_MEDIA_TYPES = ("application/json",)
SUPPORTED_LOCATIONS = {
APIPropertyLocation.QUERY,
APIPropertyLocation.PATH,
}
INVALID_LOCATION_TEMPL = (
'Unsupported APIPropertyLocation "{location}"'
" for parameter {name}. "
+ f"Valid values are {[loc.value for loc in SUPPORTED_LOCATIONS]}"
)
SCH... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-2 | """The default value of the property."""
description: Optional[str] = Field(alias="description", default=None)
"""The description of the property."""
class APIProperty(APIPropertyBase):
"""A model for a property in the query, path, header, or cookie params."""
location: APIPropertyLocation = Field(alias... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-3 | ref_name = items.ref.split("/")[-1]
schema_type = ref_name # TODO: Add ref definitions to make his valid
else:
raise ValueError(f"Unsupported array items: {items}")
if isinstance(schema_type, str):
# TODO: recurse
schema_type = (schema_type,)
retu... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-4 | )
@staticmethod
def _validate_content(content: Optional[Dict[str, MediaType]]) -> None:
if content:
raise ValueError(
"API Properties with media content not supported. "
"Media content only supported within APIRequestBodyProperty's"
)
@staticme... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-5 | schema_type = cls._get_schema_type(parameter, schema)
default_val = schema.default if schema is not None else None
return cls(
name=parameter.name,
location=location,
default=default_val,
description=parameter.description,
required=parameter.re... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-6 | if ref_name not in references_used:
references_used.append(ref_name)
prop_schema = spec.get_referenced_schema(prop_schema)
else:
continue
properties.append(
cls.from_schema(
schema=prop_schema,
... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-7 | ) -> "APIRequestBodyProperty":
"""Recursively populate from an OpenAPI Schema."""
if references_used is None:
references_used = []
schema_type = schema.type
properties: List[APIRequestBodyProperty] = []
if schema_type == "object" and schema.properties:
sch... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-8 | """The media type of the request body."""
@classmethod
def _process_supported_media_type(
cls,
media_type_obj: MediaType,
spec: OpenAPISpec,
) -> List[APIRequestBodyProperty]:
"""Process the media type of the request body."""
references_used = []
schema = medi... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-9 | default=schema.default,
description=schema.description,
properties=[],
references_used=references_used,
)
)
return api_request_body_properties
@classmethod
def from_request_body(
cls, request_body: RequestBod... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-10 | """The HTTP method of the operation."""
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="componen... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-11 | """Create an APIOperation from an OpenAPI URL."""
spec = OpenAPISpec.from_url(spec_url)
return cls.from_openapi_spec(spec, path, method)
[docs] @classmethod
def from_openapi_spec(
cls,
spec: OpenAPISpec,
path: str,
method: str,
) -> "APIOperation":
"""C... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-12 | if type_ is None:
# TODO: Handle Nones better. These often result when
# parsing specs that are < v3
return "any"
elif isinstance(type_, str):
return {
"str": "string",
"integer": "number",
"float": "number",
... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-13 | formatted_props.append(
f"{prop_desc}\n{' ' * indent}{prop_name}{prop_required}: {prop_type},"
)
return "\n".join(formatted_props)
[docs] def to_typescript(self) -> str:
"""Get typescript string representation of the operation."""
operation_name = self.operation_id... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
0fa5c8230fed-14 | """
return typescript_definition.strip()
@property
def query_params(self) -> List[str]:
return [
property.name
for property in self.properties
if property.location == APIPropertyLocation.QUERY
]
@property
def path_params(self) -> List[str]:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/api_models.html |
70e2183976d2-0 | Source code for langchain.tools.openapi.utils.openapi_utils
"""Utility functions for parsing an OpenAPI spec."""
import copy
import json
import logging
import re
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional, Union
import requests
import yaml
from openapi_schema_pydantic import ... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
70e2183976d2-1 | def _get_path_strict(self, path: str) -> PathItem:
path_item = self._paths_strict.get(path)
if not path_item:
raise ValueError(f"No path found for {path}")
return path_item
@property
def _components_strict(self) -> Components:
"""Get components or err."""
if s... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
70e2183976d2-2 | raise ValueError("No request body found in spec. ")
return request_bodies
def _get_referenced_parameter(self, ref: Reference) -> Union[Parameter, Reference]:
"""Get a parameter (or nested reference) or err."""
ref_name = ref.ref.split("/")[-1]
parameters = self._parameters_strict
... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
70e2183976d2-3 | schema = self.get_referenced_schema(schema)
return schema
def _get_referenced_request_body(
self, ref: Reference
) -> Optional[Union[Reference, RequestBody]]:
"""Get a request body (or nested reference) or err."""
ref_name = ref.ref.split("/")[-1]
request_bodies = self._r... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
70e2183976d2-4 | if openapi_version != "3.1.0":
logger.warning(
f"Attempting to load an OpenAPI {openapi_version}"
f" spec. {warning_message}"
)
else:
pass
elif isinstance(swagger_version, str):
logger.warning(
... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
70e2183976d2-5 | return cls.parse_obj(spec_dict)
[docs] @classmethod
def from_text(cls, text: str) -> "OpenAPISpec":
"""Get an OpenAPI spec from a text."""
try:
spec_dict = json.loads(text)
except json.JSONDecodeError:
spec_dict = yaml.safe_load(text)
return cls.from_spec_d... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
70e2183976d2-6 | path_item = self._get_path_strict(path)
results = []
for method in HTTPVerb:
operation = getattr(path_item, method.value, None)
if isinstance(operation, Operation):
results.append(method.value)
return results
[docs] def get_operation(self, path: str, me... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
70e2183976d2-7 | return request_body
[docs] @staticmethod
def get_cleaned_operation_id(operation: Operation, path: str, method: str) -> str:
"""Get a cleaned operation id from an operation id."""
operation_id = operation.operationId
if operation_id is None:
# Replace all punctuation of any kin... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/openapi/utils/openapi_utils.html |
31c4f6d930d9-0 | Source code for langchain.tools.google_places.tool
"""Tool for the Google search API."""
from pydantic import Field
from langchain.tools.base import BaseTool
from langchain.utilities.google_places_api import GooglePlacesAPIWrapper
[docs]class GooglePlacesTool(BaseTool):
"""Tool that adds the capability to query the... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/google_places/tool.html |
35917a17fb49-0 | Source code for langchain.tools.ddg_search.tool
"""Tool for the DuckDuckGo search API."""
from pydantic import Field
from langchain.tools.base import BaseTool
from langchain.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper
[docs]class DuckDuckGoSearchTool(BaseTool):
"""Tool that adds the capability to ... | /content/https://python.langchain.com/en/latest/_modules/langchain/tools/ddg_search/tool.html |
ad523ea50093-0 | Source code for langchain.agents.tools
"""Interface for tools."""
from functools import partial
from inspect import signature
from typing import Any, Awaitable, Callable, Optional, Type, Union
from pydantic import BaseModel, validate_arguments, validator
from langchain.tools.base import (
BaseTool,
create_schem... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html |
ad523ea50093-1 | return get_filtered_args(inferred_model, self.func)
def _run(self, *args: Any, **kwargs: Any) -> str:
"""Use the tool."""
return self.func(*args, **kwargs)
async def _arun(self, *args: Any, **kwargs: Any) -> str:
"""Use the tool asynchronously."""
if self.coroutine:
r... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html |
ad523ea50093-2 | return f"{tool_name} is not a valid tool, try another one."
[docs]def tool(
*args: Union[str, Callable],
return_direct: bool = False,
args_schema: Optional[Type[BaseModel]] = None,
infer_schema: bool = True,
) -> Callable:
"""Make tools out of functions, can be used with or without arguments.
Ar... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html |
ad523ea50093-3 | # search_api(query: str) - Searches the API for the query.
description = f"{tool_name}{signature(func)} - {func.__doc__.strip()}"
_args_schema = args_schema
if _args_schema is None and infer_schema:
_args_schema = create_schema_from_function(f"{tool_name}Schema", func... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html |
ad523ea50093-4 | return _partial
else:
raise ValueError("Too many arguments for tool decorator")
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/tools.html |
558923da0823-0 | Source code for langchain.agents.initialize
"""Load agent."""
from typing import Any, Optional, Sequence
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_types import AgentType
from langchain.agents.loading import AGENT_TO_CLASS, load_agent
from langchain.callbacks.base import BaseCallbackMa... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
558923da0823-1 | Returns:
An agent executor
"""
if agent is None and agent_path is None:
agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION
if agent is not None and agent_path is not None:
raise ValueError(
"Both `agent` and `agent_path` are specified, "
"but at most only one shoul... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
14ba62d9a654-0 | Source code for langchain.agents.agent_types
from enum import Enum
[docs]class AgentType(str, Enum):
ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description"
REACT_DOCSTORE = "react-docstore"
SELF_ASK_WITH_SEARCH = "self-ask-with-search"
CONVERSATIONAL_REACT_DESCRIPTION = "conversational-react-descri... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_types.html |
dea473ba6390-0 | Source code for langchain.agents.loading
"""Functionality for loading agents."""
import json
from pathlib import Path
from typing import Any, Dict, List, Optional, Type, Union
import yaml
from langchain.agents.agent import BaseSingleActionAgent
from langchain.agents.agent_types import AgentType
from langchain.agents.ch... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
dea473ba6390-1 | AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION: ConversationalChatAgent,
}
URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/agents/"
def _load_agent_from_tools(
config: dict, llm: BaseLLM, tools: List[Tool], **kwargs: Any
) -> BaseSingleActionAgent:
config_type = config.pop("_type")... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
dea473ba6390-2 | "then LLM must be provided"
)
if tools is None:
raise ValueError(
"If `load_from_llm_and_tools` is set to True, "
"then tools must be provided"
)
return _load_agent_from_tools(config, llm, tools, **kwargs)
config_type = config.pop("... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
dea473ba6390-3 | ):
return hub_result
else:
return _load_agent_from_file(path, **kwargs)
def _load_agent_from_file(
file: Union[str, Path], **kwargs: Any
) -> BaseSingleActionAgent:
"""Load agent from file."""
# Convert file to Path object.
if isinstance(file, str):
file_path = Path(file)
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
670412907735-0 | Source code for langchain.agents.load_tools
# flake8: noqa
"""Load tools."""
import warnings
from typing import Any, Dict, List, Optional, Callable, Tuple
from mypy_extensions import Arg, KwArg
from langchain.agents.tools import Tool
from langchain.callbacks.base import BaseCallbackManager
from langchain.chains.api imp... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-1 | from langchain.tools.wikipedia.tool import WikipediaQueryRun
from langchain.tools.wolfram_alpha.tool import WolframAlphaQueryRun
from langchain.utilities import ArxivAPIWrapper
from langchain.utilities.apify import ApifyWrapper
from langchain.utilities.bash import BashProcess
from langchain.utilities.bing_search import... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-2 | def _get_tools_requests_put() -> BaseTool:
return RequestsPutTool(requests_wrapper=TextRequestsWrapper())
def _get_tools_requests_delete() -> BaseTool:
return RequestsDeleteTool(requests_wrapper=TextRequestsWrapper())
def _get_terminal() -> BaseTool:
return Tool(
name="Terminal",
description... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-3 | return Tool(
name="PAL-MATH",
description="A language model that is really good at solving complex word math problems. Input should be a fully worded hard word math problem.",
func=PALChain.from_math_prompt(llm).run,
)
def _get_pal_colored_objects(llm: BaseLLM) -> BaseTool:
return Tool(
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-4 | func=chain.run,
)
_LLM_TOOLS: Dict[str, Callable[[BaseLLM], BaseTool]] = {
"pal-math": _get_pal_math,
"pal-colored-objects": _get_pal_colored_objects,
"llm-math": _get_llm_math,
"open-meteo-api": _get_open_meteo_api,
}
def _get_news_api(llm: BaseLLM, **kwargs: Any) -> BaseTool:
news_api_key = kw... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-5 | )
return Tool(
name="TMDB API",
description="Useful for when you want to get information from The Movie Database. The input should be a question in natural language that this API can answer.",
func=chain.run,
)
def _get_podcast_api(llm: BaseLLM, **kwargs: Any) -> BaseTool:
listen_api... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-6 | def _get_google_serper(**kwargs: Any) -> BaseTool:
return Tool(
name="Serper Search",
func=GoogleSerperAPIWrapper(**kwargs).run,
description="A low-cost Google Search API. Useful for when you need to answer questions about current events. Input should be a search query.",
)
def _get_goog... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-7 | def _get_bing_search(**kwargs: Any) -> BaseTool:
return BingSearchRun(api_wrapper=BingSearchAPIWrapper(**kwargs))
def _get_ddg_search(**kwargs: Any) -> BaseTool:
return DuckDuckGoSearchTool(api_wrapper=DuckDuckGoSearchAPIWrapper(**kwargs))
def _get_human_tool(**kwargs: Any) -> BaseTool:
return HumanInputRun... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-8 | "google-search-results-json": (
_get_google_search_results_json,
["google_api_key", "google_cse_id", "num_results"],
),
"searx-search-results-json": (
_get_searx_search_results_json,
["searx_host", "engines", "num_results", "aiosession"],
),
"bing-search": (_get_bing_sear... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-9 | ) -> List[BaseTool]:
"""Load tools based on their name.
Args:
tool_names: name of tools to load.
llm: Optional language model, may be needed to initialize certain tools.
callback_manager: Optional callback manager. If not provided, default global callback manager will be used.
Return... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-10 | raise ValueError(f"Tool {name} requires an LLM to be provided")
_get_llm_tool_func, extra_keys = _EXTRA_LLM_TOOLS[name]
missing_keys = set(extra_keys).difference(kwargs)
if missing_keys:
raise ValueError(
f"Tool {name} requires some parameters that... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
670412907735-11 | + list(_EXTRA_LLM_TOOLS)
+ list(_LLM_TOOLS)
)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
a50ba6816556-0 | Source code for langchain.agents.agent
"""Chain that takes in an input and produces an action and action input."""
from __future__ import annotations
import asyncio
import json
import logging
import time
from abc import abstractmethod
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tupl... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-1 | return None
[docs] @abstractmethod
def plan(
self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along wi... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-2 | # `force` just returns a constant string
return AgentFinish(
{"output": "Agent stopped due to iteration limit or time limit."}, ""
)
else:
raise ValueError(
f"Got unsupported early_stopping_method `{early_stopping_method}`"
)
[docs]... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-3 | save_path = Path(file_path)
else:
save_path = file_path
directory_path = save_path.parent
directory_path.mkdir(parents=True, exist_ok=True)
# Fetch dictionary to save
agent_dict = self.dict()
if save_path.suffix == ".json":
with open(file_path, "w"... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-4 | intermediate_steps: Steps the LLM has taken to date,
along with observations
**kwargs: User inputs.
Returns:
Actions specifying what tool to use.
"""
[docs] @abstractmethod
async def aplan(
self, intermediate_steps: List[Tuple[AgentAction, str]], **... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-5 | )
@property
def _agent_type(self) -> str:
"""Return Identifier of agent type."""
raise NotImplementedError
[docs] def dict(self, **kwargs: Any) -> Dict:
"""Return dictionary representation of agent."""
_dict = super().dict()
_dict["_type"] = str(self._agent_type)
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-6 | raise ValueError(f"{save_path} must be json or yaml")
[docs] def tool_run_logging_kwargs(self) -> Dict:
return {}
[docs]class AgentOutputParser(BaseOutputParser):
[docs] @abstractmethod
def parse(self, text: str) -> Union[AgentAction, AgentFinish]:
"""Parse text into agent action/finish."""
[d... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-7 | [docs] async def aplan(
self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-8 | return ["output"]
def _fix_text(self, text: str) -> str:
"""Fix the text."""
raise ValueError("fix_text not implemented for this agent.")
@property
def _stop(self) -> List[str]:
return [
f"\n{self.observation_prefix.rstrip()}",
f"\n\t{self.observation_prefix.r... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-9 | return self.output_parser.parse(full_output)
[docs] async def aplan(
self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-10 | """Return the input keys.
:meta private:
"""
return list(set(self.llm_chain.input_keys) - {"agent_scratchpad"})
@root_validator()
def validate_prompt(cls, values: Dict) -> Dict:
"""Validate that prompt matches format."""
prompt = values["llm_chain"].prompt
if "age... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-11 | [docs] @classmethod
@abstractmethod
def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate:
"""Create a prompt for this class."""
@classmethod
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
"""Validate that appropriate tools are passed in."""
pas... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-12 | output_parser=_output_parser,
**kwargs,
)
[docs] def return_stopped_response(
self,
early_stopping_method: str,
intermediate_steps: List[Tuple[AgentAction, str]],
**kwargs: Any,
) -> AgentFinish:
"""Return response when agent has been stopped due to max... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-13 | # If we can extract, we send the correct stuff
return parsed_output
else:
# If we can extract, but the tool is not the final tool,
# we just return the full output
return AgentFinish({"output": full_output}, full_output)
else:
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-14 | """Create from agent and tools."""
return cls(
agent=agent, tools=tools, callback_manager=callback_manager, **kwargs
)
@root_validator()
def validate_tools(cls, values: Dict) -> Dict:
"""Validate that tools are compatible with agent."""
agent = values["agent"]
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-15 | "If you are trying to save the agent, please use the "
"`.save_agent(...)`"
)
[docs] def save_agent(self, file_path: Union[Path, str]) -> None:
"""Save the underlying agent."""
return self.agent.save(file_path)
@property
def input_keys(self) -> List[str]:
"""Return... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-16 | self.callback_manager.on_agent_finish(
output, color="green", verbose=self.verbose
)
final_output = output.return_values
if self.return_intermediate_steps:
final_output["intermediate_steps"] = intermediate_steps
return final_output
async def _areturn(
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-17 | """
# Call the LLM to see what to do.
output = self.agent.plan(intermediate_steps, **inputs)
# If the tool chosen is the finishing tool, then we end and return.
if isinstance(output, AgentFinish):
return output
actions: List[AgentAction]
if isinstance(output, ... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-18 | return result
async def _atake_next_step(
self,
name_to_tool_map: Dict[str, BaseTool],
color_mapping: Dict[str, str],
inputs: Dict[str, str],
intermediate_steps: List[Tuple[AgentAction, str]],
) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:
"""Take a singl... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-19 | tool = name_to_tool_map[agent_action.tool]
return_direct = tool.return_direct
color = color_mapping[agent_action.tool]
tool_run_kwargs = self.agent.tool_run_logging_kwargs()
if return_direct:
tool_run_kwargs["llm_prefix"] = ""
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-20 | color_mapping = get_color_mapping(
[tool.name for tool in self.tools], excluded_colors=["green"]
)
intermediate_steps: List[Tuple[AgentAction, str]] = []
# Let's start tracking the number of iterations and time elapsed
iterations = 0
time_elapsed = 0.0
start_t... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-21 | )
return self._return(output, intermediate_steps)
async def _acall(self, inputs: Dict[str, str]) -> Dict[str, str]:
"""Run text through and get agent response."""
# Construct a mapping of tool name to tool for easy lookup
name_to_tool_map = {tool.name: tool for tool in self.tools}
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-22 | if len(next_step_output) == 1:
next_step_action = next_step_output[0]
# See if tool should return directly
tool_return = self._get_tool_return(next_step_action)
if tool_return is not None:
return ... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a50ba6816556-23 | return AgentFinish(
{self.agent.return_values[0]: observation},
"",
)
return None
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
a9f19190186a-0 | Source code for langchain.agents.agent_toolkits.openapi.toolkit
"""Requests toolkit."""
from __future__ import annotations
from typing import Any, List
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_toolkits.base import BaseToolkit
from langchain.agents.agent_toolkits.json.base import crea... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/toolkit.html |
a9f19190186a-1 | RequestsPatchTool(requests_wrapper=self.requests_wrapper),
RequestsPutTool(requests_wrapper=self.requests_wrapper),
RequestsDeleteTool(requests_wrapper=self.requests_wrapper),
]
[docs]class OpenAPIToolkit(BaseToolkit):
"""Toolkit for interacting with a OpenAPI api."""
json_agent:... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/toolkit.html |
a9f19190186a-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/toolkit.html |
952c1b58e65c-0 | Source code for langchain.agents.agent_toolkits.openapi.base
"""OpenAPI spec agent."""
from typing import Any, List, Optional
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_toolkits.openapi.prompt import (
OPENAPI_PREFIX,
OPENAPI_SUFFIX,
)
from langchain.agents.agent_toolkits.opena... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/base.html |
952c1b58e65c-1 | """Construct a json agent from an LLM and tools."""
tools = toolkit.get_tools()
prompt = ZeroShotAgent.create_prompt(
tools,
prefix=prefix,
suffix=suffix,
format_instructions=format_instructions,
input_variables=input_variables,
)
llm_chain = LLMChain(
llm... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/base.html |
30aeaf927060-0 | Source code for langchain.agents.agent_toolkits.csv.base
"""Agent for working with csvs."""
from typing import Any, Optional
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_toolkits.pandas.base import create_pandas_dataframe_agent
from langchain.llms.base import BaseLLM
[docs]def create_csv... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/csv/base.html |
d1ea5986c42a-0 | Source code for langchain.agents.agent_toolkits.vectorstore.toolkit
"""Toolkit for interacting with a vector store."""
from typing import List
from pydantic import BaseModel, Field
from langchain.agents.agent_toolkits.base import BaseToolkit
from langchain.llms.base import BaseLLM
from langchain.llms.openai import Open... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/toolkit.html |
d1ea5986c42a-1 | )
qa_tool = VectorStoreQATool(
name=self.vectorstore_info.name,
description=description,
vectorstore=self.vectorstore_info.vectorstore,
llm=self.llm,
)
description = VectorStoreQAWithSourcesTool.get_description(
self.vectorstore_info.na... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/toolkit.html |
d1ea5986c42a-2 | name=vectorstore_info.name,
description=description,
vectorstore=vectorstore_info.vectorstore,
llm=self.llm,
)
tools.append(qa_tool)
return tools
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/toolkit.html |
9c0c572199ee-0 | Source code for langchain.agents.agent_toolkits.vectorstore.base
"""VectorStore agent."""
from typing import Any, Optional
from langchain.agents.agent import AgentExecutor
from langchain.agents.agent_toolkits.vectorstore.prompt import PREFIX, ROUTER_PREFIX
from langchain.agents.agent_toolkits.vectorstore.toolkit import... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/base.html |
9c0c572199ee-1 | return AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=verbose)
[docs]def create_vectorstore_router_agent(
llm: BaseLLM,
toolkit: VectorStoreRouterToolkit,
callback_manager: Optional[BaseCallbackManager] = None,
prefix: str = ROUTER_PREFIX,
verbose: bool = False,
**kwargs: A... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/vectorstore/base.html |
c5733c638fe5-0 | Source code for langchain.agents.agent_toolkits.powerbi.toolkit
"""Toolkit for interacting with a Power BI dataset."""
from typing import List, Optional
from pydantic import Field
from langchain.agents.agent_toolkits.base import BaseToolkit
from langchain.callbacks.base import BaseCallbackManager
from langchain.chains.... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/toolkit.html |
c5733c638fe5-1 | llm=self.llm,
callback_manager=self.callback_manager,
prompt=PromptTemplate(
template=QUESTION_TO_QUERY,
input_variables=["tool_input", "tables", "schemas", "examples"],
),
),
)
... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/toolkit.html |
fd19e11b69c5-0 | Source code for langchain.agents.agent_toolkits.powerbi.chat_base
"""Power BI agent."""
from typing import Any, Dict, List, Optional
from langchain.agents import AgentExecutor
from langchain.agents.agent_toolkits.powerbi.prompt import (
POWERBI_CHAT_PREFIX,
POWERBI_CHAT_SUFFIX,
)
from langchain.agents.agent_too... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/chat_base.html |
fd19e11b69c5-1 | agent_kwargs: Optional[Dict[str, Any]] = None,
**kwargs: Dict[str, Any],
) -> AgentExecutor:
"""Construct a pbi agent from an Chat LLM and tools.
If you supply only a toolkit and no powerbi dataset, the same LLM is used for both.
"""
if toolkit is None:
if powerbi is None:
raise ... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/chat_base.html |
f7529697e2ed-0 | Source code for langchain.agents.agent_toolkits.powerbi.base
"""Power BI agent."""
from typing import Any, Dict, List, Optional
from langchain.agents import AgentExecutor
from langchain.agents.agent_toolkits.powerbi.prompt import (
POWERBI_PREFIX,
POWERBI_SUFFIX,
)
from langchain.agents.agent_toolkits.powerbi.t... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/base.html |
f7529697e2ed-1 | **kwargs: Dict[str, Any],
) -> AgentExecutor:
"""Construct a pbi agent from an LLM and tools."""
if toolkit is None:
if powerbi is None:
raise ValueError("Must provide either a toolkit or powerbi dataset")
toolkit = PowerBIToolkit(powerbi=powerbi, llm=llm, examples=examples)
tool... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/powerbi/base.html |
6f89066a113a-0 | Source code for langchain.agents.agent_toolkits.zapier.toolkit
"""Zapier Toolkit."""
from typing import List
from langchain.agents.agent_toolkits.base import BaseToolkit
from langchain.tools import BaseTool
from langchain.tools.zapier.tool import ZapierNLARunAction
from langchain.utilities.zapier import ZapierNLAWrappe... | /content/https://python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/zapier/toolkit.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.