id
stringlengths
14
16
text
stringlengths
13
2.7k
source
stringlengths
57
178
f25fc56e5192-2
max_iterations=max_iterations, max_execution_time=max_execution_time, early_stopping_method=early_stopping_method, **(agent_executor_kwargs or {}), )
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/xorbits/base.html
2f12915be0f3-0
Source code for langchain_experimental.agents.agent_toolkits.csv.base from io import IOBase from typing import Any, List, Optional, Union from langchain.agents.agent import AgentExecutor from langchain.schema.language_model import BaseLanguageModel from langchain_experimental.agents.agent_toolkits.pandas.base import ( ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/csv/base.html
821f20bc50d1-0
Source code for langchain_experimental.agents.agent_toolkits.python.base """Python agent.""" from typing import Any, Dict, Optional from langchain.agents.agent import AgentExecutor, BaseSingleActionAgent from langchain.agents.mrkl.base import ZeroShotAgent from langchain.agents.openai_functions_agent.base import OpenAI...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/python/base.html
821f20bc50d1-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...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/python/base.html
1da039b77b0e-0
Source code for langchain_experimental.agents.agent_toolkits.pandas.base """Agent for working with pandas objects.""" from typing import Any, Dict, List, Optional, Sequence, Tuple from langchain.agents.agent import AgentExecutor, BaseSingleActionAgent from langchain.agents.mrkl.base import ZeroShotAgent from langchain....
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html
1da039b77b0e-1
include_dfs_head = True else: suffix_to_use = SUFFIX_NO_DF include_dfs_head = False if input_variables is None: input_variables = ["input", "agent_scratchpad", "num_dfs"] if include_dfs_head: input_variables += ["dfs_head"] if prefix is None: prefix = MULT...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html
1da039b77b0e-2
elif include_df_in_prompt: suffix_to_use = SUFFIX_WITH_DF include_df_head = True else: suffix_to_use = SUFFIX_NO_DF include_df_head = False if input_variables is None: input_variables = ["input", "agent_scratchpad"] if include_df_head: input_variables ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html
1da039b77b0e-3
if isinstance(df, list): for item in df: if not isinstance(item, pd.DataFrame): raise ValueError(f"Expected pandas object, got {type(df)}") return _get_multi_prompt( df, prefix=prefix, suffix=suffix, input_variables=input_variab...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html
1da039b77b0e-4
tools = [PythonAstREPLTool(locals={"df": df})] system_message = SystemMessage(content=prefix + suffix_to_use) prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message) return prompt, tools def _get_functions_multi_prompt( dfs: Any, prefix: Optional[str] = None, suffix: Optional[...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html
1da039b77b0e-5
return prompt, tools def _get_functions_prompt_and_tools( df: Any, prefix: Optional[str] = None, suffix: Optional[str] = None, input_variables: Optional[List[str]] = None, include_df_in_prompt: Optional[bool] = True, number_of_head_rows: int = 5, ) -> Tuple[BasePromptTemplate, List[PythonAstREPL...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html
1da039b77b0e-6
) [docs]def create_pandas_dataframe_agent( llm: BaseLanguageModel, df: Any, agent_type: AgentType = AgentType.ZERO_SHOT_REACT_DESCRIPTION, callback_manager: Optional[BaseCallbackManager] = None, prefix: Optional[str] = None, suffix: Optional[str] = None, input_variables: Optional[List[str]] ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html
1da039b77b0e-7
agent = ZeroShotAgent( llm_chain=llm_chain, allowed_tools=tool_names, callback_manager=callback_manager, **kwargs, ) elif agent_type == AgentType.OPENAI_FUNCTIONS: _prompt, base_tools = _get_functions_prompt_and_tools( df, prefi...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/agents/agent_toolkits/pandas/base.html
97d160c91520-0
Source code for langchain_experimental.llm_bash.bash """Wrapper around subprocess to run commands.""" from __future__ import annotations import platform import re import subprocess from typing import TYPE_CHECKING, List, Union from uuid import uuid4 if TYPE_CHECKING: import pexpect [docs]class BashProcess: """ ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/bash.html
97d160c91520-1
self.process = None if persistent: self.prompt = str(uuid4()) self.process = self._initialize_persistent_process(self, self.prompt) @staticmethod def _lazy_import_pexpect() -> pexpect: """Import pexpect only when needed.""" if platform.system() == "Windows": ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/bash.html
97d160c91520-2
execute in the session """ # noqa: E501 if isinstance(commands, str): commands = [commands] commands = ";".join(commands) if self.process is not None: return self._run_persistent( commands, ) else: return self._run(...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/bash.html
97d160c91520-3
pexpect = self._lazy_import_pexpect() if self.process is None: raise ValueError("Process not initialized") self.process.sendline(command) # Clear the output with an empty string self.process.expect(self.prompt, timeout=10) self.process.sendline("") try: ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/bash.html
be58a027392c-0
Source code for langchain_experimental.llm_bash.prompt # flake8: noqa from __future__ import annotations import re from typing import List from langchain.prompts.prompt import PromptTemplate from langchain.schema import BaseOutputParser, OutputParserException _PROMPT_TEMPLATE = """If someone asks you to perform a task,...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/prompt.html
be58a027392c-1
for match in pattern.finditer(t): matched = match.group(1).strip() if matched: code_blocks.extend( [line for line in matched.split("\n") if line.strip()] ) return code_blocks @property def _type(self) -> str: return "bas...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/prompt.html
92038ec56221-0
Source code for langchain_experimental.llm_bash.base """Chain that interprets a prompt and executes bash operations.""" from __future__ import annotations import logging import warnings from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains....
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/base.html
92038ec56221-1
def raise_deprecation(cls, values: Dict) -> Dict: if "llm" in values: warnings.warn( "Directly instantiating an LLMBashChain with an llm is deprecated. " "Please instantiate with llm_chain or using the from_llm class method." ) if "llm_chain" n...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/base.html
92038ec56221-2
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager() _run_manager.on_text(inputs[self.input_key], verbose=self.verbose) t = self.llm_chain.predict( question=inputs[self.input_key], callbacks=_run_manager.get_child() ) _run_manager.on_text(t, color="gree...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_bash/base.html
4a2a61623880-0
Source code for langchain_experimental.fallacy_removal.base """Chain for applying removals of logical fallacies.""" from __future__ import annotations from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain.ch...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html
4a2a61623880-1
fallacy_critique_request="Tell if this answer meets criteria.", fallacy_revision_request=\ "Give an answer that meets better criteria.", ) ], ) fallacy_chain.run(question="How do I know if the earth is round?") ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html
4a2a61623880-2
def input_keys(self) -> List[str]: """Input keys.""" return self.chain.input_keys @property def output_keys(self) -> List[str]: """Output keys.""" if self.return_intermediate_steps: return ["output", "fallacy_critiques_and_revisions", "initial_output"] return ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html
4a2a61623880-3
if "no fallacy critique needed" in fallacy_critique.lower(): fallacy_critiques_and_revisions.append((fallacy_critique, "")) continue fallacy_revision = self.fallacy_revision_chain.run( input_prompt=input_prompt, output_from_model=response, ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html
4a2a61623880-4
if "Fallacy Revision request:" not in output_string: return output_string output_string = output_string.split("Fallacy Revision request:")[0] if "\n\n" in output_string: output_string = output_string.split("\n\n")[0] return output_string
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/base.html
42de0ca2f1f3-0
Source code for langchain_experimental.fallacy_removal.models """Models for the Logical Fallacy Chain""" from langchain_experimental.pydantic_v1 import BaseModel [docs]class LogicalFallacy(BaseModel): """Class for a logical fallacy.""" fallacy_critique_request: str fallacy_revision_request: str name: st...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/fallacy_removal/models.html
e0c4c8d2a194-0
Source code for langchain_experimental.open_clip.open_clip from typing import Any, Dict, List from langchain.pydantic_v1 import BaseModel, root_validator from langchain.schema.embeddings import Embeddings [docs]class OpenCLIPEmbeddings(BaseModel, Embeddings): model: Any preprocess: Any tokenizer: Any @r...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/open_clip/open_clip.html
e0c4c8d2a194-1
embeddings_tensor = self.model.encode_text(tokenized_text) # Normalize the embeddings norm = embeddings_tensor.norm(p=2, dim=1, keepdim=True) normalized_embeddings_tensor = embeddings_tensor.div(norm) # Convert normalized tensor to list and add to the text_features list ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/open_clip/open_clip.html
5072eb433e59-0
Source code for langchain_experimental.comprehend_moderation.base_moderation_config from typing import List, Union from pydantic import BaseModel [docs]class ModerationPiiConfig(BaseModel): threshold: float = 0.5 """Threshold for PII confidence score, defaults to 0.5 i.e. 50%""" labels: List[str] = [] "...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_config.html
5072eb433e59-1
`[ModerationPiiConfig(), ModerationToxicityConfig(), ModerationPromptSafetyConfig()]` """
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_config.html
812d4341cc9b-0
Source code for langchain_experimental.comprehend_moderation.toxicity import asyncio import importlib from typing import Any, List, Optional from langchain_experimental.comprehend_moderation.base_moderation_exceptions import ( ModerationToxicityError, ) [docs]class ComprehendToxicity: [docs] def __init__( ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html
812d4341cc9b-1
raise ModuleNotFoundError( "Could not import nltk python package. " "Please install it with `pip install nltk`." ) except LookupError: nltk.download("punkt") def _split_paragraph( self, prompt_value: str, max_size: int = 1024 * 4 ) -> List[...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html
812d4341cc9b-2
if current_chunk: # Avoid appending empty chunks chunks.append(current_chunk) current_chunk = [] current_size = 0 current_chunk.append(sentence) current_size += sentence_size # Add any remaining sentences if current_chunk: ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html
812d4341cc9b-3
toxicity_found = True break else: for item in response["ResultList"]: for label in item["Labels"]: if ( label["Name"] in toxicity_labels and label["Score"] >= thres...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/toxicity.html
fd07c70e4608-0
Source code for langchain_experimental.comprehend_moderation.prompt_safety import asyncio from typing import Any, Optional from langchain_experimental.comprehend_moderation.base_moderation_exceptions import ( ModerationPromptSafetyError, ) [docs]class ComprehendPromptSafety: [docs] def __init__( self, ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/prompt_safety.html
fd07c70e4608-1
Note: This function checks the safety of the provided prompt text using Comprehend's classify_document API and raises an error if unsafe text is detected with a score above the specified threshold. Example: comprehend_client = boto3.client('comprehend') ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/prompt_safety.html
4a4269009101-0
Source code for langchain_experimental.comprehend_moderation.pii import asyncio from typing import Any, Dict, Optional from langchain_experimental.comprehend_moderation.base_moderation_exceptions import ( ModerationPiiError, ) [docs]class ComprehendPII: [docs] def __init__( self, client: Any, ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html
4a4269009101-1
Returns: str: the original prompt Note: - The provided client should be initialized with valid AWS credentials. """ pii_identified = self.client.contains_pii_entities( Text=prompt_value, LanguageCode="en" ) if self.callback and self.callback.pi...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html
4a4269009101-2
prompt_value (str): The input text to be checked for PII entities. config (Dict[str, Any]): A configuration specifying how to handle PII entities. Returns: str: The processed prompt text with redacted PII entities or raised exceptions...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html
4a4269009101-3
if pii_found: raise ModerationPiiError else: threshold = config.get("threshold") # type: ignore pii_labels = config.get("labels") # type: ignore mask_marker = config.get("mask_character") # type: ignore pii_found = False for entity i...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/pii.html
575654d54896-0
Source code for langchain_experimental.comprehend_moderation.base_moderation_callbacks from typing import Any, Callable, Dict [docs]class BaseModerationCallbackHandler: [docs] def __init__(self) -> None: if ( self._is_method_unchanged( BaseModerationCallbackHandler.on_after_pii, s...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_callbacks.html
575654d54896-1
) -> None: """Run after Prompt Safety validation is complete.""" pass @property def pii_callback(self) -> bool: return ( self.on_after_pii.__func__ # type: ignore is not BaseModerationCallbackHandler.on_after_pii ) @property def toxicity_callback(...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_callbacks.html
ec8a65d88df2-0
Source code for langchain_experimental.comprehend_moderation.base_moderation import uuid from typing import Any, Callable, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.prompts.base import StringPromptValue from langchain.prompts.chat import ChatPromptValue from langchain.sc...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html
ec8a65d88df2-1
SystemMessage > HumanMessage > AIMessage and so on. However assuming that with every chat the chain is invoked we will only check the last message. This is assuming that all previous messages have been checked already. Only HumanMessage and AIMessage will be checked. We can perhaps ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html
ec8a65d88df2-2
example=message.example, additional_kwargs=message.additional_kwargs, ) if isinstance(message, AIMessage): messages[self.chat_message_index] = AIMessage( content=text, example=message.example, add...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html
ec8a65d88df2-3
"toxicity": ComprehendToxicity, "prompt_safety": ComprehendPromptSafety, } filters = self.config.filters # type: ignore for _filter in filters: filter_name = ( "pii" if isinstance(_filter, ModerationPiiConfig) ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html
ec8a65d88df2-4
) raise e except Exception as e: raise e
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation.html
804156d74eea-0
Source code for langchain_experimental.comprehend_moderation.amazon_comprehend_moderation from typing import Any, Dict, List, Optional from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chains.base import Chain from langchain_experimental.comprehend_moderation.base_moderation import BaseM...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html
804156d74eea-1
has either access keys or role information specified. If not specified, the default credential profile or, if on an EC2 instance, credentials from IMDS will be used. See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html """ moderation_callback: Optional[BaseModerationCa...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html
804156d74eea-2
else: # use default credentials session = boto3.Session() client_params = {} if values.get("region_name"): client_params["region_name"] = values["region_name"] values["client"] = session.client("comprehend", **client_params) ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html
804156d74eea-3
""" return [self.input_key] def _call( self, inputs: Dict[str, Any], run_manager: Optional[CallbackManagerForChainRun] = None, ) -> Dict[str, str]: """ Executes the moderation process on the input text and returns the processed output. This interna...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/amazon_comprehend_moderation.html
721a00314321-0
Source code for langchain_experimental.comprehend_moderation.base_moderation_exceptions [docs]class ModerationPiiError(Exception): """Exception raised if PII entities are detected. Attributes: message -- explanation of the error """ def __init__( self, message: str = "The prompt contains...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/comprehend_moderation/base_moderation_exceptions.html
642b24749d67-0
Source code for langchain_experimental.smart_llm.base """Chain for applying self-critique using the SmartGPT workflow.""" from typing import Any, Dict, List, Optional, Tuple, Type from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chai...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html
642b24749d67-1
often don't. Finally, a SmartLLMChain assumes that each underlying LLM outputs exactly 1 result. """ [docs] class SmartLLMChainHistory: question: str = "" ideas: List[str] = [] critique: str = "" @property def n_ideas(self) -> int: return len(self.ideas) [d...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html
642b24749d67-2
llm: Optional[BaseLanguageModel] = None """LLM to use for each steps, if no specific llm for that step is given. """ n_ideas: int = 3 """Number of ideas to generate in idea step""" return_intermediate_steps: bool = False """Whether to return ideas and critique, in addition to resolution.""" hist...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html
642b24749d67-3
"Either critique_llm or llm needs to be given. Pass llm, " "if you want to use the same llm for all steps, or pass " "ideation_llm, critique_llm and resolver_llm if you want " "to use different llms for each step." ) if not llm and not resolver_llm: ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html
642b24749d67-4
stop = None if "stop" in inputs: stop = inputs["stop"] selected_inputs = {k: inputs[k] for k in self.prompt.input_variables} prompt = self.prompt.format_prompt(**selected_inputs) _colored_text = get_colored_text(prompt.to_string(), "green") _text = "Prompt after forma...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html
642b24749d67-5
if len(result.generations) != 1: raise ValueError( f"In SmartLLM the LLM result in step {step} is not " "exactly 1 element. This should never happen" ) if len(result.generations[0]) != 1: raise ValueError( f"In SmartLLM the LLM ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html
642b24749d67-6
" by step way to be sure we have all the errors:", ), ] ) if stage == "critique": return role_strings role_strings.extend( [ (AIMessagePromptTemplate, "Critique: {critique}"), ( HumanMessagePr...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html
642b24749d67-7
"""Generate n_ideas ideas as response to user prompt.""" llm = self.ideation_llm if self.ideation_llm else self.llm prompt = self.ideation_prompt().format_prompt( **self.history.ideation_prompt_inputs() ) callbacks = run_manager.get_child() if run_manager else None if...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html
642b24749d67-8
) _colored_text = get_colored_text(critique, "yellow") _text = "Critique:\n" + _colored_text if run_manager: run_manager.on_text(_text, end="\n", verbose=self.verbose) return critique else: raise ValueError("llm is none, which should ne...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/smart_llm/base.html
10cde80c6649-0
Source code for langchain_experimental.chat_models.llm_wrapper """Generic Wrapper for chat LLMs, with sample implementations for Llama-2-chat, Llama-2-instruct and Vicuna models. """ from typing import Any, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForLLMRun, CallbackManagerFo...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/chat_models/llm_wrapper.html
10cde80c6649-1
messages: List[BaseMessage], stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> ChatResult: llm_input = self._to_chat_prompt(messages) llm_result = self.llm._generate( prompts=[llm_input], stop=stop, run_m...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/chat_models/llm_wrapper.html
10cde80c6649-2
raise ValueError("last message must be a HumanMessage") prompt_parts = [] if self.usr_0_beg is None: self.usr_0_beg = self.usr_n_beg if self.usr_0_end is None: self.usr_0_end = self.usr_n_end prompt_parts.append(self.sys_beg + messages[0].content + self.sys_end) ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/chat_models/llm_wrapper.html
10cde80c6649-3
return "llama-2-chat" sys_beg: str = "<s>[INST] <<SYS>>\n" sys_end: str = "\n<</SYS>>\n\n" ai_n_beg: str = " " ai_n_end: str = " </s>" usr_n_beg: str = "<s>[INST] " usr_n_end: str = " [/INST]" usr_0_beg: str = "" usr_0_end: str = " [/INST]" [docs]class Orca(ChatWrapper): @property ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/chat_models/llm_wrapper.html
9ba6cce9ece6-0
Source code for langchain_experimental.rl_chain.model_repository import datetime import glob import logging import os import shutil from pathlib import Path from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: import vowpal_wabbit_next as vw logger = logging.getLogger(__name__) [docs]class ModelRepositor...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/model_repository.html
9ba6cce9ece6-1
try: import vowpal_wabbit_next as vw except ImportError as e: raise ImportError( "Unable to import vowpal_wabbit_next, please install with " "`pip install vowpal_wabbit_next`." ) from e model_data = None if self.model_path.exist...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/model_repository.html
77a14ba3132e-0
Source code for langchain_experimental.rl_chain.pick_best_chain from __future__ import annotations import logging from typing import Any, Dict, List, Optional, Tuple, Type, Union from langchain.base_language import BaseLanguageModel from langchain.callbacks.manager import CallbackManagerForChainRun from langchain.chain...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
77a14ba3132e-1
Attributes: model name (Any, optional): The type of embeddings to be used for feature representation. Defaults to BERT SentenceTransformer. """ # noqa E501 [docs] def __init__( self, auto_embed: bool, model: Optional[Any] = None, *args: Any, **kwargs: Any ): super().__init__(*args, *...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
77a14ba3132e-2
else None ) if to_select_from else None ) if not context_emb or not action_embs: raise ValueError( "Context and to_select_from must be provided in the inputs dictionary" ) return context_emb, action_embs [docs] def ge...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
77a14ba3132e-3
for j, action_key in enumerate(action_embeddings.keys()): indexed_dot_product[context_key][action_key] = dot_product_matrix[i, j] return indexed_dot_product [docs] def format_auto_embed_on(self, event: PickBestEvent) -> str: chosen_action, cost, prob = self.get_label(event) co...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
77a14ba3132e-4
for elem in elements: shared.append(f"{elem}") nsc.append(f"{ns}={elem}") nsc_str = " ".join(nsc) shared.append(f"|@ {nsc_str}") return "shared " + " ".join(shared) + "\n" + "\n".join(action_lines) [docs] def format_auto_embed_off(self, ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
77a14ba3132e-5
return self.format_auto_embed_on(event) else: return self.format_auto_embed_off(event) [docs]class PickBestRandomPolicy(base.Policy[PickBestEvent]): [docs] def __init__(self, feature_embedder: base.Embedder, **kwargs: Any): self.feature_embedder = feature_embedder [docs] def predict(se...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
77a14ba3132e-6
5. The internal Vowpal Wabbit model is updated with the `BasedOn` input, the chosen `ToSelectFrom` action, and the resulting score from the scorer. 6. The final response is returned. Expected input dictionary format: - At least one variable encapsulated within `BasedOn` to serve as the selection cri...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
77a14ba3132e-7
if feature_embedder: if "auto_embed" in kwargs: logger.warning( "auto_embed will take no effect when explicit feature_embedder is provided" # noqa E501 ) # turning auto_embed off for cli setting below auto_embed = False els...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
77a14ba3132e-8
) if len(list(actions.values())) > 1: raise ValueError( "Only one variable using 'ToSelectFrom' can be provided in the inputs for the PickBest chain. Please provide only one variable containing a list to select from." # noqa E501 ) if not context: rai...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
77a14ba3132e-9
self, llm_response: str, event: PickBestEvent ) -> Tuple[Dict[str, Any], PickBestEvent]: next_chain_inputs = event.inputs.copy() # only one key, value pair in event.to_select_from value = next(iter(event.to_select_from.values())) v = ( value[event.selected.index] ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
77a14ba3132e-10
if selection_scorer is SENTINEL: selection_scorer = base.AutoSelectionScorer(llm=llm_chain.llm) return PickBest( llm_chain=llm_chain, prompt=prompt, selection_scorer=selection_scorer, **kwargs, )
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/pick_best_chain.html
284dc91a75da-0
Source code for langchain_experimental.rl_chain.base from __future__ import annotations import logging import os from abc import ABC, abstractmethod from typing import ( TYPE_CHECKING, Any, Dict, Generic, List, Optional, Tuple, Type, TypeVar, Union, ) from langchain.callbacks.man...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-1
[docs]def ToSelectFrom(anything: Any) -> _ToSelectFrom: if not isinstance(anything, list): raise ValueError("ToSelectFrom must be a list to select from") return _ToSelectFrom(anything) class _Embed: def __init__(self, value: Any, keep: bool = False): self.value = value self.keep = ke...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-2
return [parser.parse_line(line) for line in input_str.split("\n")] [docs]def get_based_on_and_to_select_from(inputs: Dict[str, Any]) -> Tuple[Dict, Dict]: to_select_from = { k: inputs[k].value for k in inputs.keys() if isinstance(inputs[k], _ToSelectFrom) } if not to_select_from: ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-3
[docs]class Event(Generic[TSelected], ABC): inputs: Dict[str, Any] selected: Optional[TSelected] [docs] def __init__(self, inputs: Dict[str, Any], selected: Optional[TSelected] = None): self.inputs = inputs self.selected = selected TEvent = TypeVar("TEvent", bound=Event) [docs]class Policy(Ge...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-4
parse_lines(text_parser, self.feature_embedder.format(event)) ) [docs] def learn(self, event: TEvent) -> None: import vowpal_wabbit_next as vw vw_ex = self.feature_embedder.format(event) text_parser = vw.TextFormatParser(self.workspace) multi_ex = parse_lines(text_parser, vw_e...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-5
return SystemMessagePromptTemplate.from_template( "PLEASE RESPOND ONLY WITH A SINGLE FLOAT AND NO OTHER TEXT EXPLANATION\n \ You are a strict judge that is called on to rank a response based on \ given criteria. You must respond with your ranking by providing a \ ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-6
) values["prompt"] = prompt values["llm_chain"] = LLMChain(llm=llm, prompt=prompt) return values [docs] def score_response( self, inputs: Dict[str, Any], llm_response: str, event: Event ) -> float: ranking = self.llm_chain.predict(llm_response=llm_response, **inputs) ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-7
- model_save_dir (str, optional): Directory for saving the VW model. Default is the current directory. - reset_model (bool): If set to True, the model starts training from scratch. Default is False. - vw_cmd (List[str], optional): Command line arguments for the VW model. - policy (Type[VwPolicy]...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-8
selected_input_key = "rl_chain_selected" selected_based_on_input_key = "rl_chain_selected_based_on" metrics: Optional[Union[MetricsTrackerRollingWindow, MetricsTrackerAverage]] = None def __init__( self, feature_embedder: Embedder, model_save_dir: str = "./", reset_model: boo...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-9
extra = Extra.forbid arbitrary_types_allowed = True @property def input_keys(self) -> List[str]: """Expect input key. :meta private: """ return [] @property def output_keys(self) -> List[str]: """Expect output key. :meta private: """ ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-10
[docs] def activate_selection_scorer(self) -> None: """ Activates the selection scorer, meaning that the chain will attempt to use the selection scorer to score responses. """ # noqa: E501 self.selection_scorer_activated = True [docs] def save_progress(self) -> None: """ ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-11
self, llm_response: str, event: TEvent ) -> Tuple[Dict[str, Any], TEvent]: ... @abstractmethod def _call_after_scoring_before_learning( self, event: TEvent, score: Optional[float] ) -> TEvent: ... def _call( self, inputs: Dict[str, Any], run_manager: O...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-12
inputs=next_chain_inputs, llm_response=output, event=event ) except Exception as e: logger.info( f"The selection scorer was not able to score, \ and the chain was not able to adjust to this response, error: {e}" ) if self.metrics an...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-13
if namespace is None: raise ValueError( "The default namespace must be provided when embedding a string or _Embed object." # noqa: E501 ) return {namespace: keep_str + encoded} [docs]def embed_dict_type(item: Dict, model: Any) -> Dict[str, Any]: """Helper function to embed a diction...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
284dc91a75da-14
return ret_list [docs]def embed( to_embed: Union[Union[str, _Embed], Dict, List[Union[str, _Embed]], List[Dict]], model: Any, namespace: Optional[str] = None, ) -> List[Dict[str, Union[str, List[str]]]]: """ Embeds the actions or context using the SentenceTransformer model (or a model that has an `e...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/base.html
5467eaf1e8be-0
Source code for langchain_experimental.rl_chain.vw_logger from os import PathLike from pathlib import Path from typing import Optional, Union [docs]class VwLogger: [docs] def __init__(self, path: Optional[Union[str, PathLike]]): self.path = Path(path) if path else None if self.path: self....
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/vw_logger.html
d66996ca92db-0
Source code for langchain_experimental.rl_chain.metrics from collections import deque from typing import TYPE_CHECKING, Dict, List, Union if TYPE_CHECKING: import pandas as pd [docs]class MetricsTrackerAverage: [docs] def __init__(self, step: int): self.history: List[Dict[str, Union[int, float]]] = [{"st...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/metrics.html
d66996ca92db-1
@property def score(self) -> float: return self.sum / len(self.queue) if len(self.queue) > 0 else 0 [docs] def on_decision(self) -> None: pass [docs] def on_feedback(self, value: float) -> None: self.sum += value self.queue.append(value) self.i += 1 if len(self....
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/rl_chain/metrics.html
4fd8ea3f9841-0
Source code for langchain_experimental.prompt_injection_identifier.hugging_face_identifier """Tool for the identification of prompt injection attacks.""" from __future__ import annotations from typing import TYPE_CHECKING from langchain.pydantic_v1 import Field from langchain.tools.base import BaseTool if TYPE_CHECKING...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/prompt_injection_identifier/hugging_face_identifier.html
aba36ae210b9-0
Source code for langchain_experimental.llm_symbolic_math.base """Chain that interprets a prompt and executes python code to do symbolic math.""" from __future__ import annotations import re from typing import Any, Dict, List, Optional from langchain.base_language import BaseLanguageModel from langchain.callbacks.manage...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_symbolic_math/base.html
aba36ae210b9-1
:meta private: """ return [self.output_key] def _evaluate_expression(self, expression: str) -> str: try: import sympy except ImportError as e: raise ImportError( "Unable to import sympy, please install it with `pip install sympy`." ...
lang/api.python.langchain.com/en/latest/_modules/langchain_experimental/llm_symbolic_math/base.html