0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vertex AI Agent EngineにデプロイしたAIエージェントをFlowから呼び出す

Posted at

初めに

以前書いたADKで開発したAIエージェントをVertex AI Agent Engineにデプロイするの続きです。今回は、Vertex AI Agent EngineにデプロイしたAIエージェントをPHPのアプリケーションから呼び出してみます。

前回のおさらい

前回の記事では、Vertex AI Agent EngineにデプロイしたAIエージェントをcurlコマンドを使用して呼び出せることを確認しました。

リクエスト
$ curl -H "Authorization: Bearer $(gcloud auth print-access-token)" -H "Content-Type: application/json" https://us-central1-aiplatform.googleapis.com/v1/projects/hoge/locations/us-central1/reasoningEngines/0000000000000000000:streamQuery?alt=sse -d '{
  "class_method": "stream_query",
  "input": {
    "user_id": "1234",
    "session_id": "427859831664148480011",
    "message": "PHPのFlowでIPアドレス制限はできますか?できるとしたら、どのように実装しますか?"
  }
}' | jq

前回との違い

RESTで呼び出す際は、リクエストヘッダーのAuthorizationにアクセストークンを付与する必要があります。curlのようなCLIでの呼び出しの際はgcloudコマンドでアクセストークンを張り付ければいいですが、PHPアプリケーションの場合そうはいかないため、別の方法を考える必要があります。

Google Authライブラリの利用

これを解決してくれるのが、google-auth-library-phpです。
phpのアプリケーションでGCPへの認証をしたい場合に利用します。

以下のようなコードを書くことで、アクセストークンを取得可能のようです。

アクセストークン取得
$scopes = ['https://www.googleapis.com/auth/cloud-platform'];
$credentials = ApplicationDefaultCredentials::getCredentials($scopes);
$token = $credentials->fetchAuthToken();
$accessToken = $token['access_token']

その他、以下の手順を踏む必要があります。

  • IAMで必要な権限の割り振ったサービスアカウントを作成する
  • サービスアカウントのjsonキーを取得し、環境変数GOOGLE_APPLICATION_CREDENTIALSとしてキーのパスを登録する

試してみる

それでは実際に試してみましょう。
まずはIAMや環境変数の準備からです。

準備

以下の手順で進めていきます。

  • IAMでサービスアカウントを作成
  • 環境変数GOOGLE_APPLICATION_CREDENTIALSの設定
  • composer reqire google/authの実行

IAMでサービスアカウントを作成

IAMのサービスアカウント画面で、アプリケーションで使用するサービスアカウントを作成します。権限は「Vertex AI ユーザ」のみでOKです。

その後、作成したサービスアカウントのjsonキーを作成してダウンロードします。

環境変数GOOGLE_APPLICATION_CREDENTIALSの設定

環境変数に以下を設定します。

  • キー:GOOGLE_APPLICATION_CREDENTIALS
  • 値:サービスアカウントのjsonキーまでのパス

composer reqire google/authの実行

composerを利用してgoogle/authをinstallします。

$ composer.phar require google/auth

実装

続いて実装に入りましょう。
プロジェクト構成は以下です。

Project
    └ Packages/
         ├ Application/
         |    └ Neos.Welcome/
         |         ├ Classes/
         |         |    └ Controller/
         |         |         ├ GcpAuthController.php
         |         └ Configration/
         |              └ Settings.yaml
         ├ Framework/
         └ Libraries/

Setting.yaml

Setting.yamlにGCPのプロジェクト情報と呼び出すVertexAIのreasoningEngineIdを定義しておきます。

Settings.yaml
Neos:
  Welcome:
    gcp:
      vertex:
        projectId: 'hogehoge'
        location: 'us-central1'
        reasoningEngineId: '00000000'

GcpAuthController.php

ここでは以下の2つを実装します。

  • アクセストークンの生成
  • API呼び出し
<?php
namespace Neos\Welcome\Controller;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Mvc\Controller\ActionController;
use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\CredentialsLoader;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class GcpAuthController extends ActionController
{
    /**
     * @Flow\Inject
     * @var \Neos\Flow\Mvc\View\JsonView
     */
    protected $view;

    /**
     * @Flow\InjectConfiguration(package="Neos.Welcome", path="gcp.vertex")
     * @var array
     */
    protected $gcpConfig;

    /**
     * Call Google Cloud AI Platform Reasoning Engine API with fixed parameters for testing
     */
    public function callReasoningEngineAction(string $userId, string $message) {
        try {
            // GCPプロジェクトの設定値の取得
            $projectId = $this->gcpConfig['projectId'];
            $location = $this->gcpConfig['location'];
            $reasoningEngineId = $this->gcpConfig['reasoningEngineId'];
            $userId = $userId;

            // アクセストークンの取得
            $scopes = ['https://www.googleapis.com/auth/cloud-platform'];
            $credentials = ApplicationDefaultCredentials::getCredentials($scopes);
            $token = $credentials->fetchAuthToken();

            // Vertex AI Agentへのリクエスト生成
            $client = new Client();
            $url = sprintf(
                'https://%s-aiplatform.googleapis.com/v1/projects/%s/locations/%s/reasoningEngines/%s:streamQuery?alt=sse',
                $location,
                $projectId,
                $location,
                $reasoningEngineId
            );

            $requestData = [
                'class_method' => 'stream_query',
                'input' => [
                    'user_id' => $userId,
                    'message' => $message
                ]
            ];

            // Vertex AI Agentの呼び出し
            $response = $client->post($url, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $token['access_token'],
                    'Content-Type' => 'application/json'
                ],
                'json' => $requestData,
                'timeout' => 60
            ]);

            $statusCode = $response->getStatusCode();
            $responseContent = $response->getBody()->getContents();
            $decoded = json_decode($responseContent, true);
            
            $extractedText = '';
            if (isset($decoded['content']['parts'][0]['text'])) {
                $extractedText = $decoded['content']['parts'][0]['text'];
            }

            $this->view->assign('value', [
                'success' => true,
                'status_code' => $statusCode,
                'extracted_text' => $extractedText,
            ]);

        } catch (RequestException $e) {
            // 割愛
        } catch (\Exception $e) {
            // 割愛
        }
    }
}

動作確認

実装できたので、Flowを起動します。

$ ./flow server:run
Server running. Please go to http://127.0.0.1:8081 to browse the application.
[Wed Jul 23 20:14:45 2025] PHP 8.2.17 Development Server (http://127.0.0.1:8081) started

curlでAPI呼び出したところ、ちゃんとレスポンスが返ってくることが確認できました!

> curl.exe -X POST `
>>    -H "Content-Type:application/json" `
>>    -d `
>> '{
>>     "userId": "123",
>>     "message": "PHPのFlowでIPアドレス制限はできますか?"
>> }' `
>>  'http://localhost:8081/Neos.Welcome/GcpAuth/callReasoningEngine' | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   732  100   636  100    96     42      6  0:00:16  0:00:14  0:00:02   177
{
  "success": true,
  "status_code": 200,
  "extracted_text": "はい、PHPのFlowフレームワークではIPアドレス制限が可能です。Flowのファイアウォール機能を使用し、`Settings.yaml`ファイルでIPパターンとCIDRパターンを設定することで、特定のIPアドレスからのアクセスを許可または拒否できます。"
}

終わりに

今回はVertex AI Agent EngineにデプロイしたAIエージェントをPHPアプリケーションから呼び出してみました。google-auth-library-phpを使用すれば簡単にトークンを作成できるので、AIエージェント開発が捗りそうです。

ここまでご覧いただきありがとうございました!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?