AI agent の構築方法
Squid の client SDK を使用して、永続的な instructions、knowledge base、接続された tools、multi-agent workflow を備えたカスタム AI agent を構築します。
Squid で AI Agent を構築する理由
アプリに AI 機能を追加するには通常、LLM API、context retrieval 用の vector database、tool-calling logic、conversation memory、security rules を組み合わせる必要があります。それぞれに個別の統合作業が必要です。
Squid はこれらすべてを統一されたプラットフォームで処理します。instructions と abilities を備えた agent を定義し、data source と tool に接続して、単一の SDK を通じて操作します。Squid が prompt construction、context retrieval、memory、orchestration を管理するため、作成したい体験に集中できます。
仕組み
内部では、agent は Large Language Model(LLM)を使用してユーザーの質問への回答を生成します。ユーザーが質問すると、永続的な instructions と最も関連性の高い context が prompt の一部として LLM に渡され、ユーザーに context を踏まえた回答が提供されます。
Squid では AI agent 用の LLM を選択でき、ユースケースに最適なものを見つけられます。以下の LLM provider はすぐに利用できます。
AI connector を追加することで、追加の provider にも接続できます。これにより、self-hosted model(例: Ollama、vLLM)、AWS Bedrock model、またはその他の OpenAI-compatible endpoint を使用できます。
Agent の構築
agent は、AI workflow における個別の personality または設定を表します。各 agent は異なる persona または use case のようなものであり、それぞれ固有の instructions と abilities によって区別されます。この設計により、特定の agent に応じて AI の応答をカスタマイズできます。
以下の例では、Squid の SDK を使用して agent を作成する方法を示します。Squid platform と SDK を使用した開発に不慣れな場合は、fullstack development に関するドキュメントをお読みください。
Agent の Upsert
AI agent をプログラムで作成または更新するには、作成または更新する agent ID を指定して upsert() method を使用します。
await squid
.ai()
.agent('banking-copilot')
.upsert({
options: {
model: 'gpt-5.5',
},
isPublic: true,
});
agent を挿入する際は、agent が使用する model を示す model field を含む options object を渡します。
isPublic parameter は、指定した agent の chat 機能を、security rulesを設定せずにアクセス可能にするかどうかを決定します。
Agent の削除
既存の agent を削除するには、delete() method を使用します。
await squid.ai().agent('banking-copilot').delete();
指定した agent ID の agent が存在しない場合、この function は error になります。
Model の更新
agent が使用する LLM model を変更するには、updateModel() を呼び出します。
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-compatible endpoint などの追加 provider 用のintegration-based modelを指定できます。
await squid.ai().agent('banking-copilot').updateModel({
integrationId: 'my-ollama',
model: 'llama3',
});
'claude-code' や 'codex' などの CLI agent modelを選択して、長時間実行される tool-driven agentic ask を実行することもできます。
また、ask() または chat() の呼び出し時に model option を使用して、request ごとに model を override することもできます。詳細は Ask Options を参照してください。
Backup Model へのフォールバック
model provider を利用できない場合、request は失敗します。代わりに 2 番目の model で Squid がその request を再試行するようにするには、backupModel を設定します。
await squid
.ai()
.agent('banking-copilot')
.upsert({
options: {
model: 'gpt-5.6-sol',
backupModel: 'claude-sonnet-5',
},
});
backupModel は model と同じ値を受け入れ、Ask Options を通じて request ごとに設定することもできます。provider outage を error として通知し続けるには、未設定のままにしてください。
Backup が使用される場合
backup は、rate limit や capacity outage など、provider 側の利用不能時のみを対象とします。以下の場合、Squid はフォールバックしません。
- invalid prompt、拒否された response format、Squid quota の使い切りなど、request 自体の理由で失敗した場合。
- request が conversation の最初の 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 は暗黙的にスキップされます。
フォールバックした Conversation は Backup を継続使用する
conversation が一度フォールバックすると、その後のライフサイクル全体で backup model に固定されます。これにより outage は turn ごとではなく一度だけ primary の retry budget を消費し、dialogue の途中で model が変更されることもありません。この固定は、それを作成した option よりも長く存続します。backupModel の変更または削除、agent の model の変更、primary の復旧を行っても、固定済み conversation はそのままです。後で固定された model を解決できなくなった場合は、conversation を移動せず request が失敗します。
固定情報を記録する場所が必要なため、Squid-managed memory が必要です。memory がない場合、すべての request が最初の request になり、それぞれが独立してフォールバックします。
最初の request は、フォールバックによって fileIds が失われる場合はフォールバックしません。添付ファイルを参照していない model から回答を得るより、outage を報告する方が望ましいためです。どちらの model も file id を読み取らない場合、id は inert でありフォールバックは続行されます。すでに固定されている conversation は、いずれの場合もその model で実行を継続します。
Backup 専用の設定を指定する
backup 専用の sampling settings が必要な場合は、bare model 名の代わりに BackupModelOptions object を渡します。
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 は model、temperature、reasoningEffort、maxTokens、maxOutputTokens、verbosity を受け入れます。
backup が処理する turn では、これらの sampling settings は backupModel からのみ読み取られます。そこに未設定の値がある場合は、agent の configuration や request 自体で値が設定されていても、backup model 独自の default が使用されます。これはフォールバックした turn だけでなく、固定済み conversation のすべての turn に適用されます。instructions、functions、knowledge bases、connected agents、response format、memory など、その他すべては常に primary configuration から取得されます。
Agent と Resource の一覧表示
squid.ai() client は、アプリ内で定義されたすべてを検出するための method を公開します。
| TypeScript | Python | 戻り値 |
|---|---|---|
listAgents() | list_agents() | configuration を含むすべての agent |
listKnowledgeBases() | list_knowledge_bases() | すべての knowledge base |
listChatModels() | list_chat_models() | 利用可能な chat model。deprecated vendor model を含めるには 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)
各 method は、次の内容を持つ record の array を返します。
- Agents(
AiAgent):id、createdAt、updatedAt、description、isPublic、auditLog、options(model、接続された knowledge base、integration、function を含む agent の完全な configuration)。 - Knowledge bases(
AiKnowledgeBase):id、name、description、embeddingModel、chatModel、metadataFields、createdAt、updatedAt。connector sync によって作成された knowledge base には、追加の sync bookkeeping field が含まれることがあります。 - Chat models(
ModelIdSpec):modelId(model selection として渡す string)、displayName、description、source('vendor'、'connector'、'custom')。integration-based model にはintegrationIdが含まれ、deprecated model には call が routing される active model を示すreplacedByが含まれます。 - AI functions(
AiFunctionMetadata):serviceFunction(ServiceName:functionName)、description、params(それぞれにname、type、description、required)。connector 提供の function にはattributes.integrationTypeが含まれ、internalと flag 付けされた entry は直接使用することを意図していません。
Agent Description の設定
agent の人間が読める description を設定または更新するには、setAgentDescription() method を使用します。これは他の agent configuration に影響せず、description のみを更新します。
await squid
.ai()
.agent('banking-copilot')
.setAgentDescription('Assists customer support staff with banking and finance questions');
または、単一の call で他のすべての agent 値とともに description を設定するために upsert() を使用できます。upsert() は agent configuration 全体を置き換えるため、含まれていない field は消去される点に注意してください。
Instructions
instructions は、agent が prompt に応答し質問に回答する方法の rules を設定します。直接的かつ簡潔にし、agent の目的を説明する必要があります。instructions は text block として指定します。
Instructions の追加
AI agent の instructions を追加または編集するには、instruction data を string として渡して updateInstructions() method を使用します。
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 Bases
knowledge base は、質問への回答時に agent が参照する検索可能な context を保存します。knowledge base を作成し、その context と metadata を管理する方法については、Knowledge Bases documentation を参照してください。
Knowledge Base を Agent に接続する
他の agent configuration に影響を与えずに、agent に 1 つ以上の knowledge base への access を付与するには、setAgentOptionInPath() を使用します。description は、各 knowledge base をいつ参照するかを agent に伝えます。
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', [
{
knowledgeBaseId: 'banking-knowledgebase',
description: 'Use for information on credit cards',
},
]);
すべての knowledge base を切断するには、empty array を渡します。
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('connectedKnowledgeBases', []);
また、単一の call で他のすべての agent 値とともに接続された knowledge base を設定するために upsert() を使用できます。upsert() は agent configuration 全体を置き換えるため、含まれていない field は消去される点に注意してください。
接続された各 knowledge base entry では、次の field がサポートされます。
| Field | Type | 必須 | 説明 |
|---|---|---|---|
knowledgeBaseId | string | はい | 接続する knowledge base |
description | string | はい | この knowledge base をいつ参照するかを agent に伝える |
includeMetadata | boolean | いいえ | agent に提供する search result に document metadata を含めます。省略時は、default が true の deprecated な ask-level includeMetadata option にフォールバックします。metadata を除外するには false を設定します。 |
enableMetadataInspection | boolean | いいえ | agent に、この knowledge base の metadata field 値を列挙・検索する tool を提供します。default は 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-level の includeMetadata option も引き続き機能しますが、knowledge-base ごとの flag が推奨されるため deprecated です。
Search Mode と Spreadsheet
knowledge base search tool では、knowledge base の backend がサポートする内容に応じ、agent が query ごとに retrieval mode を選択できます。'vector'(semantic)、'keyword'(ID や error code などの exact token に最適)、または 'hybrid' を選択します。Keyword searchを参照してください。
接続された knowledge base に spreadsheet file が含まれる場合、agent は querySpreadsheetsWithAi tool も取得します。この tool は、取得した summary に依存するのではなく、アップロードされた file に対して Python を実行し、正確な回答(count、sum、lookup、file 間の comparison)を計算します。Spreadsheet Filesを参照してください。
Agent との対話
agent を作成すると、質問または prompt の送信を開始できます。
ask() による完全な Response の取得
ask() method を使用して prompt を送信し、完全な response を string として受け取ります。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Which credit card is best for students?');
Annotation 付き Response の取得
askWithAnnotations() を使用すると、response と任意の file annotation(例: 生成された image または document)を受け取れます。
const { responseString, annotations } = await squid
.ai()
.agent('banking-copilot')
.askWithAnnotations('Generate a comparison chart of our credit cards');
chat() による Response の Streaming
chat() method を使用して、response を token ごとに stream します。これは RxJS Observable<string> を返し、各 token の到着時に蓄積済み response を emit します。UI にリアルタイム response を表示する場合に最適です。
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() method は、ask() と同じ option(voiceOptions を除く)に加え、自然な typing effect のために token 間へわずかな delay を追加する smoothTyping option(default は true)も受け入れます。
Ask Options
ask() と chat() はどちらも、request を構成する optional な options parameter を受け入れます。利用可能な option と default 値の完全な list は、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
default では、agent は session 内の以前の message を記憶します。この動作を制御するには 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': history は使用しません。各 prompt は独立して回答されます。'read-only': agent は過去の message を参照できますが、新しい message を保存しません。'read-write': agent は history の読み書きを行います(default の動作)。
memoryId は conversation を識別します。request 間で同じ memoryId を使用すると、同じ conversation を継続します。memory ID は chat history への access を許可するため、access token と同じ security で扱ってください。
指定した conversation の過去の message を取得するには、getChatHistory() を使用します。
const messages = await squid
.ai()
.agent('banking-copilot')
.getChatHistory('user-123-session');
Response Format
responseFormat を使用して agent の response format を制御します。
// 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 は valid JSON を返そうとします。{ type: 'json_schema', schema: ... }: response が指定された JSON schema に準拠することを保証する structured output。vendor chat model(Anthropic、OpenAI、Gemini、Grok)でサポートされます。schema は model の provider に送信され、provider が decoding を制約するため、response は schema に正確に一致し、再度 validation する必要はありません。
provider が拒否する schema は、provider 独自の diagnostic を含む 400 として返されます。schema をまったく扱えない protocol の model は、要求された shape なしで回答するのではなく、STRUCTURED_OUTPUT_NOT_SUPPORTED で request を拒否します。これは CLI agent modelおよび custom @llmService を通じて提供される model に適用されます。これらでは 'json_object' を使用し、prompt 内で shape を説明してください。
integration-based modelの場合、schema が尊重されるかどうかは integration の背後にある provider に依存するため、provider 間で機能する 1 つの回答が必要な場合は 'json_object' にフォールバックしてください。
Prompt への File の追加
fileUrls を使用して、image または document を 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(request ごとに unique)、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 value から計算されます。spreadsheet は file extension により認識されます。extension は fileName から、ない場合は query string を無視した URL path から取得されるため、.xlsx?signature=... で終わる signed URL は追加設定なしで検出されます。URL path 自体に extension がない場合(たとえば opaque download endpoint)は、fileName を設定してください。
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
単一の request に対して agent の default model を override します。
const response = await squid.ai().agent('banking-copilot').ask('Summarize this data', {
model: 'gpt-5.5',
});
追加 Options
| Option | Type | Default | 説明 |
|---|---|---|---|
maxTokens | number | Model max | Squid が model に送信できる maximum input token |
maxOutputTokens | number | - | model が生成する maximum token |
temperature | number | 0.5 | Sampling temperature(0~1) |
timeoutMs | number | 240000 | millisecond 単位の request timeout |
instructions | string | - | agent の default instructions に追加される instructions |
guardrails | object | - | request ごとに guardrail settingsを override |
pii | object | - | request ごとに override 不可。Prompt privacyは保存済み agent から読み取られ、ここで渡した値は無視されます |
backupModel | string or object | - | primary provider を利用できない場合に再試行する model。Backup Model へのフォールバックを参照 |
disableContext | boolean | false | この request の knowledge base context を skip |
includeReference | boolean | false | response に source reference を含める |
reasoningEffort | string | - | reasoning model 向けの 'minimal'、'low'、'medium'、'high' |
useCodeInterpreter | string | 'none' | Python code execution を有効にするには 'llm'(OpenAI と Gemini のみ) |
executionPlanOptions | object | - | agent が行動前に計画できるようにする |
Metadata による Context の Filtering
context に metadata を追加している場合は、contextMetadataFilterForKnowledgeBase chat option を使用して、特定の context のみを参照するよう AI agent に指示できます。filter 要件を満たす context のみが、client prompt への応答に使用されます。
次の例では、"company" の metadata value が "Bank of America" と等しい context のみを含めるように filter します。
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 の完全な list、$and と $or による filter の結合、agent が自身で filter を構築する方法については、Filtering Knowledge Base Context with Metadataを参照してください。
AI Functions
Squid AI Agents は、AI functionsを使用して特定の use case を処理し、より一貫した response を作成できます。
Agent への Function の追加
setAgentOptionInPath() を使用して AI function を agent に attach できます。この method は、他の agent configuration に影響を与えず、function list のみを更新します。
await squid
.ai()
.agent('banking-copilot')
.setAgentOptionInPath('functions', ['getCreditLimit']);
function list を更新するには、新しい function set を指定して再度 setAgentOptionInPath() を呼び出します。empty array を渡すと、すべての function が削除されます。単一の call で他のすべての agent 値とともに function を設定するために upsert() を使用することもできますが、upsert() は agent configuration 全体を置き換える点に注意してください。
Ask 時に Function を渡す
または、functions option を使用して、request ごとに AI function 名を渡します。これにより、その request について agent に保存されている function list が override されます。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('What is my current credit limit?', {
functions: ['getCreditLimit', 'getAccountBalance'],
});
AI function の詳細については、ドキュメントを参照してください。AI function を使用する example application は、この AI agent tutorialで確認できます。
接続された Agents
agent は他の agent に task を delegate でき、multi-agent workflow を実現できます。connected agent は callable tool として表示され、親 agent は sub-agent がユーザー request の特定部分の処理に最適であると判断した場合にそれを呼び出せます。
Connected Agents の設定
この agent に接続する agent の list を設定するには updateConnectedAgents() を使用します。description は、各 connected agent にいつ delegate するかを親 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',
},
]);
すべての agent を切断するには、empty array を渡します。
await squid.ai().agent('banking-copilot').updateConnectedAgents([]);
Ask 時に Connected Agents を渡す
request ごとに connected agent を指定することもでき、保存済み configuration を override します。
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 の深さまで recurse できます。これは quotas option を使用して調整できます。
const response = await squid
.ai()
.agent('banking-copilot')
.ask('Analyze this portfolio', {
quotas: { maxAiCallStackSize: 3 },
});
接続された Integrations
agent は data source および external service に接続でき、prompt への回答の一部として database の query、API の call、SaaS tool との対話を行えます。
Connected Integrations の設定
他の agent configuration に影響を与えずに agent に connector への access を付与するには、setAgentOptionInPath() を使用します。
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 を切断するには、empty array を指定して setAgentOptionInPath() を呼び出します。単一の call で他のすべての agent 値とともに connected integration を設定するために upsert() を使用することもできますが、upsert() は agent configuration 全体を置き換える点に注意してください。
Ask 時に Connected Integrations を渡す
connected agent と同様に、integration も request ごとに指定できます。
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 を作成してから実行します。
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 を通じてリアルタイムの status update を監視できます。
const statusUpdates = squid.ai().agent('banking-copilot').observeStatusUpdates();
statusUpdates.subscribe({
next: (status) => {
console.log(`[${status.title}] ${status.body}`);
},
});
返される Observable は、agent が実行する各 step を説明する title field と body field を持つ AiStatusMessage object を emit します。
title は agent が実行している step の種類を示します。たとえば、通常の knowledge base search では Accessing Knowledge Base が報告され、knowledge graphの navigation では Querying Knowledge Base Graph、literal text scanでは Searching Knowledge Base Text が報告されます。そのため chat UI は、それぞれを独自の step として render できます。
observeStatusUpdates() は optional な job ID も受け入れます。observeStatusUpdates(jobId) はその特定の request の update のみを emit するため、CLI agent model run など、単一の長時間実行 ask を追跡する際に便利です。argument がない場合は、agent のすべての status update を emit します。
Grounding と Source References
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 に対して claim を確認できます。
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 は、質問した user が閲覧を許可されている content のみを citation として示します。knowledge base がsource permissions を尊重する場合、user が access できない content は取得されず、model に到達せず、citation に表示されることもありません。
Agent Revisions
agent configuration の変更はすべて自動的に revision として記録されます。agent の作成時には created revision が記録され、各 update(upsert()、updateModel()、updateInstructions()、setAgentOptionInPath() を含む)では updated が記録され、agent の削除時には最終 state を保持する deleted revision が記録されます。設定は不要です。
Revision の一覧表示
listRevisions() を使用して、agent の完全な history を新しい順に取得します。
- 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 | 説明 |
|---|---|---|
agentId | string | この revision が属する agent |
revisionNumber | number | 各変更で increment される連続番号 |
action | 'created' | 'updated' | 'deleted' | revision を trigger した変更 |
createdAt | Date | revision が記録された時刻 |
agentSnapshot | AiAgent | revision 時点での完全な agent configuration |
個別の change description はありません。変更内容を確認するには、連続する snapshot を比較してください(Squid Console では自動的に行われます)。
Revision の復元と削除
restoreRevision() を使用して、agent を以前の revision に復元します。
- TypeScript
- Python
await squid.ai().agent('banking-copilot').restoreRevision(3);
await squid.ai().agent('banking-copilot').restore_revision(3)
復元は non-destructive です。まず current state が新しい revision として保存され、その後 agent configuration が snapshot に置き換えられます。history は増えるだけなので、復元自体も元に戻せます。deleted revision は復元できません。
単一の revision を完全に削除するには、deleteRevision() を使用します。
- TypeScript
- Python
await squid.ai().agent('banking-copilot').deleteRevision(3);
await squid.ai().agent('banking-copilot').delete_revision(3)
完全な method signature は、TypeScript および Python reference docs にあります。
revision を視覚的に閲覧することもできます。Squid Console の agent page には Revisions tab があり、各 revision の変更内容と、restore および delete action が表示されます。
Audit Log
configuration revision とは別に、各 agent は invocation の runtime audit log を保持します。これには user prompt、tool と integration の call、knowledge base search、final response、token usage が含まれます。
logging は agent の auditLog field によって制御され、新しい agent では default で有効です。console で toggle するか、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'},
)
log の読み取りは console 機能です。Squid Console で agent page の Audit Log tab を開いてください。log entry は SDK では公開されません。
Error Handling
Common Errors
| 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 timeout | agent が構成済みの timeoutMs(default: 4 分)より長くかかる | options の timeoutMs を増やす、prompt を簡略化する、または接続 tool の数を減らす |
| Embedding model cannot be modified | 既存 knowledge base の embeddingModel を変更しようとした | 代わりに、目的の embedding model を使用する新しい knowledge base を作成する |
Streaming における Error の処理
chat() を使用する場合、error は 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'),
});
Best Practices
Instructions
- instructions は簡潔かつ直接的にします。agent の role と、実行すべきこと(および実行すべきでないこと)を記述します。
- factual content ではなく behavioral rules(tone、scope、response style)に instructions を使用します。factual content は代わりに knowledge base に配置します。
- deploy 前に、Agent Studio の Test chat feature を使用して instructions の変更を test します。
Knowledge Bases
- knowledge base を接続する際は、説明的な
description値を使用します。特に複数接続されている場合、agent は description を基にどの knowledge base を参照するか決定します。
knowledge base content と metadata の構造化に関するガイダンスについては、knowledge base best practicesを参照してください。
Multi-Agent Workflows
- 接続する各 agent には、明確かつ具体的な description を指定します。曖昧な description は不正確な delegation につながります。
- agent 間で再帰的な call が無制限に実行されないよう、
quotas.maxAiCallStackSizeを適切な上限に設定します。 - 複雑な multi-step task には
executionPlanOptionsを使用し、agent が action 前に approach を reasoning できるようにします。
Performance
- 体感速度が重要な user-facing interaction には
chat()を使用します。streaming は完全な response を待たず、到着した token を表示します。 - request に knowledge base context が必要ない場合は、
disableContext: trueを設定して latency を削減します。 - conversation history を必要としない stateless な one-off request には、
memoryOptions.memoryMode: 'none'を使用します。
Agent の保護
Squid Client SDK を使用して agent を作成し chat を有効にする際、data の保護は極めて重要です。AI agent とその chat には sensitive information が含まれる可能性があるため、unauthorized usage や modification を防ぐために access と update を制限することが不可欠です。
AI agent の保護については、Securing AI agents documentation を参照してください。
Agent API Keys
Agent API Keys は、Agent action を呼び出す際に、よりきめ細かい security level を提供できます。詳細は Agent API Keys documentation を参照してください。