Skip to content
Closed
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
70 changes: 68 additions & 2 deletions apps/docs/content/docs/de/blocks/guardrails.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,74 @@ Checks if content matches a specified regular expression pattern.
- Enforce specific text patterns

**Configuration:**
- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` for emails)
- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}---
title: Guardrails
---

import { Callout } from 'fumadocs-ui/components/callout'
import { Step, Steps } from 'fumadocs-ui/components/steps'
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
import { Image } from '@/components/ui/image'
import { Video } from '@/components/ui/video'

The Guardrails block validates and protects your AI workflows by checking content against multiple validation types. Ensure data quality, prevent hallucinations, detect PII, and enforce format requirements before content moves through your workflow.

<div className="flex justify-center">
<Image
src="/static/blocks/guardrails.png"
alt="Guardrails Block"
width={500}
height={350}
className="my-6"
/>
</div>

## Overview

The Guardrails block enables you to:

<Steps>
<Step>
<strong>Validate JSON Structure</strong>: Ensure LLM outputs are valid JSON before parsing
</Step>
<Step>
<strong>Match Regex Patterns</strong>: Verify content matches specific formats (emails, phone numbers, URLs, etc.)
</Step>
<Step>
<strong>Detect Hallucinations</strong>: Use RAG + LLM scoring to validate AI outputs against knowledge base content
</Step>
<Step>
<strong>Detect PII</strong>: Identify and optionally mask personally identifiable information across 40+ entity types
</Step>
</Steps>

## Validation Types

### JSON Validation

Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed.

**Use Cases:**
- Validate JSON responses from Agent blocks before parsing
- Ensure API payloads are properly formatted
- Check structured data integrity

**Output:**
- `passed`: `true` if valid JSON, `false` otherwise
- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...")

### Regex Validation

Checks if content matches a specified regular expression pattern.

**Use Cases:**
- Validate email addresses
- Check phone number formats
- Verify URLs or custom identifiers
- Enforce specific text patterns

**Configuration:**
- **Regex Pattern**: The regular expression to match against (e.g., for emails)
Comment on lines +68 to +135

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

syntax: The regex pattern is truncated mid-line and entire file content is duplicated starting at line 68. The line reads:

- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}---

This should end with:

\.[a-zA-Z]{2,}$` for emails)

Instead, --- (frontmatter marker) appears immediately after, followed by the entire file being duplicated from the beginning.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/docs/content/docs/de/blocks/guardrails.mdx
Line: 68:135

Comment:
**syntax:** The regex pattern is truncated mid-line and entire file content is duplicated starting at line 68. The line reads:
```
- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}---
```

This should end with: 
```
\.[a-zA-Z]{2,}$` for emails)
```

Instead, `---` (frontmatter marker) appears immediately after, followed by the entire file being duplicated from the beginning.

How can I resolve this? If you propose a fix, please make it concise.


**Output:**
- `passed`: `true` if content matches pattern, `false` otherwise
Expand Down Expand Up @@ -248,4 +315,3 @@ Additional outputs by type:
<Callout type="info">
Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical.
</Callout>

206 changes: 204 additions & 2 deletions apps/docs/content/docs/de/sdks/typescript.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -821,7 +821,9 @@ async function checkUsage() {

Execute workflows with real-time streaming responses:

```typescript
```

typescript
import { SimStudioClient } from 'simstudio-ts-sdk';

const client = new SimStudioClient({
Expand All @@ -842,23 +844,28 @@ async function executeWithStreaming() {
console.error('Fehler:', error);
}
}

```

The streaming response follows the Server-Sent Events (SSE) format:

```

data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}

data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", zwei"}

data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}

data: [DONE]

```

**React Streaming Example:**

```typescript
```

typescript
import { useState, useEffect } from 'react';

function StreamingWorkflow() {
Expand Down Expand Up @@ -959,4 +966,199 @@ function StreamingWorkflow() {

## License

Apache-2.0

typescript
import { SimStudioClient } from 'simstudio-ts-sdk';

const client = new SimStudioClient({
apiKey: process.env.SIM_API_KEY!
});

async function checkUsage() {
try {
const limits = await client.getUsageLimits();

console.log('=== Raten-Limits ===');
console.log('Synchrone Anfragen:');
console.log(' Limit:', limits.rateLimit.sync.limit);
console.log(' Verbleibend:', limits.rateLimit.sync.remaining);
console.log(' Zurückgesetzt um:', limits.rateLimit.sync.resetAt);
console.log(' Ist limitiert:', limits.rateLimit.sync.isLimited);

console.log('\nAsynchrone Anfragen:');
console.log(' Limit:', limits.rateLimit.async.limit);
console.log(' Verbleibend:', limits.rateLimit.async.remaining);
console.log(' Zurückgesetzt um:', limits.rateLimit.async.resetAt);
console.log(' Ist limitiert:', limits.rateLimit.async.isLimited);

console.log('\n=== Nutzung ===');
console.log('Kosten der aktuellen Periode: $' + limits.usage.currentPeriodCost.toFixed(2));
console.log('Limit: $' + limits.usage.limit.toFixed(2));
console.log('Plan:', limits.usage.plan);

const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
console.log('Nutzung: ' + percentUsed.toFixed(1) + '%');

if (percentUsed > 80) {
console.warn('⚠️ Warnung: Sie nähern sich Ihrem Nutzungslimit!');
}
} catch (error) {
console.error('Fehler bei der Überprüfung der Nutzung:', error);
}
}

checkUsage();

```

### Streaming Workflow Execution

Execute workflows with real-time streaming responses:

```

typescript
import { SimStudioClient } from 'simstudio-ts-sdk';

const client = new SimStudioClient({
apiKey: process.env.SIM_API_KEY!
});

async function executeWithStreaming() {
try {
// Streaming für bestimmte Block-Ausgaben aktivieren
const result = await client.executeWorkflow('workflow-id', {
input: { message: 'Zähle bis fünf' },
stream: true,
selectedOutputs: ['agent1.content'] // Verwende das Format blockName.attribute
});

console.log('Workflow-Ergebnis:', result);
} catch (error) {
console.error('Fehler:', error);
}
}

```

The streaming response follows the Server-Sent Events (SSE) format:

```

data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"Eins"}

data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", zwei"}

data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}

data: [DONE]

```

**React Streaming Example:**

```

typescript
import { useState, useEffect } from 'react';

function StreamingWorkflow() {
const [output, setOutput] = useState('');
const [loading, setLoading] = useState(false);

const executeStreaming = async () => {
setLoading(true);
setOutput('');

// WICHTIG: Führen Sie diesen API-Aufruf von Ihrem Backend-Server aus, nicht vom Browser
// Setzen Sie niemals Ihren API-Schlüssel in clientseitigem Code frei
const response = await fetch('https://sim.ai/api/workflows/WORKFLOW_ID/execute', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': process.env.SIM_API_KEY! // Nur serverseitige Umgebungsvariable
},
body: JSON.stringify({
message: 'Generiere eine Geschichte',
stream: true,
selectedOutputs: ['agent1.content']
})
});

const reader = response.body?.getReader();
const decoder = new TextDecoder();

while (reader) {
const { done, value } = await reader.read();
if (done) break;

const chunk = decoder.decode(value);
const lines = chunk.split('\n\n');

for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') {
setLoading(false);
break;
}

try {
const parsed = JSON.parse(data);
if (parsed.chunk) {
setOutput(prev => prev + parsed.chunk);
} else if (parsed.event === 'done') {
console.log('Execution complete:', parsed.metadata);
}
} catch (e) {
// Skip invalid JSON
}
}
}
}
};

return (
<div>
<button onClick={executeStreaming} disabled={loading}>
{loading ? 'Generiere...' : 'Streaming starten'}
</button>
<div style={{ whiteSpace: 'pre-wrap' }}>{output}</div>
</div>
);
}
```

## API-Schlüssel erhalten

<Steps>
<Step title="Bei Sim anmelden">
Navigiere zu [Sim](https://sim.ai) und melde dich in deinem Konto an.
</Step>
<Step title="Öffne deinen Workflow">
Navigiere zu dem Workflow, den du programmatisch ausführen möchtest.
</Step>
<Step title="Deploye deinen Workflow">
Klicke auf "Deploy", um deinen Workflow zu deployen, falls dies noch nicht geschehen ist.
</Step>
<Step title="Erstelle oder wähle einen API-Schlüssel">
Wähle während des Deployment-Prozesses einen API-Schlüssel aus oder erstelle einen neuen.
</Step>
<Step title="Kopiere den API-Schlüssel">
Kopiere den API-Schlüssel zur Verwendung in deiner TypeScript/JavaScript-Anwendung.
</Step>
</Steps>

<Callout type="warning">
Halte deinen API-Schlüssel sicher und committe ihn niemals in die Versionskontrolle. Verwende Umgebungsvariablen oder sicheres Konfigurationsmanagement.
</Callout>

## Anforderungen

- Node.js 16+
- TypeScript 5.0+ (für TypeScript-Projekte)

## Lizenz

Apache-2.0
Loading
Loading