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

AI chat widget

単一の HTML 要素で、フル機能の AI chat 体験をあなたの Web サイトに追加できます。
Squid AI chat widget のスクリーンショット

AI Chat Widget を使う理由

あなたのサイトで、ユーザーが AI agent とチャットできるようにしたいとします。その agent には、あなたのビジネスについての知識があり、セキュリティモデルに従い、ブランドに合った見た目を持ち、さらに理想的には voice input、predefined prompts、chain-of-thought visualization をサポートしてほしいでしょう。

これをゼロから構築する場合、chat UI の実装、streaming の接続、履歴の管理、auth の統合、スタイリングなどが必要になります。Squid AI chat widget は、それらすべてを単一の web component として提供します。

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>

これだけで、input box、履歴、streaming responses、さらに開閉用の floating action button (FAB) を備えた完全な AI chat 体験が実現します。

この widget は、ページ右下の FAB から今すぐ試すことができます。

概要

Squid AI chat widget は、Squid AI agent と通信する自己完結型の web component です(または Query with AI を介して Squid database integration に直接接続することもできます。詳しくは 以下の例 を参照してください)。これは https://widget.squid.cloud/widget.umd.js でホストされる単一の UMD bundle として提供され、Shadow DOM 内に描画されるため、あなたのサイトのスタイルと衝突しません。

2 つの要素バリアント

Element動作
<squid-chat-widget>インラインの chat ブロックです。document 内の配置した場所に描画されます。サイズやレイアウトは自分で制御します。
<squid-chat-widget-with-fab-button>右下に floating action button (FAB) を表示します。クリックすると chat の開閉を切り替えます。

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

chat widget を使うべき場面

Use Case推奨
マーケティングサイトや Web アプリに AI assistant を追加するchat widget
完全にカスタムな chat UI を構築するAI agent SDK を直接使用する
特定の database について質問できる chat を埋め込むsquid-ai-query="true"squid-ai-integration-id を指定した chat widget を使用する
UI なしで programmatic な AI 呼び出しを実行するsquid.ai().agent() または executeAiQuery

Quick Start

Prerequisites

  • Squid Console で作成済みの Squid application
  • application の Agent Studio タブで作成した AI agent
  • agent の ID、Squid app ID、region(いずれも Squid Console の Backend ProjectShow env vars で確認可能)

Step 1: AI agent を作成する

  1. Squid Console で application を開き、Agent Studio タブをクリックします
  2. Create New Agent をクリックします
  3. Agent ID(後から変更不可)と説明を入力します
  4. Create をクリックします

agent を作成したら、Instructions(agent の応答ルール)と Knowledge base 項目(背景コンテキスト)を追加します。Test chat ボタンですぐに agent をテストできます。

注記

Squid には devprod の別々の environment があります。AI agent はそれらの間で共有されません。widget の squid-environment-id 属性が、agent を作成した environment と一致していることを確認してください。詳しくは environments を参照してください。

Step 2: widget script を読み込む

HTML の <head> または <body> に widget script タグを追加します。

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

Step 3: widget を描画する

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_IDus-east-1.awsYOUR_AGENT_ID をあなたの application の値に置き換えてください。

Authentication と Configuration

Public agent と private agent

agent は Agent Studio の Agent Settings(下へスクロールして Public agent)で public または private に設定できます。

  • Public agents は誰でもアクセスできます。widget に auth credentials は不要です。
  • Private agents では auth provider が必要で、Squid が呼び出し元を検証します。

Private agent を保護する

  1. auth provider を Squid に接続します
  2. squid-auth-provider 属性で auth provider の integrationId とユーザーの auth token を渡します。
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. backend で @secureAiAgent ルールを追加して、誰が chat できるかを制御します。
Backend code
@secureAiAgent('chat')
allowAccessToAgent(): boolean {
return this.isAuthenticated();
}
注記

Public agent は @secureAiAgent ルールを完全にバイパスします。auth credentials 自体は AI functions から引き続き利用可能なので、public agent 内でも特定の function 呼び出しを制限できます。詳しくは AI functions を参照してください。

See more

条件付きチェック、agent 単位のルール、Agent API Keys については、Securing AI agents and Agent API Keys を参照してください。

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

framework で custom HTML elements を有効にする

一部の frontend framework では、custom HTML elements を許可するための追加設定が必要です。

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 {}

その他の framework については、custom elements の有効化に関する各 framework のドキュメントを参照してください。

Core Concepts

Connection attributes

これらの属性は、widget がどのように Squid に接続し、どの agent または integration と通信するかを指定します。

AttributeType必須説明
squid-app-idstringはい(squid-ai-custom-api-url を使用する場合を除く)Squid application ID
squid-regionstringはい(squid-ai-custom-api-url を使用する場合を除く)application の AWS region(例: us-east-1.aws
squid-environment-idstringいいえ(デフォルトは proddev または prod。agent が存在する environment と一致している必要があります。
squid-developer-idstringいいえDeveloper ID。backend をローカルで実行している場合にのみ必要です。
squid-api-keystringいいえSquid API key。信頼できる環境でのみ使用し、ユーザー向けページでは決して使用しないでください。
squid-ai-agent-idstringはい(squid-ai-query="true" または squid-ai-custom-api-url を使用する場合を除く)chat する対象の agent ID
squid-ai-profile-idstringいいえ(deprecated)squid-ai-agent-id の古い名前です。deprecation warning が出ます。代わりに squid-ai-agent-id を使用してください。
squid-ai-integration-idstringsquid-ai-query="true" のときは必須Query with AI モード実行時に問い合わせる database integration ID
squid-ai-querybooleanいいえtrue の場合、widget は agent ではなく Query with AI を通じて database integration に対して動作します
squid-auth-providerJSONいいえ{ "integrationId": "...", "token": "..." }。private agent では必須です。
squid-ai-custom-api-urlstringいいえSquid を経由せず、chat request を処理する custom HTTP endpoint
squid-ai-custom-api-headersJSONいいえcustom API URL への request と一緒に送信する追加ヘッダー

Chat behavior attributes

AttributeType説明
squid-ai-functionsstring有効化する AI function 名のカンマ区切りリスト
squid-ai-functions-jsonJSONnamecontextpredefinedParameters を任意で含む function object の配列
squid-ai-temperaturenumber[0, 1] の temperature。低いほど決定的になります。
squid-ai-max-tokensnumberLLM response の最大 token 数
squid-ai-override-modelstringagent が使用する model を上書きします(例: gpt-4o
squid-ai-context-metadata-filterJSONKnowledge base lookup に適用される metadata filter。詳しくは filtering context を参照してください。
squid-ai-instructionsstringこの widget instance 用に agent の system prompt に追加される instructions
squid-ai-connected-agentsJSONagent が委譲可能な connected agents{ agentId, description } 配列
squid-ai-agent-chat-optionsJSON高度な chat options object。以下の Advanced chat options を参照してください。
squid-ai-enable-raw-resultsbooleansquid-ai-query="true" 使用時に、生の query result file を要求します
squid-ai-enable-code-interpreterbooleansquid-ai-query="true" 使用時に、chart と analysis のために Python code interpreter を有効化します
disable-historybooleanmessage 間での会話メモリを無効化します
chain-of-thoughtbooleanagent の reasoning steps(tool calls、queries、function executions)を表示します
show-status-tagsbooleanchain-of-thought の status updates にタグラベルを表示します
observe-statusbooleanbackend からの live status updates を監視します
include-referencebooleanagent responses に source references(citations)を表示します
enable-transcriptionbooleanユーザーが prompt を話して入力できるよう、microphone button を表示します
predefined-promptsstringユーザーに表示する推奨 prompts。カンマ区切り、改行区切り、または JSON-stringified array を指定できます。
enable-debug-logsbooleanbrowser console に debug logs を出力します

Display と customization attributes

AttributeType説明
header-titlestringchat header に表示するタイトル文字列。デフォルトは SquidAI Chat です。
intro-textstringchat を開いたときに最初にユーザーへ表示される message
avatar-image-urlstringAI message の横に表示される avatar image の URL
chat-icon-urlstringfloating action button 用の custom icon
widget-widthstringCSS の width 値(例: 400px
widget-heightstringCSS の height 値(例: 600px
themestringlight または dark。デフォルトは light です。
rtl-modebooleanArabic や Hebrew のような言語向けに right-to-left レイアウトを有効化します
use-maximize-buttonbooleanmaximize/minimize button を表示します。FAB モードでのみ意味があります。
open-on-loadbooleanページ読み込み時に FAB widget を自動で開きます
powered-by-textstring"Powered by Squid" footer text を上書きします
menu-items-jsonJSONcustom menu item を定義する { title, slotName } object の配列です。詳しくは Custom menu items を参照してください。
base-stylesheet-urlstringベース CSS file を上書きします。デフォルトは https://widget.squid.cloud/style.css です。
stylesheet-urlstringbase stylesheet の上に追加で読み込まれる CSS file
error-formatterstring or function'generic-error''original-error'(デフォルト)、または JS function (error) => string

Localization attributes

widget は、組み込み UI 文字列を差し替えるための属性セットを公開しています。

AttributeDefault
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"

Advanced chat options

squid-ai-agent-chat-options は、agent chat options interface に対応する JSON object を受け取ります。代表的な field は次のとおりです。

Field説明
agentContextすべての AI function call に渡される object。詳しくは passing context to AI functions を参照してください。
instructionsこの widget instance 用に agent の system instructions に追加される文字列
contextMetadataFilterForKnowledgeBase使用される Knowledge base entries を制限する object。詳しくは filtering context を参照してください。
functionspredefinedParameters と function ごとの context を任意で含められる function descriptor の配列
memoryOptions会話メモリ設定: memoryId, memoryMode
temperaturesampling temperature
modelこの widget instance が使用する 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>

Custom menu items

menu-items-json は、chat header menu に追加エントリを定義します。各エントリには titleslotName があります。各 slot の内容は、子要素に標準の 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 variables

widget は Shadow DOM 内に描画されます。host element 上で CSS custom properties を設定することで見た目を上書きできます。各 variable は widget のデフォルト theme にフォールバックします。

Variable制御対象
--squid-widget-header-background-colorHeader background
--squid-widget-header-title-colorHeader title text color
--squid-widget-header-menu-button-background-colorMenu button background
--squid-widget-header-menu-button-icon-urlMenu button icon image URL
--squid-widget-header-menu-item-colorMenu item text color
--squid-widget-header-menu-item-hover-background-colorMenu item hover background
--squid-widget-menu-item-back-icon-urlsub-menu 用の Back button icon
--squid-widget-body-background-colorChat body background
--squid-widget-ai-message-background-colorAI message bubble background
--squid-widget-ai-message-text-colorAI message text color
--squid-widget-user-message-background-colorUser message bubble background
--squid-widget-user-message-colorUser message text color
--squid-widget-textarea-background-colorInput textarea background
--squid-widget-textarea-border-colorInput textarea border
--squid-widget-textarea-text-colorInput textarea text color
--squid-widget-textarea-submit-image-urlSubmit button icon image URL
--squid-widget-inline-code-background-colorInline code block background
--squid-widget-inline-code-border-colorInline code block border
--squid-widget-link-colorHyperlink color
--squid-widget-powered-by-color"Powered by" footer text color
--squid-widget-fab-background-colorFAB button background
--squid-widget-fab-image-urlFAB button icon(closed 状態)
--squid-widget-fab-close-image-urlFAB button icon(open 状態)

インライン 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 属性を使って独自の外部 stylesheet ルールを適用することもできます。

events を listen する

widget は、chat history または status updates が変化するたびに change CustomEvent を dispatch します。2 種類の payload 形式がサポートされています。

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 callback prop を渡してください。

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

Code Examples

AI function の parameters を上書きする

特定の parameter を固定し、AI に選ばせたくない場合は、squid-ai-functions-jsonpredefinedParameters を使用します。対応する backend パターンについては、overriding parameter values を参照してください。

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>

agent context を backend functions に渡す

squid-ai-agent-chat-optionsagentContext field を使うと、すべての AI function call が backend で読み取れる値を付与できます。対応する backend パターンは passing context to AI functions に記載されています。

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 を使って database に対して chat する

squid-ai-query="true" を設定し、agent ID の代わりに database 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>

Custom backend webhook

squid-ai-custom-api-url を使うと、chat を独自の backend 経由でルーティングできます。widget はその URL に prompt を POST し、response はあなたが処理します。

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 での programmatic 作成

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);

Error Handling

よくあるエラー

Error原因解決策
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 trueagent ID がなく、query モードでもない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 に変更する
UNAUTHORIZED from the backendprivate agent、auth provider 未設定、または @secureAiAgent により拒否squid-auth-provider を設定し、@secureAiAgent ルールを確認する
Custom HTML element not recognizedframework で custom element の登録が必要Enabling custom HTML elements in your framework を参照してください

問題を診断するときは、enable-debug-logs="true" を使って browser console に追加情報を出力してください。

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

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.';
};

Best Practices

  1. squid-app-idsquid-region は HTML に置き、API key は絶対に置かないでください。 chat widget は browser 上で動作します。squid-api-key に入れたものは、ページを見ている誰にでも見えてしまいます。private agent では、代わりに squid-auth-provider@secureAiAgent を使用してください。
  2. squid-ai-agent-id を使い、squid-ai-profile-id は使わないでください。 後者は deprecated で、warning が出ます。
  3. squid-environment-id を agent の environment と一致させてください。 dev で作成した agent は prod では見えず、その逆も同様です。
  4. agent が public でも backend で security rules を適用してください。 Public agent では @secureAiAgent はスキップされますが、@secureAiQuery と AI function の auth checks は引き続き実行されます。
  5. 開発中は chain-of-thought="true" を設定してください。 agent が何をしているかを正確に確認できます。end user 向けには無効にするか、show-status-tags="false" と組み合わせて使用してください。
  6. CSS overrides は style= にインラインで書くより、自分の stylesheet にキャッシュして使ってください。 そうすることで、複数の widget instance 間で一貫性を保てます。
  7. widget の外で会話履歴を保存したり、product analytics に流し込みたい場合は change events を listen してください。

See Also