id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
bd137fe8f7c0-5 | logger.error("Unable to Retreive chat history messages from cassadra")
raise error
if rows:
items = [json.loads(row.history) for row in rows]
else:
items = []
messages = messages_from_dict(items)
return messages
[docs] def add_message(self, message:... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
bd137fe8f7c0-6 | logger.error("Unable to write chat history messages to cassandra")
raise error
[docs] def clear(self) -> None:
"""Clear session memory from Cassandra"""
from cassandra import OperationTimedOut, Unavailable
try:
self.session.execute(
f"DELETE FROM {self.... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/cassandra.html |
0a2b0872d805-0 | Source code for langchain.memory.chat_message_histories.momento
from __future__ import annotations
import json
from datetime import timedelta
from typing import TYPE_CHECKING, Any, Optional
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
)
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
0a2b0872d805-1 | ):
return None
elif isinstance(create_cache_response, CreateCache.Error):
raise create_cache_response.inner_exception
else:
raise Exception(f"Unexpected response cache creation: {create_cache_response}")
[docs]class MomentoChatMessageHistory(BaseChatMessageHistory):
"""Chat message h... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
0a2b0872d805-2 | you must have a Momento account at https://gomomento.com/.
Args:
session_id (str): The session ID to use for this chat session.
cache_client (CacheClient): The Momento cache client.
cache_name (str): The name of the cache to use to store the messages.
key_prefix (... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
0a2b0872d805-3 | """
try:
from momento import CacheClient
from momento.requests import CollectionTtl
except ImportError:
raise ImportError(
"Could not import momento python package. "
"Please install it with `pip install momento`."
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
0a2b0872d805-4 | session_id: str,
cache_name: str,
ttl: timedelta,
*,
configuration: Optional[momento.config.Configuration] = None,
auth_token: Optional[str] = None,
**kwargs: Any,
) -> MomentoChatMessageHistory:
"""Construct cache from CacheClient parameters."""
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
0a2b0872d805-5 | return cls(session_id, cache_client, cache_name, ttl=ttl, **kwargs)
@property
def messages(self) -> list[BaseMessage]: # type: ignore[override]
"""Retrieve the messages from Momento.
Raises:
SdkException: Momento service or network error
Exception: Unexpected response
... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
0a2b0872d805-6 | else:
raise Exception(f"Unexpected response: {fetch_response}")
[docs] def add_message(self, message: BaseMessage) -> None:
"""Store a message in the cache.
Args:
message (BaseMessage): The message object to store.
Raises:
SdkException: Momento service or n... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
0a2b0872d805-7 | [docs] def clear(self) -> None:
"""Remove the session's messages from the cache.
Raises:
SdkException: Momento service or network error.
Exception: Unexpected response.
"""
from momento.responses import CacheDelete
delete_response = self.cache_client.de... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/momento.html |
5438ec6fbc3b-0 | Source code for langchain.memory.chat_message_histories.sql
import json
import logging
from typing import List
from sqlalchemy import Column, Integer, Text, create_engine
try:
from sqlalchemy.orm import declarative_base
except ImportError:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
5438ec6fbc3b-1 | The model class.
"""
# Model decleared inside a function to have a dynamic table name
class Message(DynamicBase):
__tablename__ = table_name
id = Column(Integer, primary_key=True)
session_id = Column(Text)
message = Column(Text)
return Message
[docs]class SQLChatMessageHi... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
5438ec6fbc3b-2 | self.Session = sessionmaker(self.engine)
def _create_table_if_not_exists(self) -> None:
DynamicBase = declarative_base()
self.Message = create_message_model(self.table_name, DynamicBase)
# Create all does the check for us in case the table exists.
DynamicBase.metadata.create_all(self... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
5438ec6fbc3b-3 | with self.Session() as session:
jsonstr = json.dumps(_message_to_dict(message))
session.add(self.Message(session_id=self.session_id, message=jsonstr))
session.commit()
[docs] def clear(self) -> None:
"""Clear session memory from db"""
with self.Session() as session... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/sql.html |
d4711c4f7408-0 | Source code for langchain.memory.chat_message_histories.file
import json
import logging
from pathlib import Path
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger(__name__)
[docs]class FileChatMe... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html |
d4711c4f7408-1 | """Retrieve the messages from the local file"""
items = json.loads(self.file_path.read_text())
messages = messages_from_dict(items)
return messages
[docs] def add_message(self, message: BaseMessage) -> None:
"""Append the message to the record in the local file"""
messages = m... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html |
81ad13d7d5a1-0 | Source code for langchain.memory.chat_message_histories.dynamodb
import logging
from typing import List, Optional
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
messages_to_dict,
)
logger = logging.getLogger(__name__)
[docs]class DynamoDBCha... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
81ad13d7d5a1-1 | If you plan to use AWS cloud service, you normally don't have to
worry about setting the endpoint_url.
"""
def __init__(
self, table_name: str, session_id: str, endpoint_url: Optional[str] = None
):
import boto3
if endpoint_url:
client = boto3.resource("dynamo... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
81ad13d7d5a1-2 | except ClientError as error:
if error.response["Error"]["Code"] == "ResourceNotFoundException":
logger.warning("No record found with session id: %s", self.session_id)
else:
logger.error(error)
if response and "Item" in response:
items = respons... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
81ad13d7d5a1-3 | )
except ClientError as err:
logger.error(err)
[docs] def clear(self) -> None:
"""Clear session memory from DynamoDB"""
from botocore.exceptions import ClientError
try:
self.table.delete_item(Key={"SessionId": self.session_id})
except ClientError as err... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/dynamodb.html |
a70cc688a55f-0 | Source code for langchain.memory.chat_message_histories.mongodb
import json
import logging
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_DBNAME = "chat_history"
DEFAULT_COLL... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
a70cc688a55f-1 | session_id: str,
database_name: str = DEFAULT_DBNAME,
collection_name: str = DEFAULT_COLLECTION_NAME,
):
from pymongo import MongoClient, errors
self.connection_string = connection_string
self.session_id = session_id
self.database_name = database_name
self.col... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
a70cc688a55f-2 | except errors.OperationFailure as error:
logger.error(error)
if cursor:
items = [json.loads(document["History"]) for document in cursor]
else:
items = []
messages = messages_from_dict(items)
return messages
[docs] def add_message(self, message: Base... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
a70cc688a55f-3 | except errors.WriteError as err:
logger.error(err) | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html |
5d196f3c5630-0 | Source code for langchain.memory.chat_message_histories.redis
import json
import logging
from typing import List, Optional
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
[docs]class RedisChatMessageHistory(... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
5d196f3c5630-1 | )
try:
self.redis_client = redis.Redis.from_url(url=url)
except redis.exceptions.ConnectionError as error:
logger.error(error)
self.session_id = session_id
self.key_prefix = key_prefix
self.ttl = ttl
@property
def key(self) -> str:
"""Const... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
5d196f3c5630-2 | """Append the message to the record in Redis"""
self.redis_client.lpush(self.key, json.dumps(_message_to_dict(message)))
if self.ttl:
self.redis_client.expire(self.key, self.ttl)
[docs] def clear(self) -> None:
"""Clear session memory from Redis"""
self.redis_client.delete... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/redis.html |
b3e0313d343b-0 | Source code for langchain.memory.chat_message_histories.postgres
import json
import logging
from typing import List
from langchain.schema import (
BaseChatMessageHistory,
BaseMessage,
_message_to_dict,
messages_from_dict,
)
logger = logging.getLogger(__name__)
DEFAULT_CONNECTION_STRING = "postgresql://p... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
b3e0313d343b-1 | except psycopg.OperationalError as error:
logger.error(error)
self.session_id = session_id
self.table_name = table_name
self._create_table_if_not_exists()
def _create_table_if_not_exists(self) -> None:
create_table_query = f"""CREATE TABLE IF NOT EXISTS {self.table_name} ... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
b3e0313d343b-2 | messages = messages_from_dict(items)
return messages
[docs] def add_message(self, message: BaseMessage) -> None:
"""Append the message to the record in PostgreSQL"""
from psycopg import sql
query = sql.SQL("INSERT INTO {} (session_id, message) VALUES (%s, %s);").format(
sq... | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
b3e0313d343b-3 | if self.cursor:
self.cursor.close()
if self.connection:
self.connection.close() | https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html |
85670147e7e7-0 | Source code for langchain.agents.loading
"""Functionality for loading agents."""
import json
import logging
from pathlib import Path
from typing import Any, List, Optional, Union
import yaml
from langchain.agents.agent import BaseMultiActionAgent, BaseSingleActionAgent
from langchain.agents.tools import Tool
from langc... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
85670147e7e7-1 | config_type = config.pop("_type")
if config_type not in AGENT_TO_CLASS:
raise ValueError(f"Loading {config_type} agent not supported")
agent_cls = AGENT_TO_CLASS[config_type]
combined_config = {**config, **kwargs}
return agent_cls.from_llm_and_tools(llm, tools, **combined_config)
def load_agent_... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
85670147e7e7-2 | if load_from_tools:
if llm is None:
raise ValueError(
"If `load_from_llm_and_tools` is set to True, "
"then LLM must be provided"
)
if tools is None:
raise ValueError(
"If `load_from_llm_and_tools` is set to True, "
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
85670147e7e7-3 | elif "llm_chain_path" in config:
config["llm_chain"] = load_chain(config.pop("llm_chain_path"))
else:
raise ValueError("One of `llm_chain` and `llm_chain_path` should be specified.")
if "output_parser" in config:
logger.warning(
"Currently loading output parsers on agent is n... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
85670147e7e7-4 | path, _load_agent_from_file, "agents", {"json", "yaml"}
):
return hub_result
else:
return _load_agent_from_file(path, **kwargs)
def _load_agent_from_file(
file: Union[str, Path], **kwargs: Any
) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:
"""Load agent from file."""
# Conv... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
85670147e7e7-5 | else:
raise ValueError("File type must be json or yaml")
# Load the agent from the config now.
return load_agent_from_config(config, **kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html |
6793ce3dc17b-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.base_language import BaseLanguageMod... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
6793ce3dc17b-1 | ) -> AgentExecutor:
"""Load an agent executor given tools and LLM.
Args:
tools: List of tools this agent has access to.
llm: Language model to use as the agent.
agent: Agent type to use. If None and agent_path is also None, will default to
AgentType.ZERO_SHOT_REACT_DESCRIPTIO... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
6793ce3dc17b-2 | 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 should be."
)
if agent is not None:
if agent not in AGENT_TO_CLASS:
r... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
6793ce3dc17b-3 | elif agent_path is not None:
agent_obj = load_agent(
agent_path, llm=llm, tools=tools, callback_manager=callback_manager
)
try:
# TODO: Add tags from the serialized object directly.
tags_.append(agent_obj._agent_type)
except NotImplementedError:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/initialize.html |
b425ffafe02c-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.base_language import BaseLanguageModel
from langchain.callbacks.base im... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-1 | from langchain.tools.base import BaseTool
from langchain.tools.bing_search.tool import BingSearchRun
from langchain.tools.ddg_search.tool import DuckDuckGoSearchRun
from langchain.tools.google_search.tool import GoogleSearchResults, GoogleSearchRun
from langchain.tools.metaphor_search.tool import MetaphorSearchResults
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-2 | from langchain.tools.searx_search.tool import SearxSearchResults, SearxSearchRun
from langchain.tools.shell.tool import ShellTool
from langchain.tools.sleep.tool import SleepTool
from langchain.tools.wikipedia.tool import WikipediaQueryRun
from langchain.tools.wolfram_alpha.tool import WolframAlphaQueryRun
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-3 | from langchain.utilities.searx_search import SearxSearchWrapper
from langchain.utilities.serpapi import SerpAPIWrapper
from langchain.utilities.twilio import TwilioAPIWrapper
from langchain.utilities.wikipedia import WikipediaAPIWrapper
from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper
from langchain... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-4 | return RequestsPutTool(requests_wrapper=TextRequestsWrapper())
def _get_tools_requests_delete() -> BaseTool:
return RequestsDeleteTool(requests_wrapper=TextRequestsWrapper())
def _get_terminal() -> BaseTool:
return ShellTool()
def _get_sleep() -> BaseTool:
return SleepTool()
_BASE_TOOLS: Dict[str, Callable[... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-5 | }
def _get_pal_math(llm: BaseLanguageModel) -> BaseTool:
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... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-6 | )
def _get_llm_math(llm: BaseLanguageModel) -> BaseTool:
return Tool(
name="Calculator",
description="Useful for when you need to answer questions about math.",
func=LLMMathChain.from_llm(llm=llm).run,
coroutine=LLMMathChain.from_llm(llm=llm).arun,
)
def _get_open_meteo_api(llm: ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-7 | func=chain.run,
)
_LLM_TOOLS: Dict[str, Callable[[BaseLanguageModel], 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: BaseLanguageModel, **kwargs: Any) -> BaseTool:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-8 | name="News API",
description="Use this when you want to get information about the top headlines of current news stories. The input should be a question in natural language that this API can answer.",
func=chain.run,
)
def _get_tmdb_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
tmdb_bea... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-9 | func=chain.run,
)
def _get_podcast_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool:
listen_api_key = kwargs["listen_api_key"]
chain = APIChain.from_llm_and_api_docs(
llm,
podcast_docs.PODCAST_DOCS,
headers={"X-ListenAPI-Key": listen_api_key},
)
return Tool(
nam... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-10 | )
def _get_wolfram_alpha(**kwargs: Any) -> BaseTool:
return WolframAlphaQueryRun(api_wrapper=WolframAlphaAPIWrapper(**kwargs))
def _get_google_search(**kwargs: Any) -> BaseTool:
return GoogleSearchRun(api_wrapper=GoogleSearchAPIWrapper(**kwargs))
def _get_wikipedia(**kwargs: Any) -> BaseTool:
return Wikiped... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-11 | def _get_google_serper_results_json(**kwargs: Any) -> BaseTool:
return GoogleSerperResults(api_wrapper=GoogleSerperAPIWrapper(**kwargs))
def _get_google_search_results_json(**kwargs: Any) -> BaseTool:
return GoogleSearchResults(api_wrapper=GoogleSearchAPIWrapper(**kwargs))
def _get_serpapi(**kwargs: Any) -> Bas... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-12 | func=TwilioAPIWrapper(**kwargs).run,
)
def _get_searx_search(**kwargs: Any) -> BaseTool:
return SearxSearchRun(wrapper=SearxSearchWrapper(**kwargs))
def _get_searx_search_results_json(**kwargs: Any) -> BaseTool:
wrapper_kwargs = {k: v for k, v in kwargs.items() if k != "num_results"}
return SearxSearchR... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-13 | return DuckDuckGoSearchRun(api_wrapper=DuckDuckGoSearchAPIWrapper(**kwargs))
def _get_human_tool(**kwargs: Any) -> BaseTool:
return HumanInputRun(**kwargs)
def _get_scenexplain(**kwargs: Any) -> BaseTool:
return SceneXplainTool(**kwargs)
def _get_graphql_tool(**kwargs: Any) -> BaseTool:
graphql_endpoint = k... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-14 | ] = {
"news-api": (_get_news_api, ["news_api_key"]),
"tmdb-api": (_get_tmdb_api, ["tmdb_bearer_token"]),
"podcast-api": (_get_podcast_api, ["listen_api_key"]),
}
_EXTRA_OPTIONAL_TOOLS: Dict[str, Tuple[Callable[[KwArg(Any)], BaseTool], List[str]]] = {
"wolfram-alpha": (_get_wolfram_alpha, ["wolfram_alpha... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-15 | ["searx_host", "engines", "num_results", "aiosession"],
),
"bing-search": (_get_bing_search, ["bing_subscription_key", "bing_search_url"]),
"metaphor-search": (_get_metaphor_search, ["metaphor_api_key"]),
"ddg-search": (_get_ddg_search, []),
"google-serper": (_get_google_serper, ["serper_api_key", "... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-16 | "searx-search": (_get_searx_search, ["searx_host", "engines", "aiosession"]),
"wikipedia": (_get_wikipedia, ["top_k_results", "lang"]),
"arxiv": (
_get_arxiv,
["top_k_results", "load_max_docs", "load_all_available_meta"],
),
"pupmed": (
_get_pupmed,
["top_k_results", "loa... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-17 | "graphql": (_get_graphql_tool, ["graphql_endpoint"]),
"openweathermap-api": (_get_openweathermap, ["openweathermap_api_key"]),
}
def _handle_callbacks(
callback_manager: Optional[BaseCallbackManager], callbacks: Callbacks
) -> Callbacks:
if callback_manager is not None:
warnings.warn(
"c... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-18 | ) -> BaseTool:
"""Loads a tool from the HuggingFace Hub.
Args:
task_or_repo_id: Task or model repo id.
model_repo_id: Optional model repo id.
token: Optional token.
remote: Optional remote. Defaults to False.
**kwargs:
Returns:
A tool.
"""
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-19 | token=token,
remote=remote,
**kwargs,
)
outputs = hf_tool.outputs
if set(outputs) != {"text"}:
raise NotImplementedError("Multimodal outputs not supported yet.")
inputs = hf_tool.inputs
if set(inputs) != {"text"}:
raise NotImplementedError("Multimodal inputs not suppo... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-20 | llm: Optional language model, may be needed to initialize certain tools.
callbacks: Optional callback manager or list of callback handlers.
If not provided, default global callback manager will be used.
Returns:
List of tools.
"""
tools = []
callbacks = _handle_callbacks(
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-21 | tool_names.extend(requests_method_tools)
elif name in _BASE_TOOLS:
tools.append(_BASE_TOOLS[name]())
elif name in _LLM_TOOLS:
if llm is None:
raise ValueError(f"Tool {name} requires an LLM to be provided")
tool = _LLM_TOOLS[name](llm)
tools... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-22 | )
sub_kwargs = {k: kwargs[k] for k in extra_keys}
tool = _get_llm_tool_func(llm=llm, **sub_kwargs)
tools.append(tool)
elif name in _EXTRA_OPTIONAL_TOOLS:
_get_tool_func, extra_keys = _EXTRA_OPTIONAL_TOOLS[name]
sub_kwargs = {k: kwargs[k] for k in extra... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
b425ffafe02c-23 | list(_BASE_TOOLS)
+ list(_EXTRA_OPTIONAL_TOOLS)
+ list(_EXTRA_LLM_TOOLS)
+ list(_LLM_TOOLS)
) | https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html |
70a98a27c6e6-0 | Source code for langchain.agents.agent_types
from enum import Enum
[docs]class AgentType(str, Enum):
"""Enumerator with the Agent types."""
ZERO_SHOT_REACT_DESCRIPTION = "zero-shot-react-description"
REACT_DOCSTORE = "react-docstore"
SELF_ASK_WITH_SEARCH = "self-ask-with-search"
CONVERSATIONAL_REACT... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_types.html |
fbe2ff5864f3-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, Callable, Dict, List, Optional, Sequ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-1 | from langchain.input import get_color_mapping
from langchain.prompts.base import BasePromptTemplate
from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplate
from langchain.schema import (
AgentAction,
AgentFinish,
BaseMessage,
BaseOutputParser,
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-2 | def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-3 | Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
callbacks: Callbacks to run.
**kwargs: User inputs.
Returns:
Action specifying what tool to use.
"""
@property
@abstractmethod
def input_keys(sel... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-4 | 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] @classmethod
def from_llm_and_tools(
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-5 | _type = self._agent_type
if isinstance(_type, AgentType):
_dict["_type"] = str(_type.value)
else:
_dict["_type"] = _type
return _dict
[docs] def save(self, file_path: Union[Path, str]) -> None:
"""Save the agent.
Args:
file_path: Path to fil... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-6 | # Fetch dictionary to save
agent_dict = self.dict()
if save_path.suffix == ".json":
with open(file_path, "w") as f:
json.dump(agent_dict, f, indent=4)
elif save_path.suffix == ".yaml":
with open(file_path, "w") as f:
yaml.dump(agent_dict, f... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-7 | return None
[docs] @abstractmethod
def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[List[AgentAction], AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_step... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-8 | """Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
callbacks: Callbacks to run.
**kwargs: User inputs.
Returns:
Actions specifying what tool to use.
"""
@proper... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-9 | return AgentFinish({"output": "Agent stopped due to max iterations."}, "")
else:
raise ValueError(
f"Got unsupported early_stopping_method `{early_stopping_method}`"
)
@property
def _agent_type(self) -> str:
"""Return Identifier of agent type."""
r... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-10 | # If working with agent executor
agent.agent.save(file_path="path/agent.yaml")
"""
# Convert file to Path object.
if isinstance(file_path, str):
save_path = Path(file_path)
else:
save_path = file_path
directory_path = save_path.parent
d... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-11 | [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."""
[docs]class LLMSingleActionAgent(BaseSingleActionAgent):... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-12 | [docs] def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-13 | callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
callbacks: Callbacks to run.
**kwargs: ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-14 | }
[docs]class Agent(BaseSingleActionAgent):
"""Class responsible for calling the language model and deciding the action.
This is driven by an LLMChain. The prompt in the LLMChain MUST include
a variable called "agent_scratchpad" where the agent can put its
intermediary work.
"""
llm_chain: LLMCh... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-15 | 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... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-16 | [docs] def plan(
self,
intermediate_steps: List[Tuple[AgentAction, str]],
callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-17 | callbacks: Callbacks = None,
**kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
callbacks: Callbacks to run.
**kwargs: ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-18 | thoughts = self._construct_scratchpad(intermediate_steps)
new_inputs = {"agent_scratchpad": thoughts, "stop": self._stop}
full_inputs = {**kwargs, **new_inputs}
return full_inputs
@property
def input_keys(self) -> List[str]:
"""Return the input keys.
:meta private:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-19 | )
prompt.input_variables.append("agent_scratchpad")
if isinstance(prompt, PromptTemplate):
prompt.template += "\n{agent_scratchpad}"
elif isinstance(prompt, FewShotPromptTemplate):
prompt.suffix += "\n{agent_scratchpad}"
else:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-20 | @classmethod
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
"""Validate that appropriate tools are passed in."""
pass
@classmethod
@abstractmethod
def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:
"""Get default output parser for this class.""... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-21 | llm=llm,
prompt=cls.create_prompt(tools),
callback_manager=callback_manager,
)
tool_names = [tool.name for tool in tools]
_output_parser = output_parser or cls._get_default_output_parser()
return cls(
llm_chain=llm_chain,
allowed_tools=tool... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-22 | return AgentFinish(
{"output": "Agent stopped due to iteration limit or time limit."}, ""
)
elif early_stopping_method == "generate":
# Generate does one final forward pass
thoughts = ""
for action, observation in intermediate_steps:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-23 | # We try to extract a final answer
parsed_output = self.output_parser.parse(full_output)
if isinstance(parsed_output, AgentFinish):
# If we can extract, we send the correct stuff
return parsed_output
else:
# If we can extract, but the t... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-24 | name = "_Exception"
description = "Exception tool"
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
return query
async def _arun(
self,
query: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-25 | return_intermediate_steps: bool = False
"""Whether to return the agent's trajectory of intermediate steps
at the end in addition to the final output."""
max_iterations: Optional[int] = 15
"""The maximum number of steps to take before ending the execution
loop.
Setting to 'None' could lead t... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-26 | a final answer based on the previous steps.
"""
handle_parsing_errors: Union[
bool, str, Callable[[OutputParserException], str]
] = False
"""How to handle errors raised by the agent's output parser.
Defaults to `False`, which raises the error.
s
If `true`, the error will be sent back to ... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-27 | tools: Sequence[BaseTool],
callback_manager: Optional[BaseCallbackManager] = None,
**kwargs: Any,
) -> AgentExecutor:
"""Create from agent and tools."""
return cls(
agent=agent, tools=tools, callback_manager=callback_manager, **kwargs
)
@root_validator()
d... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-28 | )
return values
@root_validator()
def validate_return_direct_tool(cls, values: Dict) -> Dict:
"""Validate that tools are compatible with agent."""
agent = values["agent"]
tools = values["tools"]
if isinstance(agent, BaseMultiActionAgent):
for tool in tools:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-29 | )
[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 the input keys.
:meta private:
"""
return self.agent.input_keys
@pr... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-30 | def _should_continue(self, iterations: int, time_elapsed: float) -> bool:
if self.max_iterations is not None and iterations >= self.max_iterations:
return False
if (
self.max_execution_time is not None
and time_elapsed >= self.max_execution_time
):
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-31 | output: AgentFinish,
intermediate_steps: list,
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, Any]:
if run_manager:
await run_manager.on_agent_finish(
output, color="green", verbose=self.verbose
)
final_output = o... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-32 | """Take a single step in the thought-action-observation loop.
Override this to take control of how the agent makes and acts on choices.
"""
try:
# Call the LLM to see what to do.
output = self.agent.plan(
intermediate_steps,
callbacks=run_m... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
fbe2ff5864f3-33 | else:
observation = "Invalid or incomplete response"
elif isinstance(self.handle_parsing_errors, str):
observation = self.handle_parsing_errors
elif callable(self.handle_parsing_errors):
observation = self.handle_parsing_errors(e)
e... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.