initial commit
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
178
venv/Lib/site-packages/langchain_classic/agents/chat/base.py
Normal file
178
venv/Lib/site-packages/langchain_classic/agents/chat/base.py
Normal file
@@ -0,0 +1,178 @@
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from langchain_core._api import deprecated
|
||||
from langchain_core.agents import AgentAction
|
||||
from langchain_core.callbacks import BaseCallbackManager
|
||||
from langchain_core.language_models import BaseLanguageModel
|
||||
from langchain_core.prompts import BasePromptTemplate
|
||||
from langchain_core.prompts.chat import (
|
||||
ChatPromptTemplate,
|
||||
HumanMessagePromptTemplate,
|
||||
SystemMessagePromptTemplate,
|
||||
)
|
||||
from langchain_core.tools import BaseTool
|
||||
from pydantic import Field
|
||||
from typing_extensions import override
|
||||
|
||||
from langchain_classic._api.deprecation import AGENT_DEPRECATION_WARNING
|
||||
from langchain_classic.agents.agent import Agent, AgentOutputParser
|
||||
from langchain_classic.agents.chat.output_parser import ChatOutputParser
|
||||
from langchain_classic.agents.chat.prompt import (
|
||||
FORMAT_INSTRUCTIONS,
|
||||
HUMAN_MESSAGE,
|
||||
SYSTEM_MESSAGE_PREFIX,
|
||||
SYSTEM_MESSAGE_SUFFIX,
|
||||
)
|
||||
from langchain_classic.agents.utils import validate_tools_single_input
|
||||
from langchain_classic.chains.llm import LLMChain
|
||||
|
||||
|
||||
@deprecated(
|
||||
"0.1.0",
|
||||
message=AGENT_DEPRECATION_WARNING,
|
||||
removal="1.0",
|
||||
)
|
||||
class ChatAgent(Agent):
|
||||
"""Chat Agent."""
|
||||
|
||||
output_parser: AgentOutputParser = Field(default_factory=ChatOutputParser)
|
||||
"""Output parser for the agent."""
|
||||
|
||||
@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:"
|
||||
|
||||
def _construct_scratchpad(
|
||||
self,
|
||||
intermediate_steps: list[tuple[AgentAction, str]],
|
||||
) -> str:
|
||||
agent_scratchpad = super()._construct_scratchpad(intermediate_steps)
|
||||
if not isinstance(agent_scratchpad, str):
|
||||
msg = "agent_scratchpad should be of type string."
|
||||
raise ValueError(msg) # noqa: TRY004
|
||||
if agent_scratchpad:
|
||||
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}"
|
||||
)
|
||||
return agent_scratchpad
|
||||
|
||||
@classmethod
|
||||
@override
|
||||
def _get_default_output_parser(cls, **kwargs: Any) -> AgentOutputParser:
|
||||
return ChatOutputParser()
|
||||
|
||||
@classmethod
|
||||
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
|
||||
super()._validate_tools(tools)
|
||||
validate_tools_single_input(class_name=cls.__name__, tools=tools)
|
||||
|
||||
@property
|
||||
def _stop(self) -> list[str]:
|
||||
return ["Observation:"]
|
||||
|
||||
@classmethod
|
||||
def create_prompt(
|
||||
cls,
|
||||
tools: Sequence[BaseTool],
|
||||
system_message_prefix: str = SYSTEM_MESSAGE_PREFIX,
|
||||
system_message_suffix: str = SYSTEM_MESSAGE_SUFFIX,
|
||||
human_message: str = HUMAN_MESSAGE,
|
||||
format_instructions: str = FORMAT_INSTRUCTIONS,
|
||||
input_variables: list[str] | None = None,
|
||||
) -> BasePromptTemplate:
|
||||
"""Create a prompt from a list of tools.
|
||||
|
||||
Args:
|
||||
tools: A list of tools.
|
||||
system_message_prefix: The system message prefix.
|
||||
system_message_suffix: The system message suffix.
|
||||
human_message: The `HumanMessage`.
|
||||
format_instructions: The format instructions.
|
||||
input_variables: The input variables.
|
||||
|
||||
Returns:
|
||||
A prompt template.
|
||||
"""
|
||||
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_instructions.format(tool_names=tool_names)
|
||||
template = (
|
||||
f"{system_message_prefix}\n\n"
|
||||
f"{tool_strings}\n\n"
|
||||
f"{format_instructions}\n\n"
|
||||
f"{system_message_suffix}"
|
||||
)
|
||||
messages = [
|
||||
SystemMessagePromptTemplate.from_template(template),
|
||||
HumanMessagePromptTemplate.from_template(human_message),
|
||||
]
|
||||
if input_variables is None:
|
||||
input_variables = ["input", "agent_scratchpad"]
|
||||
return ChatPromptTemplate(input_variables=input_variables, messages=messages)
|
||||
|
||||
@classmethod
|
||||
def from_llm_and_tools(
|
||||
cls,
|
||||
llm: BaseLanguageModel,
|
||||
tools: Sequence[BaseTool],
|
||||
callback_manager: BaseCallbackManager | None = None,
|
||||
output_parser: AgentOutputParser | None = None,
|
||||
system_message_prefix: str = SYSTEM_MESSAGE_PREFIX,
|
||||
system_message_suffix: str = SYSTEM_MESSAGE_SUFFIX,
|
||||
human_message: str = HUMAN_MESSAGE,
|
||||
format_instructions: str = FORMAT_INSTRUCTIONS,
|
||||
input_variables: list[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> Agent:
|
||||
"""Construct an agent from an LLM and tools.
|
||||
|
||||
Args:
|
||||
llm: The language model.
|
||||
tools: A list of tools.
|
||||
callback_manager: The callback manager.
|
||||
output_parser: The output parser.
|
||||
system_message_prefix: The system message prefix.
|
||||
system_message_suffix: The system message suffix.
|
||||
human_message: The `HumanMessage`.
|
||||
format_instructions: The format instructions.
|
||||
input_variables: The input variables.
|
||||
kwargs: Additional keyword arguments.
|
||||
|
||||
Returns:
|
||||
An agent.
|
||||
"""
|
||||
cls._validate_tools(tools)
|
||||
prompt = cls.create_prompt(
|
||||
tools,
|
||||
system_message_prefix=system_message_prefix,
|
||||
system_message_suffix=system_message_suffix,
|
||||
human_message=human_message,
|
||||
format_instructions=format_instructions,
|
||||
input_variables=input_variables,
|
||||
)
|
||||
llm_chain = LLMChain(
|
||||
llm=llm,
|
||||
prompt=prompt,
|
||||
callback_manager=callback_manager,
|
||||
)
|
||||
tool_names = [tool.name for tool in tools]
|
||||
_output_parser = output_parser or cls._get_default_output_parser()
|
||||
return cls(
|
||||
llm_chain=llm_chain,
|
||||
allowed_tools=tool_names,
|
||||
output_parser=_output_parser,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@property
|
||||
def _agent_type(self) -> str:
|
||||
raise ValueError
|
||||
@@ -0,0 +1,71 @@
|
||||
import json
|
||||
import re
|
||||
from re import Pattern
|
||||
|
||||
from langchain_core.agents import AgentAction, AgentFinish
|
||||
from langchain_core.exceptions import OutputParserException
|
||||
|
||||
from langchain_classic.agents.agent import AgentOutputParser
|
||||
from langchain_classic.agents.chat.prompt import FORMAT_INSTRUCTIONS
|
||||
|
||||
FINAL_ANSWER_ACTION = "Final Answer:"
|
||||
|
||||
|
||||
class ChatOutputParser(AgentOutputParser):
|
||||
"""Output parser for the chat agent."""
|
||||
|
||||
format_instructions: str = FORMAT_INSTRUCTIONS
|
||||
"""Default formatting instructions"""
|
||||
|
||||
pattern: Pattern = re.compile(r"^.*?`{3}(?:json)?\n(.*?)`{3}.*?$", re.DOTALL)
|
||||
"""Regex pattern to parse the output."""
|
||||
|
||||
def get_format_instructions(self) -> str:
|
||||
"""Returns formatting instructions for the given output parser."""
|
||||
return self.format_instructions
|
||||
|
||||
def parse(self, text: str) -> AgentAction | AgentFinish:
|
||||
"""Parse the output from the agent into an AgentAction or AgentFinish object.
|
||||
|
||||
Args:
|
||||
text: The text to parse.
|
||||
|
||||
Returns:
|
||||
An AgentAction or AgentFinish object.
|
||||
|
||||
Raises:
|
||||
OutputParserException: If the output could not be parsed.
|
||||
ValueError: If the action could not be found.
|
||||
"""
|
||||
includes_answer = FINAL_ANSWER_ACTION in text
|
||||
try:
|
||||
found = self.pattern.search(text)
|
||||
if not found:
|
||||
# Fast fail to parse Final Answer.
|
||||
msg = "action not found"
|
||||
raise ValueError(msg)
|
||||
action = found.group(1)
|
||||
response = json.loads(action.strip())
|
||||
includes_action = "action" in response
|
||||
if includes_answer and includes_action:
|
||||
msg = (
|
||||
"Parsing LLM output produced a final answer "
|
||||
f"and a parse-able action: {text}"
|
||||
)
|
||||
raise OutputParserException(msg)
|
||||
return AgentAction(
|
||||
response["action"],
|
||||
response.get("action_input", {}),
|
||||
text,
|
||||
)
|
||||
|
||||
except Exception as exc:
|
||||
if not includes_answer:
|
||||
msg = f"Could not parse LLM output: {text}"
|
||||
raise OutputParserException(msg) from exc
|
||||
output = text.rsplit(FINAL_ANSWER_ACTION, maxsplit=1)[-1].strip()
|
||||
return AgentFinish({"output": output}, text)
|
||||
|
||||
@property
|
||||
def _type(self) -> str:
|
||||
return "chat"
|
||||
@@ -0,0 +1,29 @@
|
||||
SYSTEM_MESSAGE_PREFIX = """Answer the following questions as best you can. You have access to the following tools:""" # noqa: E501
|
||||
FORMAT_INSTRUCTIONS = """The way you use the tools is by specifying a json blob.
|
||||
Specifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).
|
||||
|
||||
The only values that should be in the "action" field are: {tool_names}
|
||||
|
||||
The $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:
|
||||
|
||||
```
|
||||
{{{{
|
||||
"action": $TOOL_NAME,
|
||||
"action_input": $INPUT
|
||||
}}}}
|
||||
```
|
||||
|
||||
ALWAYS use the following format:
|
||||
|
||||
Question: the input question you must answer
|
||||
Thought: you should always think about what to do
|
||||
Action:
|
||||
```
|
||||
$JSON_BLOB
|
||||
```
|
||||
Observation: the result of the action
|
||||
... (this Thought/Action/Observation can repeat N times)
|
||||
Thought: I now know the final answer
|
||||
Final Answer: the final answer to the original input question""" # noqa: E501
|
||||
SYSTEM_MESSAGE_SUFFIX = """Begin! Reminder to always use the exact characters `Final Answer` when responding.""" # noqa: E501
|
||||
HUMAN_MESSAGE = "{input}\n\n{agent_scratchpad}"
|
||||
Reference in New Issue
Block a user