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

カスタムフロントエンドによるAIエージェントの作成

Squidを使うと、Squid AI によるユニークなユーザー体験を作成できます。一緒に、イカに関する質問に答える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.

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: エージェントが質問に回答する際に使用する情報やツールです。Abilities については documentation をご覧ください。

エージェントの知識ベースにイカに関する事実を追加するには、Wikipedia article on squids に移動し、ページをHTMLまたはPDFファイルとして保存します。次に、Consoleで Add Abilities をクリックします。Knowledge Base の下にある File ability を選択してファイルをアップロードしてください。このAbilityを使用することで、エージェントは質問に回答する際にコンテキストを利用できます。

注意

LLMモデルは既にこのイカに関する情報を知っている可能性があります。ご自身のアプリケーションでは、利用ケースに関連するコンテキストを提供することになります。

  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 { useAiChatbot } from '@squidcloud/react';
  1. SquidFactsAI() 関数内に、以下の定数を追加してください。これらは、AIエージェントとの会話の状態管理に使用されます:
components/squid-facts-ai.tsx
const [question, setQuestion] = useState('');
const { history, chat, complete } = useAiChatbot('ai_agents', 'squid-facts');

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

useAiChatbot フックはAIエージェントをラップしています。第2パラメーターとしてAgent IDを受け取り、chatdatacomplete などの結果を返します。 useAiChatbot の詳細については、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. 追加したものに対応するインポートを追加してください。インポートは以下のようになります:
components/squid-facts-ai.tsx
import { useAiChatbot } 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エージェントにイカについての質問をしてみましょう。迷ったときのためにいくつかの例を示します:
  • イカは腕を持っていますか、それとも触手ですか?
  • イカに遭遇した場合、どのように対処すべきですか?
  • イカに関するあなたのお気に入りの事実は何ですか?
  • Tell me about the Onykia ingens.

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

結論

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

次のステップ

パブリックなSquid AIエージェントの作成方法が分かったところで、次のステップとして以下を試してみてください:

  • 利用ケースに応じた新しいエージェントを追加する。例えば、Squid AIはユーザーエンゲージメントの各部分(セールス、サポート、プロダクトエキスパートなど)に対して異なるペルソナをサポートできます。

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

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