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

カスタムフロントエンドを持つAIエージェントの作成

Squid を使うことで、Squid AI を活用したユニークなユーザー体験を作成できます。一緒に、squids に関する質問に答える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: エージェントが質問に応答する際に使用する情報やツールです。Abilitiesの詳細は、documentation をご参照ください。

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

Note

LLM models likely already know this squid information. In your own applications, you will provide context that is relevant to your use case.

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

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

Now that you have a Squid project with an AI agent, you're ready to add functionality to an app!

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 などの結果を返します。
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 関数を呼び出し、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 { 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 となります。

ページに squid の画像が表示されているのはなぜかと疑問に思うかもしれませんが、もちろんその必要はありません。これは squid に関するアプリですから。

  1. AIエージェントに squid に関する質問をしてみましょう。もし困ったら、以下の例を参考にしてください:
  • イカには腕か触手、どちらがありますか?
  • イカに遭遇したらどうすればよいですか?
  • イカについて、あなたのお気に入りのファクトは何ですか?
  • Tell me about the Onykia ingens.

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

Conclusion

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

Next steps

公開された Squid AI エージェントの作成方法が分かったところで、次のステップとして以下を実施できます:

  • ご利用ケースに基づいて新しいエージェントを追加する。例えば、Squid AI はユーザーエンゲージメントの各分野(sales, support, product experts など)に対して異なるパーソナをサポートできます。
  • Squid AI へのアクセスを制限する Squid security rule を実装する。
  • Squid middle tier を使用してデータベースをフロントエンドに接続し、Squid Client SDK 経由でデータアクセス機能を実現する。