id
stringlengths
14
16
text
stringlengths
31
2.41k
source
stringlengths
53
121
94e2996c717b-18
"\n", " ", "", ] elif language == Language.LATEX: return [ # First, try to split along Latex sections "\n\\\chapter{", "\n\\\section{", "\n\\\subsection{", "\n\\\subsubsection{...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
94e2996c717b-19
return [ # Split along compiler informations definitions "\npragma ", "\nusing ", # Split along contract definitions "\ncontract ", "\ninterface ", "\nlibrary ", # Split along method definitio...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
94e2996c717b-20
splits = self._tokenizer(text) return self._merge_splits(splits, self._separator) [docs]class SpacyTextSplitter(TextSplitter): """Implementation of splitting text that looks at sentences using Spacy.""" def __init__( self, separator: str = "\n\n", pipeline: str = "en_core_web_sm", **kwargs: Any ...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
94e2996c717b-21
separators = self.get_separators_for_language(Language.MARKDOWN) super().__init__(separators=separators, **kwargs) [docs]class LatexTextSplitter(RecursiveCharacterTextSplitter): """Attempts to split the text along Latex-formatted layout elements.""" def __init__(self, **kwargs: Any) -> None: """...
https://api.python.langchain.com/en/latest/_modules/langchain/text_splitter.html
9c176e0cb7c3-0
Source code for langchain.requests """Lightweight wrapper around requests library, with async support.""" from contextlib import asynccontextmanager from typing import Any, AsyncGenerator, Dict, Optional import aiohttp import requests from pydantic import BaseModel, Extra class Requests(BaseModel): """Wrapper aroun...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
9c176e0cb7c3-1
def delete(self, url: str, **kwargs: Any) -> requests.Response: """DELETE the URL and return the text.""" return requests.delete(url, headers=self.headers, **kwargs) @asynccontextmanager async def _arequest( self, method: str, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.Clien...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
9c176e0cb7c3-2
"""PATCH the URL and return the text asynchronously.""" async with self._arequest("PATCH", url, **kwargs) as response: yield response @asynccontextmanager async def aput( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: ...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
9c176e0cb7c3-3
"""POST to the URL and return the text.""" return self.requests.post(url, data, **kwargs).text [docs] def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PATCH the URL and return the text.""" return self.requests.patch(url, data, **kwargs).text [docs] def put(self, ur...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
9c176e0cb7c3-4
"""PUT the URL and return the text asynchronously.""" async with self.requests.aput(url, **kwargs) as response: return await response.text() [docs] async def adelete(self, url: str, **kwargs: Any) -> str: """DELETE the URL and return the text asynchronously.""" async with self.req...
https://api.python.langchain.com/en/latest/_modules/langchain/requests.html
d04e2872c89e-0
Source code for langchain.schema """Common schema objects.""" from __future__ import annotations from abc import ABC, abstractmethod from dataclasses import dataclass from typing import ( Any, Dict, Generic, List, NamedTuple, Optional, Sequence, TypeVar, Union, ) from uuid import UUI...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
d04e2872c89e-1
"""Agent's return value.""" return_values: dict log: str [docs]class Generation(Serializable): """Output of a single generation.""" text: str """Generated text output.""" generation_info: Optional[Dict[str, Any]] = None """Raw generation info response from the provider""" """May include ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
d04e2872c89e-2
"""Type of the message, used for serialization.""" return "system" [docs]class FunctionMessage(BaseMessage): name: str @property def type(self) -> str: """Type of the message, used for serialization.""" return "function" [docs]class ChatMessage(BaseMessage): """Type of message wi...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
d04e2872c89e-3
Returns: List of messages (BaseMessages). """ return [_message_from_dict(m) for m in messages] [docs]class ChatGeneration(Generation): """Output of a single generation.""" text = "" message: BaseMessage @root_validator def set_text(cls, values: Dict[str, Any]) -> Dict[str, Any]: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
d04e2872c89e-4
llm_output=self.llm_output, ) ) else: if self.llm_output is not None: llm_output = self.llm_output.copy() llm_output["token_usage"] = dict() else: llm_output = None ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
d04e2872c89e-5
"""Save the context of this model run to memory.""" [docs] @abstractmethod def clear(self) -> None: """Clear memory contents.""" [docs]class BaseChatMessageHistory(ABC): """Base interface for chat message history See `ChatMessageHistory` for default implementation. """ """ Example: ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
d04e2872c89e-6
raise NotImplementedError [docs] @abstractmethod def clear(self) -> None: """Remove all messages from the store""" [docs]class Document(Serializable): """Interface for interacting with a document.""" page_content: str metadata: dict = Field(default_factory=dict) [docs]class BaseRetriever(ABC)...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
d04e2872c89e-7
"""Parse the output of an LLM call. A method which takes in a string (assumed output of a language model ) and parses it into some structure. Args: text: output of language model Returns: structured output """ [docs] def parse_with_prompt(self, completi...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
d04e2872c89e-8
@property def _type(self) -> str: return "default" [docs] def parse(self, text: str) -> str: return text [docs]class OutputParserException(ValueError): """Exception that output parsers should raise to signify a parsing error. This exists to differentiate parsing errors from other code or ...
https://api.python.langchain.com/en/latest/_modules/langchain/schema.html
1b552510fc88-0
Source code for langchain.document_transformers """Transform documents""" from typing import Any, Callable, List, Sequence import numpy as np from pydantic import BaseModel, Field from langchain.embeddings.base import Embeddings from langchain.math_utils import cosine_similarity from langchain.schema import BaseDocumen...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers.html
1b552510fc88-1
redundant_stacked = np.column_stack(redundant) redundant_sorted = np.argsort(similarity[redundant])[::-1] included_idxs = set(range(len(embedded_documents))) for first_idx, second_idx in redundant_stacked[redundant_sorted]: if first_idx in included_idxs and second_idx in included_idxs: #...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers.html
1b552510fc88-2
arbitrary_types_allowed = True [docs] def transform_documents( self, documents: Sequence[Document], **kwargs: Any ) -> Sequence[Document]: """Filter down documents.""" stateful_documents = get_stateful_documents(documents) embedded_documents = _get_embeddings_from_stateful_docs( ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_transformers.html
8cfc73f54b33-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
8cfc73f54b33-1
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
8cfc73f54b33-2
if hub_result := try_load_from_hub( 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]...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/loading.html
cacf3f41db8b-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
10c3327965d4-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
10c3327965d4-1
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
45339159c89f-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
45339159c89f-1
return None [docs] @abstractmethod 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: Ste...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-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]...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-3
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") as f: json.dump(agent_dict, f, indent=4) elif save_path.suffix == ".yaml": with open(fil...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-4
**kwargs: Any, ) -> Union[List[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: User inputs. Returns: ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-5
Example: .. code-block:: python # 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...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-6
return _dict [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 take...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-7
} [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
45339159c89f-8
return thoughts [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 t...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-9
"""Create the full inputs for the LLMChain from intermediate steps.""" 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...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-10
"""Create a prompt for this class.""" @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: """G...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-11
# `force` just returns a constant string 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 acti...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-12
} class ExceptionTool(BaseTool): 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: Opti...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-13
`"generate"` calls the agent's LLM Chain one final time to generate 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 `Fals...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-14
f"provided tools ({[tool.name for tool in tools]})" ) 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 isinst...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-15
return {tool.name: tool for tool in self.tools}[name] 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...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-16
run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]: """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 LL...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-17
**tool_run_kwargs, ) return [(output, observation)] # 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, AgentAction): actions...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-18
color_mapping: Dict[str, str], inputs: Dict[str, str], intermediate_steps: List[Tuple[AgentAction, str]], run_manager: Optional[AsyncCallbackManagerForChainRun] = None, ) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]: """Take a single step in the thought-action-observation loo...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-19
output.tool_input, verbose=self.verbose, color=None, callbacks=run_manager.get_child() if run_manager else None, **tool_run_kwargs, ) return [(output, observation)] # If the tool chosen is the finishing tool, then we end and...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-20
**tool_run_kwargs, ) return agent_action, observation # Use asyncio.gather to run multiple tool.arun() calls concurrently result = await asyncio.gather( *[_aperform_agent_action(agent_action) for agent_action in actions] ) return list(result) d...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-21
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 self._return( tool_return, intermediate_steps, run_manager=run_...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-22
color_mapping, inputs, intermediate_steps, run_manager=run_manager, ) if isinstance(next_step_output, AgentFinish): return await self._areturn( next_step_ou...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
45339159c89f-23
if agent_action.tool in name_to_tool_map: if name_to_tool_map[agent_action.tool].return_direct: return AgentFinish( {self.agent.return_values[0]: observation}, "", ) return None
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent.html
96bcfe0241f4-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
96bcfe0241f4-1
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 langchain.tools.openweathermap.tool import OpenWeatherMapQueryRun from langchain.utiliti...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
96bcfe0241f4-2
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[[], BaseTool]] = { "python_repl": _get_python_repl, "re...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
96bcfe0241f4-3
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: BaseLanguageModel) -> BaseTool: chain = APIChain.from_llm...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
96bcfe0241f4-4
func=chain.run, ) def _get_tmdb_api(llm: BaseLanguageModel, **kwargs: Any) -> BaseTool: tmdb_bearer_token = kwargs["tmdb_bearer_token"] chain = APIChain.from_llm_and_api_docs( llm, tmdb_docs.TMDB_DOCS, headers={"Authorization": f"Bearer {tmdb_bearer_token}"}, ) return Tool( ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
96bcfe0241f4-5
def _get_google_search(**kwargs: Any) -> BaseTool: return GoogleSearchRun(api_wrapper=GoogleSearchAPIWrapper(**kwargs)) def _get_wikipedia(**kwargs: Any) -> BaseTool: return WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper(**kwargs)) def _get_arxiv(**kwargs: Any) -> BaseTool: return ArxivQueryRun(api_wrapp...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
96bcfe0241f4-6
) 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 SearxSearchResults(wrapper=SearxSearchWrapper(**wrapp...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
96bcfe0241f4-7
] = { "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
96bcfe0241f4-8
"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
96bcfe0241f4-9
**kwargs: Any, ) -> 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. """ ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
96bcfe0241f4-10
Args: tool_names: name of tools to load. 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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
96bcfe0241f4-11
f"provided: {missing_keys}" ) 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] ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/load_tools.html
28c34f5ff74a-0
Source code for langchain.agents.conversational.base """An agent designed to hold a conversation in addition to using tools.""" from __future__ import annotations from typing import Any, List, Optional, Sequence from pydantic import Field from langchain.agents.agent import Agent, AgentOutputParser from langchain.agents...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
28c34f5ff74a-1
[docs] @classmethod def create_prompt( cls, tools: Sequence[BaseTool], prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, ai_prefix: str = "AI", human_prefix: str = "Human", input_variables: Optional[List[str...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
28c34f5ff74a-2
validate_tools_single_input(cls.__name__, tools) [docs] @classmethod def from_llm_and_tools( cls, llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: s...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html
e34d7b3012a3-0
Source code for langchain.agents.conversational_chat.base """An agent designed to hold a conversation in addition to using tools.""" from __future__ import annotations from typing import Any, List, Optional, Sequence, Tuple from pydantic import Field from langchain.agents.agent import Agent, AgentOutputParser from lang...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html
e34d7b3012a3-1
return "Observation: " @property def llm_prefix(self) -> str: """Prefix to append the llm call with.""" return "Thought:" @classmethod def _validate_tools(cls, tools: Sequence[BaseTool]) -> None: super()._validate_tools(tools) validate_tools_single_input(cls.__name__, too...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html
e34d7b3012a3-2
) -> List[BaseMessage]: """Construct the scratchpad that lets the agent continue its thought process.""" thoughts: List[BaseMessage] = [] for action, observation in intermediate_steps: thoughts.append(AIMessage(content=action.log)) human_message = HumanMessage( ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html
cba691317bf1-0
Source code for langchain.agents.structured_chat.base import re from typing import Any, List, Optional, Sequence, Tuple from pydantic import Field from langchain.agents.agent import Agent, AgentOutputParser from langchain.agents.structured_chat.output_parser import ( StructuredChatOutputParserWithRetries, ) from la...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/base.html
cba691317bf1-1
return ( f"This was your previous work " f"(but I haven't seen any of it! I only see what " f"you return as final answer):\n{agent_scratchpad}" ) else: return agent_scratchpad @classmethod def _validate_tools(cls, tools: Sequence[Ba...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/base.html
cba691317bf1-2
template = "\n\n".join([prefix, formatted_tools, format_instructions, suffix]) if input_variables is None: input_variables = ["input", "agent_scratchpad"] _memory_prompts = memory_prompts or [] messages = [ SystemMessagePromptTemplate.from_template(template), ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/base.html
cba691317bf1-3
) tool_names = [tool.name for tool in tools] _output_parser = output_parser or cls._get_default_output_parser(llm=llm) return cls( llm_chain=llm_chain, allowed_tools=tool_names, output_parser=_output_parser, **kwargs, ) @property de...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/structured_chat/base.html
c07438d62305-0
Source code for langchain.agents.openai_functions_agent.base """Module implements an agent that uses OpenAI's APIs function enabled API.""" import json from dataclasses import dataclass from json import JSONDecodeError from typing import Any, List, Optional, Sequence, Tuple, Union from pydantic import root_validator fr...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html
c07438d62305-1
] else: return [AIMessage(content=agent_action.log)] def _create_function_message( agent_action: AgentAction, observation: str ) -> FunctionMessage: """Convert agent action and observation into a function message. Args: agent_action: the tool invocation request from the agent obs...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html
c07438d62305-2
function_name = function_call["name"] try: _tool_input = json.loads(function_call["arguments"]) except JSONDecodeError: raise OutputParserException( f"Could not parse tool input: {function_call} because " f"the `arguments` is not valid JSON." ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html
c07438d62305-3
of the variables. For an easy way to construct this prompt, use `OpenAIFunctionsAgent.create_prompt(...)` """ llm: BaseLanguageModel tools: Sequence[BaseTool] prompt: BasePromptTemplate [docs] def get_allowed_tools(self) -> List[str]: """Get allowed tools.""" return list([...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html
c07438d62305-4
**kwargs: User inputs. Returns: Action specifying what tool to use. """ agent_scratchpad = _format_intermediate_steps(intermediate_steps) selected_inputs = { k: kwargs[k] for k in self.prompt.input_variables if k != "agent_scratchpad" } full_inputs...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html
c07438d62305-5
) agent_decision = _parse_ai_message(predicted_message) return agent_decision [docs] @classmethod def create_prompt( cls, system_message: Optional[SystemMessage] = SystemMessage( content="You are a helpful AI assistant." ), extra_prompt_messages: Option...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html
c07438d62305-6
"""Construct an agent from an LLM and tools.""" if not isinstance(llm, ChatOpenAI): raise ValueError("Only supported with ChatOpenAI models.") prompt = cls.create_prompt( extra_prompt_messages=extra_prompt_messages, system_message=system_message, ) ret...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html
e17f399bf20c-0
Source code for langchain.agents.react.base """Chain that implements the ReAct paper from https://arxiv.org/pdf/2210.03629.pdf.""" from typing import Any, List, Optional, Sequence from pydantic import Field from langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser from langchain.agents.agent_types impo...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
e17f399bf20c-1
super()._validate_tools(tools) if len(tools) != 2: raise ValueError(f"Exactly two tools must be specified, but got {tools}") tool_names = {tool.name for tool in tools} if tool_names != {"Lookup", "Search"}: raise ValueError( f"Tool names should be Lookup a...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
e17f399bf20c-2
if term.lower() != self.lookup_str: self.lookup_str = term.lower() self.lookup_index = 0 else: self.lookup_index += 1 lookups = [p for p in self._paragraphs if self.lookup_str in p.lower()] if len(lookups) == 0: return "No Results" elif sel...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
e17f399bf20c-3
raise ValueError(f"Tool name should be Play, got {tool_names}") [docs]class ReActChain(AgentExecutor): """Chain that implements the ReAct paper. Example: .. code-block:: python from langchain import ReActChain, OpenAI react = ReAct(llm=OpenAI()) """ def __init__(self, llm...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html
1848f4c9ddcc-0
Source code for langchain.agents.mrkl.base """Attempt to implement MRKL systems as described in arxiv.org/pdf/2205.00445.pdf.""" from __future__ import annotations from typing import Any, Callable, List, NamedTuple, Optional, Sequence from pydantic import Field from langchain.agents.agent import Agent, AgentExecutor, A...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
1848f4c9ddcc-1
@property def observation_prefix(self) -> str: """Prefix to append the observation with.""" return "Observation: " @property def llm_prefix(self) -> str: """Prefix to append the llm call with.""" return "Thought:" [docs] @classmethod def create_prompt( cls, ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
1848f4c9ddcc-2
llm: BaseLanguageModel, tools: Sequence[BaseTool], callback_manager: Optional[BaseCallbackManager] = None, output_parser: Optional[AgentOutputParser] = None, prefix: str = PREFIX, suffix: str = SUFFIX, format_instructions: str = FORMAT_INSTRUCTIONS, input_variable...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
1848f4c9ddcc-3
f"a description must always be provided." ) super()._validate_tools(tools) [docs]class MRKLChain(AgentExecutor): """Chain that implements the MRKL system. Example: .. code-block:: python from langchain import OpenAI, MRKLChain from langchain.chains.mrkl.ba...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
1848f4c9ddcc-4
action_description="useful for searching" ), ChainConfig( action_name="Calculator", action=llm_math_chain.run, action_description="useful for doing math" ) ] ...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html
385ea07de428-0
Source code for langchain.agents.agent_toolkits.playwright.toolkit """Playwright web browser toolkit.""" from __future__ import annotations from typing import TYPE_CHECKING, List, Optional, Type, cast from pydantic import Extra, root_validator from langchain.agents.agent_toolkits.base import BaseToolkit from langchain....
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/playwright/toolkit.html
385ea07de428-1
"""Check that the arguments are valid.""" lazy_import_playwright_browsers() if values.get("async_browser") is None and values.get("sync_browser") is None: raise ValueError("Either async_browser or sync_browser must be specified.") return values [docs] def get_tools(self) -> List[B...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/playwright/toolkit.html
4935b06df2fc-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...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/toolkit.html
4935b06df2fc-1
func=self.json_agent.run, description=DESCRIPTION, ) request_toolkit = RequestsToolkit(requests_wrapper=self.requests_wrapper) return [*request_toolkit.get_tools(), json_agent_tool] [docs] @classmethod def from_llm( cls, llm: BaseLanguageModel, json_spe...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/toolkit.html
a0c7db5c4fbc-0
Source code for langchain.agents.agent_toolkits.openapi.base """OpenAPI spec agent.""" from typing import Any, Dict, 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...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/base.html
a0c7db5c4fbc-1
input_variables=input_variables, ) llm_chain = LLMChain( llm=llm, prompt=prompt, callback_manager=callback_manager, ) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names, **kwargs) return AgentExecutor.from_agent_...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/openapi/base.html
46b195e8550c-0
Source code for langchain.agents.agent_toolkits.python.base """Python agent.""" from typing import Any, Dict, Optional from langchain.agents.agent import AgentExecutor, BaseSingleActionAgent from langchain.agents.agent_toolkits.python.prompt import PREFIX from langchain.agents.mrkl.base import ZeroShotAgent from langch...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/python/base.html
46b195e8550c-1
elif agent_type == AgentType.OPENAI_FUNCTIONS: system_message = SystemMessage(content=prefix) _prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message) agent = OpenAIFunctionsAgent( llm=llm, prompt=_prompt, tools=tools, callback_m...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/python/base.html
b0822cf912d4-0
Source code for langchain.agents.agent_toolkits.spark.base """Agent for working with pandas objects.""" from typing import Any, Dict, List, Optional from langchain.agents.agent import AgentExecutor from langchain.agents.agent_toolkits.spark.prompt import PREFIX, SUFFIX from langchain.agents.mrkl.base import ZeroShotAge...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/spark/base.html
b0822cf912d4-1
) -> AgentExecutor: """Construct a spark agent from an LLM and dataframe.""" if not _validate_spark_df(df) and not _validate_spark_connect_df(df): raise ValueError("Spark is not installed. run `pip install pyspark`.") if input_variables is None: input_variables = ["df", "input", "agent_scrat...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/spark/base.html
6f6dbf4a4161-0
Source code for langchain.agents.agent_toolkits.nla.toolkit """Toolkit for interacting with API's using natural language.""" from __future__ import annotations from typing import Any, List, Optional, Sequence from pydantic import Field from langchain.agents.agent_toolkits.base import BaseToolkit from langchain.agents.a...
https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/nla/toolkit.html