カスタムフロントエンドでAIエージェントを作成する
Squidを使えば、Squid AIを用いたユニークなユーザー体験を作成することができます。順を追って、イカに関する質問に答えるAIエージェントの作成方法を見ていきましょう!
作成する内容
- ユニークなナレッジベースを持つReactフロントエンドアプリケーション上で動作するカスタムAIエージェント
Environment setup
- In the Squid Console, switch to the devenvironment.

- 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. 
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
You can find your environment variables under: 'Application' -> 'Show env vars' as seen below:

- Open the project in the IDE of your choice.
- Start the app locally by running the following command in the project folder:
npm run start
- To view the app, navigate to localhost:PORT, where PORT is logged in the terminal. The address will likely be http://localhost:5173.
Add the Squid AI Agent
- 
Squid Consoleで、Agent Studio タブを選択します。 
- 
Create New Agent をクリックしてエージェントを追加します。以下の情報を入力した後、Create をクリックしてください: 
- Agent ID: squid-facts
- Description: This is an agent for Squid AI's fact sharing tutorial
- 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: エージェントが質問に応答する際に使用する情報とツールです。詳しくは documentation をご覧ください。 
エージェントのナレッジベースにイカの事実を追加するには、Wikipedia article on squids に移動してページをHTMLまたはPDFファイルとして保存してください。次に、Consoleで Add Abilities をクリックします。Knowledge Base の下にある File ability を選択し、ファイルをアップロードしてください。このabilityを利用することで、エージェントは質問に答える際にコンテキストを使用できます。
LLM modelsは、すでにこのイカに関する情報を知っている可能性があります。ご自身のアプリケーションでは、ユースケースに関連するコンテキストを提供してください。
- 
AIエージェントの Agent Settings タブに移動し、Set Agent to Public までスクロールします。この設定をオンにすると、フロントエンドから誰でもエージェントにアクセスできるようになります。詳細は documentation on securing your AI agent をご参照ください。 
- 
Context の右側にある + をクリックしてコンテキストを追加します。コンテキストの名前を Squid Wikipedia に設定し、Context type を URL に変更した後、次のURLを入力してください: 
SquidプロジェクトにAIエージェントが追加されたので、アプリに機能を追加する準備が整いました!
Configure the frontend
The following steps add configuration parameters to connect the application to Squid.
- 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
- Install the required dependencies:
npm install
- Run the following command to create a .env.localfile with the Squid environment configuration needed to initialize Squid:
npm run setup-env
Customize the frontend
- フロントエンドの componentsフォルダにあるsquid-facts-ai.tsxコンポーネントを開きます。現在、このコンポーネントはほとんど空の状態です:
function SquidFactsAI() {
  return <></>;
}
export default SquidFactsAI;
- AIエージェントをフロントエンドで利用するため、ファイルの先頭に以下のimport文を追加します:
import { useAiChat } from '@squidcloud/react';
- SquidFactsAI()関数内に、下記の定数を追加します。これらはAIエージェントとの会話状態を管理するために使用されます:
const [question, setQuestion] = useState('');
const { history, chat, complete } = useAiChat('squid-facts');
変数 question と setQuestion は、ユーザーが質問する際の状態を管理するための標準的な useState フックを使用しています。
useAiChat フックは、AIエージェントをラップしています。Agent IDを引数として受け取り、chat、data、complete などの複数の結果を返します。
より詳しくは、React SDK documentation をご覧ください。
- 定数の後に、以下の関数を追加します:
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 関数を呼び出し、文字列としてのプロンプトをAIエージェントに渡します。
questionChanged と checkKey 関数は、ユーザーが質問する際のUIの変化を処理します。
- 既存のreturn文を以下のコードに置き換えます:
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 関数をトリガーするボタンも含まれています。
- 追加した要素に必要なimport文を追加します。インポートは以下のようになります:
import { useAiChat } from '@squidcloud/react';
import Messages from './messages.tsx';
import { Button, TextField } from '@mui/material';
import React, { ChangeEvent, useState } from 'react';
- 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;
Run the code
- プロジェクトのルートフォルダで、以下のコマンドを実行してアプリを表示します:
npm run start
アプリを表示するには、ターミナルに表示されたPORT番号の localhost:PORT にアクセスしてください。通常、アドレスは http://localhost:5173 となります。
なぜページにイカの画像が表示されているのか、不思議に思うかもしれませんが、もちろんその質問はしません。これはイカに関するアプリだからです。
- AIエージェントにイカについての質問をしてみましょう。もし迷ったら、以下の例を参考にしてください:
- イカには腕がありますか、それとも触腕ですか?
- イカに遭遇した場合、どうすればよいですか?
- イカに関して、あなたのお気に入りの事実は何ですか?
- Tell me about the Onykia ingens.
お気に入りのイカに関する質問とその回答を、Discord または X の Squid Squad と共有してください。
Conclusion
おめでとうございます!これでSquid AIアプリケーションが完成しました。ぜひ引き続き質問をして、このAIエージェントがどれだけイカに関する知識を持っているか確認してみてください!
次のステップ
公開されたSquid AIエージェントの作成方法が理解できたので、今後のステップとして以下のことが考えられます:
- 
ユースケースに応じて新しいエージェントを追加してください。例えば、Squid AIはユーザーとのエンゲージメントの各局面(sales、support、product experts など)に合わせた異なるペルソナをサポートできます。 
- 
Squid AIへのアクセスを制限する Squid security rule を実装してください。 
- 
Squid Client SDK を通じてデータアクセス機能を有効にするため、Squid middle tierを利用してデータベースをフロントエンドに接続してください。