@alvera-ai/platform-sdk 0.10.0-rc.8 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/.agent/AGENTS.md +499 -0
  2. package/.agent/account_management.md +456 -0
  3. package/.agent/action_status_updaters.md +264 -0
  4. package/.agent/ai_agents.md +462 -0
  5. package/.agent/ai_sandbox.md +265 -0
  6. package/.agent/async.md +112 -0
  7. package/.agent/connected_apps.md +408 -0
  8. package/.agent/cookbook/_fixtures/README.md +106 -0
  9. package/.agent/cookbook/_fixtures/accounts_receivable/_customers_accounts_receivable_customer.liquid +32 -0
  10. package/.agent/cookbook/_fixtures/accounts_receivable/_customers_accounts_receivable_mdm.liquid +20 -0
  11. package/.agent/cookbook/_fixtures/accounts_receivable/stripe_customers_batch1.csv +5 -0
  12. package/.agent/cookbook/_fixtures/foundation/_lead_submissions_foundation_generic_table.liquid +33 -0
  13. package/.agent/cookbook/_fixtures/foundation/_lead_submissions_foundation_legal_entity.liquid +88 -0
  14. package/.agent/cookbook/_fixtures/foundation/_lead_submissions_foundation_mdm.liquid +48 -0
  15. package/.agent/cookbook/_fixtures/healthcare/_cahps_appointments_healthcare_appointment.liquid +47 -0
  16. package/.agent/cookbook/_fixtures/healthcare/_cahps_appointments_healthcare_mdm.liquid +24 -0
  17. package/.agent/cookbook/_fixtures/healthcare/_cahps_appointments_healthcare_patient.liquid +38 -0
  18. package/.agent/cookbook/_fixtures/healthcare/memorandum-of-association-01.png +0 -0
  19. package/.agent/cookbook/_fixtures/healthcare/sample_two_page.pdf +43 -0
  20. package/.agent/cookbook/_fixtures/payment_risk/_compliance_screenings_payment_risk_compliance_screening.liquid +59 -0
  21. package/.agent/cookbook/_fixtures/payment_risk/_compliance_screenings_payment_risk_mdm.liquid +36 -0
  22. package/.agent/cookbook/_fixtures/payment_risk/_payment_accounts_payment_risk_mdm.liquid +30 -0
  23. package/.agent/cookbook/_fixtures/payment_risk/_payment_accounts_payment_risk_payment_account.liquid +55 -0
  24. package/.agent/cookbook/_setup/accounts_receivable.md +282 -0
  25. package/.agent/cookbook/_setup/foundation.md +277 -0
  26. package/.agent/cookbook/_setup/healthcare.md +279 -0
  27. package/.agent/cookbook/_setup/payment_risk.md +283 -0
  28. package/.agent/cookbook/action-status-updaters.md +212 -0
  29. package/.agent/cookbook/ai-agent-invoke.md +243 -0
  30. package/.agent/cookbook/appointment-review-sms-workflow.md +761 -0
  31. package/.agent/cookbook/birthday-greeting-sms-trigger.md +656 -0
  32. package/.agent/cookbook/bulk-ingest.md +254 -0
  33. package/.agent/cookbook/contact-us-triage-with-llm.md +622 -0
  34. package/.agent/cookbook/custom-tables.md +201 -0
  35. package/.agent/cookbook/dunning-sms-for-delinquent.md +619 -0
  36. package/.agent/cookbook/invite-team.md +194 -0
  37. package/.agent/cookbook/kyc-notification-on-account-activation.md +619 -0
  38. package/.agent/cookbook/rest-fetch.md +246 -0
  39. package/.agent/cookbook/sanctions-screening-with-agent-review.md +733 -0
  40. package/.agent/cookbook/score-leads-with-llm-categorization.md +624 -0
  41. package/.agent/cookbook/system-templates.md +129 -0
  42. package/.agent/cookbook/triage-prospects-by-priority.md +533 -0
  43. package/.agent/cookbook/welcome-sms-for-customers.md +607 -0
  44. package/.agent/data_activation_clients.md +559 -0
  45. package/.agent/data_sources.md +235 -0
  46. package/.agent/datalakes.md +714 -0
  47. package/.agent/debugging.md +137 -0
  48. package/.agent/errors.md +190 -0
  49. package/.agent/generic_tables.md +351 -0
  50. package/.agent/interoperability_contracts.md +417 -0
  51. package/.agent/mdm.md +293 -0
  52. package/.agent/mutations.md +126 -0
  53. package/.agent/templates.md +98 -0
  54. package/.agent/tool-call-configs.md +90 -0
  55. package/.agent/tools.md +547 -0
  56. package/.agent/type_naming.md +129 -0
  57. package/.agent/workflows.md +617 -0
  58. package/README.md +178 -0
  59. package/dist/bin/platform-sdk.d.mts +1 -0
  60. package/dist/bin/platform-sdk.mjs +106 -0
  61. package/dist/bin/platform-sdk.mjs.map +1 -0
  62. package/dist/index.d.mts +1310 -44116
  63. package/dist/index.d.mts.map +1 -1
  64. package/dist/index.mjs +1194 -7344
  65. package/dist/index.mjs.map +1 -1
  66. package/package.json +19 -10
@@ -0,0 +1,622 @@
1
+ ---
2
+ title: Triage inbound contact-us messages into three priority buckets via an LLM agent
3
+ summary: End-to-end agent-driven workflow — a chat-completion LLM agent classifies each contact-us submission into appointment_request / job_inquiry / flag_spam, the workflow's decision interpolates the agent's category, three SMS actions (one per bucket) fan out, and the run is verified row-by-row so every WEL carries exactly one matched action and two skipped.
4
+ industry: healthcare
5
+ slug: contact-us-triage-with-llm
6
+ vitest_source:
7
+ - integration-tests/tests/healthcare/agent-driven-workflow.test.ts
8
+ - integration-tests/tests/healthcare/generic-tables.test.ts
9
+ - integration-tests/tests/healthcare/tools.test.ts
10
+ - integration-tests/tests/healthcare/bootstrap.test.ts
11
+ status: green
12
+ ---
13
+
14
+ # Problem
15
+
16
+ A clinic's "Contact Us" form is a firehose of mixed intent. One
17
+ message asks to book an appointment, the next is a nurse applying
18
+ for a job, the third is promotional spam. Routing all three to the
19
+ same inbox means the appointment request waits behind the spam.
20
+
21
+ A keyword filter handles the obvious cases and misses the rest —
22
+ "I'd love to come in and see Dr. Johnson" has no booking keyword,
23
+ "openings" appears in both a job inquiry and a spam blast. The
24
+ classification is a language task, not a rules task.
25
+
26
+ The Alvera platform's agent-driven workflow primitive turns the
27
+ decision step into an LLM enrichment plus a Liquid interpolation.
28
+ An AI agent receives the submission's free text via a
29
+ context-mapping template, returns a JSON object whose `category`
30
+ field is one of three enum values, and the workflow's
31
+ decision_config interpolates that category into a one-element
32
+ decision array (`["{{ additional_context["agent-slug"].category }}"]`).
33
+ Three SMS actions are registered against the workflow, one per
34
+ bucket; the agent's output picks which one runs.
35
+
36
+ This cookbook walks the **whole** scenario: it provisions the
37
+ generic table, agent, and workflow, ingests three contact-us
38
+ submissions through the generic-table's auto-provisioned default
39
+ DAC, runs the workflow so the agent classifies each row, and
40
+ verifies the routing row-by-row — every Workflow Execution Log
41
+ carries exactly one matched action and two skipped, proving the
42
+ agent's category actually steered the fan-out.
43
+
44
+ The scenario is anchored to
45
+ `platform/integration-tests/tests/healthcare/agent-driven-workflow.test.ts`
46
+ — a green end-to-end test whose positive branch (§1, §3, §4, §6,
47
+ §7) is exactly this shape. The setup file `_setup/healthcare.md`
48
+ already provisioned the tenant + datalake + tenant-scoped client;
49
+ this cookbook starts from there.
50
+
51
+ # Composition
52
+
53
+ | Resource provisioned | Owner |
54
+ |-------------------------------------|-------------|
55
+ | Contact Us submissions dataset | build |
56
+ | SMS tool (SNS-backed) | build |
57
+ | LLM tool (Ollama chat completion) | build |
58
+ | Contact Us Triage AI agent | build |
59
+ | Contact Us Triage workflow | build |
60
+
61
+ The generic table's **default DAC** — auto-provisioned by the
62
+ platform when the generic table is created — is reused for
63
+ ingestion; no separate data source / tool / interop contract / DAC
64
+ is created. The setup file `_setup/healthcare.md` already
65
+ provisioned the tenant + datalake + tenant-scoped client; this
66
+ cookbook starts from there.
67
+
68
+ # Walkthrough
69
+
70
+ ## 001 — create the Contact Us submissions generic table
71
+
72
+ The agent-driven workflow targets a Generic Table dataset
73
+ (`dataset_type: 'generic_table'`) rather than a regulated domain
74
+ entity, because contact-us form rows do not fit a canonical FHIR
75
+ entity. The table's columns mirror the shape a website form export
76
+ would produce; the `message` column is what the agent reads, and
77
+ `category` is what the agent eventually writes back in production.
78
+ The server-derived `name` is captured — the workflow run in §009
79
+ addresses the regulated table as `regulated_<name>`.
80
+
81
+ ```typescript
82
+ const genericTableResp = await api.genericTables.create(tenantSlug, datalakeSlug, {
83
+ title: `Cookbook Contact Us ${runSuffix}`,
84
+ description: 'Inbound contact-us form submissions the Triage agent classifies.',
85
+ columns: [
86
+ {
87
+ name: 'submission_id',
88
+ title: 'Submission ID',
89
+ type: 'string',
90
+ description: 'Vendor-supplied unique submission id',
91
+ is_unique: true,
92
+ privacy_requirement: 'none',
93
+ },
94
+ {
95
+ name: 'name',
96
+ title: 'Name',
97
+ type: 'string',
98
+ description: 'Submitter full name',
99
+ is_unique: false,
100
+ privacy_requirement: 'tokenize',
101
+ },
102
+ {
103
+ name: 'email',
104
+ title: 'Email',
105
+ type: 'string',
106
+ description: 'Submitter email',
107
+ is_unique: false,
108
+ privacy_requirement: 'tokenize',
109
+ },
110
+ {
111
+ name: 'message',
112
+ title: 'Message',
113
+ type: 'string',
114
+ description: 'Free-text contact-us message — the agent classifies this',
115
+ is_unique: false,
116
+ privacy_requirement: 'none',
117
+ },
118
+ {
119
+ name: 'category',
120
+ title: 'Category',
121
+ type: 'string',
122
+ description: 'Triage bucket assigned by the Contact Us Triage agent',
123
+ is_unique: false,
124
+ privacy_requirement: 'none',
125
+ },
126
+ ],
127
+ })
128
+ genericTableId = genericTableResp.data.id!
129
+ ctx.gtName = genericTableResp.data.name!
130
+ ```
131
+
132
+ ## 002 — create the SMS tool
133
+
134
+ A single SMS tool dispatches every bucket's outbound message; the
135
+ per-bucket SMS body lives on each workflow action, not on the tool.
136
+ SNS-backed LocalStack wiring — `intent: 'sms'` tags it for
137
+ workflow-action use.
138
+
139
+ ```typescript
140
+ const smsToolResp = await api.tools.create(tenantSlug, datalakeSlug, {
141
+ name: `Cookbook SMS Tool ${runSuffix}`,
142
+ description: 'SNS-backed SMS dispatcher for the Contact Us Triage workflow, wired to LocalStack.',
143
+ intent: 'sms',
144
+ status: 'active',
145
+ datalake_id: ctx.datalakeId,
146
+ body: {
147
+ tool_body_type: 'sns',
148
+ auth_method: 'access_key',
149
+ region: 'us-east-1',
150
+ phone_number: '+15551234567',
151
+ endpoint_url: 'http://localhost:4566',
152
+ access_key_id: 'test',
153
+ secret_access_key: 'test',
154
+ },
155
+ })
156
+ toolId = smsToolResp.data.id!
157
+ ```
158
+
159
+ ## 003 — create the LLM tool
160
+
161
+ The Triage agent calls a chat-completion endpoint to classify each
162
+ row. The tool's `intent: 'llm_enrichment'` distinguishes it from
163
+ the SMS tool above. It is a **provider adapter**: `base_body` authors
164
+ the provider's request — here Ollama's native `/api/chat` shape with
165
+ `think: false` and a `format` schema so the model returns clean,
166
+ schema-constrained JSON — and `response_extractor` maps the provider's
167
+ envelope back to the canonical `{ output_json, … }` the platform reads.
168
+ The extractor's `output_schema` is required for an `llm_enrichment`
169
+ tool. The `api_key`/`auth_method` pair satisfies the REST tool's schema
170
+ even though Ollama ignores the header.
171
+
172
+ ```typescript
173
+ const ENRICHMENT_OUTPUT_SCHEMA = {
174
+ type: 'object',
175
+ properties: {
176
+ output_json: {},
177
+ input_tokens: { type: ['integer', 'null'] },
178
+ output_tokens: { type: ['integer', 'null'] },
179
+ total_tokens: { type: ['integer', 'null'] },
180
+ explanation: { type: ['string', 'null'] },
181
+ },
182
+ required: ['output_json'],
183
+ }
184
+
185
+ const OLLAMA_BASE_BODY =
186
+ '{"model": "{{ model }}", "messages": [{"role": "user", "content": "{{ rendered_prompt | json_escape }}", "images": [{% for img in images %}{% unless forloop.first %}, {% endunless %}"{{ img.data }}"{% endfor %}]}], "stream": false, "think": false, "options": {"temperature": 0, "num_ctx": 40960}, "format": {{ schema | to_json }}}'
187
+
188
+ const OLLAMA_EXTRACTOR =
189
+ '{"output_json": "{{ msg.message.content | json_escape }}", "explanation": "{{ msg.message.thinking | json_escape }}", "input_tokens": {{ msg.prompt_eval_count | default: 0 }}, "output_tokens": {{ msg.eval_count | default: 0 }}, "total_tokens": {{ msg.prompt_eval_count | default: 0 | plus: msg.eval_count }}}'
190
+
191
+ const llmToolResp = await api.tools.create(tenantSlug, datalakeSlug, {
192
+ name: `Cookbook LLM Tool ${runSuffix}`,
193
+ description: 'Ollama-backed chat-completion adapter for Contact Us triage classification.',
194
+ intent: 'llm_enrichment',
195
+ status: 'active',
196
+ datalake_id: ctx.datalakeId,
197
+ response_extractor: { type: 'custom', body: OLLAMA_EXTRACTOR, output_schema: ENRICHMENT_OUTPUT_SCHEMA },
198
+ body: {
199
+ tool_body_type: 'rest_api',
200
+ base_url: 'http://localhost:11434',
201
+ base_path: { type: 'custom', body: '/api/chat' },
202
+ auth_method: 'api_key',
203
+ api_key: 'stub-key',
204
+ api_key_name: 'Authorization',
205
+ api_key_location: 'header',
206
+ request_type: 'json',
207
+ response_type: 'json',
208
+ timeout_ms: 60_000,
209
+ base_body: { type: 'custom', body: OLLAMA_BASE_BODY },
210
+ },
211
+ })
212
+ ctx.llmToolId = llmToolResp.data.id!
213
+ ```
214
+
215
+ ## 004 — create the Contact Us Triage AI agent
216
+
217
+ The agent binds three things: the model name (sent on every
218
+ inference call), an input schema the workflow's context-mapping
219
+ must satisfy, and a response schema the agent's output must match.
220
+ The response schema's `enum: ['appointment_request','job_inquiry','flag_spam']`
221
+ constraint is what guards the downstream decision interpolation
222
+ from emitting a category the workflow has no SMS action for.
223
+ `temperature: 0.0` removes sampling noise so identical inputs
224
+ classify identically. `data_access: 'unregulated'` says the agent
225
+ only ever sees the tokenized projection of each row.
226
+
227
+ ```typescript
228
+ const TRIAGE_INPUT_SCHEMA = {
229
+ type: 'object',
230
+ properties: {
231
+ msg: { type: 'string' },
232
+ submission_id: { type: 'string' },
233
+ },
234
+ required: ['msg', 'submission_id'],
235
+ }
236
+
237
+ const TRIAGE_RESPONSE_SCHEMA = {
238
+ type: 'object',
239
+ properties: {
240
+ category: {
241
+ type: 'string',
242
+ enum: ['appointment_request', 'job_inquiry', 'flag_spam'],
243
+ },
244
+ },
245
+ required: ['category'],
246
+ }
247
+
248
+ const AGENT_PROMPT_BODY = `You are a triage assistant. Categorize the following message into EXACTLY ONE of these categories:
249
+
250
+ - "appointment_request" — the user wants to book/reschedule a medical appointment
251
+ - "job_inquiry" — the user is asking about employment or job opportunities
252
+ - "flag_spam" — the message is promotional / spam / irrelevant
253
+
254
+ Submission ID: {{ submission_id }}
255
+ Message: {{ msg }}
256
+
257
+ Respond with a JSON object: {"category": "<one of the three categories above>"}`
258
+
259
+ const agentResp = await api.aiAgents.create(tenantSlug, datalakeSlug, {
260
+ name: `Cookbook Contact Us Triage Agent ${runSuffix}`,
261
+ tool_id: ctx.llmToolId,
262
+ model: 'qwen3-vl:8b-instruct',
263
+ data_access: 'unregulated',
264
+ temperature: 0.0,
265
+ max_tokens: 1024,
266
+ enabled: true,
267
+ input_schema: TRIAGE_INPUT_SCHEMA,
268
+ llm_response_schema: TRIAGE_RESPONSE_SCHEMA,
269
+ prompt_config: { type: 'custom', body: AGENT_PROMPT_BODY },
270
+ })
271
+ aiAgentId = agentResp.data.id!
272
+ ctx.agentSlug = agentResp.data.slug!
273
+ ```
274
+
275
+ ## 005 — create the Contact Us Triage workflow
276
+
277
+ The workflow has the standard shape — filter, decision, actions —
278
+ but two things distinguish it from a static workflow. First, the
279
+ Triage agent is **nested** in the workflow create body (the
280
+ `workflow_ai_agents` array — a `cast_assoc`, not a separate attach
281
+ call), binding it into the workflow's enrichment phase with a Liquid
282
+ `context_mapping_config` that projects each submission row's fields
283
+ into the agent's input schema. Second, the `decision_config` body is a Liquid template
284
+ that interpolates the agent's `category` output (read from
285
+ `additional_context["<agent-slug>"].category`) into a
286
+ single-element decision array. The three `actions` are keyed
287
+ `decision_key: appointment_request|job_inquiry|flag_spam`;
288
+ whichever category the agent emits picks the action that fires,
289
+ leaving the other two `:skipped`.
290
+
291
+ Bracket access (`additional_context["..."]`) is used because the
292
+ agent's slug contains hyphens, which a dotted Liquid lookup could
293
+ misread as subtraction operators.
294
+
295
+ ```typescript
296
+ const BUCKETS = ['appointment_request', 'job_inquiry', 'flag_spam'] as const
297
+
298
+ const CONTEXT_MAPPING_BODY = JSON.stringify({
299
+ msg: '{{ event_dataset.message }}',
300
+ submission_id: '{{ event_dataset.submission_id }}',
301
+ })
302
+
303
+ const DECISION_CONFIG_BODY = `["{{ additional_context["${ctx.agentSlug}"].category }}"]`
304
+ const DECISION_OUTPUT_SCHEMA = { type: 'array', items: { type: 'string' } }
305
+
306
+ const workflowResp = await api.workflows.create(tenantSlug, datalakeSlug, {
307
+ name: `Cookbook Contact Us Triage Workflow ${runSuffix}`,
308
+ description: 'Triages contact-us submissions into appointment_request/job_inquiry/flag_spam via an LLM agent; one SMS action per bucket.',
309
+ dataset_type: 'generic_table',
310
+ generic_table_id: genericTableId,
311
+ skip_mdm_resolution: true,
312
+ status: 'live',
313
+ filter_config: {
314
+ type: 'custom',
315
+ body: 'true',
316
+ output_schema: { type: 'boolean' },
317
+ },
318
+ decision_config: {
319
+ type: 'custom',
320
+ body: DECISION_CONFIG_BODY,
321
+ output_schema: DECISION_OUTPUT_SCHEMA,
322
+ },
323
+ actions: BUCKETS.map((bucket) => ({
324
+ decision_key: bucket,
325
+ action_type: 'sms',
326
+ tool_id: toolId,
327
+ position: 0,
328
+ trigger_template: 'now',
329
+ idempotency_template: `{{ subject_id }}-{{ action_id }}-${bucket}-{{ "" | uuid }}`,
330
+ tool_call: {
331
+ tool_call_type: 'sms_request',
332
+ to: { type: 'custom', body: '+15551234567' },
333
+ body: {
334
+ type: 'custom',
335
+ body: `Triage [${bucket}]: {{ event_dataset.message }}`,
336
+ },
337
+ sms_type: 'transactional',
338
+ },
339
+ })),
340
+ // Nest the triage agent inline. Workflow joins omit output_schema —
341
+ // the server pins it from the agent's input_schema.
342
+ workflow_ai_agents: [
343
+ {
344
+ ai_agent_id: aiAgentId,
345
+ position: 0,
346
+ context_mapping_config: { type: 'custom', body: CONTEXT_MAPPING_BODY },
347
+ },
348
+ ],
349
+ })
350
+ workflowId = workflowResp.data.id!
351
+ ctx.workflowSlug = workflowResp.data.slug!
352
+ ```
353
+
354
+ ## 006 — find the generic table's auto-provisioned default DAC
355
+
356
+ Creating a generic table provisions two things automatically: an
357
+ identity interoperability contract and a default Data Activation
358
+ Client bound to it (name pattern `<datalake> <gt_name>
359
+ DataActivationClient`, `tool_call: manual_upload`). No data source,
360
+ tool, interop contract, or DAC needs to be created by hand for
361
+ plain row ingestion into the table — the default DAC is found by
362
+ GT-name convention in the DAC listing.
363
+
364
+ ```typescript
365
+ const deadline = Date.now() + 30_000
366
+ let found: { slug?: string | null; name?: string | null } | undefined
367
+ while (Date.now() < deadline && !found) {
368
+ const { data } = await api.dataActivationClients.list(tenantSlug, datalakeSlug)
369
+ found = (data.data ?? []).find((d) => (d.name ?? '').includes(ctx.gtName))
370
+ if (!found) await new Promise((r) => setTimeout(r, 1_000))
371
+ }
372
+ if (!found?.slug) {
373
+ throw new Error(`no default DAC found for GT ${ctx.gtName} within 30s`)
374
+ }
375
+ ctx.dacSlug = found.slug
376
+ ```
377
+
378
+ ## 007 — ingest three contact-us submissions through the default DAC
379
+
380
+ Three rows, ingested as inline JSON through the default DAC. Each
381
+ carries a deliberately distinct `message` — a clear appointment
382
+ request, an unmistakable job inquiry, and obvious promotional spam
383
+ — so the agent has something unambiguous to classify. The
384
+ `category` column is left unset on ingest; it is the agent's job
385
+ to assign one. Each ingest call returns its own batch id; all
386
+ three are pinned for the run scope in §009.
387
+
388
+ ```typescript
389
+ const submissionRows = [
390
+ {
391
+ submission_id: `SUB-APPT-${runSuffix}`,
392
+ name: 'Maria Garcia',
393
+ email: `maria-${runSuffix}@example.com`,
394
+ message:
395
+ 'I would like to schedule an appointment with Dr. Johnson next week if possible.',
396
+ },
397
+ {
398
+ submission_id: `SUB-JOB-${runSuffix}`,
399
+ name: 'James Wilson',
400
+ email: `james-${runSuffix}@example.com`,
401
+ message:
402
+ 'I am a registered nurse looking for employment opportunities at your clinic.',
403
+ },
404
+ {
405
+ submission_id: `SUB-SPAM-${runSuffix}`,
406
+ name: 'BestDeals2026',
407
+ email: `promo-${runSuffix}@cheapmeds.xyz`,
408
+ message:
409
+ 'HUGE DISCOUNT on cheap medications and miracle cures! CLICK HERE NOW for 90% off!',
410
+ },
411
+ ]
412
+
413
+ const ingestResults = await Promise.all(
414
+ submissionRows.map((row) =>
415
+ api.dataActivationClients.ingest(tenantSlug, datalakeSlug, ctx.dacSlug, { data: row }),
416
+ ),
417
+ )
418
+ ctx.submissionBatchIds = ingestResults.map((r) => r.data.batch_id!)
419
+ if (ctx.submissionBatchIds.length !== 3) {
420
+ throw new Error(`expected 3 ingest batch ids, got ${ctx.submissionBatchIds.length}`)
421
+ }
422
+ ```
423
+
424
+ ## 008 — wait for the three ingest batches to reach steady-state
425
+
426
+ Ingestion is async — the DAC enqueues per-row jobs that drain into
427
+ the generic table. Poll the DAC's activation logs until every
428
+ batch shows a row with `dataset_updated >= 1` (the submission row
429
+ was upserted into the table).
430
+
431
+ ```typescript
432
+ const targetBatches = new Set<string>(ctx.submissionBatchIds)
433
+ const deadline = Date.now() + 90_000
434
+ let greenCount = 0
435
+ while (Date.now() < deadline) {
436
+ const { data } = await api.dataActivationClients.logs.list(tenantSlug, datalakeSlug, ctx.dacSlug)
437
+ const green = new Set<string>()
438
+ for (const row of (data.data ?? []) as Array<Record<string, unknown>>) {
439
+ const b = row.batch_id
440
+ if (typeof b !== 'string' || !targetBatches.has(b)) continue
441
+ if (typeof row.dataset_updated !== 'number' || row.dataset_updated < 1) continue
442
+ green.add(b)
443
+ }
444
+ greenCount = green.size
445
+ if (greenCount === targetBatches.size) break
446
+ await new Promise((r) => setTimeout(r, 1_000))
447
+ }
448
+ if (greenCount !== targetBatches.size) {
449
+ throw new Error(`only ${greenCount}/3 submission batches reached steady-state within 90s`)
450
+ }
451
+ ```
452
+
453
+ ## 009 — run the workflow against the three submissions
454
+
455
+ `workflows.run` triggers the full agent-driven pipeline per row:
456
+ filter → agent enrichment (the Ollama call that classifies the
457
+ message) → decision (the category interpolated into the decision
458
+ array) → action fan-out. The SQL where-clause scopes the run to
459
+ exactly the three submission ids §007 ingested (`submission_id` is
460
+ the generic table's unique column, so it pins the run directly).
461
+
462
+ The Triage actions use `trigger_template: 'now'`, so they dispatch
463
+ immediately and the run reaches a terminal status — poll
464
+ `batchLogs.refresh` until it leaves `:pending`. The window is
465
+ generous because each row's enrichment is a live LLM inference
466
+ call.
467
+
468
+ ```typescript
469
+ const submissionIds = [
470
+ `SUB-APPT-${runSuffix}`,
471
+ `SUB-JOB-${runSuffix}`,
472
+ `SUB-SPAM-${runSuffix}`,
473
+ ]
474
+ const idList = submissionIds.map((id) => `'${id}'`).join(', ')
475
+
476
+ const runResp = await api.workflows.run(tenantSlug, datalakeSlug, ctx.workflowSlug, {
477
+ sql_where_clause: `submission_id IN (${idList})`,
478
+ mode: 'live',
479
+ manual_override: true,
480
+ })
481
+ ctx.runLogId = runResp.data.workflow_run_log_id!
482
+ ctx.runBatchId = runResp.data.batch_id!
483
+
484
+ const deadline = Date.now() + 240_000
485
+ let status: string | null = null
486
+ while (Date.now() < deadline) {
487
+ const { data: log } = await api.workflows.batchLogs.refresh(tenantSlug, datalakeSlug, ctx.workflowSlug, ctx.runLogId)
488
+ status = log.status ?? null
489
+ if (status && status !== 'pending') break
490
+ await new Promise((r) => setTimeout(r, 2_000))
491
+ }
492
+ if (status === 'failed') {
493
+ throw new Error('agent-driven workflow run reached :failed')
494
+ }
495
+ if (!status || status === 'pending') {
496
+ throw new Error('workflow run did not leave :pending within 240s')
497
+ }
498
+ ```
499
+
500
+ ## 010 — verify the agent's category steered the fan-out
501
+
502
+ Each submission produced a Workflow Execution Log. Every WEL has
503
+ exactly **three** action execution logs — one per bucket — and
504
+ exactly **one** is matched (`:pending` or `:completed`, the
505
+ category the agent emitted) while the other **two** are
506
+ `:skipped`. A run where a WEL had two matched actions, or zero,
507
+ would mean the agent's output did not actually steer the decision;
508
+ this step fails loudly in that case.
509
+
510
+ ```typescript
511
+ const { data: wfLogs } = await api.workflows.workflowLogs.list(tenantSlug, datalakeSlug, ctx.workflowSlug)
512
+ const ourWels = (wfLogs.data ?? []).filter(
513
+ (w) => (w as { batch_id?: string }).batch_id === ctx.runBatchId,
514
+ )
515
+ if (ourWels.length !== 3) {
516
+ throw new Error(`expected 3 WELs for the run, got ${ourWels.length}`)
517
+ }
518
+
519
+ for (const wel of ourWels) {
520
+ const welId = (wel as { id?: string }).id
521
+ const aels =
522
+ (wel as { action_execution_logs?: Array<{ status?: string; decision_key?: string }> })
523
+ .action_execution_logs ?? []
524
+ if (aels.length !== 3) {
525
+ throw new Error(`WEL ${welId}: expected 3 AELs (one per bucket), got ${aels.length}`)
526
+ }
527
+ const byStatus: Record<string, number> = {}
528
+ for (const ael of aels) {
529
+ const st = ael.status ?? 'unknown'
530
+ byStatus[st] = (byStatus[st] ?? 0) + 1
531
+ }
532
+ const matched = (byStatus.pending ?? 0) + (byStatus.completed ?? 0)
533
+ if (matched !== 1) {
534
+ throw new Error(`WEL ${welId}: expected exactly 1 matched AEL, got ${matched} — ${JSON.stringify(byStatus)}`)
535
+ }
536
+ if ((byStatus.skipped ?? 0) !== 2) {
537
+ throw new Error(`WEL ${welId}: expected 2 :skipped AELs — ${JSON.stringify(byStatus)}`)
538
+ }
539
+ const routed = aels.find((a) => a.status === 'pending' || a.status === 'completed')
540
+ if (!routed?.decision_key || !/^(appointment_request|job_inquiry|flag_spam)$/.test(routed.decision_key)) {
541
+ throw new Error(`WEL ${welId}: matched AEL has unexpected decision_key ${routed?.decision_key}`)
542
+ }
543
+ }
544
+ ```
545
+
546
+ # Branches
547
+
548
+ - **The filter is permissive** — `filter_config.body: 'true'`
549
+ passes every row, so all three submissions reach the agent. The
550
+ interesting routing happens at the decision step, not the
551
+ filter. A production triage workflow might gate on a
552
+ not-yet-handled flag in the filter; that polarity is covered by
553
+ the `appointment-review-sms-workflow` cookbook.
554
+ - **Agent emits an out-of-enum category** — the LLM response
555
+ schema's `enum` constraint guards the decision interpolation. If
556
+ the model returned an unexpected string the workflow row's
557
+ execution log would land `:failed`. The anchor vitest treats
558
+ that as a model-quality failure rather than a platform bug;
559
+ production deployments either tighten the prompt or add a
560
+ default SMS action as a fallback bucket.
561
+ - **Transport failure on the LLM call** — the anchor vitest's §8
562
+ wires a second LLM tool to a deliberately wrong Ollama URL and
563
+ asserts the WEL lands `:failed` with `error_code:
564
+ tool_execution_failed` in its `error.json` artifact. This
565
+ cookbook walks only the happy path; the failure branch is the
566
+ anchor test's own coverage.
567
+
568
+ # Rollback
569
+
570
+ The cookbook doctest harness does not currently tear down created
571
+ resources. The `_setup/healthcare.md` setup file's runSuffix-scoped
572
+ tenant / datalake / user names mean each run is naturally isolated;
573
+ the seeded local DB is cheap to reset (`mix ecto.reset` on the
574
+ platform repo).
575
+
576
+ # Outcome
577
+
578
+ After this cookbook's ten steps run green:
579
+
580
+ - A healthcare tenant exists with a healthcare-domain datalake
581
+ - A Contact Us Generic Table, an SMS tool, a chat-completion LLM
582
+ tool, a Contact Us Triage AI agent (qwen3-vl:8b-instruct, three-category
583
+ response schema), and a Contact Us Triage agent-driven workflow
584
+ are all registered
585
+ - Three contact-us submissions have been ingested through the
586
+ table's auto-provisioned default DAC
587
+ - Running the workflow drove each row through the agent: the LLM
588
+ classified the message, the decision interpolated the category,
589
+ and the matching bucket's SMS action fired
590
+ - The routing is verified row-by-row — every Workflow Execution
591
+ Log carries exactly one matched action and two `:skipped`,
592
+ proving the agent's output actually steered the fan-out
593
+
594
+ The business outcome — inbound contact-us messages triaged by an
595
+ LLM and routed to bucket-specific outreach — is demonstrated
596
+ end-to-end, not merely provisioned.
597
+
598
+ # See also
599
+
600
+ - `_setup/healthcare.md` — the inlined bootstrap that provisions
601
+ the tenant + datalake this cookbook starts from
602
+ - `appointment-review-sms-workflow.md` — the static-decision
603
+ counterpart in healthcare; same SMS wiring, full data-activation
604
+ chain, no agent
605
+ - `score-leads-with-llm-categorization.md` — the foundation
606
+ agent-driven cookbook; identical agent + generic-table shape,
607
+ four bands instead of three buckets
608
+ - `.agent/tools.md` — SMS and chat-completion tool body shapes;
609
+ intent classification
610
+ - `.agent/ai_agents.md` — AI agent registration shape; input +
611
+ response schemas; prompt config
612
+ - `.agent/workflows.md` — standard and agent-driven workflow
613
+ primitives; `ai_agents`, `context_mapping_config`, and
614
+ agent-output decision interpolation
615
+ - `.agent/generic_tables.md` — generic-table creation and the
616
+ auto-provisioned identity contract + default DAC
617
+ - `integration-tests/tests/healthcare/agent-driven-workflow.test.ts` —
618
+ the anchor green test (positive branch §1, §3, §4, §6, §7) these
619
+ snippets are lifted from
620
+ - `integration-tests/tests/healthcare/generic-tables.test.ts`,
621
+ `tools.test.ts` — the per-resource create snippets are lifted
622
+ from