id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
58f31290022d-1 | action_id=action["id"],
zapier_description=action["description"],
params_schema=action["params"],
api_wrapper=zapier_nla_wrapper,
)
for action in actions
]
return cls(tools=tools)
[docs] def get_tools(self) -> List[BaseTool]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/zapier/toolkit.html |
5770d0b9302d-0 | Source code for langchain.agents.agent_toolkits.file_management.toolkit
"""Toolkit for interacting with the local filesystem."""
from __future__ import annotations
from typing import List, Optional
from pydantic import root_validator
from langchain.agents.agent_toolkits.base import BaseToolkit
from langchain.tools impo... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/file_management/toolkit.html |
5770d0b9302d-1 | FileSearchTool,
MoveFileTool,
ReadFileTool,
WriteFileTool,
ListDirectoryTool,
]
}
[docs]class FileManagementToolkit(BaseToolkit):
"""Toolkit for interacting with a Local Files."""
root_dir: Optional[str] = None
"""If specified, all file operations are made relative to roo... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/file_management/toolkit.html |
5770d0b9302d-2 | )
return values
[docs] def get_tools(self) -> List[BaseTool]:
"""Get the tools in the toolkit."""
allowed_tools = self.selected_tools or _FILE_TOOLS.keys()
tools: List[BaseTool] = []
for tool in allowed_tools:
tool_cls = _FILE_TOOLS[tool]
tools.append(t... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/agent_toolkits/file_management/toolkit.html |
1bf93c20ff74-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 |
1bf93c20ff74-1 | MessagesPlaceholder,
SystemMessagePromptTemplate,
)
from langchain.schema import (
AgentAction,
AIMessage,
BaseMessage,
BaseOutputParser,
HumanMessage,
)
from langchain.tools.base import BaseTool
[docs]class ConversationalChatAgent(Agent):
"""An agent designed to hold a conversation in addit... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html |
1bf93c20ff74-2 | 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 |
1bf93c20ff74-3 | )
tool_names = ", ".join([tool.name for tool in tools])
_output_parser = output_parser or cls._get_default_output_parser()
format_instructions = human_message.format(
format_instructions=_output_parser.get_format_instructions()
)
final_prompt = format_instructions.for... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html |
1bf93c20ff74-4 | ) -> 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 |
1bf93c20ff74-5 | **kwargs: Any,
) -> Agent:
"""Construct an agent from an LLM and tools."""
cls._validate_tools(tools)
_output_parser = output_parser or cls._get_default_output_parser()
prompt = cls.create_prompt(
tools,
system_message=system_message,
human_message... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational_chat/base.html |
dd88fd8aa839-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 |
dd88fd8aa839-1 | BaseMessage,
FunctionMessage,
OutputParserException,
SystemMessage,
)
from langchain.tools import BaseTool
from langchain.tools.convert_to_openai import format_tool_to_openai_function
@dataclass
class _FunctionsAgentAction(AgentAction):
message_log: List[BaseMessage]
def _convert_agent_action_to_message... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html |
dd88fd8aa839-2 | ]
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 |
dd88fd8aa839-3 | ) -> List[BaseMessage]:
"""Format intermediate steps.
Args:
intermediate_steps: Steps the LLM has taken to date, along with observations
Returns:
list of messages to send to the LLM for the next prediction
"""
messages = []
for intermediate_step in intermediate_steps:
age... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html |
dd88fd8aa839-4 | 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."
)
# HACK HACK HACK:
# T... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html |
dd88fd8aa839-5 | tool_input = _tool_input
content_msg = "responded: {content}\n" if message.content else "\n"
return _FunctionsAgentAction(
tool=function_name,
tool_input=tool_input,
log=f"\nInvoking: `{function_name}` with `{tool_input}`\n{content_msg}\n",
message_log=[me... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html |
dd88fd8aa839-6 | 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 |
dd88fd8aa839-7 | raise ValueError(
"`agent_scratchpad` should be one of the variables in the prompt, "
f"got {prompt.input_variables}"
)
return values
@property
def input_keys(self) -> List[str]:
"""Get input keys. Input refers to user input here."""
return ["i... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html |
dd88fd8aa839-8 | **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 |
dd88fd8aa839-9 | **kwargs: Any,
) -> Union[AgentAction, AgentFinish]:
"""Given input, decided what to do.
Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
**kwargs: User inputs.
Returns:
Action specifying what tool to use.
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html |
dd88fd8aa839-10 | )
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 |
dd88fd8aa839-11 | if system_message:
messages = [system_message]
else:
messages = []
messages.extend(
[
*_prompts,
HumanMessagePromptTemplate.from_template("{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html |
dd88fd8aa839-12 | ) -> BaseSingleActionAgent:
"""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=s... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/openai_functions_agent/base.html |
bd52635bd8e3-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 |
bd52635bd8e3-1 | from langchain.tools.base import BaseTool
class ChainConfig(NamedTuple):
"""Configuration for chain to use in MRKL system.
Args:
action_name: Name of the action.
action: Action function to call.
action_description: Description of the action.
"""
action_name: str
action: Calla... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
bd52635bd8e3-2 | @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 |
bd52635bd8e3-3 | suffix: String to put after the list of tools.
input_variables: List of input variables the final prompt will expect.
Returns:
A PromptTemplate with the template assembled from the pieces here.
"""
tool_strings = "\n".join([f"{tool.name}: {tool.description}" for tool in t... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
bd52635bd8e3-4 | 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_variables: Optional[List[str]] = None,
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
bd52635bd8e3-5 | )
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_names,
output_parser=_output_parser,
**kwargs,
)
@classmethod
def _v... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
bd52635bd8e3-6 | )
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.base import ChainConfig
llm = OpenAI(temperature... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
bd52635bd8e3-7 | MRKL chain.
Args:
llm: The LLM to use as the agent LLM.
chains: The chains the MRKL system has access to.
**kwargs: parameters to be passed to initialization.
Returns:
An initialized MRKL chain.
Example:
.. code-block:: python
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
bd52635bd8e3-8 | action_name="Calculator",
action=llm_math_chain.run,
action_description="useful for doing math"
)
]
mrkl = MRKLChain.from_chains(llm, chains)
"""
tools = [
Tool(
name=c.action_... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/mrkl/base.html |
b7bb9cdbb3e9-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 |
b7bb9cdbb3e9-1 | from langchain.tools.base import BaseTool
class ReActDocstoreAgent(Agent):
"""Agent for the ReAct chain."""
output_parser: AgentOutputParser = Field(default_factory=ReActOutputParser)
@classmethod
def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:
return ReActOutputParser()... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html |
b7bb9cdbb3e9-2 | 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 |
b7bb9cdbb3e9-3 | def __init__(self, docstore: Docstore):
"""Initialize with a docstore, and set initial document to None."""
self.docstore = docstore
self.document: Optional[Document] = None
self.lookup_str = ""
self.lookup_index = 0
def search(self, term: str) -> str:
"""Search for a... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html |
b7bb9cdbb3e9-4 | 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 self.lookup_index >= len(lookups):
retu... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html |
b7bb9cdbb3e9-5 | return self.document.page_content.split("\n\n")
[docs]class ReActTextWorldAgent(ReActDocstoreAgent):
"""Agent for the ReAct TextWorld chain."""
[docs] @classmethod
def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate:
"""Return default prompt."""
return TEXTWORLD_PROMPT
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html |
b7bb9cdbb3e9-6 | [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: BaseLanguageModel, docstore: Docstore, **kwargs: Any):
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html |
b7bb9cdbb3e9-7 | ),
]
agent = ReActDocstoreAgent.from_llm_and_tools(llm, tools)
super().__init__(agent=agent, tools=tools, **kwargs) | https://api.python.langchain.com/en/latest/_modules/langchain/agents/react/base.html |
b5dcd7ab5fb8-0 | Source code for langchain.agents.self_ask_with_search.base
"""Chain that does self ask with search."""
from typing import Any, Sequence, Union
from pydantic import Field
from langchain.agents.agent import Agent, AgentExecutor, AgentOutputParser
from langchain.agents.agent_types import AgentType
from langchain.agents.se... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html |
b5dcd7ab5fb8-1 | output_parser: AgentOutputParser = Field(default_factory=SelfAskOutputParser)
@classmethod
def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:
return SelfAskOutputParser()
@property
def _agent_type(self) -> str:
"""Return Identifier of agent type."""
return A... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html |
b5dcd7ab5fb8-2 | tool_names = {tool.name for tool in tools}
if tool_names != {"Intermediate Answer"}:
raise ValueError(
f"Tool name should be Intermediate Answer, got {tool_names}"
)
@property
def observation_prefix(self) -> str:
"""Prefix to append the observation with.""... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html |
b5dcd7ab5fb8-3 | """
def __init__(
self,
llm: BaseLanguageModel,
search_chain: Union[GoogleSerperAPIWrapper, SerpAPIWrapper],
**kwargs: Any,
):
"""Initialize with just an LLM and a search chain."""
search_tool = Tool(
name="Intermediate Answer",
func=search... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/self_ask_with_search/base.html |
a00970c8bfd2-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 |
a00970c8bfd2-1 | ai_prefix: str = "AI"
output_parser: AgentOutputParser = Field(default_factory=ConvoOutputParser)
@classmethod
def _get_default_output_parser(
cls, ai_prefix: str = "AI", **kwargs: Any
) -> AgentOutputParser:
return ConvoOutputParser(ai_prefix=ai_prefix)
@property
def _agent_type... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html |
a00970c8bfd2-2 | 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]] = None,
) -> PromptT... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html |
a00970c8bfd2-3 | Returns:
A PromptTemplate with the template assembled from the pieces here.
"""
tool_strings = "\n".join(
[f"> {tool.name}: {tool.description}" for tool in tools]
)
tool_names = ", ".join([tool.name for tool in tools])
format_instructions = format_instruct... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html |
a00970c8bfd2-4 | super()._validate_tools(tools)
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[Agent... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html |
a00970c8bfd2-5 | tools,
ai_prefix=ai_prefix,
human_prefix=human_prefix,
prefix=prefix,
suffix=suffix,
format_instructions=format_instructions,
input_variables=input_variables,
)
llm_chain = LLMChain(
llm=llm,
prompt=prompt,
... | https://api.python.langchain.com/en/latest/_modules/langchain/agents/conversational/base.html |
08545fe6d9e6-0 | Source code for langchain.chains.loading
"""Functionality for loading chains."""
import json
from pathlib import Path
from typing import Any, Union
import yaml
from langchain.chains.api.base import APIChain
from langchain.chains.base import Chain
from langchain.chains.combine_documents.map_reduce import MapReduceDocume... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-1 | from langchain.chains.llm_math.base import LLMMathChain
from langchain.chains.llm_requests import LLMRequestsChain
from langchain.chains.pal.base import PALChain
from langchain.chains.qa_with_sources.base import QAWithSourcesChain
from langchain.chains.qa_with_sources.vector_db import VectorDBQAWithSourcesChain
from la... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-2 | def _load_llm_chain(config: dict, **kwargs: Any) -> LLMChain:
"""Load LLM chain from config dict."""
if "llm" in config:
llm_config = config.pop("llm")
llm = load_llm_from_config(llm_config)
elif "llm_path" in config:
llm = load_llm(config.pop("llm_path"))
else:
raise Val... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-3 | _load_output_parser(config)
return LLMChain(llm=llm, prompt=prompt, **config)
def _load_hyde_chain(config: dict, **kwargs: Any) -> HypotheticalDocumentEmbedder:
"""Load hypothetical document embedder chain from config dict."""
if "llm_chain" in config:
llm_chain_config = config.pop("llm_chain")
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-4 | return HypotheticalDocumentEmbedder(
llm_chain=llm_chain, base_embeddings=embeddings, **config
)
def _load_stuff_documents_chain(config: dict, **kwargs: Any) -> StuffDocumentsChain:
if "llm_chain" in config:
llm_chain_config = config.pop("llm_chain")
llm_chain = load_chain_from_config(ll... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-5 | document_prompt = load_prompt_from_config(prompt_config)
elif "document_prompt_path" in config:
document_prompt = load_prompt(config.pop("document_prompt_path"))
else:
raise ValueError(
"One of `document_prompt` or `document_prompt_path` must be present."
)
return StuffDo... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-6 | else:
raise ValueError("One of `llm_chain` or `llm_chain_config` must be present.")
if not isinstance(llm_chain, LLMChain):
raise ValueError(f"Expected LLMChain, got {llm_chain}")
if "combine_document_chain" in config:
combine_document_chain_config = config.pop("combine_document_chain")
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-7 | if collapse_document_chain_config is None:
collapse_document_chain = None
else:
collapse_document_chain = load_chain_from_config(
collapse_document_chain_config
)
elif "collapse_document_chain_path" in config:
collapse_document_chain = load_chain(c... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-8 | llm_chain = load_chain(config.pop("llm_chain_path"))
# llm attribute is deprecated in favor of llm_chain, here to support old configs
elif "llm" in config:
llm_config = config.pop("llm")
llm = load_llm_from_config(llm_config)
# llm_path attribute is deprecated in favor of llm_chain_path,
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-9 | elif "prompt_path" in config:
prompt = load_prompt(config.pop("prompt_path"))
if llm_chain:
return LLMBashChain(llm_chain=llm_chain, prompt=prompt, **config)
else:
return LLMBashChain(llm=llm, prompt=prompt, **config)
def _load_llm_checker_chain(config: dict, **kwargs: Any) -> LLMChecker... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-10 | create_draft_answer_prompt_config = config.pop("create_draft_answer_prompt")
create_draft_answer_prompt = load_prompt_from_config(
create_draft_answer_prompt_config
)
elif "create_draft_answer_prompt_path" in config:
create_draft_answer_prompt = load_prompt(
config.po... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-11 | check_assertions_prompt_config
)
elif "check_assertions_prompt_path" in config:
check_assertions_prompt = load_prompt(
config.pop("check_assertions_prompt_path")
)
if "revised_answer_prompt" in config:
revised_answer_prompt_config = config.pop("revised_answer_prompt")... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-12 | **config,
)
def _load_llm_math_chain(config: dict, **kwargs: Any) -> LLMMathChain:
llm_chain = None
if "llm_chain" in config:
llm_chain_config = config.pop("llm_chain")
llm_chain = load_chain_from_config(llm_chain_config)
elif "llm_chain_path" in config:
llm_chain = load_chain(co... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-13 | llm = load_llm(config.pop("llm_path"))
else:
raise ValueError("One of `llm_chain` or `llm_chain_path` must be present.")
if "prompt" in config:
prompt_config = config.pop("prompt")
prompt = load_prompt_from_config(prompt_config)
elif "prompt_path" in config:
prompt = load_pro... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-14 | llm_chain_config = config.pop("llm_chain")
llm_chain = load_chain_from_config(llm_chain_config)
elif "llm_chain_path" in config:
llm_chain = load_chain(config.pop("llm_chain_path"))
else:
raise ValueError("One of `llm_chain` or `llm_chain_config` must be present.")
return MapRerankDo... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-15 | # llm attribute is deprecated in favor of llm_chain, here to support old configs
elif "llm" in config:
llm_config = config.pop("llm")
llm = load_llm_from_config(llm_config)
# llm_path attribute is deprecated in favor of llm_chain_path,
# its to support old configs
elif "llm_path" in conf... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-16 | else:
raise ValueError("One of `prompt` or `prompt_path` must be present.")
if llm_chain:
return PALChain(llm_chain=llm_chain, prompt=prompt, **config)
else:
return PALChain(llm=llm, prompt=prompt, **config)
def _load_refine_documents_chain(config: dict, **kwargs: Any) -> RefineDocuments... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-17 | else:
raise ValueError(
"One of `initial_llm_chain` or `initial_llm_chain_config` must be present."
)
if "refine_llm_chain" in config:
refine_llm_chain_config = config.pop("refine_llm_chain")
refine_llm_chain = load_chain_from_config(refine_llm_chain_config)
elif "ref... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-18 | document_prompt = load_prompt(config.pop("document_prompt_path"))
return RefineDocumentsChain(
initial_llm_chain=initial_llm_chain,
refine_llm_chain=refine_llm_chain,
document_prompt=document_prompt,
**config,
)
def _load_qa_with_sources_chain(config: dict, **kwargs: Any) -> QAWi... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-19 | )
return QAWithSourcesChain(combine_documents_chain=combine_documents_chain, **config)
def _load_sql_database_chain(config: dict, **kwargs: Any) -> SQLDatabaseChain:
if "database" in kwargs:
database = kwargs.pop("database")
else:
raise ValueError("`database` must be present.")
if "llm" ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-20 | else:
prompt = None
return SQLDatabaseChain.from_llm(llm, database, prompt=prompt, **config)
def _load_vector_db_qa_with_sources_chain(
config: dict, **kwargs: Any
) -> VectorDBQAWithSourcesChain:
if "vectorstore" in kwargs:
vectorstore = kwargs.pop("vectorstore")
else:
raise Val... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-21 | "`combine_documents_chain_path` must be present."
)
return VectorDBQAWithSourcesChain(
combine_documents_chain=combine_documents_chain,
vectorstore=vectorstore,
**config,
)
def _load_retrieval_qa(config: dict, **kwargs: Any) -> RetrievalQA:
if "retriever" in kwargs:
r... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-22 | else:
raise ValueError(
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
return RetrievalQA(
combine_documents_chain=combine_documents_chain,
retriever=retriever,
**config,
)
def _load_vector_db_qa(config: ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-23 | else:
raise ValueError(
"One of `combine_documents_chain` or "
"`combine_documents_chain_path` must be present."
)
return VectorDBQA(
combine_documents_chain=combine_documents_chain,
vectorstore=vectorstore,
**config,
)
def _load_graph_cypher_chain... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-24 | if "qa_chain" in config:
qa_chain_config = config.pop("qa_chain")
qa_chain = load_chain_from_config(qa_chain_config)
else:
raise ValueError("`qa_chain` must be present.")
return GraphCypherQAChain(
graph=graph,
cypher_generation_chain=cypher_generation_chain,
qa_c... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-25 | else:
raise ValueError(
"One of `api_request_chain` or `api_request_chain_path` must be present."
)
if "api_answer_chain" in config:
api_answer_chain_config = config.pop("api_answer_chain")
api_answer_chain = load_chain_from_config(api_answer_chain_config)
elif "api_a... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-26 | api_answer_chain=api_answer_chain,
requests_wrapper=requests_wrapper,
**config,
)
def _load_llm_requests_chain(config: dict, **kwargs: Any) -> LLMRequestsChain:
if "llm_chain" in config:
llm_chain_config = config.pop("llm_chain")
llm_chain = load_chain_from_config(llm_chain_confi... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-27 | )
else:
return LLMRequestsChain(llm_chain=llm_chain, **config)
type_to_loader_dict = {
"api_chain": _load_api_chain,
"hyde_chain": _load_hyde_chain,
"llm_chain": _load_llm_chain,
"llm_bash_chain": _load_llm_bash_chain,
"llm_checker_chain": _load_llm_checker_chain,
"llm_math_chain": _... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-28 | "map_rerank_documents_chain": _load_map_rerank_documents_chain,
"refine_documents_chain": _load_refine_documents_chain,
"sql_database_chain": _load_sql_database_chain,
"vector_db_qa_with_sources_chain": _load_vector_db_qa_with_sources_chain,
"vector_db_qa": _load_vector_db_qa,
"retrieval_qa": _load_... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-29 | raise ValueError(f"Loading {config_type} chain not supported")
chain_loader = type_to_loader_dict[config_type]
return chain_loader(config, **kwargs)
[docs]def load_chain(path: Union[str, Path], **kwargs: Any) -> Chain:
"""Unified method for loading a chain from LangChainHub or local fs."""
if hub_result... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
08545fe6d9e6-30 | else:
file_path = file
# Load from either json or yaml.
if file_path.suffix == ".json":
with open(file_path) as f:
config = json.load(f)
elif file_path.suffix == ".yaml":
with open(file_path, "r") as f:
config = yaml.safe_load(f)
else:
raise ValueE... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/loading.html |
b3ad85062e3b-0 | Source code for langchain.chains.llm
"""Chain that just formats a prompt and calls an LLM."""
from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
from pydantic import Extra, Field
from langchain.base_language import BaseLanguageModel
from langchain.cal... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-1 | PromptValue,
)
[docs]class LLMChain(Chain):
"""Chain to run queries against LLMs.
Example:
.. code-block:: python
from langchain import LLMChain, OpenAI, PromptTemplate
prompt_template = "Tell me a {adjective} joke"
prompt = PromptTemplate(
input_varia... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-2 | """Output parser to use.
Defaults to one that takes the most likely string but does not change it
otherwise."""
return_final_only: bool = True
"""Whether to return only the final parsed result. Defaults to True.
If false, will return a bunch of extra information about the generation."""
llm_kwa... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-3 | if self.return_final_only:
return [self.output_key]
else:
return [self.output_key, "full_generation"]
def _call(
self,
inputs: Dict[str, Any],
run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Dict[str, str]:
response = self.generate([... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-4 | prompts,
stop,
callbacks=run_manager.get_child() if run_manager else None,
**self.llm_kwargs,
)
[docs] async def agenerate(
self,
input_list: List[Dict[str, Any]],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> LLMResult:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-5 | run_manager: Optional[CallbackManagerForChainRun] = None,
) -> Tuple[List[PromptValue], Optional[List[str]]]:
"""Prepare prompts from inputs."""
stop = None
if "stop" in input_list[0]:
stop = input_list[0]["stop"]
prompts = []
for inputs in input_list:
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-6 | raise ValueError(
"If `stop` is present in any inputs, should be present in all."
)
prompts.append(prompt)
return prompts, stop
[docs] async def aprep_prompts(
self,
input_list: List[Dict[str, Any]],
run_manager: Optional[AsyncCallbackMa... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-7 | _text = "Prompt after formatting:\n" + _colored_text
if run_manager:
await run_manager.on_text(_text, end="\n", verbose=self.verbose)
if "stop" in inputs and inputs["stop"] != stop:
raise ValueError(
"If `stop` is present in any inputs, should ... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-8 | )
try:
response = self.generate(input_list, run_manager=run_manager)
except (KeyboardInterrupt, Exception) as e:
run_manager.on_chain_error(e)
raise e
outputs = self.create_outputs(response)
run_manager.on_chain_end({"outputs": outputs})
return... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-9 | except (KeyboardInterrupt, Exception) as e:
await run_manager.on_chain_error(e)
raise e
outputs = self.create_outputs(response)
await run_manager.on_chain_end({"outputs": outputs})
return outputs
@property
def _run_output_key(self) -> str:
return self.outp... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-10 | return result
async def _acall(
self,
inputs: Dict[str, Any],
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
) -> Dict[str, str]:
response = await self.agenerate([inputs], run_manager=run_manager)
return self.create_outputs(response)[0]
[docs] def predi... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-11 | [docs] async def apredict(self, callbacks: Callbacks = None, **kwargs: Any) -> str:
"""Format prompt with kwargs and pass to LLM.
Args:
callbacks: Callbacks to pass to LLMChain
**kwargs: Keys to pass to prompt template.
Returns:
Completion from LLM.
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-12 | "instead pass an output parser directly to LLMChain."
)
result = self.predict(callbacks=callbacks, **kwargs)
if self.prompt.output_parser is not None:
return self.prompt.output_parser.parse(result)
else:
return result
[docs] async def apredict_and_parse(
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-13 | else:
return result
[docs] def apply_and_parse(
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None
) -> Sequence[Union[str, List[str], Dict[str, str]]]:
"""Call apply and then parse the results."""
warnings.warn(
"The apply_and_parse method is depr... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-14 | for res in generation
]
else:
return generation
[docs] async def aapply_and_parse(
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None
) -> Sequence[Union[str, List[str], Dict[str, str]]]:
"""Call apply and then parse the results."""
warning... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
b3ad85062e3b-15 | """Create LLMChain from LLM and template."""
prompt_template = PromptTemplate.from_template(template)
return cls(llm=llm, prompt=prompt_template) | https://api.python.langchain.com/en/latest/_modules/langchain/chains/llm.html |
6d7697b1919a-0 | Source code for langchain.chains.moderation
"""Pass input through a moderation endpoint."""
from typing import Any, Dict, List, Optional
from pydantic import root_validator
from langchain.callbacks.manager import CallbackManagerForChainRun
from langchain.chains.base import Chain
from langchain.utils import get_from_dic... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
6d7697b1919a-1 | """
client: Any #: :meta private:
model_name: Optional[str] = None
"""Moderation model name to use."""
error: bool = False
"""Whether or not to error if bad content was found."""
input_key: str = "input" #: :meta private:
output_key: str = "output" #: :meta private:
openai_api_key: Op... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
6d7697b1919a-2 | "openai_organization",
"OPENAI_ORGANIZATION",
default="",
)
try:
import openai
openai.api_key = openai_api_key
if openai_organization:
openai.organization = openai_organization
values["client"] = openai.Moderation
... | https://api.python.langchain.com/en/latest/_modules/langchain/chains/moderation.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.