how.wtf

Create and run Bash programs with LangChain

· Thomas Taylor

Using LangChain, we can create a prompt to output a bash, which is then executed via the BashProcess tool.

All of this is as easy as a few lines of Python code!

How to generate bash scripts using LangChain

First, let’s install the necessary dependencies:

1pip install langchain-core langchain-experimental langchain-openai

Now, let’s write a simplistic prompt to get OpenAI to output bash code.

For this example, we’ll target a script that outputs:

1Hello world!

Script:

 1from langchain_core.output_parsers import StrOutputParser
 2from langchain_experimental.llm_bash.bash import BashProcess
 3from langchain_openai import ChatOpenAI
 4from langchain_core.prompts import ChatPromptTemplate
 5
 6
 7def sanitize_output(text: str):
 8    _, after = text.split("```bash")
 9    return after.split("```")[0]
10
11
12template = """Write some bash code to solve the user's problem. 
13
14Return only bash code in Markdown format, e.g.:
15
16```bash
17....
18```"""
19prompt = ChatPromptTemplate.from_messages([("system", template), ("human", "{input}")])
20
21model = ChatOpenAI()
22
23chain = prompt | model | StrOutputParser() | sanitize_output | BashProcess().run
24
25print(chain.invoke({"input": "Print 'Hello world!' to the console"}))

Output:

1Hello world!

Using LangChain Expression Language (LCEL), we constructed a chain by using the pipe operator to combine:

  1. prompt
  2. model
  3. StrOutputParser
  4. sanitize_output
  5. BashProcess().run

This example was adapted from the “Code Writing” cookbook provided in the Langchain documentation.

The sanitize_output function extracts the bash code from the markdown output and pipes it to the BashProcess tool. To learn more about the bash process tool, visit the documentation.

#generative-ai   #python  

Reply to this post by email ↪