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

AI agentの構築方法

SquidのClient SDKを使用して、永続的な指示、Knowledge Base、接続されたツール、マルチエージェントワークフローを備えたカスタムAI agentを構築します。

SquidでAI Agentを構築する理由

アプリにAI機能を追加するには、通常、LLM API、コンテキスト取得用のvector database、tool-callingロジック、会話メモリ、セキュリティルールを組み合わせる必要があります。各要素には、それぞれ統合作業が必要です。

Squidは、これらすべてを統合プラットフォームで処理します。指示と機能を持つagentを定義し、データソースやツールに接続して、単一のSDKから操作します。Squidがprompt構築、コンテキスト取得、メモリ、オーケストレーションを管理するため、作りたい体験に集中できます。

仕組み

内部では、agentはLarge Language Model(LLM)を使用して、ユーザーの質問に対する回答を生成します。ユーザーが質問すると、永続的な指示と最も関連性の高いコンテキストがpromptの一部としてLLMに渡され、ユーザーにコンテキストに基づく回答を提供します。

SquidではAI agent用のLLMを選択できるため、ユースケースに最適なものを見つけられます。以下のLLM providerはすぐに利用できます。

AI connectorを追加して、追加のproviderに接続することもできます。これにより、self-hosted model(例: Ollama、vLLM)、AWS Bedrock model、その他のOpenAI互換endpointを使用できます。

Agentを構築する

agentは、AIワークフローにおける個別の人格または設定を表します。各agentは、独自の指示と機能のセットによって区別される、異なるpersonaまたはユースケースのようなものです。この設計により、特定のagentに応じたカスタマイズ済みのAI応答を実現できます。

注記

以下の例では、Squid SDKを使用してagentを作成する方法を示します。Squid platformおよびSDKを用いた開発に不慣れな場合は、fullstack開発に関するドキュメントをお読みください。

AgentをUpsertする

AI agentをプログラムから作成または更新するには、作成または更新するagent IDを指定してupsert()メソッドを使用します。

Client code
await squid
.ai()
.agent('banking-copilot')
.upsert({
options: {
model: 'gpt-5.5',
},
isPublic: true,
});

agentを挿入する際は、agentが使用するmodelを示すmodelフィールドを含むoptions objectを渡します。

isPublicパラメータは、security rulesを設定せずに指定agentのchat機能へアクセスできるかを決定します。

Agentを削除する

既存のagentを削除するには、delete()メソッドを使用します。

Client code
await squid.ai().agent('banking-copilot').delete();

指定されたagent IDのagentが存在しない場合、この関数はエラーになります。

Modelを更新する

agentが使用するLLM modelを変更するには、updateModel()を呼び出します。

Client code
await squid.ai().agent('banking-copilot').updateModel('claude-sonnet-5');

modelには、vendor model名(例: 'gpt-5.6-sol''claude-sonnet-5''gemini-3.7-flash')または、Ollama、AWS Bedrock、その他のOpenAI互換endpointといった追加provider向けのintegration-based modelを指定できます。

Client code
await squid.ai().agent('banking-copilot').updateModel({
integrationId: 'my-ollama',
model: 'llama3',
});

'claude-code''codex'などのCLI agent modelを選択して、長時間実行されるtool-driven agentic requestを処理することもできます。

ask()またはchat()を呼び出す際に、model optionを使用してrequestごとにmodelをoverrideすることもできます。詳細はAsk Optionsを参照してください。

Backup Modelへのフォールバック

model providerが利用できない場合、requestは失敗します。代わりに2つ目のmodelでそのrequestをSquidに再試行させるには、backupModelを設定します。

Client code
await squid.ai().agent('banking-copilot').upsert({
options: {
model: 'gpt-5.6-sol',
backupModel: 'claude-sonnet-5',
},
});

backupModelmodelと同じ値を受け入れ、Ask Optionsを通じてrequestごとに設定することもできます。provider障害をエラーとして表示するままにするには、設定しないでください。

Backupが使用される場合

backupは、rate limitやcapacity outageなど、provider側の利用不能のみを対象にします。以下の場合、Squidはフォールバックしません

  • 無効なprompt、拒否されたresponse format、または使い切られたSquid quotaなど、request自体の問題で失敗した場合。
  • requestが会話の最初のrequestではない場合。
  • requestがすでにoutputを生成した、またはtoolを実行した場合。

フォールバックは、Squidが自らのprovider SDKを通じて呼び出すmodel、つまりvendor modelと、openai_compatible、Bedrock、Vertexのconnectorにのみ適用されます。backend codeから自分で提供するmodelは、provider statusを持たない通常のerrorとして失敗を報告するため、その失敗がoutageとして診断されることはありません。backupのAPI keyを解決できない場合、primaryと同じmodelに解決される場合、またはいずれかのmodelがCLI agent modelである場合は、backupは暗黙的にスキップされます。

フォールバックした会話はBackupを使い続ける

会話が一度フォールバックすると、その残りのライフサイクルではbackup modelに固定されます。これにより、outageによるprimaryのretry budget消費はturnごとではなく一度だけになり、会話の途中でmodelが変わることもありません。この固定は、作成元のoptionよりも長く存続します。backupModelの変更または削除、agentのmodelの変更、primaryの復旧があっても、固定された会話はそのmodelのままです。固定されたmodelが後で解決できなくなった場合、会話を移動するのではなくrequestが失敗します。

固定情報を記録する場所が必要なため、Squid管理のメモリが必要です。memoryがなければ、すべてのrequestが最初のrequestとなり、それぞれが個別にフォールバックします。

添付ファイル

最初のrequestでは、フォールバックによりfileIdsが失われる場合はフォールバックしません。添付ファイルを一度も見ていないmodelから回答を得ることは、outageを報告するよりも悪いためです。どちらのmodelもfile IDを読み取らない場合、IDは影響を持たず、フォールバックは進行します。すでに固定された会話は、いずれの場合でもそのmodelで実行を続けます。

Backupに固有の設定を与える

backupに独自のsampling設定が必要な場合は、model名だけでなくBackupModelOptions objectを渡します。

Client code
await squid.ai().agent('banking-copilot').upsert({
options: {
model: 'gpt-5.6-sol',
temperature: 0.2,
backupModel: {
model: 'claude-sonnet-5',
temperature: 0.4,
maxOutputTokens: 4096,
},
},
});

objectはmodeltemperaturereasoningEffortmaxTokensmaxOutputTokensverbosityを受け入れます。

backupが処理するturnでは、これらのsampling設定はbackupModelからのみ読み取られます。そこで未設定の値は、agentの設定またはrequest自体で値が設定されている場合でも、backup model独自のdefaultになります。これはフォールバックしたturnだけでなく、固定された会話のすべてのturnで適用されます。指示、functions、Knowledge Base、connected agent、response format、memoryを含むその他すべては、常にprimary設定から取得されます。

AgentとResourceを一覧表示する

squid.ai() clientは、アプリで定義されたすべてを検出するためのメソッドを公開します。

TypeScriptPython戻り値
listAgents()list_agents()設定を含むすべてのagent
listKnowledgeBases()list_knowledge_bases()すべてのKnowledge Base
listChatModels()list_chat_models()利用可能なchat model。非推奨vendor modelを含めるにはincludeDeprecated: trueを渡します。
listFunctions()list_functions()登録済みのAI functions
Client code
const agents = await squid.ai().listAgents();
const models = await squid.ai().listChatModels({ includeDeprecated: false });

各メソッドは、以下の内容を含むrecordのarrayを返します。

  • AgentsAiAgent): idcreatedAtupdatedAtdescriptionisPublicauditLogoptions(model、接続されたKnowledge Base、integration、functionを含むagentの完全な設定)。
  • Knowledge basesAiKnowledgeBase): idnamedescriptionembeddingModelchatModelmetadataFieldscreatedAtupdatedAt。connector syncによって作成されたKnowledge Baseには、追加のsync bookkeeping fieldが含まれる場合があります。
  • Chat modelsModelIdSpec): modelId(model選択として渡すstring)、displayNamedescriptionsource'vendor''connector'、または'custom')。integration-based modelにはintegrationIdが含まれ、非推奨modelには、callがroutingされる有効modelを示すreplacedByが含まれます。
  • AI functionsAiFunctionMetadata): serviceFunctionServiceName:functionName)、descriptionparams(それぞれnametypedescriptionrequiredを含む)。connector提供のfunctionにはattributes.integrationTypeが含まれ、internalのflagが付いたentryは直接使用することを意図していません。

Agent Descriptionを設定する

agentの人間が読みやすいdescriptionを設定または更新するには、setAgentDescription()メソッドを使用します。これにより、他のagent設定に影響を与えずにdescriptionのみを更新します。

Client code
await squid
.ai()
.agent('banking-copilot')
.setAgentDescription('Assists customer support staff with banking and finance questions');

または、upsert()を使用して、他のすべてのagent値とともに1回のcallでdescriptionを設定できます。upsert()はagent設定全体を置き換えるため、含まれていないfieldはクリアされることに注意してください。

Instructions

Instructionsは、agentがpromptに応答し質問に答える方法のルールを設定します。直接的かつ簡潔にし、agentの目的を説明する必要があります。Instructionsはtext blockとして指定します。

Instructionsを追加する

AI agentのinstructionsを追加または編集するには、instruction dataをstringとして渡してupdateInstructions()メソッドを使用します。

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

接続されたKnowledge Base

Knowledge Baseは、質問に回答する際にagentが参照する検索可能なコンテキストを格納します。Knowledge Baseの作成、コンテキストとmetadataの管理については、Knowledge Bases documentationを参照してください。

Knowledge BaseをAgentに接続する

他のagent設定に影響を与えずにagentへ1つ以上のKnowledge Baseへのアクセスを付与するには、setAgentOptionInPath()を使用します。descriptionは、各Knowledge Baseを参照するタイミングをagentに伝えます。

Client code
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', [
{
knowledgeBaseId: 'banking-knowledgebase',
description: 'Use for information on credit cards',
},
]);

すべてのKnowledge Baseを切断するには、空のarrayを渡します。

Client code
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', []);

upsert()を使用して、接続済みKnowledge Baseを他のすべてのagent値とともに1回のcallで設定することもできます。upsert()はagent設定全体を置き換えるため、含まれていないfieldはクリアされることに注意してください。

各接続済みKnowledge Base entryは、以下のfieldをサポートします。

FieldType必須説明
knowledgeBaseIdstringはい接続するKnowledge Base
descriptionstringはいこのKnowledge Baseを参照するタイミングをagentに伝えます
includeMetadatabooleanいいえagentに提供される検索結果にdocument metadataを含めます。省略時は、defaultがtrueである非推奨のask-level includeMetadata optionにフォールバックします。metadataを除外するにはfalseに設定してください。
enableMetadataInspectionbooleanいいえagentに、このKnowledge Baseのmetadata field値を列挙および検索するためのtoolを与えます。defaultはfalseです。agent-driven metadata filteringを参照してください。
Client code
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', [
{
knowledgeBaseId: 'banking-knowledgebase',
description: 'Use for information on credit cards',
includeMetadata: true,
enableMetadataInspection: true,
},
]);

ask-levelのincludeMetadata optionも引き続き機能しますが、Knowledge Baseごとのflagが推奨されるため非推奨です。

Search ModeとSpreadsheet

Knowledge Base search toolでは、agentがqueryごとに取得modeを選択できます。Knowledge Baseのbackendがサポートする内容に応じて、'vector'(semantic)、'keyword'(IDやerror codeなどの正確なtokenに最適)、または'hybrid'を選択します。Keyword searchを参照してください。

接続済みKnowledge Baseにspreadsheet fileが含まれる場合、agentはquerySpreadsheetsWithAi toolも利用できます。このtoolは、取得したsummaryに依存する代わりに、アップロードしたfileに対してPythonを実行することで、正確な回答(count、sum、lookup、file間の比較)を計算します。Spreadsheet Filesを参照してください。

Agentと対話する

agentを作成したら、質問やpromptを送信できます。

ask()で完全なResponseを取得する

ask()メソッドを使用してpromptを送信し、完全なresponseをstringとして受け取ります。

Client code
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Which credit card is best for students?');

Annotation付きResponseを取得する

askWithAnnotations()を使用して、file annotation(生成された画像やdocumentなど)とともにresponseを取得します。

Client code
const { responseString, annotations } = await squid
.ai()
.agent('banking-copilot')
.askWithAnnotations('Generate a comparison chart of our credit cards');

chat()によるStreaming Response

chat()メソッドを使用して、responseをtokenごとにstreamします。これは、各tokenの到着時に蓄積されたresponseをemitするRxJS Observable<string>を返すため、UIでreal-time responseを表示するのに最適です。

Client code
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()メソッドは、自然なtyping効果のためtoken間にわずかなdelayを追加するsmootTyping option(defaultはtrue)に加え、ask()と同じoption(voiceOptionsを除く)を受け入れます。

Ask Options

ask()chat()はいずれも、requestを設定するための任意のoptionsパラメータを受け入れます。利用可能なoptionとdefault値の完全な一覧については、API reference documentationを参照してください。

Client code
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

defaultでは、agentはsession内の以前のmessageを記憶します。この動作を制御するにはmemoryOptionsを使用します。

Client code
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': historyを使用しません。各promptは独立して回答されます。
  • 'read-only': agentは過去のmessageを参照できますが、新しいmessageは保存しません。
  • 'read-write': agentはhistoryを読み書きします(defaultの動作)。

memoryIdは会話を識別します。request間で同じmemoryIdを使用すると、同じ会話が継続されます。chat historyへのアクセスを許可するため、memory IDはaccess tokenと同じセキュリティレベルで扱ってください。

指定した会話の過去messageを取得するには、getChatHistory()を使用します。

Client code
const messages = await squid
.ai()
.agent('banking-copilot')
.getChatHistory('user-123-session');

Response Format

responseFormatを使用してagent responseのformatを制御します。

Client code
// 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
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'],
},
},
});

利用可能なformat:

  • 'text'(default): plain text response。
  • 'json_object': modelは有効なJSONの返却を試みます。
  • { type: 'json_schema', schema: ... }: responseが指定したJSON schemaに準拠することを保証するstructured output。vendor chat model(Anthropic、OpenAI、Gemini、Grok)でサポートされています。schemaはmodelのproviderに送信され、これに従うようdecodingが制約されるため、responseはschemaと完全に一致し、再検証は不要です。

providerが拒否したschemaは、provider独自のdiagnosticを含む400として返されます。protocolがschemaをまったく渡せないmodelは、要求したshapeなしで回答するのではなく、STRUCTURED_OUTPUT_NOT_SUPPORTEDでrequestを拒否します。これはCLI agent modelおよびcustom @llmServiceを通じて提供されるmodelに適用されます。これらでは'json_object'を使用し、promptでshapeを説明してください。

integration-based modelの場合、schemaが尊重されるかはintegrationの背後にあるproviderに依存します。そのため、provider間で機能する単一の回答が必要な場合は'json_object'にフォールバックしてください。

PromptにFileを含める

fileUrlsを使用して、画像またはdocumentをpromptの一部として渡します。

Client code
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(requestごとに一意)、type'image'または'document')、purposeが必要です。

  • 'context': AIが参照できるよう、fileをpromptに直接含めます。
  • 'tools': fileはtool/function call resultの一部として返されます。

任意でfileNameを設定することもできます。これにより、modelがfileを参照するための名前が与えられ、URL pathにextensionがない場合にはfile extensionが提供されます。

Spreadsheet file(.csv.tsv.xlsx.xlsm.xls.xlsb)は特別に処理されます。添付された各spreadsheetに対して、agentはfileに対してPythonを実行し質問に回答するtoolを受け取るため、lookupとaggregationは実際のcell値から計算されます。spreadsheetはfile extensionで認識されます。extensionはfileNameから、またはそれがない場合はquery stringを無視したURL pathから取得されるため、.xlsx?signature=...で終わるsigned URLも追加設定なしで検出されます。URL path自体にextensionがない場合(たとえばopaque download endpoint)は、fileNameを設定してください。

Client code
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What was the total revenue in Q2?', {
fileUrls: [
{
id: 'sales-1',
type: 'document',
purpose: 'context',
url: downloadUrl, // path has no file extension
fileName: 'sales.xlsx',
},
],
});

RequestごとにModelをOverrideする

agentのdefault modelを1つのrequestだけoverrideします。

Client code
const response = await squid.ai().agent('banking-copilot').ask('Summarize this data', {
model: 'gpt-5.5',
});

追加Option

OptionTypeDefault説明
maxTokensnumberModel maxSquidがmodelへ送信できる最大input token
maxOutputTokensnumber-modelが生成する最大token数
temperaturenumber0.5Sampling temperature(0~1)
timeoutMsnumber240000ミリ秒単位のrequest timeout
instructionsstring-agentのdefault instructionsに追加されるinstructions
guardrailsobject-requestごとにguardrail settingsをoverride
piiobject-requestごとにoverride不可。Prompt privacyは保存済みagentから読み取られ、ここで渡した値は無視されます
backupModelstring or object-primary providerが利用できない場合に再試行するmodel。Backup Modelへのフォールバックを参照してください
disableContextbooleanfalseこのrequestでKnowledge Baseコンテキストをスキップ
includeReferencebooleanfalseresponseにsource referenceを含める
reasoningEffortstring-reasoning model向けの'minimal''low''medium'、または'high'
useCodeInterpreterstring'none'Python code executionを有効にするには'llm'を指定(OpenAIおよびGeminiのみ)
executionPlanOptionsobject-agentが実行前に計画できるようにします

MetadataでコンテキストをFilterする

コンテキストにmetadataを追加している場合、contextMetadataFilterForKnowledgeBase chat optionを使用して、AI agentが特定のコンテキストだけを参照するように指示できます。filter要件を満たすコンテキストだけが、client promptへの応答に使用されます。

次の例では、"company"のmetadata値が"Bank of America"と等しいものだけを含めるよう、コンテキストをfilterします。

Client code
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' } },
},
});

サポートされるfilter operatorの完全な一覧、$andおよび$orによるfilterの組み合わせ、agent自身がfilterを構築する方法については、Filtering Knowledge Base Context with Metadataを参照してください。

AI Functions

Squid AI Agentは、AI functionsを使用して、特定のユースケースを処理し、より一貫性のあるresponseを作成できます。

AgentにFunctionを追加する

setAgentOptionInPath()を使用してAI functionsをagentにアタッチできます。このメソッドは、他のagent設定に影響を与えずにfunction listだけを更新します。

Client code
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('functions', ['getCreditLimit']);

function listを更新するには、新しいfunction setを指定して再度setAgentOptionInPath()を呼び出します。空のarrayを渡すとすべてのfunctionが削除されます。upsert()を使用して、functionを他のすべてのagent値とともに1回のcallで設定することもできますが、upsert()はagent設定全体を置き換える点に注意してください。

Ask時にFunctionを渡す

代わりに、functions optionを使用してrequestごとにAI function名を渡すこともできます。これは、そのrequestにおけるagentの保存済みfunction listをoverrideします。

Client code
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What is my current credit limit?', {
functions: ['getCreditLimit', 'getAccountBalance'],
});

AI functionsの詳細については、ドキュメントを参照してください。AI functionsを使用するexample applicationについては、このAI agent tutorialを確認してください。

Connected Agents

agentは他のagentへtaskをdelegateできるため、multi-agent workflowを実現できます。connected agentはcall可能なtoolとして表示され、parent agentはsub-agentがユーザーrequestの特定部分を処理するのに最適であると判断した場合に呼び出せます。

Connected Agentsを設定する

このagentに接続するagent listを設定するには、updateConnectedAgents()を使用します。descriptionは、各connected agentへdelegateするタイミングをparent agentに伝えます。

Client code
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',
},
]);

すべてのagentを切断するには、空のarrayを渡します。

Client code
await squid.ai().agent('banking-copilot').updateConnectedAgents([]);

Ask時にConnected Agentsを渡す

connected agentをrequestごとに指定することもでき、保存済み設定をoverrideします。

Client code
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',
},
],
});

defaultでは、nested agent callは最大5 levelの深さまで再帰できます。これはquotas optionで調整できます。

Client code
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Analyze this portfolio', {
quotas: { maxAiCallStackSize: 3 },
});

Connected Integrations

agentはデータソースや外部serviceに接続できるため、promptへの回答の一部としてdatabase query、API call、SaaS toolとの対話を行えます。

Connected Integrationsを設定する

他のagent設定に影響を与えずにagentへconnectorへのアクセスを付与するには、setAgentOptionInPath()を使用します。

Client code
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を使用するタイミングをagentが理解するのに役立ちます。integrationTypeは、Squid Consoleで設定されたconnectorのtypeと一致する必要があります。

すべてのintegrationを切断するには、空のarrayを指定してsetAgentOptionInPath()を呼び出します。upsert()を使用して、connected integrationを他のすべてのagent値とともに1回のcallで設定することもできますが、upsert()はagent設定全体を置き換える点に注意してください。

Ask時にConnected Integrationsを渡す

connected agentと同様に、integrationもrequestごとに指定できます。

Client code
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 agent、integrationを含む複雑なtaskでは、execution planningを有効にできます。有効にすると、agentは実行前に、取るべきactionのplanを最初に作成します。

Client code
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
},
});

任意で、executionPlanOptions内のmodel fieldを使用してplanning step用の異なるmodelを指定できます。

Status Updateを監視する

agentがtool call、connected agent、integrationを伴う複雑なrequestを処理する場合、WebSocketを介してreal-time status updateを監視できます。

Client code
const statusUpdates = squid.ai().agent('banking-copilot').observeStatusUpdates();

statusUpdates.subscribe({
next: (status) => {
console.log(`[${status.title}] ${status.body}`);
},
});

返されるObservableは、agentが実行する各stepを説明するtitleおよびbody fieldを持つAiStatusMessage objectをemitします。

titleはagentが実行しているstepの種類を表します。たとえば、通常のKnowledge Base searchではAccessing Knowledge Baseが報告されます。一方、knowledge graphをナビゲートする場合はQuerying Knowledge Base Graphliteral text scanではSearching Knowledge Base Textが報告されるため、chat UIはそれぞれを独立したstepとしてrenderできます。

observeStatusUpdates()は任意のjob IDも受け入れます。observeStatusUpdates(jobId)は、その特定のrequestのupdateだけをemitします。これは、CLI agent modelのrunなど、単一の長時間実行askを追跡する場合に有用です。引数なしの場合は、agentのすべてのstatus updateをemitします。

GroundingとSource Reference

Squid AI agentはgrounded answerを提供します。つまり、modelのbuilt-in knowledgeだけではなく、agentの接続済みKnowledge Base内のrecordから導かれたresponseです。このgroundingを可視化するには、ask()またはchat()includeReference: trueを設定し、responseにsource reference(citation)を含めます。referenceは、回答のgroundingとなったKnowledge Base recordを指すため、ユーザーは主張をsourceに照らして検証できます。

Client code
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Which credit card is best for students?', {
includeReference: true,
});

Chat Widgetを使用する場合は、include-reference attributeを設定してagent responseにcitationを表示します。

referenceが引用するのは、質問したユーザーに閲覧が許可されたcontentだけです。Knowledge Baseがsource permissionを尊重する場合、ユーザーがaccessできないcontentは取得されず、modelにも届かず、citationにも表示されません。

Agent Revision

agent設定へのすべての変更は、automatically revisionとして記録されます。agentの作成時にはcreated revisionが記録され、各更新(upsert()updateModel()updateInstructions()setAgentOptionInPath()を含む)ではupdatedが記録されます。agentを削除すると、その最終stateを保持する最後のdeleted revisionが記録されます。セットアップは不要です。

Revisionを一覧表示する

listRevisions()を使用して、agentの完全なhistoryを新しい順に取得します。

Client code
const { revisions } = await squid.ai().agent('banking-copilot').listRevisions();
console.log(revisions[0].revisionNumber, revisions[0].action);

各revisionには以下が含まれます。

FieldType説明
agentIdstringこのrevisionが属するagent
revisionNumbernumber変更ごとにincrementされる連番
action'created' | 'updated' | 'deleted'revisionを発生させた変更
createdAtDaterevisionが記録された時刻
agentSnapshotAiAgentrevision時点におけるagentの完全な設定

個別の変更descriptionはありません。何が変更されたかを確認するには、連続するsnapshotを比較してください(Squid Consoleはこれを自動で行います)。

Revisionを復元・削除する

restoreRevision()を使用して、agentを以前のrevisionへ復元します。

Client code
await squid.ai().agent('banking-copilot').restoreRevision(3);

復元はnon-destructiveです。最初にcurrent stateが新しいrevisionとして保存され、その後agent設定がsnapshotに置き換えられます。historyは増加するだけのため、復元自体を取り消すこともできます。deleted revisionは復元できません。

単一のrevisionを完全に削除するには、deleteRevision()を使用します。

Client code
await squid.ai().agent('banking-copilot').deleteRevision(3);

完全なmethod signatureは、TypeScriptおよびPythonのreference docsにあります。

revisionを視覚的に確認することもできます。Squid Consoleのagent pageにはRevisions tabがあり、各revisionでの変更内容、復元action、削除actionを確認できます。

Audit Log

設定revisionとは別に、各agentはinvocationのruntime audit logを保持します。user prompt、toolとintegration call、Knowledge Base search、最終response、token usageが含まれます。

logはagentのauditLog fieldによって制御され、新しいagentではdefaultで有効です。consoleで切り替えるか、upsert()に含めて設定します。

Client code
await squid
.ai()
.agent('banking-copilot')
.upsert({
options: { model: 'gpt-5.5' },
isPublic: true,
auditLog: false,
});

logの閲覧はconsoleの機能です。Squid Consoleでagent pageのAudit Log tabを開いてください。log entryはSDKを通じて公開されません。

Error Handling

よくあるError

Error原因解決策
Agent not found存在しないagent IDに対してdelete()get()、または他のmethodを呼び出した最初にget()を呼び出してagent IDの存在を確認するか、upsert()でagentが作成されるようにします
Context not found存在しないcontext IDでdeleteContext()またはgetContext()を呼び出した削除または取得の前にlistContexts()を使用してcontext IDを確認します
Request timeoutagentが設定済みのtimeoutMs(default: 4分)より長くかかるoptionでtimeoutMsを増やす、promptを簡略化する、または接続するtool数を減らします
Embedding model cannot be modified既存のKnowledge BaseでembeddingModelを変更しようとした代わりに、目的のembedding modelで新しいKnowledge Baseを作成します

StreamingでErrorを処理する

chat()を使用する場合、errorはObservableのerror callbackを通じて配信されます。

Client code
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'),
});

Best Practices

Instructions

  • instructionsは簡潔かつ直接的にします。agentのroleと、実行すべきこと(および実行すべきでないこと)を説明してください。
  • factual contentではなくbehavioral rule(tone、scope、response style)にinstructionsを使用してください。factual contentはKnowledge Baseに配置します。
  • deploy前に、Agent StudioのTest chat機能を使用してinstructionsの変更をtestしてください。

Knowledge Bases

  • Knowledge Baseを接続する際は、説明的なdescription値を使用してください。特に複数が接続されている場合、descriptionはagentがどのKnowledge Baseを参照するか決定する方法です。

Knowledge Base contentとmetadataの構造化に関するガイダンスについては、knowledge base best practicesを参照してください。

Multi-Agent Workflows

  • 各connected agentには、明確で具体的なdescriptionを付けてください。曖昧なdescriptionは誤ったdelegationにつながります。
  • agent間で制御不能なrecursive callが発生しないよう、quotas.maxAiCallStackSizeを適切なlimitに設定してください。
  • 複雑なmulti-step taskにはexecutionPlanOptionsを使用し、agentがaction前にapproachをreasoningできるようにしてください。

Performance

  • 体感速度が重要なuser-facing interactionにはchat()を使用してください。streamingでは、完全なresponseを待つのではなく、到着したtokenを表示できます。
  • requestにKnowledge Baseコンテキストが不要な場合は、disableContext: trueを設定してlatencyを削減してください。
  • 会話historyを必要としないstatelessなone-off requestには、memoryOptions.memoryMode: 'none'を使用してください。

Agentを保護する

Squid Client SDKを使用してagentを作成しchatを有効化する際、データを保護することは非常に重要です。AI agentとagentとのchatには機密情報が含まれる可能性があるため、不正な使用や変更を防ぐためにaccessとupdateを制限することが不可欠です。

AI agentの保護については、Securing AI agents documentationを確認してください。

Agent API Keys

Agent API Keyは、Agent actionを呼び出す際により詳細なsecurity levelを提供できます。詳細については、Agent API Keys documentationを参照してください。