メむンコンテンツぞスキップ
芋出し画像

LangChain Agentsを䜿っおテストコヌドから「テストの通るコヌド」を自動生成するプログラムを曞いおみた

    先日以䞋のような蚘事を曞いおみたものの、いちいち結果をChatGPTに手でコピペしながら怜蚌するのはダサいなず思っおいたした。

    そういうわけでRSpecが通るたで愚盎に怜蚌生成を繰り返すようなコヌドを曞いおみたものの、修正履歎たでChatGPTのコンテキストに持たせようずするず、すぐに最倧トヌクン数を超えおしたい倱敗しおしたいたす。

    最倧トヌクン数を超えないように頭の良いコンテキストを持たせるような実装も可胜だずは思いたすが、結構耇雑な実装になっおしたいそうです。

    そんな䞭で出䌚ったのがこのツむヌトでした。

    I saw a somewhat astonishing thing today. GPT was asked a question that it needed to write code to answer, and given access to a Python REPL. It wrote buggy code, then based on the error message it fixed its own code until it worked (and gave the correct answer). It debugged. pic.twitter.com/O6cdxH8gvC

    — John Wiseman (@lemonodor) February 22, 2023

    確かにLangChain Agentsを䜿えば、LLMで生成したコヌドを実行しお確認するずいった䞀連の行動を自動化できそうです。

    時間が無い人向けの動画

    こんな感じに動䜜するものを぀くりたした。

    LangChain Agentsずは

    LangChain Chains

    LangChainではChainsずいう指定した順序でLLMを連続実行できる仕組みがありたす。LangChainの名の通り象城的な機胜です。AgentsはChainsの発展系なので、たずはChainsの動きから。

    以䞋はドキュメントのサンプルにある、「colorful socks」を補造するような䌚瀟の名前ずしお良さそうなものを掚論させた䞊で、そんな名前の䌚瀟がキャッチフレヌズにしそうな蚀葉を掚論させるコヌドです。

    from langchain.chat_models import ChatOpenAI
    from langchain.chains import SimpleSequentialChain
    from langchain.prompts.chat import (
        ChatPromptTemplate,
        HumanMessagePromptTemplate,
    )
    
    # 䌚瀟名を掚論
    human_message_prompt = HumanMessagePromptTemplate(
            prompt=PromptTemplate(
                template="What is a good name for a company that makes {product}?",
                input_variables=["product"],
            )
        )
    chat_prompt_template = ChatPromptTemplate.from_messages([human_message_prompt])
    chat = ChatOpenAI(temperature=0.9)
    chain = LLMChain(llm=chat, prompt=chat_prompt_template)
    
    # キャッチフレヌズを掚論
    second_prompt = PromptTemplate(
        input_variables=["company_name"],
        template="Write a catchphrase for the following company: {company_name}",
    )
    chain_two = LLMChain(llm=llm, prompt=second_prompt)
    
    # 掚論をチェヌンで組み合わせる
    overall_chain = SimpleSequentialChain(chains=[chain, chain_two], verbose=True)
    
    # 実行
    catchphrase = overall_chain.run("colorful socks")
    print(catchphrase)

    結果は以䞋のようになりたす。
    連続しお掚論が実行されおいるこずが分かりたす。

    > Entering new SimpleSequentialChain chain...
    
    Cheerful Toes.
    
    "Spread smiles from your toes!"
    
    > Finished SimpleSequentialChain chain.
    
    "Spread smiles from your toes!"

    LangChain Agents

    察しおAgentsは、利甚しお良いツヌルを゚ヌゞェントに䞎えおおくず、指定されたプロンプトを解決するためにLLMが自埋的に道具を遞定し、問題解決をしおくれる仕組みです。

    䟋えば以䞋はGoogle怜玢を行うAPIず蚈算を行うツヌルを組み合わせた䟋です。

    from langchain.agents import load_tools
    from langchain.agents import initialize_agent
    from langchain.llms import OpenAIChat
    
    llm = OpenAIChat(temperature=0)
    
    tools = load_tools(["serpapi", "llm-math"], llm=llm)
    
    agent = initialize_agent(
        tools, 
        llm, 
        agent="zero-shot-react-description", 
        verbose=True
    )
    
    agent.run("日本で䞀番長い川の長さを調べ、その長さを䞉乗しおください")

    実行結果は以䞋の通りです。
    信濃川を怜玢した結果を螏たえお蚈算機で蚈算しおいるこずが分かりたす。

    > Entering new AgentExecutor chain...
    I don't speak Japanese, so I should use a search engine to translate the question and find the answer.
    Action: Search
    Action Input: "What is the length of the longest river in Japan and what is its cubed length?"
    
    Observation: The 11,900 square kilometres (4,600 sq mi) basin of the Shinano-Chikuma River system is the third largest in Japan and at 367 kilometres (228 mi), is the longest river in the country.
    Thought:Now that I have the answer, I need to use a calculator to find the cubed length.
    Action: Calculator
    Action Input: 367^3
    Observation: Answer: 49430863
    
    Thought:I now know the final answer
    Final Answer: 49430863
    
    > Finished chain.
    '49430863'

    党く同じプロンプトをChatGPTに䞎えおみるず、信濃川の長さは孊習デヌタから導き出せおいるものの、蚈算結果が誀っおいたす。

    日本で䞀番長い川は信濃川で、長さは367キロメヌトルです。 したがっお、信濃川の長さを䞉乗するず、玄48,541,463キロメヌトルになりたす。
    
    蚈算匏: (367 km)^3 = 367 km × 367 km × 367 km = 48,541,463 km

    生成したコヌドを自動怜蚌する仕組みをAgentsで䜜成する

    前回は点字生成プログラムを題材にしおいたしたが、今回はもう少し仕様をシンプルにしお、逆ポヌランド蚘法で䞎えられた蚈算匏を蚈算する「逆ポヌランド蚈算機」を題材にしおみようず思いたす。

    逆ポヌランド蚘法ずは以䞋のような衚蚘法のこずです↓

    • 「a+b」なら「ab+」ず衚蚘する

    • 「a*(b+c)」なら「abc+*」ず衚蚘する

    • 「(a+b)/(c-d)」なら「ab+cd-/」ず衚蚘する

    この衚蚘法のメリットは、カッコによる挔算順の優先床の考慮なしに巊から順に数字か蚘号をスタックに積んで行けば、スタックをポップし続けるだけで蚈算できるこずにありたす。

    テストコヌドを生成する

    そんなわけでたずはテストコヌドを生成したす。

    今回はテストコヌドをChatGPTで生成した䞊で、このテストコヌドをパスするたでLangChainにコヌドを生成し続けおもらうこずにしたす。

    あなたは優秀なRubyプログラマヌです。
    逆ポヌランド蚘法で衚珟された文字列を受け取り、蚈算を実行するプログラムのテストコヌドをRSpecで䜜成しなさい。
    出力はRubyコヌドのみずし、それ以倖の䜙蚈な文字は出力しないでください。
    テストには正垞系ず異垞系を含めるようにしおください。

    以䞋が生成されたRSpecのコヌドです。

    require_relative 'rpn_calculator'
    
    describe RPNCalculator do
      describe "#evaluate" do
        let(:calculator) { RPNCalculator.new }
    
        context "with a valid expression" do
          it "evaluates addition correctly" do
            expect(calculator.evaluate("5 3 +")).to eq(8)
          end
    
          it "evaluates subtraction correctly" do
            expect(calculator.evaluate("5 3 -")).to eq(2)
          end
    
          it "evaluates multiplication correctly" do
            expect(calculator.evaluate("5 3 *")).to eq(15)
          end
    
          it "evaluates division correctly" do
            expect(calculator.evaluate("10 2 /")).to eq(5)
          end
    
          it "evaluates complex expressions correctly" do
            expect(calculator.evaluate("5 3 + 4 * 7 -")).to eq(25)
          end
        end
    
        context "with an invalid expression" do
          it "raises an error for division by zero" do
            expect { calculator.evaluate("5 0 /") }.to raise_error(ZeroDivisionError)
          end
    
          it "raises an error if the input does not follow the rules" do
            expect { calculator.evaluate("5 + 3") }.to raise_error(ArgumentError)
          end
        end
      end
    end

    RSpecを実行しお生成コヌドを怜蚌するカスタムツヌルを䜜成する

    コヌド生成結果に察しおRSpecを実行する仕組みはLangChainに甚意されおいないので、独自にツヌルを定矩したす。

    from langchain.agents.tools import Tool
    import traceback
    import subprocess
    
    class_name = "rpn_calculator"
    
    class RSpecExecutor:
      def __init__(self):
        pass
    
      def run(self, ruby_code):
        try:
          with open(f"{class_name}.rb", 'w') as f:
            f.write(trim(ruby_code))
          result = subprocess.check_output(['rspec', f"{class_name}_spec.rb"])
          output = result.decode('utf-8')
        except subprocess.CalledProcessError as e:
          output = e.output.decode('utf-8')
        except Exception:
          output = traceback.format_exc()
    
        return output
    
    rspec_exec = Tool(
      "RSpec Executor",
      RSpecExecutor().run,
      "A tool to test generated ruby code. Input should be a valid generated ruby code."
    )

    本筋ずはズレたすが、どうプロンプトを工倫しおも空の改行や「```」で囲たれた結果を返すこずが倚かったため、LLMが返した結果をトリムする関数を以䞋のように定矩しおいたす。

    def trim(string):
      lines = string.split('\n')
      while lines and (lines[0].strip() == '' or lines[0].startswith('`')):
        lines = lines[1:]
      while lines and (lines[-1].strip() == '' or lines[-1].startswith('`')):
        lines = lines[:-1]
      return '\n'.join(lines)

    ゚ヌゞェントはToolの第䞉匕数に指定する解説を理解しお道具を遞定するため、どういうずきに䜿うべきツヌルなのか゚ヌゞェントが理解できるように明確に曞いおおく必芁がありたす。

    LangChainで実行するコヌドを䜜成する

    あずはAgentsを利甚しお実行するコヌドを曞くだけです。
    コヌドは䞋蚘の通りで、ずおもシンプルです。

    from langchain.llms import OpenAIChat
    from langchain.agents import initialize_agent
    
    llm = OpenAIChat(temperature=0.0)
    tools = [rspec_exec]
    agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
    
    with open(f"{class_name}_spec.rb", 'r') as f:
      rspec_code = f.read()
    
    prompt = f"""
    You are an excellent professional Ruby programmer.
    Create a Ruby code that meets the following test code specifications
    code that meets the following test code specifications.
    
    - Do not modify the test code.
    - No test code should be output.
    - When creating ruby code, please make sure to output only ruby code.
    - Make sure that there are no syntax errors in the generated ruby code.
    - To check whether a given input is a processable input, create a separate validate function and check it.
    - Validate function must be written in the class.
    
    # test code:
    {rspec_code}
    """
    
    agent.run(prompt)

    実のずころ、シンプルなプロンプトだけでは実装が明埌日の方向ぞ行っおしたうこずが倚かったため、「クラス内にバリデヌションのための関数を䜜れ」などず、実装の现かいずころたで口出しするプロンプトを曞いおしたっおいたす。

    たた、゚ヌゞェントは日本語を理解できないので日本語を䞎えるず英語に翻蚳した䞊で凊理を継続したす、プロンプトは英語で指定するようにしおいたす。

    実行結果

    コヌドを実行しおみるず、たずは1回目の生成結果をもずにRSpec Executorを䜿っおテストを実行しようずしたす。

    > Entering new AgentExecutor chain...
    I need to create a Ruby code that meets the specifications of the test code.
    Action: RSpec Executor
    Action Input: 
    ```
    class RPNCalculator
      def validate(input)
        input_array = input.split(" ")
        operators = ["+", "-", "*", "/"]
        input_array.each do |char|
          if !operators.include?(char) && !char.match?(/\d+/)
            return false
          end
        end
        return true
      end
    
      def evaluate(input)
        raise ArgumentError unless validate(input)
    
        stack = []
        input.split.each do |char|
          case char
          when "+"
            stack << stack.pop(2).reduce(:+)
          when "-"
            stack << stack.pop(2).reduce(:-)
          when "*"
            stack << stack.pop(2).reduce(:*)
          when "/"
            stack << stack.pop(2).reduce(:/)
          else
            stack << char.to_i
          end
        end
        stack.first
      end
    end
    ```
    
    Observation: ......F
    
    Failures:
    
      1) RPNCalculator#evaluate with an invalid expression raises an error if the input does not follow the rules
         Failure/Error: expect { calculator.evaluate("5 + 3") }.to raise_error(ArgumentError)
           expected ArgumentError but nothing was raised
         # ./rpn_calculator_spec.rb:35:in `block (4 levels) in <top (required)>'
    
    Finished in 0.06175 seconds (files took 0.48972 seconds to load)
    7 examples, 1 failure
    
    Failed examples:
    
    rspec ./rpn_calculator_spec.rb:34 # RPNCalculator#evaluate with an invalid expression raises an error if the input does not follow the rules

    ですが「5 + 3」を入力したずきの実行結果がテストコヌドず食い違っおしたっおおり、テストが倱敗したす。

    するずテスト結果を螏たえお以䞋のように

    Thought:The code is failing the test for an invalid expression. I need to check the validate function to see if it's correctly identifying invalid expressions.

    validate関数を改善する必芁があるず考察し、改善案を提瀺したす。

    Action: RSpec Executor
    Action Input: 
    ```
    class RPNCalculator
      def validate(input)
        input_array = input.split(" ")
        operators = ["+", "-", "*", "/"]
        input_array.each do |char|
          if !operators.include?(char) && !char.match?(/\d+/)
            return false
          end
        end
        return true
      end
    
      def evaluate(input)
        raise ArgumentError unless validate(input)
    
        stack = []
        input.split.each do |char|
          case char
          when "+"
            stack << stack.pop(2).reduce(:+)
          when "-"
            stack << stack.pop(2).reduce(:-)
          when "*"
            stack << stack.pop(2).reduce(:*)
          when "/"
            stack << stack.pop(2).reduce(:/)
          else
            stack << char.to_i
          end
        end
        stack.first
      end
    end
    
    describe RPNCalculator do
      describe "#validate" do
        let(:calculator) { RPNCalculator.new }
    
        context "with a valid expression" do
          it "returns true" do
            expect(calculator.validate("5 3 +")).to eq(true)
          end
        end
    
        context "with an invalid expression" do
          it "returns false for invalid characters" do
            expect(calculator.validate("5 + 3")).to eq(false)
          end
    
          it "returns false for too many operators" do
            expect(calculator.validate("5 3 + +")).to eq(false)
          end
    
          it "returns false for too many operands" do
            expect(calculator.validate("5 3 2 +")).to eq(false)
          end
        end
      end
    end
    ```

    生成したコヌドを曎に確認するよう、独自にテストコヌドも远加しおいるようです。

    Observation: .FFF......F
    
    Failures:
    
      1) RPNCalculator#validate with an invalid expression returns false for invalid characters
         Failure/Error: DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure }
    
           expected: false
                got: true
    
           (compared using ==)
    
           Diff:
           @@ -1 +1 @@
           -false
           +true
         # ./rpn_calculator.rb:47:in `block (4 levels) in <top (required)>'
    
      2) RPNCalculator#validate with an invalid expression returns false for too many operators
         Failure/Error: DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure }
    
           expected: false
                got: true
    
           (compared using ==)
    
           Diff:
           @@ -1 +1 @@
           -false
           +true
         # ./rpn_calculator.rb:51:in `block (4 levels) in <top (required)>'
    
      3) RPNCalculator#validate with an invalid expression returns false for too many operands
         Failure/Error: DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure }
    
           expected: false
                got: true
    
           (compared using ==)
    
           Diff:
           @@ -1 +1 @@
           -false
           +true
         # ./rpn_calculator.rb:55:in `block (4 levels) in <top (required)>'
    
      4) RPNCalculator#evaluate with an invalid expression raises an error if the input does not follow the rules
         Failure/Error: expect { calculator.evaluate("5 + 3") }.to raise_error(ArgumentError)
           expected ArgumentError but nothing was raised
         # ./rpn_calculator_spec.rb:35:in `block (4 levels) in <top (required)>'
    
    Finished in 0.06958 seconds (files took 0.34411 seconds to load)
    11 examples, 4 failures
    
    Failed examples:
    
    rspec './rpn_calculator.rb[1:1:2:1]' # RPNCalculator#validate with an invalid expression returns false for invalid characters
    rspec './rpn_calculator.rb[1:1:2:2]' # RPNCalculator#validate with an invalid expression returns false for too many operators
    rspec './rpn_calculator.rb[1:1:2:3]' # RPNCalculator#validate with an invalid expression returns false for too many operands
    rspec ./rpn_calculator_spec.rb:34 # RPNCalculator#evaluate with an invalid expression raises an error if the input does not follow the rules

    今床は異垞系が軒䞊み倱敗しおしたいたす。
    この結果を螏たえおLLMが曎にコヌドを倉曎したずころ・・・

    Thought:The validate function is not correctly identifying invalid expressions. I need to update the function to correctly identify invalid expressions.
    Action: RSpec Executor
    Action Input: 
    ```
    class RPNCalculator
      def validate(input)
        input_array = input.split(" ")
        operators = ["+", "-", "*", "/"]
        operand_count = 0
        operator_count = 0
        input_array.each do |char|
          if !operators.include?(char) && !char.match?(/\d+/)
            return false
          elsif operators.include?(char)
            operator_count += 1
            return false if operator_count > operand_count - 1
          else
            operand_count += 1
          end
        end
        return false if operand_count - operator_count != 1
        return true
      end
    
      def evaluate(input)
        raise ArgumentError unless validate(input)
    
        stack = []
        input.split.each do |char|
          case char
          when "+"
            stack << stack.pop(2).reduce(:+)
          when "-"
            stack << stack.pop(2).reduce(:-)
          when "*"
            stack << stack.pop(2).reduce(:*)
          when "/"
            stack << stack.pop(2).reduce(:/)
          else
            stack << char.to_i
          end
        end
        stack.first
      end
    end
    
    describe RPNCalculator do
      describe "#validate" do
        let(:calculator) { RPNCalculator.new }
    
        context "with a valid expression" do
          it "returns true" do
            expect(calculator.validate("5 3 +")).to eq(true)
          end
        end
    
        context "with an invalid expression" do
          it "returns false for invalid characters" do
            expect(calculator.validate("5 + 3")).to eq(false)
          end
    
          it "returns false for too many operators" do
            expect(calculator.validate("5 3 + +")).to eq(false)
          end
    
          it "returns false for too many operands" do
            expect(calculator.validate("5 3 2 +")).to eq(false)
          end
    
          it "returns false for too few operands" do
            expect(calculator.validate("5 +")).to eq(false)
          end
        end
      end
    end
    ```

    無事テストが通りたした🎉

    Observation: ............
    
    Finished in 0.01266 seconds (files took 0.27404 seconds to load)
    12 examples, 0 failures
    
    
    Thought:The code is passing all tests now. I can submit the final code as the solution to the problem.
    Final Answer: 
    ```
    class RPNCalculator
      def validate(input)
        input_array = input.split(" ")
        operators = ["+", "-", "*", "/"]
        operand_count = 0
        operator_count = 0
        input_array.each do |char|
          if !operators.include?(char) && !char.match?(/\d+/)
            return false
          elsif operators.include?(char)
            operator_count += 1
            return false if operator_count > operand_count - 1
          else
            operand_count += 1
          end
        end
        return false if operand_count - operator_count != 1
        return true
      end
    
      def evaluate(input)
        raise ArgumentError unless validate(input)
    
        stack = []
        input.split.each do |char|
          case char
          when "+"
            stack << stack.pop(2).reduce(:+)
          when "-"
            stack << stack.pop(2).reduce(:-)
          when "*"
            stack << stack.pop(2).reduce(:*)
          when "/"
            stack << stack.pop(2).reduce(:/)
          else
            stack << char.to_i
          end
        end
        stack.first
      end
    end
    ```
    
    > Finished chain.

    最終的には独自に远加したテストコヌドを陀いたバヌゞョンを提出しおくれたした。独自にテストコヌドを远加しお動䜜怜蚌する動きをするずは、なかなか頭が良い・・・。

    考察

    • テストコヌドは通ったものの、生成されたコヌド自䜓は綺麗なものずは蚀えないし脆匱である。

    • 倧きめのテストコヌドを䞎えるず最倧トヌクン数をすぐオヌバヌしおしたうので実甚性は良くない。

    • 運が悪いず延々ずテストの通らないコヌドを生成し続けおしたう最倧トヌクン数制限オヌバヌで匷制終了する。

    生成されたコヌドが汚い件に぀いおは、リファクタリング原則をコンテキストずしお䞎えた䞊で、テストが通るように改善し続けるよう指瀺するこずで自動化できるかも知れたせん。

    ずはいえ前回は結局テストを通すようなコヌドを生成できなかったのに察しお、今回はテストが通るずころたで自動化できたので、少しは進歩があったかなヌず思いたす。

    珟堎からは以䞊です。

     
     
    ふわっずしたアむデアをITで圢にするお仕事をしおいたす。 #2021幎4月に東京から山梚に移䜏 #四児の父 ■Zenn https://zenn.dev/mah ■お仕事のご盞談はこちらから→ https://www.generative-agents.co.jp/

    あなたぞのおすすめ