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

AIチャットウィジェット

1つのHTML要素で、フル機能のAIチャットをWebサイトに組み込めます。​
Screenshot of the Squid AI chat widget

AIチャットウィジェットを使う理由​

サイト上でユーザーがAIエージェントとチャットできるようにしたいとします。エージェントには、ビジネスについての知識、セキュリティモデルへの準拠、ブランドに合った外観が求められます。さらに、音声入力、定義済みプロンプト、chain-of-thoughtの可視化にも対応していることが理想的です。

これを一から構築するには、チャットUIの作成、ストリーミングの接続、履歴の処理、認証の統合、スタイリングが必要です。Squid AIチャットウィジェットは、これらすべてを1つのWebコンポーネントとして提供します。

Client code
<script async src="https://widget.squid.cloud/widget.umd.js"></script>

<squid-chat-widget-with-fab-button
squid-app-id="YOUR_APP_ID"
squid-region="us-east-1.aws"
squid-environment-id="prod"
squid-ai-agent-id="YOUR_AGENT_ID"
></squid-chat-widget-with-fab-button>

これだけで、入力ボックス、履歴、ストリーミング応答、チャットを開閉するフローティングアクションボタン(FAB)を備えた、フル機能のAIチャットを利用できます。

ページの右下にあるFABから、今すぐこのウィジェットを試せます。

概要​

Squid AIチャットウィジェットは、Squid AIエージェントと通信する自己完結型のWebコンポーネントです。Query with AIを介してSquidのデータベースintegrationと直接通信することもできます(以下の例を参照)。https://widget.squid.cloud/widget.umd.jsでホストされる単一のUMD bundleとして提供され、Shadow DOM内にレンダリングされるため、サイトのスタイルと競合しません。

2種類の要素​

要素動作
<squid-chat-widget>インラインのチャットブロック。ドキュメント内の配置した場所にレンダリングされます。サイズとレイアウトは自分で制御します。
<squid-chat-widget-with-fab-button>右下に表示されるフローティングアクションボタン(FAB)。クリックしてチャットを開閉します。

どちらの要素も同じ属性を受け付けます。

チャットウィジェットの使用場面​

ユースケース推奨
マーケティングサイトやWebアプリにAIアシスタントを追加するチャットウィジェット
完全にカスタムなチャットUIを構築するAI agent SDKを直接使用
特定のデータベースについて質問できるチャットを埋め込むsquid-ai-query="true"とsquid-ai-integration-idを指定したチャットウィジェット
UIなしでプログラムからAIを呼び出すsquid.ai().agent()またはexecuteAiQuery

クイックスタート​

前提条件​

  • Squid Consoleで作成したSquidアプリケーション
  • アプリケーションのAgent Studioタブで作成したAIエージェント
  • エージェントのID、SquidアプリのID、リージョン(すべてSquid ConsoleのBackend ProjectにあるShow env varsで確認できます)

ステップ1:AIエージェントを作成する​

  1. Squid Consoleでアプリケーションを開き、Agent Studioタブをクリックします
  2. Create New Agentをクリックします
  3. Agent ID(後で変更できません)と説明を入力します
  4. Createをクリックします

エージェントの作成後、Instructions(エージェントの応答方法に関するルール)とKnowledge baseの項目(背景となるコンテキスト)を追加します。Test chatボタンですぐにエージェントをテストできます。

注記

Squidには、独立したdev環境とprod環境があります。AIエージェントは環境間で共有されません。ウィジェットのsquid-environment-id属性が、エージェントを作成した環境と一致していることを確認してください。環境を参照してください。

ステップ2:ウィジェットのスクリプトを読み込む​

HTMLの<head>または<body>にウィジェットのscriptタグを追加します。

Client code
<script async src="https://widget.squid.cloud/widget.umd.js"></script>

ステップ3:ウィジェットをレンダリングする​

Client code
<squid-chat-widget-with-fab-button
squid-app-id="YOUR_APP_ID"
squid-region="us-east-1.aws"
squid-environment-id="prod"
squid-ai-agent-id="YOUR_AGENT_ID"
header-title="Acme Assistant"
intro-text="Hi! Ask me anything about Acme."
></squid-chat-widget-with-fab-button>

YOUR_APP_ID、us-east-1.aws、YOUR_AGENT_IDをアプリケーションの値に置き換えます。

認証と設定​

Publicエージェントとprivateエージェント​

エージェントはAgent StudioのAgent Settingsでpublicまたはprivateに設定できます(Public agentまでスクロールします)。

  • Publicエージェントには誰でもアクセスできます。ウィジェットに認証情報は必要ありません。
  • Privateエージェントには、Squidが呼び出し元を検証するための認証プロバイダーが必要です。

Privateエージェントを保護する​

  1. Squidに認証プロバイダーを接続します
  2. 認証プロバイダーのintegrationIdとユーザーの認証トークンをsquid-auth-provider属性で渡します。
Client code
<squid-chat-widget
squid-app-id="YOUR_APP_ID"
squid-region="us-east-1.aws"
squid-environment-id="prod"
squid-ai-agent-id="YOUR_AGENT_ID"
squid-auth-provider='{"integrationId": "AUTH_INTEGRATION_ID", "token": "AUTH_TOKEN"}'
></squid-chat-widget>
  1. バックエンドに@secureAiAgentルールを追加して、チャットできるユーザーを制御します。
Backend code
@secureAiAgent('chat')
allowAccessToAgent(): boolean {
return this.isAuthenticated();
}
注記

Publicエージェントは@secureAiAgentルールを完全にバイパスします。認証情報は引き続きAI functionで利用できるため、publicエージェント内の特定のfunction呼び出しを制限できます。AI functionsを参照してください。

詳細

条件チェック、エージェント単位のルール、Agent API Keysについては、AIエージェントとAgent API Keysの保護を参照してください。

認証フローの詳細については、認証を参照してください。

フレームワークでカスタムHTML要素を有効にする​

一部のフロントエンドフレームワークでは、カスタムHTML要素を使用するために追加の設定が必要です。

React(src/declarations.d.ts):

Client code
declare namespace JSX {
interface IntrinsicElements {
'squid-chat-widget': any;
'squid-chat-widget-with-fab-button': any;
}
}

Angular(src/app/app.module.ts):

Client code
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class AppModule {}

その他のフレームワークについては、カスタム要素の有効化に関する各フレームワークのドキュメントを参照してください。

基本概念​

接続属性​

これらの属性は、Squidへの接続方法と、通信するエージェントまたはintegrationをウィジェットに指定します。

属性型必須説明
squid-app-idstringはい(squid-ai-custom-api-urlを使用する場合を除く)SquidアプリケーションのID
squid-regionstringはい(squid-ai-custom-api-urlを使用する場合を除く)アプリケーションのAWSリージョン(例:us-east-1.aws)
squid-environment-idstringいいえ(デフォルトはprod)devまたはprod。エージェントが存在する環境と一致する必要があります。
squid-developer-idstringいいえDeveloper ID。バックエンドをローカルで実行する場合にのみ必要です。
squid-api-keystringいいえSquid API key。信頼できる場所でのみ使用し、ユーザー向けページでは絶対に使用しないでください。
squid-ai-agent-idstringはい(squid-ai-query="true"またはsquid-ai-custom-api-urlを使用する場合を除く)チャットするエージェントのID
squid-ai-profile-idstringいいえ(非推奨)squid-ai-agent-idの旧名称。非推奨の警告がログに出力されます。代わりにsquid-ai-agent-idを使用してください。
squid-ai-integration-idstringsquid-ai-query="true"の場合は必須Query with AIモードでクエリを実行するデータベースintegrationのID
squid-ai-querybooleanいいえtrueの場合、ウィジェットはエージェントではなくQuery with AIを介してデータベースintegrationに対して動作します
squid-auth-providerJSONいいえ{ "integrationId": "...", "token": "..." }。Privateエージェントでは必須です。
squid-ai-custom-api-urlstringいいえSquidを経由せずにチャットリクエストを処理するカスタムHTTPエンドポイント
squid-ai-custom-api-headersJSONいいえカスタムAPI URLへのリクエストに追加して送信するヘッダー

チャット動作の属性​

属性型説明
squid-ai-functionsstring有効にするAI function名のカンマ区切りリスト
squid-ai-functions-jsonJSONname、context、predefinedParametersをオプションで含むfunctionオブジェクトの配列
squid-ai-temperaturenumber[0, 1]のtemperature。低いほど決定的になります。
squid-ai-max-tokensnumberLLM応答の最大トークン数
squid-ai-override-modelstringエージェントが使用するモデルを上書きします(例:gpt-6.2-sol)
squid-ai-context-metadata-filterJSONknowledge baseの検索に適用するメタデータフィルター。コンテキストのフィルタリングを参照してください。
squid-ai-instructionsstringこのウィジェットインスタンス用に、エージェントのシステムプロンプトに追加する指示
squid-ai-connected-agentsJSONエージェントが処理を委任できるconnected agentsの{ agentId, description }の配列
squid-ai-agent-chat-optionsJSON高度なチャットオプションのオブジェクト。以下の高度なチャットオプションを参照してください。
squid-ai-enable-raw-resultsbooleansquid-ai-query="true"の使用時に、生のクエリ結果ファイルを要求します
squid-ai-enable-code-interpreterbooleansquid-ai-query="true"の使用時に、グラフや分析のためのPython code interpreterを有効にします
disable-historybooleanメッセージ間の会話メモリを無効にします
chain-of-thoughtbooleanエージェントの推論ステップ(ツール呼び出し、クエリ、functionの実行)を表示します
show-status-tagsbooleanchain-of-thoughtのステータス更新にタグラベルを表示します
observe-statusbooleanバックエンドからのリアルタイムのステータス更新を監視します
include-referencebooleanエージェントの応答に参照元(引用)を表示します
enable-transcriptionbooleanユーザーがプロンプトを音声で入力できるようにマイクボタンを表示します
predefined-promptsstringユーザーに表示する推奨プロンプト。カンマ区切り、改行区切り、またはJSON文字列化された配列で指定します。
enable-debug-logsbooleanブラウザーのコンソールにデバッグログを出力します
Publicエージェントは機能を拡張する属性を無視します

ウィジェットはアプリのAPI keyなしでエージェントを呼び出します。そのため、publicエージェントでは、エージェントの機能を拡張し得る属性(squid-ai-functions、squid-ai-functions-json、squid-ai-connected-agents、squid-ai-enable-code-interpreter、connected integrationの上書き)は無視され、保存済みのエージェント設定が適用されます。これらの機能はエージェント自体で設定してください。Publicエージェントのオプションを参照してください。

表示とカスタマイズの属性​

属性型説明
header-titlestringチャットヘッダーのタイトルテキスト。デフォルトはSquidAI Chatです。
intro-textstringチャットを開いたときにユーザーに表示される最初のメッセージ
avatar-image-urlstringAIメッセージの横に表示されるアバター画像のURL
chat-icon-urlstringフローティングアクションボタンのカスタムアイコン
widget-widthstringCSSの幅の値(例:400px)
widget-heightstringCSSの高さの値(例:600px)
themestringlightまたはdark。デフォルトはlightです。
rtl-modebooleanアラビア語やヘブライ語などの右から左へのレイアウトを有効にします
use-maximize-buttonboolean最大化・最小化ボタンを表示します。FABモードでのみ有効です。
open-on-loadbooleanページの読み込み時にFABウィジェットを自動的に開きます
powered-by-textstringフッターの「Powered by Squid」テキストを上書きします
menu-items-jsonJSONカスタムメニュー項目を定義する{ title, slotName }オブジェクトの配列。カスタムメニュー項目を参照してください。
base-stylesheet-urlstringベースCSSファイルを上書きします。デフォルトはhttps://widget.squid.cloud/style.cssです。
stylesheet-urlstringベースのスタイルシートに重ねて読み込む追加のCSSファイル
error-formatterstringまたはfunction'generic-error'、'original-error'(デフォルト)、またはJS functionの(error) => string

ローカライズ属性​

ウィジェットには、組み込みのUI文字列を置き換えるための属性が用意されています。

属性デフォルト
text-placeholder"Type here and press enter..."
text-thinking"Thinking..."
text-thought-for"Thought for"
text-suggested-prompts"Suggested Prompts"
text-suggested-prompts-description"Explore what this agent can do with a few examples."
text-milliseconds"milliseconds"
text-seconds"seconds"
text-minutes"minutes"

高度なチャットオプション​

squid-ai-agent-chat-optionsは、エージェントのチャットオプションインターフェースに対応するJSONオブジェクトを受け付けます。主なフィールドは次のとおりです。

フィールド説明
agentContextすべてのAI function呼び出しに渡されるオブジェクト。AI functionへのコンテキストの受け渡しを参照してください。
instructionsこのウィジェットインスタンス用に、エージェントのシステム指示に追加する文字列
contextMetadataFilterForKnowledgeBase使用するknowledge baseのエントリーを制限するオブジェクト。コンテキストのフィルタリングを参照してください。
functionsオプションのpredefinedParametersとfunctionごとのcontextを含むfunction記述子の配列
memoryOptions会話メモリの設定:memoryId、memoryMode
temperatureサンプリングのtemperature
modelこのウィジェットインスタンスが使用するモデルを上書きします

例:

Client code
<squid-chat-widget
squid-app-id="YOUR_APP_ID"
squid-region="us-east-1.aws"
squid-ai-agent-id="YOUR_AGENT_ID"
squid-ai-agent-chat-options='{
"agentContext": { "tenantId": "acme" },
"instructions": "Always reply in Spanish.",
"contextMetadataFilterForKnowledgeBase": {
"product-docs": { "version": "v2" }
},
"memoryOptions": { "memoryMode": "read-write", "memoryId": "session-123" }
}'
></squid-chat-widget>

カスタムメニュー項目​

menu-items-jsonは、チャットヘッダーのメニューに追加する項目を定義します。各項目にはtitleとslotNameがあります。子要素に標準のslot=属性を使用して、各スロットのコンテンツを指定します。

Client code
<squid-chat-widget
squid-app-id="YOUR_APP_ID"
squid-region="us-east-1.aws"
squid-ai-agent-id="YOUR_AGENT_ID"
menu-items-json='[
{ "title": "Documentation", "slotName": "docs" },
{ "title": "Contact us", "slotName": "contact" }
]'
>
<div slot="docs">
<h3>Documentation</h3>
<p>Read our docs at <a href="https://docs.example.com">docs.example.com</a>.</p>
</div>
<div slot="contact">
<h3>Contact us</h3>
<p>Email <a href="mailto:hello@example.com">hello@example.com</a></p>
</div>
</squid-chat-widget>

CSS変数​

ウィジェットはShadow DOM内にレンダリングされます。ホスト要素にCSSカスタムプロパティを設定することで、外観を上書きできます。各変数には、フォールバックとしてウィジェットのデフォルトテーマが使用されます。

変数制御する対象
--squid-widget-header-background-colorヘッダーの背景
--squid-widget-header-title-colorヘッダータイトルのテキスト色
--squid-widget-header-menu-button-background-colorメニューボタンの背景
--squid-widget-header-menu-button-icon-urlメニューボタンのアイコン画像URL
--squid-widget-header-menu-item-colorメニュー項目のテキスト色
--squid-widget-header-menu-item-hover-background-colorメニュー項目にホバーしたときの背景
--squid-widget-menu-item-back-icon-urlサブメニューの戻るボタンのアイコン
--squid-widget-body-background-colorチャット本文の背景
--squid-widget-ai-message-background-colorAIメッセージの吹き出しの背景
--squid-widget-ai-message-text-colorAIメッセージのテキスト色
--squid-widget-user-message-background-colorユーザーメッセージの吹き出しの背景
--squid-widget-user-message-colorユーザーメッセージのテキスト色
--squid-widget-textarea-background-color入力用textareaの背景
--squid-widget-textarea-border-color入力用textareaの枠線
--squid-widget-textarea-text-color入力用textareaのテキスト色
--squid-widget-textarea-submit-image-url送信ボタンのアイコン画像URL
--squid-widget-inline-code-background-colorインラインコードブロックの背景
--squid-widget-inline-code-border-colorインラインコードブロックの枠線
--squid-widget-link-colorハイパーリンクの色
--squid-widget-powered-by-colorフッターの「Powered by」テキストの色
--squid-widget-fab-background-colorFABボタンの背景
--squid-widget-fab-image-urlFABボタンのアイコン(閉じた状態)
--squid-widget-fab-close-image-urlFABボタンのアイコン(開いた状態)

インラインのstyleを使用する例:

Client code
<squid-chat-widget
squid-app-id="YOUR_APP_ID"
squid-region="us-east-1.aws"
squid-ai-agent-id="YOUR_AGENT_ID"
style="
--squid-widget-header-background-color: #1a73e8;
--squid-widget-ai-message-background-color: #e8f0fe;
--squid-widget-user-message-background-color: #1a73e8;
--squid-widget-user-message-color: #ffffff;
"
></squid-chat-widget>

class属性を使用して、独自の外部スタイルシートルールを適用することもできます。

イベントのリッスン​

ウィジェットは、チャット履歴またはステータス更新が変化するたびに、changeのCustomEventを発行します。2種類のペイロード形式がサポートされています。

Client code
const widget = document.querySelector('squid-chat-widget')!;

widget.addEventListener('change', (event: CustomEvent) => {
if (event.detail.type === 'history') {
// event.detail.history is an array of ChatMessage objects
console.log('History updated:', event.detail.history);
} else if (event.detail.type === 'status') {
// event.detail.status is an array of AiStatusMessage objects
console.log('Status updated:', event.detail.status);
}
});

Reactでは、代わりにonChangeコールバックpropを渡します。

Client code
<SquidChatWidgetWithFabButtonEntryPoint
squidAppId="YOUR_APP_ID"
squidRegion="us-east-1.aws"
squidAiAgentId="YOUR_AGENT_ID"
onChange={(event) => {
console.log(event.detail);
}}
/>

コード例​

AI functionのパラメーターを上書きする​

特定のパラメーターをAIに選択させずに固定したい場合は、squid-ai-functions-jsonを介してpredefinedParametersを使用します。対応するバックエンドのパターンについては、パラメーター値の上書きを参照してください。

Client code
<squid-chat-widget
squid-app-id="YOUR_APP_ID"
squid-region="us-east-1.aws"
squid-ai-agent-id="YOUR_AGENT_ID"
squid-ai-functions-json='[
{ "name": "saveSection", "predefinedParameters": { "sectionId": "introduction" } }
]'
></squid-chat-widget>

エージェントのコンテキストをバックエンドfunctionに渡す​

squid-ai-agent-chat-optionsのagentContextフィールドを使用して、すべてのAI function呼び出しがバックエンドで読み取れる値を付与します。対応するバックエンドのパターンは、AI functionへのコンテキストの受け渡しに記載されています。

Client code
<squid-chat-widget
squid-app-id="YOUR_APP_ID"
squid-region="us-east-1.aws"
squid-ai-agent-id="YOUR_AGENT_ID"
squid-ai-agent-chat-options='{
"agentContext": { "documentId": "doc-42" },
"functions": [
{ "name": "saveSection", "context": { "codenameList": ["LITANIA", "LEOPARD"] } }
]
}'
></squid-chat-widget>

Query with AIでデータベースとチャットする​

squid-ai-query="true"を設定し、エージェントIDの代わりにデータベースintegrationのIDを指定します。基盤となる機能については、Query with AIを参照してください。

Client code
<squid-chat-widget
squid-app-id="YOUR_APP_ID"
squid-region="us-east-1.aws"
squid-ai-query="true"
squid-ai-integration-id="postgres"
squid-ai-enable-code-interpreter="true"
predefined-prompts='[
"How many users signed up last week?",
"Show me a chart of orders per region.",
"Which products had no sales this month?"
]'
></squid-chat-widget>

カスタムバックエンドwebhook​

squid-ai-custom-api-urlを使用して、チャットを独自のバックエンドにルーティングします。ウィジェットはそのURLにプロンプトをPOSTし、応答は自分で処理します。

Client code
<squid-chat-widget
squid-ai-custom-api-url="https://YOUR_APP-prod.us-east-1.aws.squid.cloud/webhooks/chat?projectId=YOUR_PROJECT_ID"
></squid-chat-widget>
Backend code
import { webhook, SquidService, WebhookRequest } from '@squidcloud/backend';

interface ChatRequest {
prompt: string;
}

interface ChatResponse {
response: string;
}

export class ChatService extends SquidService {
@webhook('chat')
async chat(request: WebhookRequest<ChatRequest>): Promise<ChatResponse> {
const userPrompt = request.body.prompt;
const projectId = request.queryParams['projectId'];

// Custom logic to handle the user prompt and project ID.
return { response: `Echo: ${userPrompt}` };
}
}

JavaScriptでプログラムから作成する​

Client code
const widget = document.createElement('squid-chat-widget');
widget.setAttribute('squid-app-id', 'YOUR_APP_ID');
widget.setAttribute('squid-region', 'us-east-1.aws');
widget.setAttribute('squid-ai-agent-id', 'YOUR_AGENT_ID');
widget.setAttribute('header-title', 'Acme Assistant');
widget.setAttribute('squid-ai-agent-chat-options', JSON.stringify({ memoryOptions: { memoryMode: 'read-write', memoryId: 'session-1' } }));

// Function-typed props are set as DOM properties, not attributes.
(widget as any)['error-formatter'] = (error: unknown) => `Something went wrong: ${error}`;

document.body.appendChild(widget);

エラー処理​

よくあるエラー​

エラー原因解決策
squid-app-id must be specifiedsquid-app-id属性がないsquid-app-idを追加する(またはsquid-ai-custom-api-urlを使用する)
squid-region must be specifiedsquid-region属性がないsquid-regionを追加する
squid-ai-agent-id must be specified or squid-ai-query must be trueエージェントIDがなく、クエリモードでも実行していないsquid-ai-agent-idを追加するか、squid-ai-query="true"とsquid-ai-integration-idを設定する
squid-ai-integration-id must be specified when using squid-ai-querysquid-ai-query="true"が設定されているが、integration IDがないsquid-ai-integration-idを追加する
squid-ai-profile-id is deprecated, use squid-ai-agent-id instead旧バージョンの属性名を使用しているsquid-ai-agent-idに変更する
バックエンドからのUNAUTHORIZEDPrivateエージェントで認証プロバイダーがない、または@secureAiAgentによって拒否されたsquid-auth-providerを設定し、@secureAiAgentルールを確認する
カスタムHTML要素が認識されないフレームワークでカスタム要素の登録が必要フレームワークでカスタムHTML要素を有効にするを参照する

問題を診断する際は、enable-debug-logs="true"を使用して、ブラウザーのコンソールに追加情報を出力できます。

エラー表示をカスタマイズする​

error-formatterを使用して、ユーザーへのエラーの表示方法を制御します。組み込みの値は、'generic-error'(共通の単一メッセージ)と'original-error'(実際のエラーメッセージ、デフォルト)です。functionを渡すこともできます。

Client code
const widget = document.querySelector('squid-chat-widget')!;
(widget as any)['error-formatter'] = (error: unknown) => {
if (error instanceof Error) return error.message;
return 'Something went wrong. Please try again.';
};

ベストプラクティス​

  1. squid-app-idとsquid-regionはHTMLに記載し、API keyは絶対に記載しないでください。 チャットウィジェットはブラウザーで実行されます。squid-api-keyに設定した内容は、ページを閲覧する誰からでも見えます。Privateエージェントでは、代わりにsquid-auth-providerと@secureAiAgentを使用してください。
  2. squid-ai-profile-idではなくsquid-ai-agent-idを使用してください。 前者は非推奨であり、警告がログに出力されます。
  3. squid-environment-idをエージェントの環境に合わせてください。 devで作成したエージェントはprodからは見えず、その逆も同様です。
  4. エージェントがpublicの場合でも、バックエンドにセキュリティルールを適用してください。 Publicエージェントは@secureAiAgentをスキップしますが、@secureAiQueryとAI functionの認証チェックは引き続き実行されます。
  5. 開発中はchain-of-thought="true"を設定してください。 エージェントの動作を正確に確認できます。エンドユーザー向けにはオフにするか、show-status-tags="false"にしてオンのままにします。
  6. CSSの上書きはstyle=でインライン化せず、独自のスタイルシートにキャッシュしてください。 複数のウィジェットインスタンスの表示を同期できます。
  7. changeイベントをリッスンしてください。 ウィジェットの外部に会話履歴を保存したり、プロダクト分析に渡したりする場合に使用します。

関連項目​