Agent Automations
AI agent を自動で実行:保存された prompt を cron schedule に従って、または event が発行されるたびに agent が実行します。
Automations を使う理由
Agent は、誰かが質問すると回答します。しかし、新しいサポートケースの毎晩の要約、受信メールの振り分け、SMS への対応など、誰かが質問するわけではない作業も数多くあります。Automations がなければ、agent を呼び出すだけの scheduler や event handler を用意する必要があります。
Automation は prompt を agent に保存し、自動で実行します。
await this.squid.ai().agent('support-copilot').upsertAutomation({
type: 'schedule',
name: 'Nightly case summary',
prompt: 'Summarize the support cases opened in the last 24 hours and file the summary.',
cron: '0 3 * * *',
timeZone: 'America/New_York',
});
概要
Automation は、agent が自動で実行する保存済みの prompt です。次の 2 種類があります。
- Schedule automation:cron expression(5 フィールド、または秒を含む 6 フィールド)に従い、IANA time zone(デフォルトは UTC)で評価され、最大で 1 分に 1 回実行されます。
- Event automation:backend code または connector から
squid.events().emit()で該当する type の event が発行されるたびに実行されます。Event はデータとして prompt に追加されるため、agent は何が実行をトリガーしたかを確認できます。
各実行は、owner の権限を持ち、memory を持たない通常の agent turn です。各実行は他の実行や chat history を参照できません。実行は job として追跡され、agent の監査が有効な場合は agent の audit log に記録されます。
Automations は client SDK の squid.ai().agent(id) で管理します。すべての method には app API key が必要なため、backend code から呼び出してください。Agent は最大 100 個の automation を持つことができます。Console の Studio では、agent の Automations タブに automation が表示され、コードを書かずに追加、編集、実行、無効化することもできます。
Automation の method は TypeScript client SDK で利用できます。Python SDK ではまだ利用できません。
クイックスタート
前提条件
- 既存の agent。例では
support-copilotを使用します。作成方法については AI Agent の構築方法を参照してください。 - デプロイ済みの Squid backend。Automation の method には app API key が必要です。
ステップ 1:Schedule automation を作成する
import { executable, SquidService } from '@squidcloud/backend';
export class AutomationSetupService extends SquidService {
@executable()
async createNightlySummary(): Promise<string> {
const automation = await this.squid.ai().agent('support-copilot').upsertAutomation({
type: 'schedule',
name: 'Nightly case summary',
prompt: 'Summarize the support cases opened in the last 24 hours.',
cron: '0 3 * * *', // every day at 03:00
timeZone: 'America/New_York',
});
return automation.id; // generated when you omit `id`
}
}
ステップ 2:1 回実行して確認する
runAutomation() は、automation の有効・無効にかかわらず直ちに実行を開始し、その実行の job を返します。
const { jobId } = await this.squid.ai().agent('support-copilot').runAutomation(automationId);
// Wait for the run and read the agent's answer.
const result = await this.squid.job().awaitJob(jobId);
console.log((result as { responseString: string }).responseString);
以降は schedule に従って実行されます。Automation の nextRunAt で次回の実行時刻を確認できます。
Automations の管理
すべての method は squid.ai().agent(agentId) にあり、app API key が必要です。
| Method | 動作 |
|---|---|
listAutomations() | Agent の automations を古い順に一覧表示します。 |
getAutomation(automationId) | Automation を 1 件返します。その ID に該当するものがない場合は undefined を返します。 |
upsertAutomation(params) | Automation を作成するか、同じ id を持つ automation を置き換えます。更新時に省略されたオプションのフィールドは削除されます。 |
setAutomationEnabled(automationId, enabled) | 定義の他の部分を変更せずに automation を有効または無効にします。Schedule を有効にすると、現在時刻を基準に次回の実行時刻が設定されます。 |
runAutomation(automationId) | 無効な automation でも直ちに実行を開始し、{ jobId } を返します。 |
deleteAutomation(automationId) | Automation を削除します。存在しない場合もエラーにはなりません。 |
各 automation の取得時には、実行履歴のフィールドも返されます。直近の実行については lastRunAt と lastJobId、有効な schedule については nextRunAt、実行がスキップされた場合は skippedRuns、lastSkippedAt、lastSkipReason が返されます(スキップされた実行を参照)。
Event Automations
Event automation は、該当する type の event が発行されると agent を実行します。
await this.squid.ai().agent('support-copilot').upsertAutomation({
type: 'event',
name: 'Triage incoming mail',
eventType: 'mail-received',
prompt: 'Triage this email: label it, and open a case if it reports a problem.',
maxRunsPerHour: 100, // guard against floods; defaults to 1000
});
独自の backend code を含め、squid.events().emit() を呼び出すすべてのものがトリガーできます。
import { generateUUID } from '@squidcloud/client';
await this.squid.events().emit({
id: generateUUID(), // a re-emit of the same id is dropped while the first run's job record exists
type: 'order-escalated',
payload: { orderId: 'ord_8731', reason: 'late delivery' },
// Optional: override the automation's default prompt for this event only.
prompt: 'An order was escalated. Draft an apology email and propose a credit.',
});
Prompt は次のように選択されます。Event 自体の prompt が優先され、なければ automation のデフォルトの prompt が使用されます。どちらもない event では実行は開始されません。いずれの場合も、event の type、ID、payload がデータとして prompt に追加され、agent が payload の内容を指示ではなく情報として扱うようにマークされます。
Connector events
いくつかの connector は、automation がリッスンできる event を発行します。
| Event type | 発行元 |
|---|---|
mail-received | Mail connector。メールの受信ごとに発行 |
slack-webhook-event | Slack connector |
teams-webhook-event | Teams connector |
twilio-sms-event | Twilio connector。SMS の受信ごとに発行 |
ai-voice-session-event | Voice agents。セッションの各マイルストーン(開始、終了、状態変更)で発行 |
Agent が同じ type の connector を複数持つ場合は、integrationIds で automation を特定の connector に紐付けます。すると、指定した integration ID のいずれかを持つ event に対してのみ automation が実行されます。
await this.squid
.ai()
.agent('support-copilot')
.upsertAutomation({
type: 'event',
name: 'Support inbox only',
eventType: 'mail-received',
prompt: 'Triage this email.',
integrationIds: ['support-mailbox'], // ignore events from other mail connectors
});
スキップされた実行
実行予定だった automation が実行されなかった場合、スキップが記録されます。理由は lastSkipReason で確認できます。
| 理由 | 意味 |
|---|---|
no_prompt | Event に prompt がなく、automation にもデフォルトの prompt がありません。 |
hourly_limit | Event automation が maxRunsPerHour に達しました。 |
overloaded | アプリケーションの event 実行のうち、開始待ちのものが多すぎます。 |
previous_run_in_progress | Schedule の実行時刻になったとき、前回の実行がまだ進行中でした。 |
実行の監視
Agent で auditLog が有効な場合、automation の実行は agent の audit log に記録されます。各実行の entry には automationId、automationName、automationTrigger(schedule、event、manual)のタグが付きます。Event による実行には、さらに automationEventType、automationEventId、automationPromptSource(event または default)が付きます。Log をフィルタリングして、1 つの automation の実行を確認できます。
const { entries } = await this.squid.ai().agent('support-copilot').auditLogs({ where: { automationId } });
for (const entry of entries) {
console.log(entry.createdAt, entry.tags['automationTrigger'], entry.prompt);
}
runAutomation() で開始した実行については、クイックスタートで示したように job を待機します。Job ID を持つ人は誰でもその job の結果を読み取れるため、返された job ID は非公開にしてください。
エラー処理
| エラー | 意味 |
|---|---|
API_KEY_REQUIRED | App API key なしで呼び出されました。Automation の method は backend code から呼び出してください。 |
automation.cron is not a valid cron expression: ... | Cron の形式が正しくありません。5 フィールド、または秒を含む 6 フィールドを使用してください。 |
automation.cron must not run more often than once a minute | 秒単位の cron は、1 分に 1 回を超える頻度では実行できません。 |
automation.timeZone is not a valid IANA time zone: ... | Offset ではなく、America/New_York のような zone 名を使用してください。 |
AUTOMATION_NOT_FOUND | setAutomationEnabled または runAutomation で、agent が持っていない automation が指定されました。 |
The automation has no default prompt: it runs only for events that carry their own | デフォルトの prompt がない event automation に対して runAutomation が呼び出されました。 |
AUTOMATION_RUN_NOT_STARTED | 手動実行を開始できませんでした。再試行してください。 |
An agent may have at most 100 automations | 追加する前に、不要になった automation を削除してください。 |
Agent を削除すると、その automations も削除されます。無効な automation は定義と履歴を保持しますが、実行は開始されません。
ベストプラクティス
- すべての emitter が prompt を送信する場合を除き、event automation にデフォルトの prompt を設定してください。 Event 側にも automation 側にも prompt がない場合、event は通知なくスキップされます(
no_prompt)。 - 想定される event の発生頻度に合わせて
maxRunsPerHourを設定してください。 デフォルトの 1000 は暴走するループを防ぎますが、受信量の多い mailbox の振り分け automation には、適切な値を検討して設定してください。 - 一定期間内の安全な再試行には event の
idを使用してください。 最初の実行の job record が存在する間は、同じ event ID の再発行は破棄されます。完了した job は完了からおよそ 1 時間後に削除され、その後は同じ ID で新しい実行が開始されます。短期間の再試行には source record から導出した安定した ID で event を発行し、それより長い期間については独自のデータで重複排除してください。 - Prompt は自己完結させてください。 実行には memory も chat history もありません。Agent に必要なものはすべて、prompt、追加された event、または agent 自体の instructions と接続された sources に含める必要があります。
- Automation の開発中は agent の audit log を有効にしてください。 Trigger、prompt source、event のタグにより、実行された理由や受け取った内容を簡単に確認できます。