メインコンテンツまでスキップ

カスタムフロントエンドで AI エージェントを作成する

Squid を使うと、Squid AI を利用してユニークなユーザー体験を作成できます。Squid に関する質問に答える AI エージェントを作っていきましょう!

作成するもの

  • React フロントエンドアプリケーション上で動作し、独自のナレッジベースを持つカスタム AI エージェント

環境設定

  1. In the Squid Console, switch to the dev environment.

switch environment

  1. Download the ai-tutorial-squid-facts code sample using the following command. Replace the placeholders with the values from your Squid application as shown in the console.

  2. npx @squidcloud/cli init-sample ai-tutorial-squid-facts --template ai-tutorial-squid-facts --appId YOUR_SQUID_APP_ID --apiKey YOUR_SQUID_API_KEY --environmentId dev --squidDeveloperId YOUR_SQUID_DEVELOPER_ID --region YOUR_REGION

TIP

You can find your environment variables under: 'Application' -> 'Show env vars' as seen below:

switch environment

  1. Open the project in the IDE of your choice.
  2. Start the app locally by running the following command in the project folder:
npm run start
  1. To view the app, navigate to localhost:PORT, where PORT is logged in the terminal. The address will likely be http://localhost:5173.

Squid AI Agent を追加する

  1. Squid Console で、Agent Studio タブを選択します。

  2. Create New Agent をクリックしてエージェントを追加します。次の詳細を入力し、Create をクリックします。

  • Agent ID: squid-facts
  • Description: This is an agent for Squid AI's fact sharing tutorial
  1. AI エージェントの Overview ページには、LLM Model、Instructions、Abilities の 3 つのセクションがあります。
  • LLM Model: エージェントを動かす基盤となる AI モデルです。デフォルトの GPT-4o モデルを使用するか、別のモデルを選択できます。

  • Instructions: AI エージェントがどのように応答し、質問に答えるかのルールセットです。トーンや目的に関する内容を含められます。squid-facts エージェントの instructions を次の内容に編集します。

    You're a friendly AI who shares random facts about squids and answers user questions about squids.
    Important: Only answer based on the provided context.
  • Abilities: 質問に応答する際にエージェントが利用する情報とツールです。abilities についての詳細は、documentation を参照してください。

エージェントのナレッジベースにイカの事実(squid facts)を追加するには、Wikipedia article on squids に移動し、ページを HTML または PDF ファイルとして保存します。次にコンソールで Add Abilities をクリックします。Knowledge Base の下にある File ability を選択し、ファイルをアップロードします。この ability により、エージェントは質問に答える際にコンテキストを利用できます。

Note

LLM models はおそらくすでにこのイカ情報を知っています。実際のアプリケーションでは、ユースケースに関連するコンテキストを提供します。

  1. AI エージェントの Agent Settings タブに移動し、下にスクロールして Set Agent to Public を見つけます。この設定をオンにして、フロントエンドから誰でもアクセスできるようにします。詳細は、documentation on securing your AI agent を参照してください。

  2. Context の隣にある + をクリックしてコンテキストを追加します。コンテキスト名を Squid Wikipedia にします。Context typeURL に変更し、次の URL を入力します。

これで AI エージェントを備えた Squid プロジェクトが用意できたので、アプリに機能を追加する準備ができました!

フロントエンドを設定する

The following steps add configuration parameters to connect the application to Squid.

  1. Open a new terminal window and navigate to the project's frontend. You should now have two open terminal windows: one for the app's backend and one for the frontend.
cd frontend
  1. Install the required dependencies:
npm install
  1. Run the following command to create a .env.local file with the Squid environment configuration needed to initialize Squid:
npm run setup-env

フロントエンドをカスタマイズする

  1. フロントエンドで、components フォルダ内にある squid-facts-ai.tsx コンポーネントを開きます。このフォルダには、現時点ではほとんど空のコンポーネントが入っています。
components/squid-facts-ai.tsx
function SquidFactsAI() {
return <></>;
}

export default SquidFactsAI;
  1. フロントエンドで AI エージェントを使用するために、ファイルの先頭に次の import 文を追加します。
components/squid-facts-ai.tsx
import { useAiChat } from '@squidcloud/react';
  1. SquidFactsAI() 関数内に、次の定数を追加します。これらは AI エージェントとの会話状態を管理するために使用します。
components/squid-facts-ai.tsx
const [question, setQuestion] = useState('');
const { history, chat, complete } = useAiChat('squid-facts');

変数 questionsetQuestion は、ユーザーが入力する質問の状態を管理するために標準的な useState フックを使用しています。

useAiChat フックは AI エージェントをラップします。第 2 パラメータに Agent ID を取り、chatdatacomplete など複数の結果を返します。
useAiChat の詳細は、React SDK documentation を参照してください。

  1. 定数の後に、次の関数を追加します。
components/squid-facts-ai.tsx
function askQuestion() {
chat(question);
setQuestion('');
}

function questionChanged(e: ChangeEvent) {
setQuestion((e.target as HTMLInputElement).value);
}

function checkKey(ele: React.KeyboardEvent<HTMLDivElement>) {
if (ele.key === 'Enter') {
askQuestion();
}
}

askQuestion 関数は Squid Client SDK の chat 関数を呼び出します。chat は、AI エージェントへのプロンプトを文字列として受け取ります。

questionChangedcheckKey 関数は、ユーザーが質問を入力する際の UI 変更を処理します。

  1. 既存の return を、次のコードに置き換えます。
components/squid-facts-ai.tsx
return (
<>
<div className="scrolling">
<Messages messages={history} />
</div>
<div className="question">
<TextField fullWidth id="outlined-basic" label="Enter your question" variant="outlined" onChange={questionChanged} onKeyDown={(event) => checkKey(event)} value={question} />
<Button variant="contained" disabled={!complete} onClick={askQuestion}>
Ask question
</Button>
</div>
</>
);

このコードはチャット履歴を Messages コンポーネントに渡し、ユーザーと AI エージェントの会話を表示します。また、ユーザーが質問を入力するための入力コンポーネントと、askQuestion 関数をトリガーするボタンも含まれています。

  1. 追加したものに必要な import を追加します。import は次のようになります。
components/squid-facts-ai.tsx
import { useAiChat } from '@squidcloud/react';
import Messages from './messages.tsx';
import { Button, TextField } from '@mui/material';
import React, { ChangeEvent, useState } from 'react';
  1. messages.tsx ファイルを開きます。ファイルの内容をすべて次のコードに置き換えます。このコードはチャットメッセージ配列を走査し、表示します。
components/messages.tsx
import { useEffect, useRef } from 'react';
import { ChatMessage } from '@squidcloud/react';

interface ChatHistoryProps {
messages: ChatMessage[];
}

const Messages: React.FC<ChatHistoryProps> = ({ messages }) => {
const messagesEndRef = useRef<HTMLDivElement>(null);

const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
};

useEffect(() => {
scrollToBottom();
}, [messages]);

return (
<div>
{messages.map(({ id, message, type }) => (
<div key={id}>
<span key={id}>
{type}: {message}
</span>
</div>
))}
<div ref={messagesEndRef} />
</div>
);
};

export default Messages;

コードを実行する

  1. ルートプロジェクトフォルダで、次のコマンドを実行してアプリを表示します。
npm run start

アプリを表示するには、ターミナルに出力された PORT を使って localhost:PORT に移動します。アドレスは通常 http://localhost:5173 です。

ページにイカの画像があるのはなぜかって? もちろん聞きませんよね。イカのアプリなんですから。

  1. AI エージェントにイカについていくつか質問してみましょう。もし思いつかなければ、例えば次のような質問があります。
  • イカには腕(arms)がありますか、それとも触手(tentacles)がありますか?
  • イカに遭遇したらどうすればいいですか?
  • イカについての好きな豆知識は何ですか?
  • Onykia ingens について教えてください。

お気に入りのイカに関する質問と回答を、Discord または X の Squid Squad で共有してください。

まとめ

おめでとうございます!これで Squid AI アプリケーションを作成できました。引き続き質問して、この AI エージェントがイカについてどれだけ知っているか試してみてください!

次のステップ

Public な Squid AI agents の作り方が分かったので、次にできることをいくつか紹介します。

  • ユースケースに合わせた新しいエージェントを追加する。例えば Squid AI は、ユーザーエンゲージメントの各領域(営業、サポート、プロダクトエキスパートなど)ごとに異なる persona をサポートできます。

  • Squid AI へのアクセスを制限する Squid security rule を実装する。

  • Squid Client SDK を通じてデータアクセス機能を有効化するため、Squid middle tier を使ってデータベースをフロントエンドに接続する。