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

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

Squidを使えば、Squid AIを用いたユニークなユーザー体験を作成することができます。順を追って、イカに関する質問に答えるAIエージェントの作成方法を見ていきましょう!

作成する内容

  • ユニークなナレッジベースを持つReactフロントエンドアプリケーション上で動作するカスタムAIエージェント

Environment setup

  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.

Add the 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: エージェントが質問に応答する際に使用する情報とツールです。詳しくは documentation をご覧ください。

エージェントのナレッジベースにイカの事実を追加するには、Wikipedia article on squids に移動してページをHTMLまたはPDFファイルとして保存してください。次に、Consoleで 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を入力してください:

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

Configure the frontend

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

Customize the frontend

  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エージェントをラップしています。Agent IDを引数として受け取り、chatdatacomplete などの複数の結果を返します。 より詳しくは、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 関数を呼び出し、文字列としてのプロンプトを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文を追加します。インポートは以下のようになります:
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;

Run the code

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

アプリを表示するには、ターミナルに表示されたPORT番号の localhost:PORT にアクセスしてください。通常、アドレスは http://localhost:5173 となります。

なぜページにイカの画像が表示されているのか、不思議に思うかもしれませんが、もちろんその質問はしません。これはイカに関するアプリだからです。

  1. 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を利用してデータベースをフロントエンドに接続してください。