LangChainを用いてLLMの出力を整える

イントロダクション

現代の家庭ではスマートホームが当たり前になってきています。スマートデバイスや自動で動く機構、人工知能を接続することで、家をよりスマートに、便利な居住空間に変えることができます。この目的のため、LLMをHome Assistantに統合し、さらに賢いHome Assistantを作成したいと思います。この目標を達成するためには、まずLLMがスマートホームデバイスを管理できる制御信号を出力できるようにすることが重要です。

ai_assistant

このwikiでは、大規模言語モデルの出力を整える(フォーマットする)ためのLangChainの使い方と、エッジコンピューティングデバイスにデプロイする方法を学習します。大規模言語モデルの優れた理解能力を活用するローカルチャットボットを構築した後、LangChainツールを利用して、大規模モデルの出力を修正してみましょう。

LLMとは

大規模言語モデル(LLM)はGPTのような深層学習に基づく人工知能モデルの一種で、自然言語処理のタスクに優れています。テキストを理解し生成できる能力を持ち、テキスト生成や翻訳、QAシステムなど様々なアプリケーションで広く使用されています。

LLMの出力のフォーマットを必要とする理由

大規模言語モデル(LLM)の出力をフォーマットすることは、LLM出力をより理解できるようにし、特定のアプリケーションに合わせるために重要です。多くの場合、LLMによって生成されたテキストは、冗長なテキストや不要な詳細情報、または一貫性のない書式構成が含まれていることがあります。出力をフォーマットすることで、テキストの不要な部分の削除や、特定の基準を満たすことができ、アプリケーションの要件に沿わせることができます。このプロセスは、LLM出力を様々なシステムやアプリケーションに効率的に統合し、生成された内容に関連があり、かつそれが有用であることを保証するのに重要です。

LLMの出力をフォーマットする方法

今回はユーザーフレンドリーなツールであるLangChainを利用します。LangChainは、言語モデルを使用してエンドツーエンドのアプリケーションを構築する開発者をアシストするために設計されたフレームワークです。大規模言語モデルとチャットモデルでサポートされるアプリケーションの作成プロセスを簡素化する一連のツールやコンポーネント、インターフェースを提供します。

エッジデバイスにデプロイする方法

  • ステップ1 Jetpack 5.0以降のOSを搭載したJetsonデバイスを準備する必要があります。(ここではreComputer J4012を使用しています)

  • ステップ2 ターミナルを開き、依存関係のソフトウェアをインストールします。

pip3 install --no-cache-dir --verbose LangChain[llm] openai
pip3 install --no-cache-dir --verbose gradio==3.38.0
  • ステップ3 新しいPythonスクリプト”format_opt.py”を作成し、次のコードを挿入します。
format_opt.py (クリックして展開)



import copy

import gradio as gr
from LangChain.llms import LlamaCpp
from LangChain.output_parsers import StructuredOutputParser, ResponseSchema
from LangChain.prompts import PromptTemplate
from LangChain.llms import OpenAI
import os
os.environ["OPENAI_API_KEY"] = "your openai api key"


class ChatBot:
    def __init__(self, llama_model_path=None,history_length=3):
        self.chat_history = []
        self.history_threshold = history_length
        self.llm = None
        if llama_model_path is not None:
            self.llm = LlamaCpp(
                model_path=llama_model_path,
                temperature=0.75,
                max_tokens=2000,
                top_p=1
            )
        else:
            self.llm = OpenAI(model_name="text-davinci-003")

        response_schemas = [
            ResponseSchema(name="user_input", description="This is the user's input"),
            ResponseSchema(name="suggestion", type="string", description="your suggestion"),
            ResponseSchema(name="control", description="This is your response"),
            ResponseSchema(name="temperature", type="int", description="This is used to indicate the degrees "
                                                                       "centigrade temperature of the air conditioner.")
        ]
        self.output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
        self.format_instructions = self.output_parser.get_format_instructions()

        self.template = """
            Now you are a smart speaker, and you need to determine whether to turn on the air conditioner based on the
            user's input.
            In the suggestion section, please reply normal conversation.
            In the control section, if you need to turn on the air conditioner, please reply with <1>; if you need to 
            turn off the air conditioner, please reply with <0>.
            
            {format_instructions}
            
            Please do not generate any comments.
            
            % USER INPUT:
            {user_input}

            YOUR RESPONSE:
        """
        self.prompt = PromptTemplate(
            input_variables=["user_input"],
            partial_variables={"format_instructions": self.format_instructions},
            template=self.template
        )

    def format_chat_prompt(self, message):
        prompt = ""
        for turn in self.chat_history:
            user_message, bot_message = turn
            prompt = f"{prompt}\nUser: {user_message}\nAssistant: {bot_message}"
        prompt = f"{prompt}\nUser: {message}\nAssistant:"
        return prompt

    def respond(self, message):
        prompt = self.prompt.format(user_input=message)
        formatted_prompt = self.format_chat_prompt(prompt)
        bot_message = self.llm(formatted_prompt)
        # self.output_parser.parse(bot_message)

        if len(self.chat_history) >= self.history_threshold:
            del self.chat_history[0]
        self.chat_history.append((message, bot_message))
        return "", self.chat_history

    def run_webui(self):
        with gr.Blocks() as demo:
            gr.Markdown("# This is a demo for format output of LLM")
            chatbot = gr.Chatbot(height=500)
            msg = gr.Textbox(label="Prompt")
            btn = gr.Button("Submit")
            clear = gr.ClearButton(components=[msg, chatbot], value="Clear console")

            btn.click(self.respond, inputs=[msg], outputs=[msg, chatbot])
            msg.submit(self.respond, inputs=[msg], outputs=[msg, chatbot])

        gr.close_all()
        demo.launch()

if __name__ == '__main__':
    chatbot_ins = ChatBot("/home/nvidia/Mirror/llama-2-7b-chat.Q4_0.gguf")
    chatbot_ins.run_webui()


  • ステップ4 ターミナルでpython3 format_opt.pyを入力してスクリプトを実行します。その後、ブラウザでhttp://127.0.0.1:7861/を開き、WebUIにアクセスし効果をテストします。

format_llm_opt

次のステップ

  • NVIDIA Rivaを統合し、テキスト入力を音声対話に置き換える。
  • Home Assistantを接続して、LLMからの出力を用いてスマートホームデバイスを制御する。

テクニカルサポートと製品に関するフォーラム

ご購入いただいた製品をスムーズにお使いいただけるよう、Seeedでは様々なサポートを提供しています。ご希望に合わせてコンタクトの方法をお選びください。

出典 : Seeed Studio資料 Wiki - Format Output with LangChain

https://wiki.seeedstudio.com/How_to_Format_the_Output_of_LLM_Using_LangChain_on_Jetson/

*このガイドはSeeed Studioの許可を得て、スイッチサイエンスが翻訳しています。