Skip to main content

Bash链 (Bash chain)

This notebook展示了使用LLMs和bash进程执行简单的文件系统命令。

from langchain.chains import LLMBashChain
from langchain.llms import OpenAI

llm = OpenAI(temperature=0)

text = "请编写一个打印'Hello World'到控制台的bash脚本。"

bash_chain = LLMBashChain.from_llm(llm, verbose=True)

bash_chain.run(text)
    

> 进入新的LLMBashChain链...
请编写一个打印'Hello World'到控制台的bash脚本。

```bash
echo "Hello World"
```
代码:['echo "Hello World"']
答案:Hello World

> 完成链。






'Hello World\n'

自定义提示

您还可以自定义使用的提示。这是一个示例,提示避免使用'echo'实用程序

from langchain.prompts.prompt import PromptTemplate
from langchain.chains.llm_bash.prompt import BashOutputParser

_PROMPT_TEMPLATE = """如果有人要求您执行任务,您的工作是提供一系列的bash命令来执行任务。您的答案中不需要放入“#!/bin/bash”。请确保逐步推理,使用以下格式:
问题:“将名为'target'的目录中的文件复制到与target相同级别的名为'myNewDirectory'的新目录中”
我需要执行以下操作:
- 列出目录中的所有文件
- 创建一个新目录
- 将第一个目录中的文件复制到第二个目录中
```bash
ls
mkdir myNewDirectory
cp -r target/* myNewDirectory

编写脚本时,请勿使用'echo'。

这是格式。开始吧!问题:{question}"""

PROMPT = PromptTemplate(
input_variables=["question"],
template=_PROMPT_TEMPLATE,
output_parser=BashOutputParser(),
)

bash_chain = LLMBashChain.from_llm(llm, prompt=PROMPT, verbose=True)

text = "请编写一个打印'Hello World'到控制台的bash脚本。"

bash_chain.run(text)
    

> 进入新的LLMBashChain链...
请编写一个打印'Hello World'到控制台的bash脚本。

```bash
printf "Hello World\n"
```
代码:['printf "Hello World\\n"']
答案:Hello World

> 完成链。






'Hello World\n'

持久终端

默认情况下,每次调用链时,链将在单独的子进程中运行。可以通过使用持久bash进程进行实例化来更改此行为。

from langchain.utilities.bash import BashProcess


persistent_process = BashProcess(persistent=True)
bash_chain = LLMBashChain.from_llm(llm, bash_process=persistent_process, verbose=True)

text = "列出当前目录,然后向上移动一级。"

bash_chain.run(text)
    

> 进入新的LLMBashChain链...
列出当前目录,然后向上移动一级。

```bash
ls
cd ..
```
代码:['ls', 'cd ..']
答案:api.html llm_summarization_checker.html
constitutional_chain.html moderation.html
llm_bash.html openai_openapi.yaml
llm_checker.html openapi.html
llm_math.html pal.html
llm_requests.html sqlite.html
> 完成链。






'api.html\t\t\tllm_summarization_checker.html\r\nconstitutional_chain.html\tmoderation.html\r\nllm_bash.html\t\t\topenai_openapi.yaml\r\nllm_checker.html\t\topenapi.html\r\nllm_math.html\t\t\tpal.html\r\nllm_requests.html\t\tsqlite.html'
# 再次运行相同的命令,查看调用之间的状态是否保持不变
bash_chain.run(text)
    

> 进入新的LLMBashChain链...
列出当前目录,然后向上移动一级。

```bash
ls
cd ..
```
代码:['ls', 'cd ..']
答案:examples getting_started.html index_examples
generic how_to_guides.rst
> 完成链。






'examples\t\tgetting_started.html\tindex_examples\r\ngeneric\t\t\thow_to_guides.rst'