アプリケーション テンプレートをカスタマイズする。

アプリケーションを開発するでは、アプリケーションの開発に事前構築済みのテンプレート(reasoning_engines.LangchainAgent)を使用しました。このセクションでは、独自のアプリケーション テンプレートをカスタマイズする手順について説明します。これは、事前構築済みテンプレートで提供される機能を超えるニーズがある場合に役立ちます。

Reasoning Engine のアプリケーション テンプレートは、Python クラスとして定義されます。たとえば、次の Python コードは、Vertex AI にデプロイ可能な LangChain アプリケーションの例です(CLASS_NAME 変数に MyAgent などの値を指定できます)。

from typing import Callable, Sequence

class CLASS_NAME:
    def __init__(
            self,
            model: str,
            tools: Sequence[Callable],
            project: str,
            location: str,
        ):
        self.model_name = model
        self.tools = tools
        self.project = project
        self.location = location

    def set_up(self):
        """All unpickle-able logic should go here.

        The .set_up() method should not be called for an object that is being
        prepared for deployment.
        """
        import vertexai
        from langchain_google_vertexai import ChatVertexAI
        from langchain.agents import AgentExecutor
        from langchain.agents.format_scratchpad.tools import format_to_tool_messages
        from langchain.agents.output_parsers.tools import ToolsAgentOutputParser
        from langchain.tools.base import StructuredTool
        from langchain_core import prompts

        vertexai.init(project=self.project, location=self.location)

        prompt = {
            "input": lambda x: x["input"],
            "agent_scratchpad": (
                lambda x: format_to_tool_messages(x["intermediate_steps"])
            ),
        } | prompts.ChatPromptTemplate.from_messages([
            ("user", "{input}"),
            prompts.MessagesPlaceholder(variable_name="agent_scratchpad"),
        ])

        llm = ChatVertexAI(model_name=self.model_name)
        if self.tools:
            llm = llm.bind_tools(tools=self.tools)

        self.agent_executor = AgentExecutor(
            agent=prompt | llm | ToolsAgentOutputParser(),
            tools=[StructuredTool.from_function(tool) for tool in self.tools],
        )

    def query(self, input: str):
        """Query the application.

        Args:
            input: The user prompt.

        Returns:
            The output of querying the application with the given input.
        """
        return self.agent_executor.invoke(input={"input": input})

Python クラスを作成する場合、Reasoning Engine では次の 3 つのメソッドが重要になります。

  1. __init__():
    • このメソッドは、アプリケーション構成パラメータにのみ使用します。たとえば、このメソッドを使用して、モデル パラメータと安全性属性をユーザーの入力引数として収集できます。このメソッドを使用して、プロジェクト ID、リージョン、アプリケーション認証情報、API キーなどのパラメータを収集することもできます。
    • コンストラクタは、推論エンジンにデプロイできるように「pickle 対応」である必要があるオブジェクトを返します。そのため、サービス クライアントを初期化し、データベースへの接続を確立する際は、__init__ メソッドではなく .set_up メソッドを使用する必要があります。
    • このメソッドは省略可能です。指定しない場合、Vertex AI はクラスのデフォルトの Python コンストラクタを使用します。
  2. set_up():
    • このメソッドを使用して、アプリの初期化ロジックを定義する必要があります。たとえば、このメソッドを使用して、データベースまたは依存サービスへの接続を確立したり、依存パッケージをインポートしたり、クエリの処理に使用するデータの事前計算を行うことができます。
    • このメソッドは省略可能です。指定しない場合、Vertex AI は、ユーザークエリを処理する前にアプリケーションで .set_up メソッドを呼び出す必要がないと見なします。
  3. query():
    • このメソッドを使用して、ユーザークエリを処理するランタイム ロジックを定義する必要があります。たとえば、このメソッドを使用して、生成 AI モデルでコンテンツを生成したり、外部 API からリアルタイム データを取得します。
    • このメソッドは必須です。指定しない場合、アプリケーションのリモート インスタンスを作成しようとすると、ReasoningEngine サービスはエラーを返します。
    • このメソッドには、処理の内容を定義して属性を文書化し、入力に型アノテーションを提供する明確な docstring を指定する必要があります。query メソッドで変数引数を使用しないでください。

アプリケーションをローカルでテストする

次のコードを使用して、ローカルメモリでアプリケーションをインスタンス化します。

agent = CLASS_NAME(
    model=model,  # Required.
    tools=[get_exchange_rate],  # Optional.
    project=PROJECT_ID,
    location=LOCATION,
)
agent.set_up()

ローカル インスタンスにテストクエリを送信して、アプリケーションをテストできます。

response = agent.query(
    input="What is the exchange rate from US dollars to Swedish currency?"
)

レスポンスは、次のようなディクショナリ形式になります。

{"input": "What is the exchange rate from US dollars to Swedish currency?",
 # ...
 "output": "For 1 US dollar you will get 10.7345 Swedish Krona."}

次のステップ