AI chat widget
単一の HTML 要素で、フル機能の AI chat 体験をあなたの Web サイトに追加できます。
AI Chat Widget を使う理由
あなたのサイトで、ユーザーが AI agent とチャットできるようにしたいとします。その agent には、あなたのビジネスについての知識があり、セキュリティモデルに従い、ブランドに合った見た目を持ち、さらに理想的には voice input、predefined prompts、chain-of-thought visualization をサポートしてほしいでしょう。
これをゼロから構築する場合、chat UI の実装、streaming の接続、履歴の管理、auth の統合、スタイリングなどが必要になります。Squid AI chat widget は、それらすべてを単一の web component として提供します。
<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 Project → Show env vars で確認可能)
Step 1: AI agent を作成する
- Squid Console で application を開き、Agent Studio タブをクリックします
- Create New Agent をクリックします
- Agent ID(後から変更不可)と説明を入力します
- Create をクリックします
agent を作成したら、Instructions(agent の応答ルール)と Knowledge base 項目(背景コンテキスト)を追加します。Test chat ボタンですぐに agent をテストできます。
Squid には dev と prod の別々の environment があります。AI agent はそれらの間で共有されません。widget の squid-environment-id 属性が、agent を作成した environment と一致していることを確認してください。詳しくは environments を参照してください。
Step 2: widget script を読み込む
HTML の <head> または <body> に widget script タグを追加します。
<script async src="https://widget.squid.cloud/widget.umd.js"></script>
Step 3: widget を描画する
<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 をあなたの 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 を保護する
- auth provider を Squid に接続します
squid-auth-provider属性で auth provider のintegrationIdとユーザーの auth token を渡します。
<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>
- backend で
@secureAiAgentルールを追加して、誰が chat できるかを制御します。
- TypeScript
- Python
@secureAiAgent('chat')
allowAccessToAgent(): boolean {
return this.isAuthenticated();
}
@secure_ai_agent('chat')
def allow_access_to_agent(self) -> bool:
return self.is_authenticated()
Public agent は @secureAiAgent ルールを完全にバイパスします。auth credentials 自体は AI functions から引き続き利用可能なので、public agent 内でも特定の function 呼び出しを制限できます。詳しくは AI functions を参照してください。
条件付きチェック、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):
declare namespace JSX {
interface IntrinsicElements {
'squid-chat-widget': any;
'squid-chat-widget-with-fab-button': any;
}
}
Angular (src/app/app.module.ts):
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 と通信するかを指定します。
| Attribute | Type | 必須 | 説明 |
|---|---|---|---|
squid-app-id | string | はい(squid-ai-custom-api-url を使用する場合を除く) | Squid application ID |
squid-region | string | はい(squid-ai-custom-api-url を使用する場合を除く) | application の AWS region(例: us-east-1.aws) |
squid-environment-id | string | いいえ(デフォルトは prod) | dev または prod。agent が存在する environment と一致している必要があります。 |
squid-developer-id | string | いいえ | Developer ID。backend をローカルで実行している場合にのみ必要です。 |
squid-api-key | string | いいえ | Squid API key。信頼できる環境でのみ使用し、ユーザー向けページでは決して使用しないでください。 |
squid-ai-agent-id | string | はい(squid-ai-query="true" または squid-ai-custom-api-url を使用する場合を除く) | chat する対象の agent ID |
squid-ai-profile-id | string | いいえ(deprecated) | squid-ai-agent-id の古い名前です。deprecation warning が出ます。代わりに squid-ai-agent-id を使用してください。 |
squid-ai-integration-id | string | squid-ai-query="true" のときは必須 | Query with AI モード実行時に問い合わせる database integration ID |
squid-ai-query | boolean | いいえ | true の場合、widget は agent ではなく Query with AI を通じて database integration に対して動作します |
squid-auth-provider | JSON | いいえ | { "integrationId": "...", "token": "..." }。private agent では必須です。 |
squid-ai-custom-api-url | string | いいえ | Squid を経由せず、chat request を処理する custom HTTP endpoint |
squid-ai-custom-api-headers | JSON | いいえ | custom API URL への request と一緒に送信する追加ヘッダー |
Chat behavior attributes
| Attribute | Type | 説明 |
|---|---|---|
squid-ai-functions | string | 有効化する AI function 名のカンマ区切りリスト |
squid-ai-functions-json | JSON | name、context、predefinedParameters を任意で含む function object の配列 |
squid-ai-temperature | number | [0, 1] の temperature。低いほど決定的になります。 |
squid-ai-max-tokens | number | LLM response の最大 token 数 |
squid-ai-override-model | string | agent が使用する model を上書きします(例: gpt-4o) |
squid-ai-context-metadata-filter | JSON | Knowledge base lookup に適用される metadata filter。詳しくは filtering context を参照してください。 |
squid-ai-instructions | string | この widget instance 用に agent の system prompt に追加される instructions |
squid-ai-connected-agents | JSON | agent が委譲可能な connected agents の { agentId, description } 配列 |
squid-ai-agent-chat-options | JSON | 高度な chat options object。以下の Advanced chat options を参照してください。 |
squid-ai-enable-raw-results | boolean | squid-ai-query="true" 使用時に、生の query result file を要求します |
squid-ai-enable-code-interpreter | boolean | squid-ai-query="true" 使用時に、chart と analysis のために Python code interpreter を有効化します |
disable-history | boolean | message 間での会話メモリを無効化します |
chain-of-thought | boolean | agent の reasoning steps(tool calls、queries、function executions)を表示します |
show-status-tags | boolean | chain-of-thought の status updates にタグラベルを表示します |
observe-status | boolean | backend からの live status updates を監視します |
include-reference | boolean | agent responses に source references(citations)を表示します |
enable-transcription | boolean | ユーザーが prompt を話して入力できるよう、microphone button を表示します |
predefined-prompts | string | ユーザーに表示する推奨 prompts。カンマ区切り、改行区切り、または JSON-stringified array を指定できます。 |
enable-debug-logs | boolean | browser console に debug logs を出力します |
Display と customization attributes
| Attribute | Type | 説明 |
|---|---|---|
header-title | string | chat header に表示するタイトル文字列。デフォルトは SquidAI Chat です。 |
intro-text | string | chat を開いたときに最初にユーザーへ表示される message |
avatar-image-url | string | AI message の横に表示される avatar image の URL |
chat-icon-url | string | floating action button 用の custom icon |
widget-width | string | CSS の width 値(例: 400px) |
widget-height | string | CSS の height 値(例: 600px) |
theme | string | light または dark。デフォルトは light です。 |
rtl-mode | boolean | Arabic や Hebrew のような言語向けに right-to-left レイアウトを有効化します |
use-maximize-button | boolean | maximize/minimize button を表示します。FAB モードでのみ意味があります。 |
open-on-load | boolean | ページ読み込み時に FAB widget を自動で開きます |
powered-by-text | string | "Powered by Squid" footer text を上書きします |
menu-items-json | JSON | custom menu item を定義する { title, slotName } object の配列です。詳しくは Custom menu items を参照してください。 |
base-stylesheet-url | string | ベース CSS file を上書きします。デフォルトは https://widget.squid.cloud/style.css です。 |
stylesheet-url | string | base stylesheet の上に追加で読み込まれる CSS file |
error-formatter | string or function | 'generic-error'、'original-error'(デフォルト)、または JS function (error) => string |
Localization attributes
widget は、組み込み UI 文字列を差し替えるための属性セットを公開しています。
| Attribute | Default |
|---|---|
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 を参照してください。 |
functions | predefinedParameters と function ごとの context を任意で含められる function descriptor の配列 |
memoryOptions | 会話メモリ設定: memoryId, memoryMode |
temperature | sampling temperature |
model | この widget instance が使用する model を上書きします |
例:
<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 に追加エントリを定義します。各エントリには title と slotName があります。各 slot の内容は、子要素に標準の slot= 属性を使って指定してください。
<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-color | Header background |
--squid-widget-header-title-color | Header title text color |
--squid-widget-header-menu-button-background-color | Menu button background |
--squid-widget-header-menu-button-icon-url | Menu button icon image URL |
--squid-widget-header-menu-item-color | Menu item text color |
--squid-widget-header-menu-item-hover-background-color | Menu item hover background |
--squid-widget-menu-item-back-icon-url | sub-menu 用の Back button icon |
--squid-widget-body-background-color | Chat body background |
--squid-widget-ai-message-background-color | AI message bubble background |
--squid-widget-ai-message-text-color | AI message text color |
--squid-widget-user-message-background-color | User message bubble background |
--squid-widget-user-message-color | User message text color |
--squid-widget-textarea-background-color | Input textarea background |
--squid-widget-textarea-border-color | Input textarea border |
--squid-widget-textarea-text-color | Input textarea text color |
--squid-widget-textarea-submit-image-url | Submit button icon image URL |
--squid-widget-inline-code-background-color | Inline code block background |
--squid-widget-inline-code-border-color | Inline code block border |
--squid-widget-link-color | Hyperlink color |
--squid-widget-powered-by-color | "Powered by" footer text color |
--squid-widget-fab-background-color | FAB button background |
--squid-widget-fab-image-url | FAB button icon(closed 状態) |
--squid-widget-fab-close-image-url | FAB button icon(open 状態) |
インライン style を使う例:
<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 形式がサポートされています。
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 を渡してください。
<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-json で predefinedParameters を使用します。対応する backend パターンについては、overriding parameter values を参照してください。
<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-options の agentContext field を使うと、すべての AI function call が backend で読み取れる値を付与できます。対応する backend パターンは passing context to AI functions に記載されています。
<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 を参照してください。
<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 はあなたが処理します。
<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>
- TypeScript
- Python
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}` };
}
}
from squidcloud_backend import SquidService, WebhookRequest, WebhookResponse, webhook
class ChatService(SquidService):
@webhook('chat')
async def chat(self, request: WebhookRequest) -> WebhookResponse:
user_prompt = request['body']['prompt']
project_id = request.get('queryParams', {}).get('projectId')
# Custom logic to handle the user prompt and project ID.
return self.create_webhook_response(body={'response': f'Echo: {user_prompt}'})
JavaScript での programmatic 作成
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 specified | squid-app-id 属性が不足している | squid-app-id を追加する(または squid-ai-custom-api-url を使用する) |
squid-region must be specified | squid-region 属性が不足している | squid-region を追加する |
squid-ai-agent-id must be specified or squid-ai-query must be true | agent 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-query | squid-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 backend | private agent、auth provider 未設定、または @secureAiAgent により拒否 | squid-auth-provider を設定し、@secureAiAgent ルールを確認する |
| Custom HTML element not recognized | framework で custom element の登録が必要 | Enabling custom HTML elements in your framework を参照してください |
問題を診断するときは、enable-debug-logs="true" を使って browser console に追加情報を出力してください。
エラー表示をカスタマイズする
error-formatter を使うと、エラーをユーザーにどう表示するかを制御できます。組み込みの値は 'generic-error'(共通の単一メッセージ)と 'original-error'(実際のエラーメッセージ、デフォルト)です。function を渡すこともできます。
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
squid-app-idとsquid-regionは HTML に置き、API key は絶対に置かないでください。 chat widget は browser 上で動作します。squid-api-keyに入れたものは、ページを見ている誰にでも見えてしまいます。private agent では、代わりにsquid-auth-providerと@secureAiAgentを使用してください。squid-ai-agent-idを使い、squid-ai-profile-idは使わないでください。 後者は deprecated で、warning が出ます。squid-environment-idを agent の environment と一致させてください。devで作成した agent はprodでは見えず、その逆も同様です。- agent が public でも backend で security rules を適用してください。 Public agent では
@secureAiAgentはスキップされますが、@secureAiQueryと AI function の auth checks は引き続き実行されます。 - 開発中は
chain-of-thought="true"を設定してください。 agent が何をしているかを正確に確認できます。end user 向けには無効にするか、show-status-tags="false"と組み合わせて使用してください。 - CSS overrides は
style=にインラインで書くより、自分の stylesheet にキャッシュして使ってください。 そうすることで、複数の widget instance 間で一貫性を保てます。 - widget の外で会話履歴を保存したり、product analytics に流し込みたい場合は
changeevents を listen してください。
See Also
- AI agent - widget が接続する agent を作成・設定する
- AI functions - 会話中に agent が呼び出せる backend functions
- Query with AI - widget を使って database に質問する
- Authentication - private agents 向けに auth provider を接続する
- Building a vacation packing planner using an AI agent - エンドツーエンドのチュートリアル
- Creating a Squid expert using a Squid AI Agent
- Securing your AI agent