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

RAG Agent を実装する

ドキュメントを AI agent の knowledge base に統合し、その後あなたのデータに対してアクションを実行する

作成するもの

  • 製品マニュアルをコンテキストとして使用し、家電に関する質問に回答し、リクエストに応じてメンテナンスタスクのリストを作成する AI agent を搭載したアプリ

このチュートリアルでは、以下の機能を使用します:

AI AbilitiesInternal ConnectorsBackend Functions
Knowledge baseBuilt-in DatabaseWebhooks

Huge thanks to our partners at Otairo for collaborating with us on this tutorial!

Environment setup

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

switch environment

  1. Download the ai-home-maintenance 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-home-maintenance --template ai-home-maintenance --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.
NOTE

アプリケーションは正常に起動するはずですが、次のステップを完了するまで完全には機能しません。

AI agent を追加する

各 agent は、独自の命令と abilities によって識別される異なるペルソナまたはユースケースを表します。

  1. Squid Console で、Agent Studio タブに移動します。

  2. Create New Agent をクリックして agent を追加します。次の詳細を入力してください:

  • Agent ID: maintenance-scheduler
  • Description: This is an agent for Squid AI's home maintenance tutorial
  1. Create をクリックして agent を作成します。

  2. Instructions フィールドに、エージェントに以下のインストラクションを追加します:

Respond to queries about home maintenance documents. Only use the provided context to generate responses. Never respond based on your general knowledge. When applicable, list the source document used. If a question cannot be answered using the provided context, state that clearly and do not attempt to answer using general knowledge.

これらのインストラクションは、AI agent にどのアクションを実行するかを指示します。

  1. 次に、Agent Settings タブに移動します。Set Agent to Public までスクロールし、この設定をオンに切り替えます。
    これにより、セキュリティルールを記述することなく、agent にパブリックアクセスが可能になります。
IMPORTANT

本番環境にデプロイする前に、適切なセキュリティルールが設定されていることを確認し、パブリックアクセスが有効な状態で agent を実行しないようにしてください。エージェントのセキュリティ設定方法については、this reference を参照してください。

バックグラウンド知識を追加する

knowledge base ability は、質問に回答する際に agent にコンテキストを提供します。コンテキストを追加することで、基盤となる AI モデルに含まれていない特定のトピックに関して、agent が適切な回答を提供できるようになります。

  1. 以下の家電用マニュアルを PDF ファイルとしてダウンロードします:

Oven:

https://media3.bosch-home.com/Documents/8001203758_A.pdf

Microwave:

https://media3.bosch-home.com/Documents/9001152447_B.pdf

Dishwasher:

https://media3.bosch-home.com/Documents/9001641455_A.pdf

Washer/dryer:

https://products-salsify.geappliances.com/image/upload/s--pdIsKW0u--/izid0w85hg3mbckeyyo1.pdf

あるいは、オンラインでご自身の家電のマニュアルを検索し、コンテキストとして提供することも可能です。これにより、それらに関する質問ができるようになります。

  1. Add Abilities をクリックし、Knowledge Base の下にある File ability を選択します。

  2. 4 つのファイルそれぞれをアップロードします。アップロード中はしばらくお待ちください。agent は自動的にドキュメントから内容を抽出し、テキストをその knowledge base に追加します。

Squid アプリケーションを探索する

プロジェクトのルートディレクトリで以下のコマンドを実行して、両方のサーバーを起動します:

npm run start

両方のサーバーが起動した状態で、Web ブラウザから http://localhost:5173/ にアクセスしてください。これで、Squid アプリケーションの機能を探索する準備が整いました:

  1. 家電に関する質問をしてみましょう。例えば、以下のように尋ねることができます:
How do I clean my cooktop?

AI agent は、マニュアルから取得した詳細情報をチャットで回答します。

  1. AI agent に家電のメンテナンスタスクのリストを作成するよう指示します:
Create a list of maintenance tasks.

しばらくすると、新しいタスクがアプリケーションの右側にリストとして表示されます。これは、AI agent がマニュアルをコンテキストとして使用してメンテナンスタスクを生成し、あなたに代わってタスクをデータベースに書き込むことができたことを意味します。

  1. いくつかのタスクを完了した後、Squid の Query with AI 機能を使用してさらに質問することができます。この機能は、あなたのデータベーススキーマの知識を基に、プロンプトに沿ったクエリを生成します。

    アプリの自動検出されたスキーマを保存するには、Squid Console にアクセスし、Connectors タブに移動して built_in_db... ボタンをクリックし、ドロップダウンメニューから Schema を選択してください。

  2. Save Schema をクリックして、アプリの自動検出されたスキーマを保存します。

  3. いくつかのタスクにチェックを入れて完了済みとしてマークし、次に AI agent に以下の質問をします:

Which maintenance tasks have I completed?

AI agent は、データベースをクエリして完了したタスクを判別します。これは、AI agent がその場でデータベースクエリを生成できることを意味します!

  1. AI agent は、より複雑な指示を認識して応答することができます。例えば、以下のように AI agent にプロンプトを与えます:
Look up in the manual to determine how often I should clean my washer-dryer lint filter. Based on that interval, if I run two loads of laundry a day, how often should I clean the filter?

AI agent は、リントフィルターの清掃頻度を判断し、その間隔に基づいて論理的な回答を提供します。

コードを見る

Squid によって動作する AI agent を搭載したフルスタックアプリケーションの構築に成功しました!内部で何が起こっているのか気になりますか?このセクションでは、コードの詳細を解説します。

フロントエンドでの AI agent の設定

Squid React SDK の useAiChat フックを使用して、以下のコードで AI agent に接続できます:

frontend/src/App.tsx
const { history, chat, complete } = useAiChat('maintenance-scheduler');

AI agent への機能追加

Squid AI Agent は、プロンプトに基づいてさまざまなアクションを実行できます。これは、Squid バックエンドで @aiFunction デコレーターを使用して関数を指定し、その関数を options パラメータの一部としてプロンプトと共に渡すことで実現されます。

例えば、以下の AI 関数は、家電マニュアルから作成されたメンテナンスタスクのリストを生成し、logMaintenanceScheduleInternal() 関数を使用してタスクを built-in database に書き込みます:

backend/src/service/example-service.ts
  @aiFunction(
'If someone asks for a list of maintenance tasks, run this function. This function creates a maintenance task for a list of tasks. Pass each created task to this function. If the user asks how to complete a specific task, then do not run this function. !Important: if a user asks questions about **existing** tasks in the database, then do not run this function.',
[
{
name: 'task',
description: 'the task to complete',
type: 'string',
required: true,
},
{
name: 'interval',
description: 'the frequency or interval at which the task needs to be done',
type: 'string',
required: true,
},
{
name: 'appliance',
description:
'the appliance that requires the given maintenance. Provide the manufacturer name of the appliance, along with the type of appliance',
type: 'string',
required: true,
},
],
)
async
createTaskItem(params
:
{
task: string;
interval: string;
appliance: string
}
)
{
const { task, interval, appliance } = params;
await this.logMaintenanceScheduleInternal({ task, interval, appliance, completed: false });
}

@aiFunction デコレーターには、関数の目的を説明するパラメータが含まれていることに注意してください。AI agent は、この情報を使用して関数を呼び出すタイミングを判断します。

2 番目の AI 関数は、プロンプトに基づいて情報を取得するためにデータベースをクエリします:

backend/src/service/example-service.ts
  @aiFunction(
" !Important: Call this function when a client prompt requests information about the **existing** tasks in their database. This function queries the database for tasks that meet the client's request. Include the exected query in your response",
[
{
name: 'prompt',
description: 'the request from the client',
type: 'string',
required: true,
},
],
)
async
checkTasksAI(params
:
{
prompt: string
}
):
Promise < string > {
const { prompt } = params;
const response = await this.squid.ai().executeAiQuery('built_in_db', prompt);
return `${response.answer} \n ${response.executedQuery}`;
}

フロントエンドでは、以下のコードで各プロンプトとともに関数が渡されます:

frontend/src/App.tsx
chat(question, { functions: ['checkTasksAI', 'createTaskItem'] }); // Add functions in the second parameter

その後、AI agent はプロンプトに応じて関数を実行するタイミングを判断します。

AI 関数の詳細については、AI functions documentation を参照してください。

次のステップ

おめでとうございます!
ドキュメントを読んで質問に回答し、ドキュメントの内容に基づいてデータベースへの書き込みや、クライアントのプロンプトに基づくデータベースからの読み取りができるアプリケーションに AI agent を追加しました。