AIエージェントの構築方法
Squidのclient SDKを使用して、永続的な指示、ナレッジベース、接続されたツール、マルチエージェントのワークフローを備えたカスタムAIエージェントを構築します。
なぜSquidでAIエージェントを構築するのか
アプリにAI機能を追加するには通常、LLM API、コンテキスト取得用のベクターデータベース、tool-callingロジック、会話メモリ、セキュリティルールをつなぎ合わせる必要があります。各要素ごとに個別の統合作業が必要です。
Squidはこれらすべてを統合されたプラットフォームで扱います。指示と能力を持つエージェントを定義し、データソースやツールに接続し、単一のSDKを通じて対話します。Squidがpromptの構築、コンテキスト取得、メモリ、オーケストレーションを管理するため、あなたは作りたい体験に集中できます。
仕組み
内部的には、エージェントはLarge Language Model (LLM) を使用してユーザーの質問への回答を生成します。ユーザーが質問すると、永続的な指示と最も関連性の高いコンテキストがpromptの一部としてLLMに渡され、ユーザーにコンテキスト化された回答を提供します。
SquidではAIエージェントに使用するLLMを選べるため、ユースケースに最適なものを選択できます。以下のLLMプロバイダーが標準で利用可能です。
また、AI connector を追加することで追加プロバイダーにも接続できます。これにより、セルフホストモデル(例: Ollama、vLLM)、AWS Bedrockモデル、またはその他のOpenAI互換エンドポイントを利用できます。
エージェントの構築
エージェントは、AIワークフローにおける明確な性格(persona)または設定を表します。各エージェントは、それぞれ独自の指示と能力によって区別される別のpersona/ユースケースのようなものです。この設計により、特定のエージェントに応じてAIからの応答をカスタマイズできます。
以下の例は、SquidのSDKを使用してエージェントを作成する方法を示しています。SquidプラットフォームとSDKを使った開発に不慣れな場合は、フルスタック開発に関するドキュメントをご覧ください。
エージェントのUpsert
AIエージェントをプログラムで作成または更新するには、upsert() メソッドを使用し、作成または更新するagent IDを指定します。
await squid
.ai()
.agent('banking-copilot')
.upsert({
options: {
model: 'gpt-5.5',
},
isPublic: true,
});
エージェントを挿入する際は、エージェントが使用するモデルを示す model フィールドを持つ options オブジェクトを渡します。
isPublic パラメータは、指定したエージェントのチャット機能に、security rules を設定せずにアクセスできるかどうかを決定します。
エージェントの削除
既存のエージェントを削除するには、delete() メソッドを使用します。
await squid.ai().agent('banking-copilot').delete();
この関数は、指定されたagent IDに対応するエージェントが存在しない場合にエラーになります。
モデルの更新
エージェントが使用するLLMモデルを変更するには、updateModel() を呼び出します。
await squid.ai().agent('banking-copilot').updateModel('claude-sonnet-4-6');
モデルはベンダーのモデル名(例: 'gpt-5.5'、'claude-sonnet-4-6'、'gemini-3.5-flash')または、Ollama、AWS Bedrock、任意のOpenAI互換エンドポイントなど追加プロバイダー向けのintegration-based model にできます。
await squid.ai().agent('banking-copilot').updateModel({
integrationId: 'my-ollama',
model: 'llama3',
});
また、'claude-code' や 'codex' などの CLI agent model を選択して、長時間実行されるツール駆動の agentic な ask を実行することもできます。
また、ask() または chat() 呼び出し時に model オプションを使ってリクエスト単位でモデルを上書きすることもできます。詳細は Ask Options を参照してください。
エージェントとリソースの一覧取得
squid.ai() client は、アプリに定義されたすべてのリソースを取得するためのディスカバリーメソッドを公開しています。
| TypeScript | Python | Returns |
|---|---|---|
listAgents() | list_agents() | すべてのエージェントとその設定 |
listKnowledgeBases() | list_knowledge_bases() | すべてのKnowledge Base |
listChatModels() | list_chat_models() | 利用可能なチャットモデル。非推奨のベンダーモデルを含めるには includeDeprecated: true を渡します。 |
listFunctions() | list_functions() | 登録済みの AI functions |
- TypeScript
- Python
const agents = await squid.ai().listAgents();
const models = await squid.ai().listChatModels({ includeDeprecated: false });
agents = await squid.ai().list_agents()
models = await squid.ai().list_chat_models(include_deprecated=False)
各メソッドは、次の内容を持つレコードの配列を返します。
- Agents(
AiAgent):id、createdAt、updatedAt、description、isPublic、auditLog、およびoptions(モデルや、接続された Knowledge Base、integrations、functions を含むエージェントの完全な設定)。 - Knowledge bases(
AiKnowledgeBase):id、name、description、embeddingModel、chatModel、metadataFields、createdAt、updatedAt。connector の同期によって作成された Knowledge Base には、追加の同期管理フィールドが含まれる場合があります。 - Chat models(
ModelIdSpec):modelId(model selection として渡す文字列)、displayName、description、source('vendor'、'connector'、'custom'のいずれか)。integration ベースのモデルにはintegrationIdが含まれ、非推奨のモデルには、呼び出しのルーティング先となるアクティブなモデルを示すreplacedByが含まれます。 - AI functions(
AiFunctionMetadata):serviceFunction(ServiceName:functionName)、description、params(それぞれname、type、description、requiredを持つ)。connector が提供する functions にはattributes.integrationTypeが含まれ、internalフラグが付いたエントリは直接の使用を意図していません。
エージェント説明の設定
エージェントの人間が読める説明を設定または更新するには、setAgentDescription() メソッドを使用します。これは説明だけを更新し、他のエージェント設定には影響しません。
await squid
.ai()
.agent('banking-copilot')
.setAgentDescription('Assists customer support staff with banking and finance questions');
代わりに upsert() を使用して、説明を他のすべてのエージェント値と一緒に1回の呼び出しで設定することもできます。なお、upsert() はエージェント設定全体を置き換えるため、含めなかったフィールドはクリアされます。
Instructions
Instructionsは、エージェントがpromptに どのように 反応し、質問に答えるかのルールを設定します。指示は率直かつシンプルにし、エージェントの目的を説明してください。Instructionsはテキストブロックとして提供されます。
Instructionsの追加
AIエージェントにInstructionsを追加または編集するには、updateInstructions() メソッドを使用し、指示データを文字列として渡します。
const instruction = 'You are a helpful copilot that assists customer support staff by providing answers to their questions about banking and finance products.';
await squid.ai().agent('banking-copilot').updateInstructions(instruction);
Connected Knowledge Bases
Knowledge Baseは、エージェントが質問に答える際に参照する検索可能なContextを保存します。Knowledge Baseの作成、およびContextとmetadataの管理については、Knowledge Baseのドキュメント を参照してください。
Knowledge Baseをエージェントに接続する
setAgentOptionInPath() を使用して、他のエージェント設定に影響を与えずに、エージェントに1つ以上のKnowledge Baseへのアクセス権を付与します。description は、各Knowledge Baseを参照すべきタイミングをエージェントに伝えます。
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', [
{
knowledgeBaseId: 'banking-knowledgebase',
description: 'Use for information on credit cards',
},
]);
すべてのKnowledge Baseを切断するには、空配列を渡します。
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', []);
また、upsert() を使用して、接続されたKnowledge Baseを他のすべてのエージェント値と一緒に1回の呼び出しで設定することもできます。なお、upsert() はエージェント設定全体を置き換えるため、含めなかったフィールドはクリアされます。
接続する各Knowledge Baseエントリは、次のフィールドをサポートします。
| Field | Type | Required | Description |
|---|---|---|---|
knowledgeBaseId | string | Yes | 接続するKnowledge Base |
description | string | Yes | このKnowledge Baseをいつ参照すべきかをエージェントに伝えます |
includeMetadata | boolean | No | エージェントに提供される検索結果にドキュメントmetadataを含めます。省略した場合は非推奨のask単位 includeMetadata オプション(デフォルトは true)にフォールバックします。metadataを除外するには明示的に false を設定してください。 |
enableMetadataInspection | boolean | No | このKnowledge Baseのmetadataフィールド値を列挙・検索するツールをエージェントに与えます。デフォルトは false。詳細は agent-driven metadata filtering を参照してください。 |
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', [
{
knowledgeBaseId: 'banking-knowledgebase',
description: 'Use for information on credit cards',
includeMetadata: true,
enableMetadataInspection: true,
},
]);
ask単位の includeMetadata オプションも引き続き動作しますが、Knowledge Baseごとのフラグの使用が推奨され、非推奨(deprecated)となっています。
エージェントとの対話
エージェントを作成したら、質問をしたりpromptを与えたりする準備が整いました。
ask() で完全な応答を取得する
ask() メソッドを使用してpromptを送信し、完全な応答を文字列として受け取ります。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Which credit card is best for students?');
注釈付きで応答を取得する
askWithAnnotations() を使用すると、応答に加えてファイル注釈(例: 生成された画像やドキュメント)も受け取れます。
const { responseString, annotations } = await squid
.ai()
.agent('banking-copilot')
.askWithAnnotations('Generate a comparison chart of our credit cards');
chat() で応答をストリーミングする
chat() メソッドを使用して、応答をtokenごとにストリーミングします。これは各token到着時に蓄積された応答をemitするRxJSの Observable<string> を返し、UIでリアルタイム応答を表示するのに理想的です。
import { Subscription } from 'rxjs';
const stream = squid
.ai()
.agent('banking-copilot')
.chat('Which credit card is best for students?');
const subscription: Subscription = stream.subscribe({
next: (accumulatedResponse) => {
// Each emission contains the full response so far
console.log(accumulatedResponse);
},
complete: () => {
console.log('Response complete');
},
error: (err) => {
console.error('Error:', err);
},
});
chat() メソッドは ask() と同じoptions(voiceOptions を除く)を受け取り、さらに各token間にわずかな遅延を入れて自然なタイピング効果を加える smoothTyping オプション(デフォルトは true)を追加で受け取ります。
Ask Options
ask() と chat() の両方は、リクエストを設定するための任意の options パラメータを受け取ります。利用可能なoptionsとデフォルト値の完全な一覧は、API reference documentation を参照してください。
await squid.ai().agent('banking-copilot').ask('Which credit card is best for students?', {
maxOutputTokens: 4096,
temperature: 0.7,
model: 'claude-sonnet-4-6',
});
MemoryとChat History
デフォルトでは、エージェントはsession内の以前のメッセージを記憶します。memoryOptions を使用してこの挙動を制御します。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What did I ask earlier?', {
memoryOptions: {
memoryMode: 'read-write', // 'none' | 'read-only' | 'read-write'
memoryId: 'user-123-session', // Unique ID for this conversation
expirationMinutes: 60, // How long to keep the history
},
});
'none': 履歴を使用しません。各promptは独立して回答されます。'read-only': エージェントは過去メッセージを参照できますが、新しいメッセージは保存しません。'read-write': エージェントは履歴の読み書きを行います(デフォルト動作)。
memoryId は会話を識別します。リクエスト間で同じ memoryId を使用すると同一の会話が継続されます。memory IDはチャット履歴へのアクセスを付与するため、access tokenと同程度のセキュリティで扱ってください。
特定の会話の過去メッセージを取得するには、getChatHistory() を使用します。
const messages = await squid
.ai()
.agent('banking-copilot')
.getChatHistory('user-123-session');
Response Format
responseFormat を使用して、エージェントの応答形式を制御します。
// Get a JSON response
const json = await squid
.ai()
.agent('banking-copilot')
.ask('List our credit cards with their fees', {
responseFormat: 'json_object',
});
// Get a response that strictly conforms to a JSON schema (Anthropic models)
const structured = await squid
.ai()
.agent('banking-copilot')
.ask('Analyze the sentiment of this review', {
model: 'claude-sonnet-4-6',
responseFormat: {
type: 'json_schema',
schema: {
type: 'object',
properties: {
sentiment: { type: 'string', enum: ['positive', 'negative', 'neutral'] },
confidence: { type: 'number' },
},
required: ['sentiment', 'confidence'],
},
},
});
利用可能な形式:
'text'(デフォルト): プレーンテキスト応答。'json_object': モデルは有効なJSONを返そうとします。{ type: 'json_schema', schema: ... }: 提供されたJSON schemaに応答が適合することを保証するstructured output。現在Anthropicモデルでサポートされています。
promptにファイルを含める
fileUrls を使用して、promptの一部として画像やドキュメントを渡します。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What does this document say?', {
fileUrls: [
{
id: 'doc-1',
type: 'document',
purpose: 'context',
url: 'https://example.com/statement.pdf',
description: 'Customer bank statement',
},
],
});
各file URLには id(リクエスト内で一意)、type('image' または 'document')、そして purpose が必要です。
'context': ファイルはAIが参照できるようpromptに直接含められます。'tools': ファイルはtool/function call結果の一部として返されます。
リクエスト単位でモデルを上書きする
1回のリクエストに限って、エージェントのデフォルトモデルを上書きします。
const response = await squid.ai().agent('banking-copilot').ask('Summarize this data', {
model: 'gpt-5.5',
});
追加オプション
| Option | Type | Default | Description |
|---|---|---|---|
maxTokens | number | Model max | Squidがモデルへ送信できる最大入力tokens |
maxOutputTokens | number | - | モデルが生成すべき最大tokens |
temperature | number | 0.5 | Sampling temperature (0-1) |
timeoutMs | number | 240000 | リクエストタイムアウト(ミリ秒) |
instructions | string | - | エージェントのデフォルトInstructionsに追記される追加指示 |
guardrails | object | - | リクエスト単位でguardrail settingsを上書き |
disableContext | boolean | false | このリクエストではKnowledge Base contextをスキップ |
includeReference | boolean | false | 応答にsource referencesを含める |
reasoningEffort | string | - | 'minimal', 'low', 'medium', または 'high'(reasoning models向け) |
useCodeInterpreter | string | 'none' | Pythonコード実行を有効化するには 'llm'(OpenAIとGeminiのみ) |
executionPlanOptions | object | - | エージェントがplan before actingできるようにする |
MetadataでContextをフィルタリングする
Contextにmetadataを追加した場合、contextMetadataFilterForKnowledgeBase chat optionを使用して、AIエージェントが特定のContextのみを参照するように指示できます。フィルター要件を満たすContextのみが、クライアントpromptへの応答に使用されます。
次の例は、metadata値 "company" が "Bank of America" に等しいものだけを含むようにContextをフィルタリングします。
await squid
.ai()
.agent('banking-copilot')
.ask('Which Bank of America credit card is best for students?', {
contextMetadataFilterForKnowledgeBase: {
['banking-knowledgebase']: { company: { $eq: 'Bank of America' } },
},
});
サポートされるフィルター演算子の一覧、$and と $or によるフィルターの組み合わせ、およびエージェント自身によるフィルター構築については、MetadataでKnowledge Base Contextをフィルタリングする を参照してください。
AI Functions
Squid AI Agentsは、AI functions を使用して特定のユースケースに対応し、より一貫した応答を作成できます。
エージェントにFunctionsを追加する
setAgentOptionInPath() を使用してAI functionsをエージェントにアタッチできます。これは他のエージェント設定に影響を与えず、functionリストのみを更新します。
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('functions', ['getCreditLimit']);
functionリストを更新するには、新しいfunctionセットで setAgentOptionInPath() を再度呼び出します。空配列を渡すとすべてのfunctionsが削除されます。upsert() を使用してfunctionsを他のすべてのエージェント値と一緒に1回の呼び出しで設定することもできますが、upsert() はエージェント設定全体を置き換える点に注意してください。
Ask時にFunctionsを渡す
代わりに、リクエスト単位で functions オプションを使用してAI function名を渡すこともできます。これはそのリクエストに限り、エージェントに保存されているfunctionリストを上書きします。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What is my current credit limit?', {
functions: ['getCreditLimit', 'getAccountBalance'],
});
AI functionsについて詳しくは、ドキュメント を参照してください。AI functionsを使用したアプリ例については、このAI agent tutorial を確認してください。
Connected Agents
エージェントはタスクを他のエージェントに委譲でき、マルチエージェントのワークフローを実現します。Connected agentは呼び出し可能なtoolとして親エージェントに表示され、ユーザーの要求の一部を処理するのにサブエージェントが最適だと判断した場合に親が呼び出します。
Connected Agentsの設定
updateConnectedAgents() を使用して、このエージェントに接続されたエージェントのリストを設定します。description は、各connected agentにいつ委譲するかを親エージェントに伝えます。
await squid
.ai()
.agent('banking-copilot')
.updateConnectedAgents([
{
agentId: 'fraud-detection-agent',
description: 'Call this agent when the user asks about suspicious transactions or potential fraud',
},
]);
すべてのエージェントを切断するには、空配列を渡します。
await squid.ai().agent('banking-copilot').updateConnectedAgents([]);
Ask時にConnected Agentsを渡す
リクエスト単位でconnected agentsを指定して、保存済み設定を上書きすることもできます。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Is this transaction suspicious?', {
connectedAgents: [
{
agentId: 'fraud-detection-agent',
description: 'Call this agent for fraud analysis',
},
{
agentId: 'compliance-agent',
description: 'Call this agent for regulatory compliance checks',
},
],
});
デフォルトでは、ネストしたエージェント呼び出しは最大5階層まで再帰できます。quotas オプションで調整できます。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Analyze this portfolio', {
quotas: { maxAiCallStackSize: 3 },
});
Connected Integrations
エージェントはデータソースや外部サービスに接続でき、promptへの回答の一部としてデータベースへのクエリ、API呼び出し、SaaSツールとの連携が可能です。
Connected Integrationsの設定
setAgentOptionInPath() を使用して、他のエージェント設定に影響を与えずに、エージェントにconnectorへのアクセス権を付与します。
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedIntegrations', [
{
integrationId: 'my-postgres',
integrationType: 'postgres',
description: 'Use this database to look up customer account information',
},
]);
description は、このintegrationをいつ使うべきかをエージェントが理解するのに役立ちます。integrationType は Squid Console で設定したconnectorのtypeと一致している必要があります。
すべてのintegrationを切断するには、空配列で setAgentOptionInPath() を呼び出します。また、upsert() を使用してconnected integrationsを他のすべてのエージェント値と一緒に1回の呼び出しで設定することもできますが、upsert() はエージェント設定全体を置き換える点に注意してください。
Ask時にConnected Integrationsを渡す
Connected agentsと同様に、integrationsもリクエスト単位で指定できます。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What are my recent transactions?', {
connectedIntegrations: [
{
integrationId: 'my-postgres',
integrationType: 'postgres',
description: 'Customer transaction database',
},
],
});
Execution Planning
複数のtool、connected agents、またはintegrationsを含む複雑なタスクでは、execution planningを有効にできます。有効にすると、エージェントは実行前に取るべきアクションの計画を作成してから実行します。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Compare our credit card offerings with competitor rates', {
executionPlanOptions: {
enabled: true,
reasoningEffort: 'high', // 'minimal' | 'low' | 'medium' | 'high'
allowClarificationQuestions: true, // Let the agent ask follow-up questions
},
});
任意で、planningステップに別モデルを指定するために executionPlanOptions 内の model フィールドを使用できます。
ステータス更新の観測
エージェントがtool calls、connected agents、またはintegrationsを含む複雑なリクエストを処理する際、WebSocketを介してリアルタイムのステータス更新を観測できます。
const statusUpdates = squid.ai().agent('banking-copilot').observeStatusUpdates();
statusUpdates.subscribe({
next: (status) => {
console.log(`[${status.title}] ${status.body}`);
},
});
返されるObservableは、エージェントが行う各ステップを説明する title と body フィールドを持つ AiStatusMessage オブジェクトをemitします。
observeStatusUpdates() は optional な job ID も受け取ります。observeStatusUpdates(jobId) はその特定の request の更新のみを emit するため、CLI agent model の実行など、単一の長時間実行される ask を追跡する場合に便利です。引数なしの場合は、エージェントのすべての status updates を emit します。
Agent Revisions
エージェントの設定に対するすべての変更は、自動的に revision として記録されます。エージェントの作成は created revision を記録し、各更新(upsert()、updateModel()、updateInstructions()、setAgentOptionInPath() を含む)は updated を記録し、エージェントの削除は最後の状態を保存する最終的な deleted revision を記録します。設定は不要です。
Revisionsの一覧取得
listRevisions() を使用して、エージェントの完全な履歴を新しい順で取得します。
- TypeScript
- Python
const { revisions } = await squid.ai().agent('banking-copilot').listRevisions();
console.log(revisions[0].revisionNumber, revisions[0].action);
revisions = await squid.ai().agent('banking-copilot').list_revisions()
print(revisions[0]['revisionNumber'], revisions[0]['action'])
各 revision には次が含まれます。
| Field | Type | Description |
|---|---|---|
agentId | string | この revision が属するエージェント |
revisionNumber | number | 変更ごとにインクリメントされる連番 |
action | 'created' | 'updated' | 'deleted' | この revision のトリガーとなった変更 |
createdAt | Date | revision が記録された日時 |
agentSnapshot | AiAgent | revision 時点でのエージェント設定全体のスナップショット |
個別の変更説明はありません。何が変わったかを確認するには、連続するスナップショットを比較してください(Squid Console はこれを自動で行います)。
Revisionsの復元と削除
restoreRevision() でエージェントを以前の revision に復元します。
- TypeScript
- Python
await squid.ai().agent('banking-copilot').restoreRevision(3);
await squid.ai().agent('banking-copilot').restore_revision(3)
復元は非破壊的です。まず現在の状態が新しい revision として保存され、その後エージェントの設定がスナップショットで置き換えられます。履歴は増える一方なので、復元自体を取り消すこともできます。deleted の revision は復元できません。
単一の revision を完全に削除するには deleteRevision() を使用します。
- TypeScript
- Python
await squid.ai().agent('banking-copilot').deleteRevision(3);
await squid.ai().agent('banking-copilot').delete_revision(3)
メソッドの完全なシグネチャは、TypeScript および Python のリファレンスドキュメントを参照してください。
revisions は視覚的に確認することもできます。Squid Console のエージェントページにある Revisions タブには、各 revision で何が変わったかが表示され、復元と削除のアクションが用意されています。
Audit Log
設定の revisions とは別に、各エージェントは呼び出しのランタイム audit log を保持します。ユーザーの prompt、tool や integration の呼び出し、Knowledge Base の検索、最終的な応答、token 使用量が記録されます。
ログの記録はエージェントの auditLog フィールドで制御され、新規エージェントではデフォルトで有効です。console で切り替えるか、upsert() に含めて切り替えます。
- TypeScript
- Python
await squid.ai().agent('banking-copilot').upsert({
options: { model: 'gpt-5.5' },
isPublic: true,
auditLog: false,
});
await squid.ai().agent('banking-copilot').upsert(
is_public=True,
audit_log=False,
options={'model': 'gpt-5.5'},
)
ログの閲覧は console の機能です。Squid Console のエージェントページで Audit Log タブを開いてください。ログのエントリは SDK からは公開されていません。
エラーハンドリング
よくあるエラー
| Error | Cause | Solution |
|---|---|---|
| Agent not found | 存在しないagent IDに対して delete()、get() などを呼び出している | まず get() を呼び出してagent IDが存在することを確認するか、upsert() で作成されることを保証する |
| Context not found | 存在しないcontext IDで deleteContext() または getContext() を呼び出している | 削除または取得の前に listContexts() を使ってcontext IDを確認する |
| Request timeout | エージェントが設定された timeoutMs(デフォルト: 4分)より長くかかっている | optionsで timeoutMs を増やす、promptを単純化する、接続されたtoolsの数を減らす |
| Embedding model cannot be modified | 既存のKnowledge Baseで embeddingModel を変更しようとしている | 代わりに、目的のembedding modelで新しいKnowledge Baseを作成する |
ストリーミングでのエラーハンドリング
chat() を使用する場合、エラーはObservableのerror callbackで通知されます。
const stream = squid.ai().agent('banking-copilot').chat('Analyze this data');
stream.subscribe({
next: (response) => console.log(response),
error: (err) => {
console.error('Agent error:', err.message);
},
complete: () => console.log('Done'),
});
ベストプラクティス
Instructions
- Instructionsは簡潔かつ直接的に保ちます。エージェントの役割と、すべきこと(すべきでないこと)を説明してください。
- 事実情報ではなく行動ルール(トーン、スコープ、応答スタイル)にInstructionsを使ってください。事実情報はKnowledge Baseに入れます。
- デプロイ前に、Agent Studioの Test chat 機能を使用してInstructionsの変更をテストしてください。
Knowledge Bases
- Knowledge Baseを接続する際は、説明的な
description値を使用してください。descriptionは、特に複数接続されている場合に、エージェントが参照すべきKnowledge Baseを判断する方法です。
Knowledge Baseのコンテンツとmetadataの構成に関するガイダンスは、Knowledge Baseのベストプラクティス を参照してください。
マルチエージェントワークフロー
- 各connected agentには明確で具体的なdescriptionを付けてください。曖昧なdescriptionは誤った委譲につながります。
- エージェント間で暴走する再帰呼び出しを避けるため、
quotas.maxAiCallStackSizeを妥当な上限に設定してください。 - 複雑な複数ステップのタスクでは
executionPlanOptionsを使用し、エージェントが実行前にアプローチを推論できるようにします。
パフォーマンス
- 体感速度が重要なユーザー向けのやり取りには
chat()を使用してください。ストリーミングは完全な応答を待つのではなく、到着したtokenを表示します。 - リクエストでKnowledge Base contextが不要な場合は
disableContext: trueを設定してレイテンシを削減します。 - 会話履歴が不要なステートレスな単発リクエストには
memoryOptions.memoryMode: 'none'を使用します。
エージェントのセキュリティ確保
Squid Client SDKを使用してエージェントを作成しチャットを有効にする際、データの保護は極めて重要です。AIエージェントおよびそれらとのチャットには機密情報が含まれる可能性があるため、不正な利用や変更を防ぐためにアクセスと更新を制限することが重要です。
AIエージェントのセキュリティ確保については、Securing AI agents ドキュメントを参照してください。
Agent API Keys
Agent API Keysは、Agent actionsを呼び出す際に、よりきめ細かなセキュリティレベルを提供できます。詳細は Agent API Keys ドキュメントを参照してください。