Persistent Terminal#

langchain’s default BashProcess tool does not persist changes to the shell. For example, the LLM is unable to change the current working directory and execute new commands from there:

[1]:
from langchain.agents import initialize_agent, load_tools
from langchain.llms import OpenAI

llm = OpenAI(temperature=0)
tools = load_tools(["terminal"], llm=llm)
agent = initialize_agent(
    tools, llm, agent="zero-shot-react-description", verbose=True
)
agent.run(
    "Print the current directory. Go two levels up. Print the current directory again."
)


> Entering new AgentExecutor chain...
 I need to use the terminal to print the current directory and then go two levels up.
Action: Terminal
Action Input: pwd
Observation: /home/amos/projects/gpt-experiments/langchain-contrib/docs/tools

Thought: I need to use the terminal to go two levels up.
Action: Terminal
Action Input: cd ../../
Observation:
Thought: I need to use the terminal to print the current directory again.
Action: Terminal
Action Input: pwd
Observation: /home/amos/projects/gpt-experiments/langchain-contrib/docs/tools

Thought: I now know the final answer.
Final Answer: The current directory is /home/amos/projects/gpt-experiments/langchain-contrib/docs/tools after going two levels up.

> Finished chain.
[1]:
'The current directory is /home/amos/projects/gpt-experiments/langchain-contrib/docs/tools after going two levels up.'

langchain-contrib offers a drop-in replacement that does offer this ability. Simply import langchain_contrib.tools and then load the persistent_terminal tool instead:

[2]:
import langchain_contrib.tools  # noqa: F401

tools = load_tools(["persistent_terminal"], llm=llm)
agent = initialize_agent(
    tools, llm, agent="zero-shot-react-description", verbose=True
)
agent.run(
    "Print the current directory. Go two levels up. Print the current directory again."
)


> Entering new AgentExecutor chain...
 I need to use the terminal to print the current directory and then go two levels up.
Action: Terminal
Action Input: pwd
Observation: /home/amos/projects/gpt-experiments/langchain-contrib/docs/tools

Thought: I need to use the terminal to go two levels up.
Action: Terminal
Action Input: cd ../../
Observation:
Thought: I need to use the terminal to print the current directory again.
Action: Terminal
Action Input: pwd
Observation: /home/amos/projects/gpt-experiments/langchain-contrib

Thought: I now know the final answer.
Final Answer: The current directory is /home/amos/projects/gpt-experiments/langchain-contrib.

> Finished chain.
[2]:
'The current directory is /home/amos/projects/gpt-experiments/langchain-contrib.'