Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 46 additions & 71 deletions apps/docs/components/workflow-preview/examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1445,14 +1445,28 @@ const GUARDRAILS_START = {
position: { x: 0, y: 0 },
} as const

const GUARDRAILS_GATE = {
id: 'condition',
name: 'Condition',
type: 'condition',
typeLabel: 'Condition',
bgColor: '#FF752F',
position: { x: 640, y: 0 },
} as const
/** A Function block in a guardrails example: the passing path (top) or the error path (bottom). */
function guardrailsFunction(id: string, name: string, code: string, path: 'pass' | 'error') {
return {
id,
name,
type: 'function',
typeLabel: 'Function',
sentence: ['Run', { subBlockId: 'Code', noun: 'code' }],
bgColor: '#FF402F',
position: { x: 640, y: path === 'pass' ? -60 : 140 },
rows: [{ title: 'Code', value: code }],
}
}

/** A guardrails example's edges: the check passes to `passId`, and fails through its error port to `errorId`. */
function guardrailsEdges(passId: string, errorId: string): PreviewWorkflow['edges'] {
return [
{ id: 'start-guardrails', source: 'start', target: 'guardrails' },
{ id: `guardrails-${passId}`, source: 'guardrails', target: passId },
{ id: `guardrails-${errorId}`, source: 'guardrails', target: errorId, sourceHandle: 'error' },
]
}

/** Guardrails example: validate JSON before parsing it. */
export const GUARDRAILS_JSON_WORKFLOW: PreviewWorkflow = {
Expand All @@ -1473,46 +1487,15 @@ export const GUARDRAILS_JSON_WORKFLOW: PreviewWorkflow = {
{ title: 'Validation', value: 'Valid JSON' },
],
},
{
...GUARDRAILS_GATE,
rows: [],
branches: [
{ id: 'condition-if', label: 'If', value: '<guardrails.passed>' },
{ id: 'condition-else', label: 'else' },
],
},
{
id: 'parse',
name: 'Parse',
type: 'function',
typeLabel: 'Function',
sentence: ['Run', { subBlockId: 'Code', noun: 'code' }],
bgColor: '#FF402F',
position: { x: 960, y: -60 },
rows: [{ title: 'Code', value: 'return JSON.parse(<agent.content>);' }],
},
{
id: 'reject',
name: 'Reject',
type: 'function',
typeLabel: 'Function',
sentence: ['Run', { subBlockId: 'Code', noun: 'code' }],
bgColor: '#FF402F',
position: { x: 960, y: 140 },
rows: [{ title: 'Code', value: 'return { valid: false, error: <guardrails.error> };' }],
},
],
edges: [
{ id: 'start-guardrails', source: 'start', target: 'guardrails' },
{ id: 'guardrails-condition', source: 'guardrails', target: 'condition' },
{ id: 'condition-parse', source: 'condition', target: 'parse', sourceHandle: 'condition-if' },
{
id: 'condition-reject',
source: 'condition',
target: 'reject',
sourceHandle: 'condition-else',
},
guardrailsFunction('parse', 'Parse', 'return JSON.parse(<agent.content>);', 'pass'),
guardrailsFunction(
'reject',
'Reject',
'return { valid: false, error: <guardrails.error> };',
'error'
),
],
edges: guardrailsEdges('parse', 'reject'),
}

/** Guardrails example: check an answer is grounded in the knowledge base. */
Expand Down Expand Up @@ -1541,19 +1524,15 @@ export const GUARDRAILS_HALLUCINATION_WORKFLOW: PreviewWorkflow = {
{ title: 'Model', value: 'claude-sonnet-5-5' },
],
},
{
...GUARDRAILS_GATE,
rows: [],
branches: [
{ id: 'condition-if', label: 'If', value: '<guardrails.score> >= 3' },
{ id: 'condition-else', label: 'else' },
],
},
],
edges: [
{ id: 'start-guardrails', source: 'start', target: 'guardrails' },
{ id: 'guardrails-condition', source: 'guardrails', target: 'condition' },
guardrailsFunction('answer', 'Answer', 'return <agent.content>;', 'pass'),
guardrailsFunction(
'flag',
'Flag',
'return { grounded: false, score: <guardrails.score>, reason: <guardrails.error> };',
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
'error'
),
],
edges: guardrailsEdges('answer', 'flag'),
}

/** Guardrails example: block user input that contains PII. */
Expand Down Expand Up @@ -1586,19 +1565,15 @@ export const GUARDRAILS_PII_WORKFLOW: PreviewWorkflow = {
{ title: 'Action', value: 'Block Request' },
],
},
{
...GUARDRAILS_GATE,
rows: [],
branches: [
{ id: 'condition-if', label: 'If', value: '<guardrails.passed>' },
{ id: 'condition-else', label: 'else' },
],
},
],
edges: [
{ id: 'start-guardrails', source: 'start', target: 'guardrails' },
{ id: 'guardrails-condition', source: 'guardrails', target: 'condition' },
guardrailsFunction('process', 'Process', 'return <start.input>;', 'pass'),
guardrailsFunction(
'reject',
'Reject',
'return { rejected: true, found: <guardrails.detectedEntities> };',
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
'error'
),
],
edges: guardrailsEdges('process', 'reject'),
}

/** HITL example: a human approves AI content before it ships. */
Expand Down
25 changes: 15 additions & 10 deletions apps/docs/content/docs/workflows/blocks/guardrails.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,27 @@ description: Validate JSON, match a pattern, assess grounding, or detect PII.
import { Callout } from '@/components/ui/callout'
import { BlockPreview, WorkflowPreview, GUARDRAILS_JSON_WORKFLOW, GUARDRAILS_HALLUCINATION_WORKFLOW, GUARDRAILS_PII_WORKFLOW } from '@/components/workflow-preview'

The **Guardrails block** checks content and returns a result. Each block runs one validation type; chain blocks for multiple checks. Validation alone does not choose the next path—connect a Condition to act on it.
The **Guardrails block** checks content. Each block runs one validation type; chain blocks for multiple checks. A passing check continues along the normal output. A failed check leaves through the block's **error port**, so connect the error port to handle it.

<Callout type="warn">
Do not branch on `<guardrails.passed>` with a Condition. A failed check never reaches the Condition, and with nothing on the error port the run completes without output. In workflow code, wire the failure with `onError`: `check.onError(reject)`.
</Callout>

<BlockPreview type="guardrails" />

## Validate before parsing

<WorkflowPreview workflow={GUARDRAILS_JSON_WORKFLOW} />

Select **Valid JSON**, check `<agent.content>`, and branch on `<guardrails.passed>` before parsing it in Function. This checks JSON syntax, not a schema's required fields or types.
Select **Valid JSON** and check `<agent.content>`. Valid JSON continues to the Function that parses it; invalid JSON takes the error port to **Reject**, which reads the parse error as `<guardrails.error>`. This checks JSON syntax, not a schema's required fields or types.

## Configuration

Set **Content to Validate** to text or an earlier output, then select **Validation Type**.

### Valid JSON

Passes when the content parses as JSON. Invalid content returns `passed: false` and a parse error. Use a Function after this check if you also need schema validation.
Passes when the content parses as JSON. Invalid content fails the check with a parse error in `error`. Use a Function after this check if you also need schema validation.

### Regex match

Expand All @@ -32,7 +36,7 @@ Enter **Regex Pattern**, for example an email pattern:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
```

Patterns use RE2's linear-time engine. Lookahead, lookbehind, and backreferences are unsupported and fail validation. To require that content does not contain a pattern, match the pattern and invert `passed` in a Condition.
Patterns use RE2's linear-time engine. Lookahead, lookbehind, and backreferences are unsupported and fail validation. To require that content does not contain a pattern, use a Condition or Function instead: a Regex Match that fails always takes the error port.

### Hallucination check

Expand Down Expand Up @@ -71,8 +75,8 @@ The picker groups these regional identifiers. Availability depends on the select

| Action | Result when PII is found |
| --- | --- |
| **Block Request** (default) | `passed: false`, detected entities, and an error summary |
| **Mask PII** | Replaced text in `maskedText`; `passed: true` when masking succeeds |
| **Block Request** (default) | Fails the check through the error port, with the detected entities and an error summary |
| **Mask PII** | Passes, with replaced text in `maskedText` |

With no PII found, Mask returns the original text. Read `detectedEntities` to distinguish no detection from successful masking.

Expand All @@ -84,10 +88,10 @@ Use `<guardrails.maskedText>` downstream in Mask mode. The original content is s

| Reference | Value |
| --- | --- |
| `<guardrails.passed>` | Validation outcome; for Mask, whether masking succeeded |
| `<guardrails.passed>` | `true` after a passing check; a failed check takes the error port instead |
| `<guardrails.validationType>` | Check that ran |
| `<guardrails.input>` | Original checked content |
| `<guardrails.error>` | Failure message, when present |
| `<guardrails.error>` | Why the check failed, for the block on the error port |
| `<guardrails.score>` / `<guardrails.reasoning>` | Grounding score and explanation for Hallucination Check |
| `<guardrails.detectedEntities>` | PII entities with type, location, detected text, and confidence |
| `<guardrails.maskedText>` | Masked text in Mask mode |
Expand All @@ -96,16 +100,17 @@ Use `<guardrails.maskedText>` downstream in Mask mode. The original content is s

<WorkflowPreview workflow={GUARDRAILS_HALLUCINATION_WORKFLOW} />

Use `passed` for the configured threshold, or `score` for an explicit downstream comparison. Hallucination checks run synchronously; choose the model and chunk count according to the latency your workflow allows.
A score below **Confidence** fails the check through the error port, where `<guardrails.score>` and `<guardrails.error>` say why. A grounded answer continues along the normal output. Hallucination checks run synchronously; choose the model and chunk count according to the latency your workflow allows.

## Block PII in input

<WorkflowPreview workflow={GUARDRAILS_PII_WORKFLOW} />

Branch on `passed` to process clean input or reject detected PII. Selecting only the types relevant to your task keeps the check focused.
Clean input continues along the normal output; detected PII takes the error port to **Reject**. Selecting only the types relevant to your task keeps the check focused.

## Related docs

- [Connections and error paths](/workflows/connections)
- [Condition](/workflows/blocks/condition)
- [Function](/workflows/blocks/function)
- [Credentials and execution-log protection](/platform/credentials)
10 changes: 6 additions & 4 deletions apps/sim/blocks/blocks/guardrails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ export const GuardrailsBlock: BlockConfig = {
- Use regex validation for format checking (emails, phone numbers, URLs, etc.)
- Use hallucination check to validate LLM outputs against knowledge base content
- Use PII detection to block or mask sensitive personal information
- Access validation result with <guardrails.passed> (true/false)
- A failed check leaves through the error port, not the normal output: connect the error port to handle it (in workflow code, check.onError(handler)); the handler reads why as <guardrails.error>
- Do not branch on <guardrails.passed> with a Condition: on a failed check the Condition never runs, and the run ends with no output
- For hallucination check, access <guardrails.score> (0-10 confidence) and <guardrails.reasoning>
- For PII detection, access <guardrails.detectedEntities> and <guardrails.maskedText>
- Chain with Condition block to handle validation failures
`,
docsLink: 'https://docs.sim.ai/workflows/blocks/guardrails',
category: 'blocks',
Expand Down Expand Up @@ -309,7 +309,8 @@ Return ONLY the regex pattern - no explanations, no quotes, no forward slashes,
},
passed: {
type: 'boolean',
description: 'Whether validation passed (true/false)',
description:
'Whether validation passed. A failed check leaves through the error port, so the normal output only sees true',
},
score: {
type: 'number',
Expand All @@ -326,7 +327,8 @@ Return ONLY the regex pattern - no explanations, no quotes, no forward slashes,
},
error: {
type: 'string',
description: 'Error message if validation failed',
description:
'Why validation failed, read by the block connected to the error port (onError in workflow code)',
},
},
}
2 changes: 1 addition & 1 deletion packages/sim-cli/src/commands/protocol/source-primer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ function sharedRules(extra: { renames?: string; patterns?: string; debug?: strin
- **References**: \`${SOURCE_ENTRY_FILE}\` reads \`x.content\`, text as \`\` t\`…\` \`\`, env as \`env.NAME\`. A function file (\`codeFile('./functions/x.js')\`) reads \`$ref.<key>.<path>\` (key: display name lowercased, no spaces or dots), \`$ref.loop.currentItem\` / \`.index\` in a body (\`parallel\` too), \`$env.NAME\`; \`.py\`/\`.sh\` files \`<key.path>\`, \`{{NAME}}\`. A block that never ran reads \`null\` (\`''\` in text).
${PATTERNS_HEADING} (\`.sim/examples/\`, indexed atop \`cookbook.ts\`; any builder: \`${PARAMS_COMMAND} <builder>\`):
- Condition: keys test in order, first true wins, \`else: true\` last; wire \`route.high.to(alert)\`.
- Loop: \`const each = loop.forEach('Each Order', { collection: recent.rows }, (p) => {\`; inside, \`p.currentItem.data.orderId\` and \`p.index\`; after, \`each.results\`.
- Loop: \`const each = loop.forEach('Each Order', { collection: recent.rows }, (p) => {\`; inside \`p.currentItem.data.orderId\`, \`p.index\`; after \`each.results[i][0]\`.
- Failure: \`lookup.onError(failed)\`; \`failed\` reads its message as \`lookup.error\` (any block; a Function's adds the line: \`.errorMessage\` doesn't).
- Retry: an \`api\` block resends with \`retries: 3\`, \`retryDelayMs: 500\`; any block's Retry on fail: 3rd argument, \`{ retry: { enabled: true, maxTries: 3, waitBetweenTriesMs: 2000 } }\`.
- Child: \`const enrich = runWorkflow('Enrich Lead', {\` with \`workflowId: childWorkflow('enrich-lead')\`, \`inputMapping: { email: start.email }\`; read \`enrich.result.data.<field>\`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,49 @@ describe('sim workflows source params', () => {
await params('table.upsertRow', '--full')
const full = stdoutJson() as { builder: { params: { common: unknown[] } } }
expect(full.builder.params.common.length).toBeGreaterThan(brief.builder.required.length)
expect(JSON.stringify(full).length).toBeGreaterThan(JSON.stringify(brief).length * 2)
expect(JSON.stringify(full.builder).length).toBeGreaterThan(
JSON.stringify(brief.builder).length * 2
)
})

it('names the --full lookup in the JSON brief as typed, and that lookup types the optional params', async () => {
cacheCatalogText(join(dir, 'config'), WORKSPACE_ID, FIXTURE_TEXT)
writeBase()
/** The CLI from its root, so a printed command line runs as typed. */
const sim = async (...argv: string[]) => {
const root = new Command('sim').option('--workspace <id>')
const source = root.command('workflows').command('source')
attachWorkflowSourceParams(source)
source.commands.forEach((command) => command.exitOverride())
await root.parseAsync(['node', 'sim', ...argv])
}

await sim(
'--workspace',
WORKSPACE_ID,
'workflows',
'source',
'params',
'slack.tool.sendMessage',
'--dir',
dir
)
const { builder, next } = stdoutJson() as {
builder: { optional: string[] }
next?: { command: string; reason: string }
}
const words = (next?.command ?? '').split(' ').map((word) => word.replace(/^'(.*)'$/, '$1'))
expect(words.slice(0, 3)).toEqual(['sim', '--workspace', WORKSPACE_ID])
expect(words).toContain('--full')

vi.mocked(console.log).mockClear()
await sim(...words.slice(1))
const full = stdoutJson() as {
builder: { key: string; params: { common: Array<{ key: string; type: string }> } }
}
expect(full.builder.key).toBe('slack.sendMessage')
const typed = full.builder.params.common.map((param) => param.key)
expect(builder.optional.every((key) => typed.includes(key))).toBe(true)
})

it('keeps the call signature of a builder whose required params core.d.ts types', async () => {
Expand Down
16 changes: 14 additions & 2 deletions packages/sim-cli/src/commands/protocol/workflow-source-params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
} from '@sim/workflow-sdk/codegen'
import type { Command } from 'commander'
import { printLine } from '#sim-cli/output/io'
import { typedCommandLine } from '#sim-cli/runtime/run-next'
import { isMachineFormat, type ResolvedProfile } from '../../config/index'
import { actingProfileFrom } from '../../context'
import { CliUsageError, SourceDirError } from './local-errors'
Expand Down Expand Up @@ -72,8 +73,19 @@ export function attachWorkflowSourceParams(source: Command): void {
switch (found.kind) {
case 'builder':
if (machine) {
const builder = options.full ? found.reference : compactBuilder(found.reference)
printProtocolResult(profile.output, { builder })
printProtocolResult(
profile.output,
options.full
? { builder: found.reference }
: {
builder: compactBuilder(found.reference),
next: {
command: `${typedCommandLine(command, [found.reference.key])} --full`,
reason:
"Every param's type, enum, default and doc: the brief names the optional ones only.",
},
}
)
} else {
printLine(
(options.full ? renderBuilderReference : renderCompactBuilder)(found.reference)
Expand Down
2 changes: 1 addition & 1 deletion packages/workflow-code/src/json-fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ export function refValueKind(
}
const block = scope.block(head.name)
if (!block || segments.length === 0) return 'untyped'
// A loop or parallel's `results` is the array of every iteration's output.
// A loop or parallel's `results` holds one list per iteration, of its body blocks' outputs.
if (block.subflow) {
const [first] = segments
return segments.length === 1 && first?.kind === 'name' && first.name === 'results'
Expand Down
8 changes: 4 additions & 4 deletions packages/workflow-sdk/cookbook/examples/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ export default workflow(
inputMapping: { email: start.email },
})

// Parallel: one branch per item, run at once. p.currentItem is the item and p.index its
// position; each.results lists every branch's output once all finish. (loop.forEach is the
// sequential form.) In a function code file inside the body, the same values are
// $ref.parallel.currentItem and $ref.parallel.index.
// Parallel: one branch per item, run at once (loop.forEach is the sequential form).
// p.currentItem is the item and p.index its position; once all finish, each.results[i] lists
// branch i's body-block outputs (one block: each.results[i][0]). In a function code file
// inside the body, the same values are $ref.parallel.currentItem and $ref.parallel.index.
const each = parallel.collection('Each Domain', { collection: start.domains }, (p) => {
const brief = agent('Company Brief', {
model: 'claude-sonnet-4-6',
Expand Down
4 changes: 2 additions & 2 deletions packages/workflow-sdk/cookbook/examples/cookbook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,8 @@ export default workflow('Cookbook', { description: 'One example of each common b
else: true,
})

// Loop over a list: p.currentItem is one element and p.index its position; the loop's results
// is the list of iteration outputs. In js`` code a reference is the value itself, not text
// Loop over a list: p.currentItem is one element and p.index its position; each.results[i] is
// iteration i's body-block outputs (one block: [i][0]). In js`` code a reference is the value itself, not text
// spliced in: write it where an expression goes, never inside quotes ('${x}' would give the
// JSON, quotes included). A function code file (code: codeFile('./functions/line.js')) reads
// other blocks as $ref.<block key>.<path> ($ref.recentorders.rows) and, inside the loop body,
Expand Down

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/workflow-sdk/src/codegen/core-text.generated.ts

Large diffs are not rendered by default.

Loading