Skip to content

Commit 7198a1c

Browse files
hwchase17amosjyng
andauthored
Harrison/refactor agent (#781)
Co-authored-by: Amos Ng <[email protected]>
1 parent 5bb2952 commit 7198a1c

File tree

1 file changed

+29
-16
lines changed

1 file changed

+29
-16
lines changed

langchain/agents/agent.py

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,29 @@ def _fix_text(self, text: str) -> str:
4848
def _stop(self) -> List[str]:
4949
return [f"\n{self.observation_prefix}"]
5050

51+
def _construct_scratchpad(
52+
self, intermediate_steps: List[Tuple[AgentAction, str]]
53+
) -> str:
54+
"""Construct the scratchpad that lets the agent continue its thought process."""
55+
thoughts = ""
56+
for action, observation in intermediate_steps:
57+
thoughts += action.log
58+
thoughts += f"\n{self.observation_prefix}{observation}\n{self.llm_prefix}"
59+
return thoughts
60+
61+
def _get_next_action(self, full_inputs: Dict[str, str]) -> AgentAction:
62+
full_output = self.llm_chain.predict(**full_inputs)
63+
parsed_output = self._extract_tool_and_input(full_output)
64+
while parsed_output is None:
65+
full_output = self._fix_text(full_output)
66+
full_inputs["agent_scratchpad"] += full_output
67+
output = self.llm_chain.predict(**full_inputs)
68+
full_output += output
69+
parsed_output = self._extract_tool_and_input(full_output)
70+
return AgentAction(
71+
tool=parsed_output[0], tool_input=parsed_output[1], log=full_output
72+
)
73+
5174
def plan(
5275
self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any
5376
) -> Union[AgentAction, AgentFinish]:
@@ -61,24 +84,14 @@ def plan(
6184
Returns:
6285
Action specifying what tool to use.
6386
"""
64-
thoughts = ""
65-
for action, observation in intermediate_steps:
66-
thoughts += action.log
67-
thoughts += f"\n{self.observation_prefix}{observation}\n{self.llm_prefix}"
87+
thoughts = self._construct_scratchpad(intermediate_steps)
6888
new_inputs = {"agent_scratchpad": thoughts, "stop": self._stop}
6989
full_inputs = {**kwargs, **new_inputs}
70-
full_output = self.llm_chain.predict(**full_inputs)
71-
parsed_output = self._extract_tool_and_input(full_output)
72-
while parsed_output is None:
73-
full_output = self._fix_text(full_output)
74-
full_inputs["agent_scratchpad"] += full_output
75-
output = self.llm_chain.predict(**full_inputs)
76-
full_output += output
77-
parsed_output = self._extract_tool_and_input(full_output)
78-
tool, tool_input = parsed_output
79-
if tool == self.finish_tool_name:
80-
return AgentFinish({"output": tool_input}, full_output)
81-
return AgentAction(tool, tool_input, full_output)
90+
91+
action = self._get_next_action(full_inputs)
92+
if action.tool == self.finish_tool_name:
93+
return AgentFinish({"output": action.tool_input}, action.log)
94+
return action
8295

8396
def prepare_for_new_call(self) -> None:
8497
"""Prepare the agent for new call, if needed."""

0 commit comments

Comments
 (0)