mirror of
https://github.com/simstudioai/sim.git
synced 2026-01-09 06:58:07 -05:00
fix(i18n): fix SDK and guardrails translation corruption, restore i18n gh action for docs (#1652)
* fix(i18n): fix SDK and guardrails translation corruption * re-enable i18n gh action
This commit is contained in:
12
.github/workflows/i18n.yml
vendored
12
.github/workflows/i18n.yml
vendored
@@ -1,13 +1,11 @@
|
||||
name: 'Auto-translate Documentation'
|
||||
|
||||
# Temporarily disabled
|
||||
on:
|
||||
workflow_dispatch: # Allow manual triggers only
|
||||
# push:
|
||||
# branches: [ staging ]
|
||||
# paths:
|
||||
# - 'apps/docs/content/docs/en/**'
|
||||
# - 'apps/docs/i18n.json'
|
||||
push:
|
||||
branches: [ staging ]
|
||||
paths:
|
||||
- 'apps/docs/content/docs/en/**'
|
||||
- 'apps/docs/i18n.json'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
@@ -8,7 +8,7 @@ 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.
|
||||
Der Guardrails-Block validiert und schützt Ihre KI-Workflows, indem er Inhalte anhand mehrerer Validierungstypen überprüft. Stellen Sie die Datenqualität sicher, verhindern Sie Halluzinationen, erkennen Sie personenbezogene Daten und erzwingen Sie Formatanforderungen, bevor Inhalte durch Ihren Workflow fließen.
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Image
|
||||
@@ -20,201 +20,201 @@ The Guardrails block validates and protects your AI workflows by checking conten
|
||||
/>
|
||||
</div>
|
||||
|
||||
## Overview
|
||||
## Übersicht
|
||||
|
||||
The Guardrails block enables you to:
|
||||
Mit dem Guardrails-Block können Sie:
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
<strong>Validate JSON Structure</strong>: Ensure LLM outputs are valid JSON before parsing
|
||||
<strong>JSON-Struktur validieren</strong>: Stellen Sie sicher, dass LLM-Ausgaben gültiges JSON sind, bevor sie geparst werden
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Match Regex Patterns</strong>: Verify content matches specific formats (emails, phone numbers, URLs, etc.)
|
||||
<strong>Regex-Muster abgleichen</strong>: Überprüfen Sie, ob Inhalte bestimmten Formaten entsprechen (E-Mails, Telefonnummern, URLs usw.)
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Detect Hallucinations</strong>: Use RAG + LLM scoring to validate AI outputs against knowledge base content
|
||||
<strong>Halluzinationen erkennen</strong>: Nutzen Sie RAG + LLM-Scoring, um KI-Ausgaben anhand von Wissensdatenbankinhalten zu validieren
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Detect PII</strong>: Identify and optionally mask personally identifiable information across 40+ entity types
|
||||
<strong>PII erkennen</strong>: Identifizieren und optional maskieren Sie personenbezogene Daten über mehr als 40 Entitätstypen hinweg
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Validation Types
|
||||
## Validierungstypen
|
||||
|
||||
### JSON Validation
|
||||
### JSON-Validierung
|
||||
|
||||
Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed.
|
||||
Überprüft, ob Inhalte korrekt formatiertes JSON sind. Perfekt, um sicherzustellen, dass strukturierte LLM-Ausgaben sicher geparst werden können.
|
||||
|
||||
**Use Cases:**
|
||||
- Validate JSON responses from Agent blocks before parsing
|
||||
- Ensure API payloads are properly formatted
|
||||
- Check structured data integrity
|
||||
**Anwendungsfälle:**
|
||||
- Validieren von JSON-Antworten aus Agent-Blöcken vor dem Parsen
|
||||
- Sicherstellen, dass API-Payloads korrekt formatiert sind
|
||||
- Überprüfen der Integrität strukturierter Daten
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if valid JSON, `false` otherwise
|
||||
- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...")
|
||||
- `passed`: `true` wenn gültiges JSON, sonst `false`
|
||||
- `error`: Fehlermeldung bei fehlgeschlagener Validierung (z.B. "Invalid JSON: Unexpected token...")
|
||||
|
||||
### Regex Validation
|
||||
### Regex-Validierung
|
||||
|
||||
Checks if content matches a specified regular expression pattern.
|
||||
Überprüft, ob Inhalte einem bestimmten regulären Ausdrucksmuster entsprechen.
|
||||
|
||||
**Use Cases:**
|
||||
- Validate email addresses
|
||||
- Check phone number formats
|
||||
- Verify URLs or custom identifiers
|
||||
- Enforce specific text patterns
|
||||
**Anwendungsfälle:**
|
||||
- Validieren von E-Mail-Adressen
|
||||
- Überprüfen von Telefonnummernformaten
|
||||
- Verifizieren von URLs oder benutzerdefinierten Kennungen
|
||||
- Durchsetzen spezifischer Textmuster
|
||||
|
||||
**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)
|
||||
**Konfiguration:**
|
||||
- **Regex-Muster**: Der reguläre Ausdruck, der abgeglichen werden soll (z.B. `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` für E-Mails)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if content matches pattern, `false` otherwise
|
||||
- `error`: Error message if validation fails
|
||||
- `passed`: `true` wenn der Inhalt dem Muster entspricht, `false` andernfalls
|
||||
- `error`: Fehlermeldung bei fehlgeschlagener Validierung
|
||||
|
||||
### Hallucination Detection
|
||||
### Halluzinationserkennung
|
||||
|
||||
Uses Retrieval-Augmented Generation (RAG) with LLM scoring to detect when AI-generated content contradicts or isn't grounded in your knowledge base.
|
||||
Verwendet Retrieval-Augmented Generation (RAG) mit LLM-Bewertung, um zu erkennen, wann KI-generierte Inhalte im Widerspruch zu Ihrer Wissensdatenbank stehen oder nicht darin begründet sind.
|
||||
|
||||
**How It Works:**
|
||||
1. Queries your knowledge base for relevant context
|
||||
2. Sends both the AI output and retrieved context to an LLM
|
||||
3. LLM assigns a confidence score (0-10 scale)
|
||||
- **0** = Full hallucination (completely ungrounded)
|
||||
- **10** = Fully grounded (completely supported by knowledge base)
|
||||
4. Validation passes if score ≥ threshold (default: 3)
|
||||
**Funktionsweise:**
|
||||
1. Durchsucht Ihre Wissensdatenbank nach relevantem Kontext
|
||||
2. Sendet sowohl die KI-Ausgabe als auch den abgerufenen Kontext an ein LLM
|
||||
3. LLM weist einen Konfidenzwert zu (Skala 0-10)
|
||||
- **0** = Vollständige Halluzination (völlig unbegründet)
|
||||
- **10** = Vollständig fundiert (komplett durch Wissensdatenbank gestützt)
|
||||
4. Validierung besteht, wenn der Wert ≥ Schwellenwert (Standard: 3)
|
||||
|
||||
**Configuration:**
|
||||
- **Knowledge Base**: Select from your existing knowledge bases
|
||||
- **Model**: Choose LLM for scoring (requires strong reasoning - GPT-4o, Claude 3.7 Sonnet recommended)
|
||||
- **API Key**: Authentication for selected LLM provider (auto-hidden for hosted/Ollama models)
|
||||
- **Confidence Threshold**: Minimum score to pass (0-10, default: 3)
|
||||
- **Top K** (Advanced): Number of knowledge base chunks to retrieve (default: 10)
|
||||
**Konfiguration:**
|
||||
- **Wissensdatenbank**: Auswahl aus Ihren vorhandenen Wissensdatenbanken
|
||||
- **Modell**: LLM für die Bewertung wählen (erfordert starkes Reasoning - GPT-4o, Claude 3.7 Sonnet empfohlen)
|
||||
- **API-Schlüssel**: Authentifizierung für den ausgewählten LLM-Anbieter (automatisch ausgeblendet für gehostete/Ollama-Modelle)
|
||||
- **Konfidenz-Schwellenwert**: Mindestwert zum Bestehen (0-10, Standard: 3)
|
||||
- **Top K** (Erweitert): Anzahl der abzurufenden Wissensdatenbank-Chunks (Standard: 10)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if confidence score ≥ threshold
|
||||
- `score`: Confidence score (0-10)
|
||||
- `reasoning`: LLM's explanation for the score
|
||||
- `error`: Error message if validation fails
|
||||
- `passed`: `true` wenn Konfidenzwert ≥ Schwellenwert
|
||||
- `score`: Konfidenzwert (0-10)
|
||||
- `reasoning`: Erklärung des LLM für den Wert
|
||||
- `error`: Fehlermeldung bei fehlgeschlagener Validierung
|
||||
|
||||
**Use Cases:**
|
||||
- Validate Agent responses against documentation
|
||||
- Ensure customer support answers are factually accurate
|
||||
- Verify generated content matches source material
|
||||
- Quality control for RAG applications
|
||||
**Anwendungsfälle:**
|
||||
- Validierung von Agent-Antworten anhand der Dokumentation
|
||||
- Sicherstellen, dass Kundenservice-Antworten sachlich korrekt sind
|
||||
- Überprüfen, ob generierte Inhalte mit dem Quellmaterial übereinstimmen
|
||||
- Qualitätskontrolle für RAG-Anwendungen
|
||||
|
||||
### PII Detection
|
||||
### PII-Erkennung
|
||||
|
||||
Detects personally identifiable information using Microsoft Presidio. Supports 40+ entity types across multiple countries and languages.
|
||||
Erkennt personenbezogene Daten mit Microsoft Presidio. Unterstützt über 40 Entitätstypen in mehreren Ländern und Sprachen.
|
||||
|
||||
<div className="mx-auto w-3/5 overflow-hidden rounded-lg">
|
||||
<Video src="guardrails.mp4" width={500} height={350} />
|
||||
</div>
|
||||
|
||||
**How It Works:**
|
||||
1. Scans content for PII entities using pattern matching and NLP
|
||||
2. Returns detected entities with locations and confidence scores
|
||||
3. Optionally masks detected PII in the output
|
||||
**Funktionsweise:**
|
||||
1. Scannt Inhalte nach PII-Entitäten mittels Mustererkennung und NLP
|
||||
2. Gibt erkannte Entitäten mit Positionen und Konfidenzwerten zurück
|
||||
3. Maskiert optional erkannte PII in der Ausgabe
|
||||
|
||||
**Configuration:**
|
||||
- **PII Types to Detect**: Select from grouped categories via modal selector
|
||||
- **Common**: Person name, Email, Phone, Credit card, IP address, etc.
|
||||
- **USA**: SSN, Driver's license, Passport, etc.
|
||||
- **UK**: NHS number, National insurance number
|
||||
- **Spain**: NIF, NIE, CIF
|
||||
- **Italy**: Fiscal code, Driver's license, VAT code
|
||||
- **Poland**: PESEL, NIP, REGON
|
||||
- **Singapore**: NRIC/FIN, UEN
|
||||
- **Australia**: ABN, ACN, TFN, Medicare
|
||||
- **India**: Aadhaar, PAN, Passport, Voter number
|
||||
- **Mode**:
|
||||
- **Detect**: Only identify PII (default)
|
||||
- **Mask**: Replace detected PII with masked values
|
||||
- **Language**: Detection language (default: English)
|
||||
**Konfiguration:**
|
||||
- **Zu erkennende PII-Typen**: Auswahl aus gruppierten Kategorien über Modal-Selektor
|
||||
- **Allgemein**: Personenname, E-Mail, Telefon, Kreditkarte, IP-Adresse usw.
|
||||
- **USA**: SSN, Führerschein, Reisepass usw.
|
||||
- **UK**: NHS-Nummer, Sozialversicherungsnummer
|
||||
- **Spanien**: NIF, NIE, CIF
|
||||
- **Italien**: Steuernummer, Führerschein, Umsatzsteuer-ID
|
||||
- **Polen**: PESEL, NIP, REGON
|
||||
- **Singapur**: NRIC/FIN, UEN
|
||||
- **Australien**: ABN, ACN, TFN, Medicare
|
||||
- **Indien**: Aadhaar, PAN, Reisepass, Wählernummer
|
||||
- **Modus**:
|
||||
- **Erkennen**: Nur PII identifizieren (Standard)
|
||||
- **Maskieren**: Erkannte PII durch maskierte Werte ersetzen
|
||||
- **Sprache**: Erkennungssprache (Standard: Englisch)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `false` if any selected PII types are detected
|
||||
- `detectedEntities`: Array of detected PII with type, location, and confidence
|
||||
- `maskedText`: Content with PII masked (only if mode = "Mask")
|
||||
- `error`: Error message if validation fails
|
||||
**Ausgabe:**
|
||||
- `passed`: `false` wenn ausgewählte PII-Typen erkannt werden
|
||||
- `detectedEntities`: Array erkannter PII mit Typ, Position und Konfidenz
|
||||
- `maskedText`: Inhalt mit maskierter PII (nur wenn Modus = "Mask")
|
||||
- `error`: Fehlermeldung, wenn die Validierung fehlschlägt
|
||||
|
||||
**Use Cases:**
|
||||
- Block content containing sensitive personal information
|
||||
- Mask PII before logging or storing data
|
||||
- Compliance with GDPR, HIPAA, and other privacy regulations
|
||||
- Sanitize user inputs before processing
|
||||
**Anwendungsfälle:**
|
||||
- Blockieren von Inhalten mit sensiblen persönlichen Informationen
|
||||
- Maskieren von PII vor der Protokollierung oder Speicherung von Daten
|
||||
- Einhaltung von DSGVO, HIPAA und anderen Datenschutzbestimmungen
|
||||
- Bereinigung von Benutzereingaben vor der Verarbeitung
|
||||
|
||||
## Configuration
|
||||
## Konfiguration
|
||||
|
||||
### Content to Validate
|
||||
### Zu validierender Inhalt
|
||||
|
||||
The input content to validate. This typically comes from:
|
||||
- Agent block outputs: `<agent.content>`
|
||||
- Function block results: `<function.output>`
|
||||
- API responses: `<api.output>`
|
||||
- Any other block output
|
||||
Der zu validierende Eingabeinhalt. Dieser stammt typischerweise aus:
|
||||
- Ausgaben von Agent-Blöcken: `<agent.content>`
|
||||
- Ergebnisse von Funktionsblöcken: `<function.output>`
|
||||
- API-Antworten: `<api.output>`
|
||||
- Jede andere Blockausgabe
|
||||
|
||||
### Validation Type
|
||||
### Validierungstyp
|
||||
|
||||
Choose from four validation types:
|
||||
- **Valid JSON**: Check if content is properly formatted JSON
|
||||
- **Regex Match**: Verify content matches a regex pattern
|
||||
- **Hallucination Check**: Validate against knowledge base with LLM scoring
|
||||
- **PII Detection**: Detect and optionally mask personally identifiable information
|
||||
Wählen Sie aus vier Validierungstypen:
|
||||
- **Gültiges JSON**: Prüfen, ob der Inhalt korrekt formatiertes JSON ist
|
||||
- **Regex-Übereinstimmung**: Überprüfen, ob der Inhalt einem Regex-Muster entspricht
|
||||
- **Halluzinationsprüfung**: Validierung gegen Wissensdatenbank mit LLM-Bewertung
|
||||
- **PII-Erkennung**: Erkennung und optional Maskierung personenbezogener Daten
|
||||
|
||||
## Outputs
|
||||
## Ausgaben
|
||||
|
||||
All validation types return:
|
||||
Alle Validierungstypen liefern zurück:
|
||||
|
||||
- **`<guardrails.passed>`**: Boolean indicating if validation passed
|
||||
- **`<guardrails.validationType>`**: The type of validation performed
|
||||
- **`<guardrails.input>`**: The original input that was validated
|
||||
- **`<guardrails.error>`**: Error message if validation failed (optional)
|
||||
- **`<guardrails.passed>`**: Boolean, der angibt, ob die Validierung erfolgreich war
|
||||
- **`<guardrails.validationType>`**: Die Art der durchgeführten Validierung
|
||||
- **`<guardrails.input>`**: Die ursprüngliche Eingabe, die validiert wurde
|
||||
- **`<guardrails.error>`**: Fehlermeldung, wenn die Validierung fehlgeschlagen ist (optional)
|
||||
|
||||
Additional outputs by type:
|
||||
Zusätzliche Ausgaben nach Typ:
|
||||
|
||||
**Hallucination Check:**
|
||||
- **`<guardrails.score>`**: Confidence score (0-10)
|
||||
- **`<guardrails.reasoning>`**: LLM's explanation
|
||||
**Halluzinationsprüfung:**
|
||||
- **`<guardrails.score>`**: Konfidenzwert (0-10)
|
||||
- **`<guardrails.reasoning>`**: Erklärung des LLM
|
||||
|
||||
**PII Detection:**
|
||||
- **`<guardrails.detectedEntities>`**: Array of detected PII entities
|
||||
- **`<guardrails.maskedText>`**: Content with PII masked (if mode = "Mask")
|
||||
**PII-Erkennung:**
|
||||
- **`<guardrails.detectedEntities>`**: Array erkannter PII-Entitäten
|
||||
- **`<guardrails.maskedText>`**: Inhalt mit maskierter PII (wenn Modus = "Mask")
|
||||
|
||||
## Example Use Cases
|
||||
## Beispielanwendungsfälle
|
||||
|
||||
### Validate JSON Before Parsing
|
||||
### JSON vor dem Parsen validieren
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Ensure Agent output is valid JSON</h4>
|
||||
<h4 className="font-medium">Szenario: Sicherstellen, dass die Agent-Ausgabe gültiges JSON ist</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent generates structured JSON response</li>
|
||||
<li>Guardrails validates JSON format</li>
|
||||
<li>Condition block checks `<guardrails.passed>`</li>
|
||||
<li>If passed → Parse and use data, If failed → Retry or handle error</li>
|
||||
<li>Agent generiert strukturierte JSON-Antwort</li>
|
||||
<li>Guardrails validiert das JSON-Format</li>
|
||||
<li>Bedingungsblock prüft `<guardrails.passed>`</li>
|
||||
<li>Bei Erfolg → Daten parsen und verwenden, Bei Fehler → Wiederholen oder Fehler behandeln</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
### Prevent Hallucinations
|
||||
### Halluzinationen verhindern
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Validate customer support responses</h4>
|
||||
<h4 className="font-medium">Szenario: Validierung von Kundendienstantworten</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent generates response to customer question</li>
|
||||
<li>Guardrails checks against support documentation knowledge base</li>
|
||||
<li>If confidence score ≥ 3 → Send response</li>
|
||||
<li>If confidence score \< 3 → Flag for human review</li>
|
||||
<li>Agent generiert Antwort auf Kundenfrage</li>
|
||||
<li>Guardrails prüft gegen die Wissensdatenbank der Support-Dokumentation</li>
|
||||
<li>Wenn Konfidenzwert ≥ 3 → Antwort senden</li>
|
||||
<li>Wenn Konfidenzwert \< 3 → Für manuelle Überprüfung markieren</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
### Block PII in User Inputs
|
||||
### PII in Benutzereingaben blockieren
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Sanitize user-submitted content</h4>
|
||||
<h4 className="font-medium">Szenario: Bereinigung von benutzergenerierten Inhalten</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>User submits form with text content</li>
|
||||
<li>Guardrails detects PII (emails, phone numbers, SSN, etc.)</li>
|
||||
<li>If PII detected → Reject submission or mask sensitive data</li>
|
||||
<li>If no PII → Process normally</li>
|
||||
<li>Benutzer reicht Formular mit Textinhalt ein</li>
|
||||
<li>Guardrails erkennt PII (E-Mails, Telefonnummern, Sozialversicherungsnummern usw.)</li>
|
||||
<li>Bei erkannter PII → Einreichung ablehnen oder sensible Daten maskieren</li>
|
||||
<li>Ohne PII → Normal verarbeiten</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
@@ -222,30 +222,29 @@ Additional outputs by type:
|
||||
<Video src="guardrails-example.mp4" width={500} height={350} />
|
||||
</div>
|
||||
|
||||
### Validate Email Format
|
||||
### E-Mail-Format validieren
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Check email address format</h4>
|
||||
<h4 className="font-medium">Szenario: E-Mail-Adressformat überprüfen</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent extracts email from text</li>
|
||||
<li>Guardrails validates with regex pattern</li>
|
||||
<li>If valid → Use email for notification</li>
|
||||
<li>If invalid → Request correction</li>
|
||||
<li>Agent extrahiert E-Mail aus Text</li>
|
||||
<li>Guardrails validiert mit Regex-Muster</li>
|
||||
<li>Bei Gültigkeit → E-Mail für Benachrichtigung verwenden</li>
|
||||
<li>Bei Ungültigkeit → Korrektur anfordern</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Chain with Condition blocks**: Use `<guardrails.passed>` to branch workflow logic based on validation results
|
||||
- **Use JSON validation before parsing**: Always validate JSON structure before attempting to parse LLM outputs
|
||||
- **Choose appropriate PII types**: Only select the PII entity types relevant to your use case for better performance
|
||||
- **Set reasonable confidence thresholds**: For hallucination detection, adjust threshold based on your accuracy requirements (higher = stricter)
|
||||
- **Use strong models for hallucination detection**: GPT-4o or Claude 3.7 Sonnet provide more accurate confidence scoring
|
||||
- **Mask PII for logging**: Use "Mask" mode when you need to log or store content that may contain PII
|
||||
- **Test regex patterns**: Validate your regex patterns thoroughly before deploying to production
|
||||
- **Monitor validation failures**: Track `<guardrails.error>` messages to identify common validation issues
|
||||
- **Verkettung mit Condition-Blöcken**: Verwende `<guardrails.passed>` um Workflow-Logik basierend auf Validierungsergebnissen zu verzweigen
|
||||
- **JSON-Validierung vor dem Parsen verwenden**: Validiere immer die JSON-Struktur, bevor du versuchst, LLM-Ausgaben zu parsen
|
||||
- **Passende PII-Typen auswählen**: Wähle nur die PII-Entitätstypen aus, die für deinen Anwendungsfall relevant sind, um bessere Leistung zu erzielen
|
||||
- **Vernünftige Konfidenz-Schwellenwerte festlegen**: Passe für die Halluzinationserkennung den Schwellenwert basierend auf deinen Genauigkeitsanforderungen an (höher = strenger)
|
||||
- **Starke Modelle für Halluzinationserkennung verwenden**: GPT-4o oder Claude 3.7 Sonnet bieten genauere Konfidenz-Bewertungen
|
||||
- **PII für Logging maskieren**: Verwende den "Mask"-Modus, wenn du Inhalte protokollieren oder speichern musst, die PII enthalten könnten
|
||||
- **Regex-Muster testen**: Validiere deine Regex-Muster gründlich, bevor du sie in der Produktion einsetzt
|
||||
- **Validierungsfehler überwachen**: Verfolge `<guardrails.error>` Nachrichten, um häufige Validierungsprobleme zu identifizieren
|
||||
|
||||
<Callout type="info">
|
||||
Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical.
|
||||
Guardrails-Validierung erfolgt synchron in deinem Workflow. Für die Halluzinationserkennung solltest du schnellere Modelle (wie GPT-4o-mini) wählen, wenn Latenz kritisch ist.
|
||||
</Callout>
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ new SimStudioClient(config: SimStudioConfig)
|
||||
|
||||
##### executeWorkflow()
|
||||
|
||||
Führen Sie einen Workflow mit optionalen Eingabedaten aus.
|
||||
Führt einen Workflow mit optionalen Eingabedaten aus.
|
||||
|
||||
```typescript
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
@@ -99,7 +99,7 @@ const result = await client.executeWorkflow('workflow-id', {
|
||||
- `selectedOutputs` (string[]): Block-Ausgaben, die im `blockName.attribute`Format gestreamt werden sollen (z.B. `["agent1.content"]`)
|
||||
- `async` (boolean): Asynchron ausführen (Standard: false)
|
||||
|
||||
**Rückgabe:** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
**Rückgabewert:** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
|
||||
Wenn `async: true`, wird sofort mit einer Task-ID zum Abfragen zurückgegeben. Andernfalls wird auf den Abschluss gewartet.
|
||||
|
||||
@@ -115,7 +115,7 @@ console.log('Is deployed:', status.isDeployed);
|
||||
**Parameter:**
|
||||
- `workflowId` (string): Die ID des Workflows
|
||||
|
||||
**Rückgabe:** `Promise<WorkflowStatus>`
|
||||
**Rückgabewert:** `Promise<WorkflowStatus>`
|
||||
|
||||
##### validateWorkflow()
|
||||
|
||||
@@ -131,7 +131,7 @@ if (isReady) {
|
||||
**Parameter:**
|
||||
- `workflowId` (string): Die ID des Workflows
|
||||
|
||||
**Rückgabe:** `Promise<boolean>`
|
||||
**Rückgabewert:** `Promise<boolean>`
|
||||
|
||||
##### getJobStatus()
|
||||
|
||||
@@ -148,7 +148,7 @@ if (status.status === 'completed') {
|
||||
**Parameter:**
|
||||
- `taskId` (string): Die Task-ID, die von der asynchronen Ausführung zurückgegeben wurde
|
||||
|
||||
**Rückgabe:** `Promise<JobStatus>`
|
||||
**Rückgabewert:** `Promise<JobStatus>`
|
||||
|
||||
**Antwortfelder:**
|
||||
- `success` (boolean): Ob die Anfrage erfolgreich war
|
||||
@@ -161,7 +161,7 @@ if (status.status === 'completed') {
|
||||
|
||||
##### executeWithRetry()
|
||||
|
||||
Führt einen Workflow mit automatischer Wiederholung bei Ratenlimitfehlern unter Verwendung von exponentiellem Backoff aus.
|
||||
Einen Workflow mit automatischer Wiederholung bei Rate-Limit-Fehlern unter Verwendung von exponentiellem Backoff ausführen.
|
||||
|
||||
```typescript
|
||||
const result = await client.executeWithRetry('workflow-id', {
|
||||
@@ -184,13 +184,13 @@ const result = await client.executeWithRetry('workflow-id', {
|
||||
- `maxDelay` (number): Maximale Verzögerung in ms (Standard: 30000)
|
||||
- `backoffMultiplier` (number): Backoff-Multiplikator (Standard: 2)
|
||||
|
||||
**Rückgabewert:** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
**Rückgabe:** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
|
||||
Die Wiederholungslogik verwendet exponentiellen Backoff (1s → 2s → 4s → 8s...) mit ±25% Jitter, um den Thundering-Herd-Effekt zu vermeiden. Wenn die API einen `retry-after`Header bereitstellt, wird dieser stattdessen verwendet.
|
||||
Die Wiederholungslogik verwendet exponentielles Backoff (1s → 2s → 4s → 8s...) mit ±25% Jitter, um den Thundering-Herd-Effekt zu vermeiden. Wenn die API einen `retry-after` Header bereitstellt, wird dieser stattdessen verwendet.
|
||||
|
||||
##### getRateLimitInfo()
|
||||
|
||||
Ruft die aktuellen Ratenlimit-Informationen aus der letzten API-Antwort ab.
|
||||
Ruft die aktuellen Rate-Limit-Informationen aus der letzten API-Antwort ab.
|
||||
|
||||
```typescript
|
||||
const rateLimitInfo = client.getRateLimitInfo();
|
||||
@@ -201,7 +201,7 @@ if (rateLimitInfo) {
|
||||
}
|
||||
```
|
||||
|
||||
**Rückgabewert:** `RateLimitInfo | null`
|
||||
**Rückgabe:** `RateLimitInfo | null`
|
||||
|
||||
##### getUsageLimits()
|
||||
|
||||
@@ -215,7 +215,7 @@ console.log('Current period cost:', limits.usage.currentPeriodCost);
|
||||
console.log('Plan:', limits.usage.plan);
|
||||
```
|
||||
|
||||
**Rückgabewert:** `Promise<UsageLimits>`
|
||||
**Rückgabe:** `Promise<UsageLimits>`
|
||||
|
||||
**Antwortstruktur:**
|
||||
|
||||
@@ -357,8 +357,8 @@ class SimStudioError extends Error {
|
||||
**Häufige Fehlercodes:**
|
||||
- `UNAUTHORIZED`: Ungültiger API-Schlüssel
|
||||
- `TIMEOUT`: Zeitüberschreitung der Anfrage
|
||||
- `RATE_LIMIT_EXCEEDED`: Ratengrenze überschritten
|
||||
- `USAGE_LIMIT_EXCEEDED`: Nutzungsgrenze überschritten
|
||||
- `RATE_LIMIT_EXCEEDED`: Rate-Limit überschritten
|
||||
- `USAGE_LIMIT_EXCEEDED`: Nutzungslimit überschritten
|
||||
- `EXECUTION_ERROR`: Workflow-Ausführung fehlgeschlagen
|
||||
|
||||
## Beispiele
|
||||
@@ -604,26 +604,105 @@ async function executeClientSideWorkflow() {
|
||||
});
|
||||
|
||||
console.log('Workflow result:', result);
|
||||
|
||||
|
||||
// Update UI with result
|
||||
document.getElementById('result')!.textContent =
|
||||
document.getElementById('result')!.textContent =
|
||||
JSON.stringify(result.output, null, 2);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach to button click
|
||||
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
|
||||
```
|
||||
|
||||
### Datei-Upload
|
||||
|
||||
Datei-Objekte werden automatisch erkannt und in das Base64-Format konvertiert. Fügen Sie sie in Ihrem Input unter dem Feldnamen ein, der dem API-Trigger-Inputformat Ihres Workflows entspricht.
|
||||
|
||||
Das SDK konvertiert Datei-Objekte in dieses Format:
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: 'file',
|
||||
data: 'data:mime/type;base64,base64data',
|
||||
name: 'filename',
|
||||
mime: 'mime/type'
|
||||
}
|
||||
```
|
||||
|
||||
Alternativ können Sie Dateien manuell im URL-Format bereitstellen:
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: 'url',
|
||||
data: 'https://example.com/file.pdf',
|
||||
name: 'file.pdf',
|
||||
mime: 'application/pdf'
|
||||
}
|
||||
```
|
||||
|
||||
<Tabs items={['Browser', 'Node.js']}>
|
||||
<Tab value="Browser">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
|
||||
});
|
||||
|
||||
// From file input
|
||||
async function handleFileUpload(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const files = Array.from(input.files || []);
|
||||
|
||||
// Include files under the field name from your API trigger's input format
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
documents: files, // Must match your workflow's "files" field name
|
||||
instructions: 'Analyze these documents'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Result:', result);
|
||||
}
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="Node.js">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
import fs from 'fs';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.SIM_API_KEY!
|
||||
});
|
||||
|
||||
// Read file and create File object
|
||||
const fileBuffer = fs.readFileSync('./document.pdf');
|
||||
const file = new File([fileBuffer], 'document.pdf', {
|
||||
type: 'application/pdf'
|
||||
});
|
||||
|
||||
// Include files under the field name from your API trigger's input format
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
documents: [file], // Must match your workflow's "files" field name
|
||||
query: 'Summarize this document'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Callout type="warning">
|
||||
Bei der Verwendung des SDK im Browser sollten Sie darauf achten, keine sensiblen API-Schlüssel offenzulegen. Erwägen Sie die Verwendung eines Backend-Proxys oder öffentlicher API-Schlüssel mit eingeschränkten Berechtigungen.
|
||||
</Callout>
|
||||
|
||||
### React Hook-Beispiel
|
||||
### React Hook Beispiel
|
||||
|
||||
Erstellen eines benutzerdefinierten React-Hooks für die Workflow-Ausführung:
|
||||
Erstellen Sie einen benutzerdefinierten React-Hook für die Workflow-Ausführung:
|
||||
|
||||
```typescript
|
||||
import { useState, useCallback } from 'react';
|
||||
@@ -815,11 +894,27 @@ async function checkUsage() {
|
||||
console.log(' Is limited:', limits.rateLimit.async.isLimited);
|
||||
|
||||
console.log('\n=== Usage ===');
|
||||
console.log('Current period cost:
|
||||
console.log('Current period cost: $' + limits.usage.currentPeriodCost.toFixed(2));
|
||||
console.log('Limit: $' + limits.usage.limit.toFixed(2));
|
||||
console.log('Plan:', limits.usage.plan);
|
||||
|
||||
### Streaming Workflow Execution
|
||||
const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
|
||||
console.log('Usage: ' + percentUsed.toFixed(1) + '%');
|
||||
|
||||
Execute workflows with real-time streaming responses:
|
||||
if (percentUsed > 80) {
|
||||
console.warn('⚠️ Warning: You are approaching your usage limit!');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking usage:', error);
|
||||
}
|
||||
}
|
||||
|
||||
checkUsage();
|
||||
```
|
||||
|
||||
### Streaming-Workflow-Ausführung
|
||||
|
||||
Führen Sie Workflows mit Echtzeit-Streaming-Antworten aus:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -830,33 +925,33 @@ const client = new SimStudioClient({
|
||||
|
||||
async function executeWithStreaming() {
|
||||
try {
|
||||
// Streaming für bestimmte Block-Ausgaben aktivieren
|
||||
// Enable streaming for specific block outputs
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: { message: 'Count to five' },
|
||||
stream: true,
|
||||
selectedOutputs: ['agent1.content'] // Format blockName.attribute verwenden
|
||||
selectedOutputs: ['agent1.content'] // Use blockName.attribute format
|
||||
});
|
||||
|
||||
console.log('Workflow-Ergebnis:', result);
|
||||
console.log('Workflow result:', result);
|
||||
} catch (error) {
|
||||
console.error('Fehler:', error);
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The streaming response follows the Server-Sent Events (SSE) format:
|
||||
Die Streaming-Antwort folgt dem Server-Sent Events (SSE) Format:
|
||||
|
||||
```
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", zwei"}
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"}
|
||||
|
||||
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
**React Streaming Example:**
|
||||
**React Streaming Beispiel:**
|
||||
|
||||
```typescript
|
||||
import { useState, useEffect } from 'react';
|
||||
@@ -869,13 +964,13 @@ function StreamingWorkflow() {
|
||||
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 im Client-seitigen Code frei
|
||||
// IMPORTANT: Make this API call from your backend server, not the browser
|
||||
// Never expose your API key in client-side code
|
||||
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
|
||||
'X-API-Key': process.env.SIM_API_KEY! // Server-side environment variable only
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message: 'Generate a story',
|
||||
@@ -907,10 +1002,10 @@ function StreamingWorkflow() {
|
||||
if (parsed.chunk) {
|
||||
setOutput(prev => prev + parsed.chunk);
|
||||
} else if (parsed.event === 'done') {
|
||||
console.log('Ausführung abgeschlossen:', parsed.metadata);
|
||||
console.log('Execution complete:', parsed.metadata);
|
||||
}
|
||||
} catch (e) {
|
||||
// Ungültiges JSON überspringen
|
||||
// Skip invalid JSON
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -920,7 +1015,7 @@ function StreamingWorkflow() {
|
||||
return (
|
||||
<div>
|
||||
<button onClick={executeStreaming} disabled={loading}>
|
||||
{loading ? 'Generiere...' : 'Streaming starten'}
|
||||
{loading ? 'Generating...' : 'Start Streaming'}
|
||||
</button>
|
||||
<div style={{ whiteSpace: 'pre-wrap' }}>{output}</div>
|
||||
</div>
|
||||
@@ -928,35 +1023,35 @@ function StreamingWorkflow() {
|
||||
}
|
||||
```
|
||||
|
||||
## Getting Your API Key
|
||||
## API-Schlüssel erhalten
|
||||
|
||||
<Steps>
|
||||
<Step title="Log in to Sim">
|
||||
Navigate to [Sim](https://sim.ai) and log in to your account.
|
||||
<Step title="Bei Sim anmelden">
|
||||
Navigieren Sie zu [Sim](https://sim.ai) und melden Sie sich bei Ihrem Konto an.
|
||||
</Step>
|
||||
<Step title="Open your workflow">
|
||||
Navigate to the workflow you want to execute programmatically.
|
||||
<Step title="Öffnen Sie Ihren Workflow">
|
||||
Navigieren Sie zu dem Workflow, den Sie programmatisch ausführen möchten.
|
||||
</Step>
|
||||
<Step title="Deploy your workflow">
|
||||
Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.
|
||||
<Step title="Deployen Sie Ihren Workflow">
|
||||
Klicken Sie auf "Deploy", um Ihren Workflow zu deployen, falls dies noch nicht geschehen ist.
|
||||
</Step>
|
||||
<Step title="Create or select an API key">
|
||||
During the deployment process, select or create an API key.
|
||||
<Step title="API-Schlüssel erstellen oder auswählen">
|
||||
Wählen Sie während des Deployment-Prozesses einen API-Schlüssel aus oder erstellen Sie einen neuen.
|
||||
</Step>
|
||||
<Step title="Copy the API key">
|
||||
Copy the API key to use in your TypeScript/JavaScript application.
|
||||
<Step title="API-Schlüssel kopieren">
|
||||
Kopieren Sie den API-Schlüssel zur Verwendung in Ihrer TypeScript/JavaScript-Anwendung.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Callout type="warning">
|
||||
Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management.
|
||||
Halten Sie Ihren API-Schlüssel sicher und committen Sie ihn niemals in die Versionskontrolle. Verwenden Sie Umgebungsvariablen oder sicheres Konfigurationsmanagement.
|
||||
</Callout>
|
||||
|
||||
## Requirements
|
||||
## Anforderungen
|
||||
|
||||
- Node.js 16+
|
||||
- TypeScript 5.0+ (for TypeScript projects)
|
||||
- TypeScript 5.0+ (für TypeScript-Projekte)
|
||||
|
||||
## License
|
||||
## Lizenz
|
||||
|
||||
Apache-2.0
|
||||
@@ -679,10 +679,6 @@ Alternatively, you can manually provide files using the URL format:
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
// Attach to button click
|
||||
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
|
||||
```
|
||||
|
||||
<Callout type="warning">
|
||||
When using the SDK in the browser, be careful not to expose sensitive API keys. Consider using a backend proxy or public API keys with limited permissions.
|
||||
</Callout>
|
||||
|
||||
@@ -8,213 +8,213 @@ 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.
|
||||
El bloque Guardrails valida y protege tus flujos de trabajo de IA comprobando el contenido contra múltiples tipos de validación. Asegura la calidad de los datos, previene alucinaciones, detecta información personal identificable (PII) y aplica requisitos de formato antes de que el contenido avance por tu flujo de trabajo.
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Image
|
||||
src="/static/blocks/guardrails.png"
|
||||
alt="Guardrails Block"
|
||||
alt="Bloque Guardrails"
|
||||
width={500}
|
||||
height={350}
|
||||
className="my-6"
|
||||
/>
|
||||
</div>
|
||||
|
||||
## Overview
|
||||
## Descripción general
|
||||
|
||||
The Guardrails block enables you to:
|
||||
El bloque Guardrails te permite:
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
<strong>Validate JSON Structure</strong>: Ensure LLM outputs are valid JSON before parsing
|
||||
<strong>Validar estructura JSON</strong>: Asegura que las salidas de LLM sean JSON válido antes de analizarlas
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Match Regex Patterns</strong>: Verify content matches specific formats (emails, phone numbers, URLs, etc.)
|
||||
<strong>Coincidir con patrones Regex</strong>: Verifica que el contenido coincida con formatos específicos (correos electrónicos, números de teléfono, URLs, etc.)
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Detect Hallucinations</strong>: Use RAG + LLM scoring to validate AI outputs against knowledge base content
|
||||
<strong>Detectar alucinaciones</strong>: Utiliza puntuación RAG + LLM para validar las salidas de IA contra el contenido de la base de conocimientos
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Detect PII</strong>: Identify and optionally mask personally identifiable information across 40+ entity types
|
||||
<strong>Detectar PII</strong>: Identifica y opcionalmente enmascara información personal identificable en más de 40 tipos de entidades
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Validation Types
|
||||
## Tipos de validación
|
||||
|
||||
### JSON Validation
|
||||
### Validación JSON
|
||||
|
||||
Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed.
|
||||
Valida que el contenido tenga un formato JSON adecuado. Perfecto para garantizar que las salidas estructuradas de LLM puedan analizarse de forma segura.
|
||||
|
||||
**Use Cases:**
|
||||
- Validate JSON responses from Agent blocks before parsing
|
||||
- Ensure API payloads are properly formatted
|
||||
- Check structured data integrity
|
||||
**Casos de uso:**
|
||||
- Validar respuestas JSON de bloques Agent antes de analizarlas
|
||||
- Asegurar que las cargas útiles de API estén correctamente formateadas
|
||||
- Comprobar la integridad de datos estructurados
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if valid JSON, `false` otherwise
|
||||
- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...")
|
||||
- `passed`: `true` si es JSON válido, `false` en caso contrario
|
||||
- `error`: Mensaje de error si la validación falla (p. ej., "JSON inválido: Token inesperado...")
|
||||
|
||||
### Regex Validation
|
||||
### Validación Regex
|
||||
|
||||
Checks if content matches a specified regular expression pattern.
|
||||
Comprueba si el contenido coincide con un patrón de expresión regular especificado.
|
||||
|
||||
**Use Cases:**
|
||||
- Validate email addresses
|
||||
- Check phone number formats
|
||||
- Verify URLs or custom identifiers
|
||||
- Enforce specific text patterns
|
||||
**Casos de uso:**
|
||||
- Validar direcciones de correo electrónico
|
||||
- Comprobar formatos de números de teléfono
|
||||
- Verificar URLs o identificadores personalizados
|
||||
- Aplicar patrones de texto específicos
|
||||
|
||||
**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)
|
||||
**Configuración:**
|
||||
- **Patrón Regex**: La expresión regular para comparar (p. ej., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` para correos electrónicos)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if content matches pattern, `false` otherwise
|
||||
- `error`: Error message if validation fails
|
||||
- `passed`: `true` si el contenido coincide con el patrón, `false` en caso contrario
|
||||
- `error`: Mensaje de error si la validación falla
|
||||
|
||||
### Hallucination Detection
|
||||
### Detección de alucinaciones
|
||||
|
||||
Uses Retrieval-Augmented Generation (RAG) with LLM scoring to detect when AI-generated content contradicts or isn't grounded in your knowledge base.
|
||||
Utiliza generación aumentada por recuperación (RAG) con puntuación de LLM para detectar cuando el contenido generado por IA contradice o no está fundamentado en tu base de conocimientos.
|
||||
|
||||
**How It Works:**
|
||||
1. Queries your knowledge base for relevant context
|
||||
2. Sends both the AI output and retrieved context to an LLM
|
||||
3. LLM assigns a confidence score (0-10 scale)
|
||||
- **0** = Full hallucination (completely ungrounded)
|
||||
- **10** = Fully grounded (completely supported by knowledge base)
|
||||
4. Validation passes if score ≥ threshold (default: 3)
|
||||
**Cómo funciona:**
|
||||
1. Consulta tu base de conocimientos para obtener contexto relevante
|
||||
2. Envía tanto la salida de la IA como el contexto recuperado a un LLM
|
||||
3. El LLM asigna una puntuación de confianza (escala de 0-10)
|
||||
- **0** = Alucinación completa (totalmente infundada)
|
||||
- **10** = Completamente fundamentado (totalmente respaldado por la base de conocimientos)
|
||||
4. La validación se aprueba si la puntuación ≥ umbral (predeterminado: 3)
|
||||
|
||||
**Configuration:**
|
||||
- **Knowledge Base**: Select from your existing knowledge bases
|
||||
- **Model**: Choose LLM for scoring (requires strong reasoning - GPT-4o, Claude 3.7 Sonnet recommended)
|
||||
- **API Key**: Authentication for selected LLM provider (auto-hidden for hosted/Ollama models)
|
||||
- **Confidence Threshold**: Minimum score to pass (0-10, default: 3)
|
||||
- **Top K** (Advanced): Number of knowledge base chunks to retrieve (default: 10)
|
||||
**Configuración:**
|
||||
- **Base de conocimientos**: Selecciona entre tus bases de conocimientos existentes
|
||||
- **Modelo**: Elige LLM para puntuación (requiere razonamiento sólido - se recomienda GPT-4o, Claude 3.7 Sonnet)
|
||||
- **Clave API**: Autenticación para el proveedor LLM seleccionado (oculta automáticamente para modelos alojados/Ollama)
|
||||
- **Umbral de confianza**: Puntuación mínima para aprobar (0-10, predeterminado: 3)
|
||||
- **Top K** (Avanzado): Número de fragmentos de la base de conocimientos a recuperar (predeterminado: 10)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if confidence score ≥ threshold
|
||||
- `score`: Confidence score (0-10)
|
||||
- `reasoning`: LLM's explanation for the score
|
||||
- `error`: Error message if validation fails
|
||||
- `passed`: `true` si la puntuación de confianza ≥ umbral
|
||||
- `score`: Puntuación de confianza (0-10)
|
||||
- `reasoning`: Explicación del LLM para la puntuación
|
||||
- `error`: Mensaje de error si la validación falla
|
||||
|
||||
**Use Cases:**
|
||||
- Validate Agent responses against documentation
|
||||
- Ensure customer support answers are factually accurate
|
||||
- Verify generated content matches source material
|
||||
- Quality control for RAG applications
|
||||
**Casos de uso:**
|
||||
- Validar respuestas de agentes contra documentación
|
||||
- Asegurar que las respuestas de atención al cliente sean precisas
|
||||
- Verificar que el contenido generado coincida con el material de origen
|
||||
- Control de calidad para aplicaciones RAG
|
||||
|
||||
### PII Detection
|
||||
### Detección de PII
|
||||
|
||||
Detects personally identifiable information using Microsoft Presidio. Supports 40+ entity types across multiple countries and languages.
|
||||
Detecta información de identificación personal utilizando Microsoft Presidio. Compatible con más de 40 tipos de entidades en múltiples países e idiomas.
|
||||
|
||||
<div className="mx-auto w-3/5 overflow-hidden rounded-lg">
|
||||
<Video src="guardrails.mp4" width={500} height={350} />
|
||||
</div>
|
||||
|
||||
**How It Works:**
|
||||
1. Scans content for PII entities using pattern matching and NLP
|
||||
2. Returns detected entities with locations and confidence scores
|
||||
3. Optionally masks detected PII in the output
|
||||
**Cómo funciona:**
|
||||
1. Escanea el contenido en busca de entidades PII mediante coincidencia de patrones y PNL
|
||||
2. Devuelve las entidades detectadas con ubicaciones y puntuaciones de confianza
|
||||
3. Opcionalmente enmascara la PII detectada en la salida
|
||||
|
||||
**Configuration:**
|
||||
- **PII Types to Detect**: Select from grouped categories via modal selector
|
||||
- **Common**: Person name, Email, Phone, Credit card, IP address, etc.
|
||||
- **USA**: SSN, Driver's license, Passport, etc.
|
||||
- **UK**: NHS number, National insurance number
|
||||
- **Spain**: NIF, NIE, CIF
|
||||
- **Italy**: Fiscal code, Driver's license, VAT code
|
||||
- **Poland**: PESEL, NIP, REGON
|
||||
- **Singapore**: NRIC/FIN, UEN
|
||||
**Configuración:**
|
||||
- **Tipos de PII a detectar**: Seleccione de categorías agrupadas mediante selector modal
|
||||
- **Común**: Nombre de persona, Email, Teléfono, Tarjeta de crédito, Dirección IP, etc.
|
||||
- **EE.UU.**: SSN, Licencia de conducir, Pasaporte, etc.
|
||||
- **Reino Unido**: Número NHS, Número de seguro nacional
|
||||
- **España**: NIF, NIE, CIF
|
||||
- **Italia**: Código fiscal, Licencia de conducir, Código de IVA
|
||||
- **Polonia**: PESEL, NIP, REGON
|
||||
- **Singapur**: NRIC/FIN, UEN
|
||||
- **Australia**: ABN, ACN, TFN, Medicare
|
||||
- **India**: Aadhaar, PAN, Passport, Voter number
|
||||
- **Mode**:
|
||||
- **Detect**: Only identify PII (default)
|
||||
- **Mask**: Replace detected PII with masked values
|
||||
- **Language**: Detection language (default: English)
|
||||
- **India**: Aadhaar, PAN, Pasaporte, Número de votante
|
||||
- **Modo**:
|
||||
- **Detectar**: Solo identificar PII (predeterminado)
|
||||
- **Enmascarar**: Reemplazar PII detectada con valores enmascarados
|
||||
- **Idioma**: Idioma de detección (predeterminado: inglés)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `false` if any selected PII types are detected
|
||||
- `detectedEntities`: Array of detected PII with type, location, and confidence
|
||||
- `maskedText`: Content with PII masked (only if mode = "Mask")
|
||||
- `error`: Error message if validation fails
|
||||
**Salida:**
|
||||
- `passed`: `false` si se detectan los tipos de PII seleccionados
|
||||
- `detectedEntities`: Array de PII detectada con tipo, ubicación y confianza
|
||||
- `maskedText`: Contenido con PII enmascarada (solo si modo = "Mask")
|
||||
- `error`: Mensaje de error si la validación falla
|
||||
|
||||
**Use Cases:**
|
||||
- Block content containing sensitive personal information
|
||||
- Mask PII before logging or storing data
|
||||
- Compliance with GDPR, HIPAA, and other privacy regulations
|
||||
- Sanitize user inputs before processing
|
||||
**Casos de uso:**
|
||||
- Bloquear contenido que contiene información personal sensible
|
||||
- Enmascarar PII antes de registrar o almacenar datos
|
||||
- Cumplimiento con GDPR, HIPAA y otras regulaciones de privacidad
|
||||
- Sanear entradas de usuario antes del procesamiento
|
||||
|
||||
## Configuration
|
||||
## Configuración
|
||||
|
||||
### Content to Validate
|
||||
### Contenido a validar
|
||||
|
||||
The input content to validate. This typically comes from:
|
||||
- Agent block outputs: `<agent.content>`
|
||||
- Function block results: `<function.output>`
|
||||
- API responses: `<api.output>`
|
||||
- Any other block output
|
||||
El contenido de entrada para validar. Esto típicamente proviene de:
|
||||
- Salidas de bloques de agente: `<agent.content>`
|
||||
- Resultados de bloques de función: `<function.output>`
|
||||
- Respuestas de API: `<api.output>`
|
||||
- Cualquier otra salida de bloque
|
||||
|
||||
### Validation Type
|
||||
### Tipo de validación
|
||||
|
||||
Choose from four validation types:
|
||||
- **Valid JSON**: Check if content is properly formatted JSON
|
||||
- **Regex Match**: Verify content matches a regex pattern
|
||||
- **Hallucination Check**: Validate against knowledge base with LLM scoring
|
||||
- **PII Detection**: Detect and optionally mask personally identifiable information
|
||||
Elija entre cuatro tipos de validación:
|
||||
- **JSON válido**: Comprobar si el contenido es JSON correctamente formateado
|
||||
- **Coincidencia Regex**: Verificar si el contenido coincide con un patrón regex
|
||||
- **Comprobación de alucinaciones**: Validar contra base de conocimiento con puntuación LLM
|
||||
- **Detección de PII**: Detectar y opcionalmente enmascarar información de identificación personal
|
||||
|
||||
## Outputs
|
||||
## Salidas
|
||||
|
||||
All validation types return:
|
||||
Todos los tipos de validación devuelven:
|
||||
|
||||
- **`<guardrails.passed>`**: Boolean indicating if validation passed
|
||||
- **`<guardrails.validationType>`**: The type of validation performed
|
||||
- **`<guardrails.input>`**: The original input that was validated
|
||||
- **`<guardrails.error>`**: Error message if validation failed (optional)
|
||||
- **`<guardrails.passed>`**: Booleano que indica si la validación fue exitosa
|
||||
- **`<guardrails.validationType>`**: El tipo de validación realizada
|
||||
- **`<guardrails.input>`**: La entrada original que fue validada
|
||||
- **`<guardrails.error>`**: Mensaje de error si la validación falló (opcional)
|
||||
|
||||
Additional outputs by type:
|
||||
Salidas adicionales por tipo:
|
||||
|
||||
**Hallucination Check:**
|
||||
- **`<guardrails.score>`**: Confidence score (0-10)
|
||||
- **`<guardrails.reasoning>`**: LLM's explanation
|
||||
**Verificación de alucinaciones:**
|
||||
- **`<guardrails.score>`**: Puntuación de confianza (0-10)
|
||||
- **`<guardrails.reasoning>`**: Explicación del LLM
|
||||
|
||||
**PII Detection:**
|
||||
- **`<guardrails.detectedEntities>`**: Array of detected PII entities
|
||||
- **`<guardrails.maskedText>`**: Content with PII masked (if mode = "Mask")
|
||||
**Detección de PII:**
|
||||
- **`<guardrails.detectedEntities>`**: Array de entidades PII detectadas
|
||||
- **`<guardrails.maskedText>`**: Contenido con PII enmascarado (si el modo = "Mask")
|
||||
|
||||
## Example Use Cases
|
||||
## Ejemplos de casos de uso
|
||||
|
||||
### Validate JSON Before Parsing
|
||||
### Validar JSON antes de analizarlo
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Ensure Agent output is valid JSON</h4>
|
||||
<h4 className="font-medium">Escenario: Asegurar que la salida del agente sea JSON válido</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent generates structured JSON response</li>
|
||||
<li>Guardrails validates JSON format</li>
|
||||
<li>Condition block checks `<guardrails.passed>`</li>
|
||||
<li>If passed → Parse and use data, If failed → Retry or handle error</li>
|
||||
<li>El agente genera una respuesta JSON estructurada</li>
|
||||
<li>Guardrails valida el formato JSON</li>
|
||||
<li>El bloque de condición verifica `<guardrails.passed>`</li>
|
||||
<li>Si pasa → Analizar y usar datos, Si falla → Reintentar o manejar el error</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
### Prevent Hallucinations
|
||||
### Prevenir alucinaciones
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Validate customer support responses</h4>
|
||||
<h4 className="font-medium">Escenario: Validar respuestas de atención al cliente</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent generates response to customer question</li>
|
||||
<li>Guardrails checks against support documentation knowledge base</li>
|
||||
<li>If confidence score ≥ 3 → Send response</li>
|
||||
<li>If confidence score \< 3 → Flag for human review</li>
|
||||
<li>El agente genera una respuesta a la pregunta del cliente</li>
|
||||
<li>Guardrails verifica contra la base de conocimientos de documentación de soporte</li>
|
||||
<li>Si la puntuación de confianza ≥ 3 → Enviar respuesta</li>
|
||||
<li>Si la puntuación de confianza \< 3 → Marcar para revisión humana</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
### Block PII in User Inputs
|
||||
### Bloquear PII en entradas de usuario
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Sanitize user-submitted content</h4>
|
||||
<h4 className="font-medium">Escenario: Sanear contenido enviado por usuarios</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>User submits form with text content</li>
|
||||
<li>Guardrails detects PII (emails, phone numbers, SSN, etc.)</li>
|
||||
<li>If PII detected → Reject submission or mask sensitive data</li>
|
||||
<li>If no PII → Process normally</li>
|
||||
<li>El usuario envía un formulario con contenido de texto</li>
|
||||
<li>Guardrails detecta PII (correos electrónicos, números de teléfono, SSN, etc.)</li>
|
||||
<li>Si se detecta PII → Rechazar el envío o enmascarar datos sensibles</li>
|
||||
<li>Si no hay PII → Procesar normalmente</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
@@ -222,30 +222,29 @@ Additional outputs by type:
|
||||
<Video src="guardrails-example.mp4" width={500} height={350} />
|
||||
</div>
|
||||
|
||||
### Validate Email Format
|
||||
### Validar formato de correo electrónico
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Check email address format</h4>
|
||||
<h4 className="font-medium">Escenario: Comprobar el formato de dirección de correo electrónico</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent extracts email from text</li>
|
||||
<li>Guardrails validates with regex pattern</li>
|
||||
<li>If valid → Use email for notification</li>
|
||||
<li>If invalid → Request correction</li>
|
||||
<li>El agente extrae el correo electrónico del texto</li>
|
||||
<li>Guardrails valida con un patrón regex</li>
|
||||
<li>Si es válido → Usar el correo electrónico para notificación</li>
|
||||
<li>Si no es válido → Solicitar corrección</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
## Best Practices
|
||||
## Mejores prácticas
|
||||
|
||||
- **Chain with Condition blocks**: Use `<guardrails.passed>` to branch workflow logic based on validation results
|
||||
- **Use JSON validation before parsing**: Always validate JSON structure before attempting to parse LLM outputs
|
||||
- **Choose appropriate PII types**: Only select the PII entity types relevant to your use case for better performance
|
||||
- **Set reasonable confidence thresholds**: For hallucination detection, adjust threshold based on your accuracy requirements (higher = stricter)
|
||||
- **Use strong models for hallucination detection**: GPT-4o or Claude 3.7 Sonnet provide more accurate confidence scoring
|
||||
- **Mask PII for logging**: Use "Mask" mode when you need to log or store content that may contain PII
|
||||
- **Test regex patterns**: Validate your regex patterns thoroughly before deploying to production
|
||||
- **Monitor validation failures**: Track `<guardrails.error>` messages to identify common validation issues
|
||||
- **Encadena con bloques de Condición**: Usa `<guardrails.passed>` para ramificar la lógica del flujo de trabajo según los resultados de validación
|
||||
- **Usa validación JSON antes de analizar**: Siempre valida la estructura JSON antes de intentar analizar las salidas de LLM
|
||||
- **Elige los tipos de PII apropiados**: Selecciona solo los tipos de entidades PII relevantes para tu caso de uso para un mejor rendimiento
|
||||
- **Establece umbrales de confianza razonables**: Para la detección de alucinaciones, ajusta el umbral según tus requisitos de precisión (más alto = más estricto)
|
||||
- **Usa modelos potentes para la detección de alucinaciones**: GPT-4o o Claude 3.7 Sonnet proporcionan una puntuación de confianza más precisa
|
||||
- **Enmascara PII para el registro**: Usa el modo "Mask" cuando necesites registrar o almacenar contenido que pueda contener PII
|
||||
- **Prueba patrones regex**: Valida tus patrones de expresiones regulares minuciosamente antes de implementarlos en producción
|
||||
- **Monitorea fallos de validación**: Rastrea los mensajes `<guardrails.error>` para identificar problemas comunes de validación
|
||||
|
||||
<Callout type="info">
|
||||
Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical.
|
||||
La validación de Guardrails ocurre de forma sincrónica en tu flujo de trabajo. Para la detección de alucinaciones, elige modelos más rápidos (como GPT-4o-mini) si la latencia es crítica.
|
||||
</Callout>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: TypeScript/JavaScript SDK
|
||||
title: SDK de TypeScript/JavaScript
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
@@ -7,10 +7,10 @@ import { Card, Cards } from 'fumadocs-ui/components/card'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
El SDK oficial de TypeScript/JavaScript para Sim proporciona seguridad de tipos completa y es compatible tanto con entornos Node.js como de navegador, lo que te permite ejecutar flujos de trabajo programáticamente desde tus aplicaciones Node.js, aplicaciones web y otros entornos JavaScript.
|
||||
El SDK oficial de TypeScript/JavaScript para Sim proporciona seguridad de tipos completa y es compatible tanto con entornos Node.js como con navegadores, lo que te permite ejecutar flujos de trabajo programáticamente desde tus aplicaciones Node.js, aplicaciones web y otros entornos JavaScript.
|
||||
|
||||
<Callout type="info">
|
||||
El SDK de TypeScript proporciona seguridad de tipos completa, soporte para ejecución asíncrona, limitación automática de velocidad con retroceso exponencial y seguimiento de uso.
|
||||
El SDK de TypeScript proporciona seguridad de tipos completa, soporte para ejecución asíncrona, limitación automática de tasa con retroceso exponencial y seguimiento de uso.
|
||||
</Callout>
|
||||
|
||||
## Instalación
|
||||
@@ -96,12 +96,12 @@ const result = await client.executeWorkflow('workflow-id', {
|
||||
- `input` (any): Datos de entrada para pasar al flujo de trabajo
|
||||
- `timeout` (number): Tiempo de espera en milisegundos (predeterminado: 30000)
|
||||
- `stream` (boolean): Habilitar respuestas en streaming (predeterminado: false)
|
||||
- `selectedOutputs` (string[]): Bloquear salidas para transmitir en formato `blockName.attribute` (por ejemplo, `["agent1.content"]`)
|
||||
- `selectedOutputs` (string[]): Salidas de bloques para transmitir en formato `blockName.attribute` (p. ej., `["agent1.content"]`)
|
||||
- `async` (boolean): Ejecutar de forma asíncrona (predeterminado: false)
|
||||
|
||||
**Devuelve:** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
|
||||
Cuando `async: true`, devuelve inmediatamente un ID de tarea para sondeo. De lo contrario, espera a que se complete.
|
||||
Cuando `async: true`, devuelve inmediatamente un ID de tarea para consultar. De lo contrario, espera hasta completarse.
|
||||
|
||||
##### getWorkflowStatus()
|
||||
|
||||
@@ -146,7 +146,7 @@ if (status.status === 'completed') {
|
||||
```
|
||||
|
||||
**Parámetros:**
|
||||
- `taskId` (string): El ID de tarea devuelto de la ejecución asíncrona
|
||||
- `taskId` (string): El ID de tarea devuelto por la ejecución asíncrona
|
||||
|
||||
**Devuelve:** `Promise<JobStatus>`
|
||||
|
||||
@@ -161,7 +161,7 @@ if (status.status === 'completed') {
|
||||
|
||||
##### executeWithRetry()
|
||||
|
||||
Ejecuta un flujo de trabajo con reintento automático en errores de límite de tasa utilizando retroceso exponencial.
|
||||
Ejecutar un flujo de trabajo con reintento automático en errores de límite de tasa usando retroceso exponencial.
|
||||
|
||||
```typescript
|
||||
const result = await client.executeWithRetry('workflow-id', {
|
||||
@@ -247,7 +247,7 @@ console.log('Plan:', limits.usage.plan);
|
||||
|
||||
##### setApiKey()
|
||||
|
||||
Actualiza la clave API.
|
||||
Actualiza la clave de API.
|
||||
|
||||
```typescript
|
||||
client.setApiKey('new-api-key');
|
||||
@@ -501,9 +501,9 @@ Configura el cliente usando variables de entorno:
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Integración con Express de Node.js
|
||||
### Integración con Node.js Express
|
||||
|
||||
Integra con un servidor Express.js:
|
||||
Integración con un servidor Express.js:
|
||||
|
||||
```typescript
|
||||
import express from 'express';
|
||||
@@ -582,7 +582,7 @@ export default async function handler(
|
||||
}
|
||||
```
|
||||
|
||||
### Uso del navegador
|
||||
### Uso en el navegador
|
||||
|
||||
Uso en el navegador (con configuración CORS adecuada):
|
||||
|
||||
@@ -604,19 +604,98 @@ async function executeClientSideWorkflow() {
|
||||
});
|
||||
|
||||
console.log('Workflow result:', result);
|
||||
|
||||
|
||||
// Update UI with result
|
||||
document.getElementById('result')!.textContent =
|
||||
document.getElementById('result')!.textContent =
|
||||
JSON.stringify(result.output, null, 2);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach to button click
|
||||
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
|
||||
```
|
||||
|
||||
### Carga de archivos
|
||||
|
||||
Los objetos File son detectados automáticamente y convertidos a formato base64. Inclúyelos en tu entrada bajo el nombre de campo que coincida con el formato de entrada del disparador API de tu flujo de trabajo.
|
||||
|
||||
El SDK convierte los objetos File a este formato:
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: 'file',
|
||||
data: 'data:mime/type;base64,base64data',
|
||||
name: 'filename',
|
||||
mime: 'mime/type'
|
||||
}
|
||||
```
|
||||
|
||||
Alternativamente, puedes proporcionar archivos manualmente usando el formato URL:
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: 'url',
|
||||
data: 'https://example.com/file.pdf',
|
||||
name: 'file.pdf',
|
||||
mime: 'application/pdf'
|
||||
}
|
||||
```
|
||||
|
||||
<Tabs items={['Browser', 'Node.js']}>
|
||||
<Tab value="Browser">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
|
||||
});
|
||||
|
||||
// From file input
|
||||
async function handleFileUpload(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const files = Array.from(input.files || []);
|
||||
|
||||
// Include files under the field name from your API trigger's input format
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
documents: files, // Must match your workflow's "files" field name
|
||||
instructions: 'Analyze these documents'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Result:', result);
|
||||
}
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="Node.js">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
import fs from 'fs';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.SIM_API_KEY!
|
||||
});
|
||||
|
||||
// Read file and create File object
|
||||
const fileBuffer = fs.readFileSync('./document.pdf');
|
||||
const file = new File([fileBuffer], 'document.pdf', {
|
||||
type: 'application/pdf'
|
||||
});
|
||||
|
||||
// Include files under the field name from your API trigger's input format
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
documents: [file], // Must match your workflow's "files" field name
|
||||
query: 'Summarize this document'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Callout type="warning">
|
||||
Cuando uses el SDK en el navegador, ten cuidado de no exponer claves API sensibles. Considera usar un proxy de backend o claves API públicas con permisos limitados.
|
||||
</Callout>
|
||||
@@ -748,9 +827,9 @@ async function executeAsync() {
|
||||
executeAsync();
|
||||
```
|
||||
|
||||
### Límite de tasa y reintentos
|
||||
### Limitación de tasa y reintentos
|
||||
|
||||
Maneja límites de tasa automáticamente con retroceso exponencial:
|
||||
Maneja los límites de tasa automáticamente con retroceso exponencial:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
|
||||
@@ -788,7 +867,7 @@ async function executeWithRetryHandling() {
|
||||
|
||||
### Monitoreo de uso
|
||||
|
||||
Monitorea el uso de tu cuenta y sus límites:
|
||||
Monitorea el uso y los límites de tu cuenta:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -814,19 +893,19 @@ async function checkUsage() {
|
||||
console.log(' Resets at:', limits.rateLimit.async.resetAt);
|
||||
console.log(' Is limited:', limits.rateLimit.async.isLimited);
|
||||
|
||||
console.log('\n=== Uso ===');
|
||||
console.log('Costo del período actual: $' + limits.usage.currentPeriodCost.toFixed(2));
|
||||
console.log('Límite: $' + limits.usage.limit.toFixed(2));
|
||||
console.log('\n=== Usage ===');
|
||||
console.log('Current period cost: $' + 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('Uso: ' + percentUsed.toFixed(1) + '%');
|
||||
console.log('Usage: ' + percentUsed.toFixed(1) + '%');
|
||||
|
||||
if (percentUsed > 80) {
|
||||
console.warn('⚠️ Advertencia: ¡Estás acercándote a tu límite de uso!');
|
||||
console.warn('⚠️ Warning: You are approaching your usage limit!');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error al verificar el uso:', error);
|
||||
console.error('Error checking usage:', error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -846,40 +925,35 @@ const client = new SimStudioClient({
|
||||
|
||||
async function executeWithStreaming() {
|
||||
try {
|
||||
// Habilita streaming para salidas de bloques específicos
|
||||
// Enable streaming for specific block outputs
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: { message: 'Count to five' },
|
||||
stream: true,
|
||||
selectedOutputs: ['agent1.content'] // Usa el formato blockName.attribute
|
||||
selectedOutputs: ['agent1.content'] // Use blockName.attribute format
|
||||
});
|
||||
|
||||
console.log('Resultado del flujo de trabajo:', result);
|
||||
console.log('Workflow result:', result);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
The streaming response follows the Server-Sent Events (SSE) format:
|
||||
La respuesta en streaming sigue el formato de eventos enviados por el servidor (SSE):
|
||||
|
||||
```
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", dos"}
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"}
|
||||
|
||||
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
|
||||
data: [DONE]
|
||||
|
||||
```
|
||||
|
||||
**React Streaming Example:**
|
||||
**Ejemplo de streaming en React:**
|
||||
|
||||
```
|
||||
|
||||
typescript
|
||||
```typescript
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
function StreamingWorkflow() {
|
||||
@@ -941,44 +1015,43 @@ function StreamingWorkflow() {
|
||||
return (
|
||||
<div>
|
||||
<button onClick={executeStreaming} disabled={loading}>
|
||||
{loading ? 'Generando...' : 'Iniciar streaming'}
|
||||
{loading ? 'Generating...' : 'Start Streaming'}
|
||||
</button>
|
||||
<div style={{ whiteSpace: 'pre-wrap' }}>{output}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Getting Your API Key
|
||||
## Obtener tu clave API
|
||||
|
||||
<Steps>
|
||||
<Step title="Log in to Sim">
|
||||
Navigate to [Sim](https://sim.ai) and log in to your account.
|
||||
<Step title="Inicia sesión en Sim">
|
||||
Navega a [Sim](https://sim.ai) e inicia sesión en tu cuenta.
|
||||
</Step>
|
||||
<Step title="Open your workflow">
|
||||
Navigate to the workflow you want to execute programmatically.
|
||||
<Step title="Abre tu flujo de trabajo">
|
||||
Navega al flujo de trabajo que quieres ejecutar programáticamente.
|
||||
</Step>
|
||||
<Step title="Deploy your workflow">
|
||||
Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.
|
||||
<Step title="Despliega tu flujo de trabajo">
|
||||
Haz clic en "Desplegar" para desplegar tu flujo de trabajo si aún no ha sido desplegado.
|
||||
</Step>
|
||||
<Step title="Create or select an API key">
|
||||
During the deployment process, select or create an API key.
|
||||
<Step title="Crea o selecciona una clave API">
|
||||
Durante el proceso de despliegue, selecciona o crea una clave API.
|
||||
</Step>
|
||||
<Step title="Copy the API key">
|
||||
Copy the API key to use in your TypeScript/JavaScript application.
|
||||
<Step title="Copia la clave API">
|
||||
Copia la clave API para usarla en tu aplicación TypeScript/JavaScript.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Callout type="warning">
|
||||
Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management.
|
||||
Mantén tu clave API segura y nunca la incluyas en el control de versiones. Utiliza variables de entorno o gestión segura de configuración.
|
||||
</Callout>
|
||||
|
||||
## Requirements
|
||||
## Requisitos
|
||||
|
||||
- Node.js 16+
|
||||
- TypeScript 5.0+ (for TypeScript projects)
|
||||
- TypeScript 5.0+ (para proyectos TypeScript)
|
||||
|
||||
## License
|
||||
## Licencia
|
||||
|
||||
Apache-2.0
|
||||
@@ -8,213 +8,213 @@ 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.
|
||||
Le bloc Guardrails valide et protège vos flux de travail IA en vérifiant le contenu selon plusieurs types de validation. Assurez la qualité des données, prévenez les hallucinations, détectez les PII et imposez des exigences de format avant que le contenu ne circule dans votre flux de travail.
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Image
|
||||
src="/static/blocks/guardrails.png"
|
||||
alt="Guardrails Block"
|
||||
alt="Bloc Guardrails"
|
||||
width={500}
|
||||
height={350}
|
||||
className="my-6"
|
||||
/>
|
||||
</div>
|
||||
|
||||
## Overview
|
||||
## Aperçu
|
||||
|
||||
The Guardrails block enables you to:
|
||||
Le bloc Guardrails vous permet de :
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
<strong>Validate JSON Structure</strong>: Ensure LLM outputs are valid JSON before parsing
|
||||
<strong>Valider la structure JSON</strong> : garantir que les sorties LLM sont en JSON valide avant l'analyse
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Match Regex Patterns</strong>: Verify content matches specific formats (emails, phone numbers, URLs, etc.)
|
||||
<strong>Correspondre aux modèles Regex</strong> : vérifier que le contenu correspond à des formats spécifiques (emails, numéros de téléphone, URLs, etc.)
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Detect Hallucinations</strong>: Use RAG + LLM scoring to validate AI outputs against knowledge base content
|
||||
<strong>Détecter les hallucinations</strong> : utiliser le scoring RAG + LLM pour valider les sorties IA par rapport au contenu de la base de connaissances
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Detect PII</strong>: Identify and optionally mask personally identifiable information across 40+ entity types
|
||||
<strong>Détecter les PII</strong> : identifier et éventuellement masquer les informations personnellement identifiables à travers plus de 40 types d'entités
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Validation Types
|
||||
## Types de validation
|
||||
|
||||
### JSON Validation
|
||||
### Validation JSON
|
||||
|
||||
Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed.
|
||||
Vérifie que le contenu est correctement formaté en JSON. Parfait pour s'assurer que les sorties LLM structurées peuvent être analysées en toute sécurité.
|
||||
|
||||
**Use Cases:**
|
||||
- Validate JSON responses from Agent blocks before parsing
|
||||
- Ensure API payloads are properly formatted
|
||||
- Check structured data integrity
|
||||
**Cas d'utilisation :**
|
||||
- Valider les réponses JSON des blocs Agent avant l'analyse
|
||||
- S'assurer que les charges utiles API sont correctement formatées
|
||||
- Vérifier l'intégrité des données structurées
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if valid JSON, `false` otherwise
|
||||
- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...")
|
||||
- `passed`: `true` si le JSON est valide, `false` sinon
|
||||
- `error`: Message d'erreur si la validation échoue (par ex., "JSON invalide : Token inattendu...")
|
||||
|
||||
### Regex Validation
|
||||
### Validation Regex
|
||||
|
||||
Checks if content matches a specified regular expression pattern.
|
||||
Vérifie si le contenu correspond à un modèle d'expression régulière spécifié.
|
||||
|
||||
**Use Cases:**
|
||||
- Validate email addresses
|
||||
- Check phone number formats
|
||||
- Verify URLs or custom identifiers
|
||||
- Enforce specific text patterns
|
||||
**Cas d'utilisation :**
|
||||
- Valider les adresses email
|
||||
- Vérifier les formats de numéros de téléphone
|
||||
- Vérifier les URLs ou identifiants personnalisés
|
||||
- Imposer des modèles de texte spécifiques
|
||||
|
||||
**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)
|
||||
**Configuration :**
|
||||
- **Modèle Regex** : L'expression régulière à faire correspondre (par ex., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` pour les emails)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if content matches pattern, `false` otherwise
|
||||
- `error`: Error message if validation fails
|
||||
- `passed`: `true` si le contenu correspond au modèle, `false` sinon
|
||||
- `error`: Message d'erreur si la validation échoue
|
||||
|
||||
### Hallucination Detection
|
||||
### Détection d'hallucination
|
||||
|
||||
Uses Retrieval-Augmented Generation (RAG) with LLM scoring to detect when AI-generated content contradicts or isn't grounded in your knowledge base.
|
||||
Utilise la génération augmentée par récupération (RAG) avec notation par LLM pour détecter quand le contenu généré par l'IA contredit ou n'est pas fondé sur votre base de connaissances.
|
||||
|
||||
**How It Works:**
|
||||
1. Queries your knowledge base for relevant context
|
||||
2. Sends both the AI output and retrieved context to an LLM
|
||||
3. LLM assigns a confidence score (0-10 scale)
|
||||
- **0** = Full hallucination (completely ungrounded)
|
||||
- **10** = Fully grounded (completely supported by knowledge base)
|
||||
4. Validation passes if score ≥ threshold (default: 3)
|
||||
**Comment ça fonctionne :**
|
||||
1. Interroge votre base de connaissances pour obtenir un contexte pertinent
|
||||
2. Envoie à la fois la sortie de l'IA et le contexte récupéré à un LLM
|
||||
3. Le LLM attribue un score de confiance (échelle de 0 à 10)
|
||||
- **0** = Hallucination complète (totalement non fondée)
|
||||
- **10** = Entièrement fondé (complètement soutenu par la base de connaissances)
|
||||
4. La validation réussit si le score ≥ seuil (par défaut : 3)
|
||||
|
||||
**Configuration:**
|
||||
- **Knowledge Base**: Select from your existing knowledge bases
|
||||
- **Model**: Choose LLM for scoring (requires strong reasoning - GPT-4o, Claude 3.7 Sonnet recommended)
|
||||
- **API Key**: Authentication for selected LLM provider (auto-hidden for hosted/Ollama models)
|
||||
- **Confidence Threshold**: Minimum score to pass (0-10, default: 3)
|
||||
- **Top K** (Advanced): Number of knowledge base chunks to retrieve (default: 10)
|
||||
**Configuration :**
|
||||
- **Base de connaissances** : Sélectionnez parmi vos bases de connaissances existantes
|
||||
- **Modèle** : Choisissez un LLM pour la notation (nécessite un raisonnement solide - GPT-4o, Claude 3.7 Sonnet recommandés)
|
||||
- **Clé API** : Authentification pour le fournisseur LLM sélectionné (masquée automatiquement pour les modèles hébergés/Ollama)
|
||||
- **Seuil de confiance** : Score minimum pour réussir (0-10, par défaut : 3)
|
||||
- **Top K** (Avancé) : Nombre de fragments de base de connaissances à récupérer (par défaut : 10)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if confidence score ≥ threshold
|
||||
- `score`: Confidence score (0-10)
|
||||
- `reasoning`: LLM's explanation for the score
|
||||
- `error`: Error message if validation fails
|
||||
- `passed`: `true` si le score de confiance ≥ seuil
|
||||
- `score`: Score de confiance (0-10)
|
||||
- `reasoning`: Explication du LLM pour le score
|
||||
- `error`: Message d'erreur si la validation échoue
|
||||
|
||||
**Use Cases:**
|
||||
- Validate Agent responses against documentation
|
||||
- Ensure customer support answers are factually accurate
|
||||
- Verify generated content matches source material
|
||||
- Quality control for RAG applications
|
||||
**Cas d'utilisation :**
|
||||
- Valider les réponses des agents par rapport à la documentation
|
||||
- Assurer que les réponses du support client sont factuellement exactes
|
||||
- Vérifier que le contenu généré correspond au matériel source
|
||||
- Contrôle qualité pour les applications RAG
|
||||
|
||||
### PII Detection
|
||||
### Détection de PII
|
||||
|
||||
Detects personally identifiable information using Microsoft Presidio. Supports 40+ entity types across multiple countries and languages.
|
||||
Détecte les informations personnellement identifiables à l'aide de Microsoft Presidio. Prend en charge plus de 40 types d'entités dans plusieurs pays et langues.
|
||||
|
||||
<div className="mx-auto w-3/5 overflow-hidden rounded-lg">
|
||||
<Video src="guardrails.mp4" width={500} height={350} />
|
||||
</div>
|
||||
|
||||
**How It Works:**
|
||||
1. Scans content for PII entities using pattern matching and NLP
|
||||
2. Returns detected entities with locations and confidence scores
|
||||
3. Optionally masks detected PII in the output
|
||||
**Comment ça fonctionne :**
|
||||
1. Analyse le contenu pour détecter les entités PII en utilisant la correspondance de modèles et le NLP
|
||||
2. Renvoie les entités détectées avec leurs emplacements et scores de confiance
|
||||
3. Masque optionnellement les PII détectées dans la sortie
|
||||
|
||||
**Configuration:**
|
||||
- **PII Types to Detect**: Select from grouped categories via modal selector
|
||||
- **Common**: Person name, Email, Phone, Credit card, IP address, etc.
|
||||
- **USA**: SSN, Driver's license, Passport, etc.
|
||||
- **UK**: NHS number, National insurance number
|
||||
- **Spain**: NIF, NIE, CIF
|
||||
- **Italy**: Fiscal code, Driver's license, VAT code
|
||||
- **Poland**: PESEL, NIP, REGON
|
||||
- **Singapore**: NRIC/FIN, UEN
|
||||
- **Australia**: ABN, ACN, TFN, Medicare
|
||||
- **India**: Aadhaar, PAN, Passport, Voter number
|
||||
- **Mode**:
|
||||
- **Detect**: Only identify PII (default)
|
||||
- **Mask**: Replace detected PII with masked values
|
||||
- **Language**: Detection language (default: English)
|
||||
**Configuration :**
|
||||
- **Types de PII à détecter** : Sélectionnez parmi les catégories groupées via le sélecteur modal
|
||||
- **Commun** : Nom de personne, Email, Téléphone, Carte de crédit, Adresse IP, etc.
|
||||
- **USA** : SSN, Permis de conduire, Passeport, etc.
|
||||
- **Royaume-Uni** : Numéro NHS, Numéro d'assurance nationale
|
||||
- **Espagne** : NIF, NIE, CIF
|
||||
- **Italie** : Code fiscal, Permis de conduire, Code TVA
|
||||
- **Pologne** : PESEL, NIP, REGON
|
||||
- **Singapour** : NRIC/FIN, UEN
|
||||
- **Australie** : ABN, ACN, TFN, Medicare
|
||||
- **Inde** : Aadhaar, PAN, Passeport, Numéro d'électeur
|
||||
- **Mode** :
|
||||
- **Détecter** : Identifier uniquement les PII (par défaut)
|
||||
- **Masquer** : Remplacer les PII détectées par des valeurs masquées
|
||||
- **Langue** : Langue de détection (par défaut : anglais)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `false` if any selected PII types are detected
|
||||
- `detectedEntities`: Array of detected PII with type, location, and confidence
|
||||
- `maskedText`: Content with PII masked (only if mode = "Mask")
|
||||
- `error`: Error message if validation fails
|
||||
**Sortie :**
|
||||
- `passed` : `false` si des types de PII sélectionnés sont détectés
|
||||
- `detectedEntities` : Tableau des PII détectées avec type, emplacement et niveau de confiance
|
||||
- `maskedText` : Contenu avec PII masquées (uniquement si mode = "Mask")
|
||||
- `error` : Message d'erreur si la validation échoue
|
||||
|
||||
**Use Cases:**
|
||||
- Block content containing sensitive personal information
|
||||
- Mask PII before logging or storing data
|
||||
- Compliance with GDPR, HIPAA, and other privacy regulations
|
||||
- Sanitize user inputs before processing
|
||||
**Cas d'utilisation :**
|
||||
- Bloquer le contenu contenant des informations personnelles sensibles
|
||||
- Masquer les PII avant la journalisation ou le stockage des données
|
||||
- Conformité avec le RGPD, HIPAA et autres réglementations sur la confidentialité
|
||||
- Assainir les entrées utilisateur avant traitement
|
||||
|
||||
## Configuration
|
||||
|
||||
### Content to Validate
|
||||
### Contenu à valider
|
||||
|
||||
The input content to validate. This typically comes from:
|
||||
- Agent block outputs: `<agent.content>`
|
||||
- Function block results: `<function.output>`
|
||||
- API responses: `<api.output>`
|
||||
- Any other block output
|
||||
Le contenu d'entrée à valider. Cela provient généralement de :
|
||||
- Sorties de blocs d'agent : `<agent.content>`
|
||||
- Résultats de blocs de fonction : `<function.output>`
|
||||
- Réponses API : `<api.output>`
|
||||
- Toute autre sortie de bloc
|
||||
|
||||
### Validation Type
|
||||
### Type de validation
|
||||
|
||||
Choose from four validation types:
|
||||
- **Valid JSON**: Check if content is properly formatted JSON
|
||||
- **Regex Match**: Verify content matches a regex pattern
|
||||
- **Hallucination Check**: Validate against knowledge base with LLM scoring
|
||||
- **PII Detection**: Detect and optionally mask personally identifiable information
|
||||
Choisissez parmi quatre types de validation :
|
||||
- **JSON valide** : Vérifier si le contenu est au format JSON correctement formaté
|
||||
- **Correspondance Regex** : Vérifier si le contenu correspond à un modèle regex
|
||||
- **Vérification d'hallucination** : Valider par rapport à une base de connaissances avec notation LLM
|
||||
- **Détection de PII** : Détecter et éventuellement masquer les informations personnellement identifiables
|
||||
|
||||
## Outputs
|
||||
## Sorties
|
||||
|
||||
All validation types return:
|
||||
Tous les types de validation renvoient :
|
||||
|
||||
- **`<guardrails.passed>`**: Boolean indicating if validation passed
|
||||
- **`<guardrails.validationType>`**: The type of validation performed
|
||||
- **`<guardrails.input>`**: The original input that was validated
|
||||
- **`<guardrails.error>`**: Error message if validation failed (optional)
|
||||
- **`<guardrails.passed>`** : Booléen indiquant si la validation a réussi
|
||||
- **`<guardrails.validationType>`** : Le type de validation effectuée
|
||||
- **`<guardrails.input>`** : L'entrée originale qui a été validée
|
||||
- **`<guardrails.error>`** : Message d'erreur si la validation a échoué (facultatif)
|
||||
|
||||
Additional outputs by type:
|
||||
Sorties supplémentaires par type :
|
||||
|
||||
**Hallucination Check:**
|
||||
- **`<guardrails.score>`**: Confidence score (0-10)
|
||||
- **`<guardrails.reasoning>`**: LLM's explanation
|
||||
**Vérification d'hallucination :**
|
||||
- **`<guardrails.score>`** : Score de confiance (0-10)
|
||||
- **`<guardrails.reasoning>`** : Explication du LLM
|
||||
|
||||
**PII Detection:**
|
||||
- **`<guardrails.detectedEntities>`**: Array of detected PII entities
|
||||
- **`<guardrails.maskedText>`**: Content with PII masked (if mode = "Mask")
|
||||
**Détection de PII :**
|
||||
- **`<guardrails.detectedEntities>`** : Tableau des entités PII détectées
|
||||
- **`<guardrails.maskedText>`** : Contenu avec PII masquées (si mode = "Mask")
|
||||
|
||||
## Example Use Cases
|
||||
## Exemples de cas d'utilisation
|
||||
|
||||
### Validate JSON Before Parsing
|
||||
### Valider le JSON avant l'analyse
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Ensure Agent output is valid JSON</h4>
|
||||
<h4 className="font-medium">Scénario : s'assurer que la sortie de l'agent est un JSON valide</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent generates structured JSON response</li>
|
||||
<li>Guardrails validates JSON format</li>
|
||||
<li>Condition block checks `<guardrails.passed>`</li>
|
||||
<li>If passed → Parse and use data, If failed → Retry or handle error</li>
|
||||
<li>L'agent génère une réponse JSON structurée</li>
|
||||
<li>Guardrails valide le format JSON</li>
|
||||
<li>Le bloc de condition vérifie `<guardrails.passed>`</li>
|
||||
<li>Si réussi → Analyser et utiliser les données, Si échoué → Réessayer ou gérer l'erreur</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
### Prevent Hallucinations
|
||||
### Prévenir les hallucinations
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Validate customer support responses</h4>
|
||||
<h4 className="font-medium">Scénario : valider les réponses du support client</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent generates response to customer question</li>
|
||||
<li>Guardrails checks against support documentation knowledge base</li>
|
||||
<li>If confidence score ≥ 3 → Send response</li>
|
||||
<li>If confidence score \< 3 → Flag for human review</li>
|
||||
<li>L'agent génère une réponse à la question du client</li>
|
||||
<li>Guardrails vérifie par rapport à la base de connaissances de la documentation d'assistance</li>
|
||||
<li>Si le score de confiance ≥ 3 → Envoyer la réponse</li>
|
||||
<li>Si le score de confiance \< 3 → Signaler pour révision humaine</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
### Block PII in User Inputs
|
||||
### Bloquer les PII dans les entrées utilisateur
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Sanitize user-submitted content</h4>
|
||||
<h4 className="font-medium">Scénario : assainir le contenu soumis par l'utilisateur</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>User submits form with text content</li>
|
||||
<li>Guardrails detects PII (emails, phone numbers, SSN, etc.)</li>
|
||||
<li>If PII detected → Reject submission or mask sensitive data</li>
|
||||
<li>If no PII → Process normally</li>
|
||||
<li>L'utilisateur soumet un formulaire avec du contenu textuel</li>
|
||||
<li>Guardrails détecte les PII (emails, numéros de téléphone, numéros de sécurité sociale, etc.)</li>
|
||||
<li>Si PII détectées → Rejeter la soumission ou masquer les données sensibles</li>
|
||||
<li>Si aucune PII → Traiter normalement</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
@@ -222,30 +222,29 @@ Additional outputs by type:
|
||||
<Video src="guardrails-example.mp4" width={500} height={350} />
|
||||
</div>
|
||||
|
||||
### Validate Email Format
|
||||
### Valider le format d'email
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Check email address format</h4>
|
||||
<h4 className="font-medium">Scénario : vérifier le format d'adresse email</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent extracts email from text</li>
|
||||
<li>Guardrails validates with regex pattern</li>
|
||||
<li>If valid → Use email for notification</li>
|
||||
<li>If invalid → Request correction</li>
|
||||
<li>L'agent extrait l'email du texte</li>
|
||||
<li>Guardrails valide avec un modèle d'expression régulière</li>
|
||||
<li>Si valide → Utiliser l'email pour la notification</li>
|
||||
<li>Si invalide → Demander une correction</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
## Best Practices
|
||||
## Bonnes pratiques
|
||||
|
||||
- **Chain with Condition blocks**: Use `<guardrails.passed>` to branch workflow logic based on validation results
|
||||
- **Use JSON validation before parsing**: Always validate JSON structure before attempting to parse LLM outputs
|
||||
- **Choose appropriate PII types**: Only select the PII entity types relevant to your use case for better performance
|
||||
- **Set reasonable confidence thresholds**: For hallucination detection, adjust threshold based on your accuracy requirements (higher = stricter)
|
||||
- **Use strong models for hallucination detection**: GPT-4o or Claude 3.7 Sonnet provide more accurate confidence scoring
|
||||
- **Mask PII for logging**: Use "Mask" mode when you need to log or store content that may contain PII
|
||||
- **Test regex patterns**: Validate your regex patterns thoroughly before deploying to production
|
||||
- **Monitor validation failures**: Track `<guardrails.error>` messages to identify common validation issues
|
||||
- **Chaîner avec des blocs Condition** : Utilisez `<guardrails.passed>` pour créer des branches dans la logique du workflow selon les résultats de validation
|
||||
- **Valider le JSON avant l'analyse** : Toujours valider la structure JSON avant de tenter d'analyser les sorties du LLM
|
||||
- **Choisir les types de PII appropriés** : Sélectionnez uniquement les types d'entités PII pertinents pour votre cas d'utilisation afin d'améliorer les performances
|
||||
- **Définir des seuils de confiance raisonnables** : Pour la détection d'hallucinations, ajustez le seuil selon vos exigences de précision (plus élevé = plus strict)
|
||||
- **Utiliser des modèles performants pour la détection d'hallucinations** : GPT-4o ou Claude 3.7 Sonnet fournissent un score de confiance plus précis
|
||||
- **Masquer les PII pour la journalisation** : Utilisez le mode « Mask » lorsque vous devez journaliser ou stocker du contenu susceptible de contenir des PII
|
||||
- **Tester les modèles regex** : Validez soigneusement vos modèles d'expressions régulières avant de les déployer en production
|
||||
- **Surveiller les échecs de validation** : Suivez les messages `<guardrails.error>` pour identifier les problèmes de validation courants
|
||||
|
||||
<Callout type="info">
|
||||
Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical.
|
||||
La validation des guardrails s'effectue de manière synchrone dans votre workflow. Pour la détection d'hallucinations, choisissez des modèles plus rapides (comme GPT-4o-mini) si la latence est critique.
|
||||
</Callout>
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: TypeScript/JavaScript SDK
|
||||
title: SDK TypeScript/JavaScript
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
@@ -7,10 +7,10 @@ import { Card, Cards } from 'fumadocs-ui/components/card'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
Le SDK officiel TypeScript/JavaScript pour Sim offre une sécurité de type complète et prend en charge les environnements Node.js et navigateur, vous permettant d'exécuter des workflows par programmation depuis vos applications Node.js, applications web et autres environnements JavaScript.
|
||||
Le SDK officiel TypeScript/JavaScript pour Sim offre une sécurité de type complète et prend en charge les environnements Node.js et navigateur, vous permettant d'exécuter des flux de travail par programmation depuis vos applications Node.js, applications web et autres environnements JavaScript.
|
||||
|
||||
<Callout type="info">
|
||||
Le SDK TypeScript offre une sécurité de type complète, la prise en charge de l'exécution asynchrone, une limitation automatique du débit avec backoff exponentiel et le suivi d'utilisation.
|
||||
Le SDK TypeScript fournit une sécurité de type complète, une prise en charge de l'exécution asynchrone, une limitation automatique du débit avec backoff exponentiel et un suivi d'utilisation.
|
||||
</Callout>
|
||||
|
||||
## Installation
|
||||
@@ -43,7 +43,7 @@ Installez le SDK en utilisant votre gestionnaire de paquets préféré :
|
||||
|
||||
## Démarrage rapide
|
||||
|
||||
Voici un exemple simple pour commencer :
|
||||
Voici un exemple simple pour vous aider à démarrer :
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -74,14 +74,14 @@ new SimStudioClient(config: SimStudioConfig)
|
||||
```
|
||||
|
||||
**Configuration :**
|
||||
- `config.apiKey` (string) : votre clé API Sim
|
||||
- `config.apiKey` (string) : Votre clé API Sim
|
||||
- `config.baseUrl` (string, optionnel) : URL de base pour l'API Sim (par défaut `https://sim.ai`)
|
||||
|
||||
#### Méthodes
|
||||
|
||||
##### executeWorkflow()
|
||||
|
||||
Exécuter un workflow avec des données d'entrée optionnelles.
|
||||
Exécuter un flux de travail avec des données d'entrée optionnelles.
|
||||
|
||||
```typescript
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
@@ -91,17 +91,17 @@ const result = await client.executeWorkflow('workflow-id', {
|
||||
```
|
||||
|
||||
**Paramètres :**
|
||||
- `workflowId` (string) : L'ID du workflow à exécuter
|
||||
- `options` (ExecutionOptions, optionnel) :
|
||||
- `workflowId` (string) : L'identifiant du workflow à exécuter
|
||||
- `options` (ExecutionOptions, facultatif) :
|
||||
- `input` (any) : Données d'entrée à transmettre au workflow
|
||||
- `timeout` (number) : Délai d'expiration en millisecondes (par défaut : 30000)
|
||||
- `stream` (boolean) : Activer les réponses en streaming (par défaut : false)
|
||||
- `selectedOutputs` (string[]) : Bloquer les sorties à diffuser au format `blockName.attribute` (par exemple, `["agent1.content"]`)
|
||||
- `selectedOutputs` (string[]) : Sorties de blocs à diffuser au format `blockName.attribute` (par exemple, `["agent1.content"]`)
|
||||
- `async` (boolean) : Exécuter de manière asynchrone (par défaut : false)
|
||||
|
||||
**Retourne :** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
|
||||
Lorsque `async: true`, retourne immédiatement avec un ID de tâche pour l'interrogation. Sinon, attend la fin de l'exécution.
|
||||
Lorsque `async: true`, retourne immédiatement un identifiant de tâche pour l'interrogation. Sinon, attend la fin de l'exécution.
|
||||
|
||||
##### getWorkflowStatus()
|
||||
|
||||
@@ -113,7 +113,7 @@ console.log('Is deployed:', status.isDeployed);
|
||||
```
|
||||
|
||||
**Paramètres :**
|
||||
- `workflowId` (string) : L'ID du workflow
|
||||
- `workflowId` (string) : L'identifiant du workflow
|
||||
|
||||
**Retourne :** `Promise<WorkflowStatus>`
|
||||
|
||||
@@ -129,7 +129,7 @@ if (isReady) {
|
||||
```
|
||||
|
||||
**Paramètres :**
|
||||
- `workflowId` (string) : L'ID du workflow
|
||||
- `workflowId` (string) : L'identifiant du workflow
|
||||
|
||||
**Retourne :** `Promise<boolean>`
|
||||
|
||||
@@ -146,22 +146,22 @@ if (status.status === 'completed') {
|
||||
```
|
||||
|
||||
**Paramètres :**
|
||||
- `taskId` (string) : L'ID de tâche retourné par l'exécution asynchrone
|
||||
- `taskId` (string) : L'identifiant de tâche retourné par l'exécution asynchrone
|
||||
|
||||
**Retourne :** `Promise<JobStatus>`
|
||||
|
||||
**Champs de réponse :**
|
||||
- `success` (boolean) : Indique si la requête a réussi
|
||||
- `taskId` (string) : L'ID de la tâche
|
||||
- `status` (string) : L'un des statuts suivants : `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
|
||||
- `metadata` (object) : Contient `startedAt`, `completedAt`, et `duration`
|
||||
- `output` (any, optionnel) : La sortie du workflow (une fois terminé)
|
||||
- `error` (any, optionnel) : Détails de l'erreur (en cas d'échec)
|
||||
- `estimatedDuration` (number, optionnel) : Durée estimée en millisecondes (lorsqu'en traitement/en file d'attente)
|
||||
- `taskId` (string) : L'identifiant de la tâche
|
||||
- `status` (string) : L'un des états suivants : `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
|
||||
- `metadata` (object) : Contient `startedAt`, `completedAt` et `duration`
|
||||
- `output` (any, facultatif) : La sortie du workflow (une fois terminé)
|
||||
- `error` (any, facultatif) : Détails de l'erreur (en cas d'échec)
|
||||
- `estimatedDuration` (number, facultatif) : Durée estimée en millisecondes (lorsqu'en traitement/en file d'attente)
|
||||
|
||||
##### executeWithRetry()
|
||||
|
||||
Exécute un workflow avec une nouvelle tentative automatique en cas d'erreurs de limite de débit en utilisant un backoff exponentiel.
|
||||
Exécuter un workflow avec une nouvelle tentative automatique en cas d'erreurs de limitation de débit, en utilisant un backoff exponentiel.
|
||||
|
||||
```typescript
|
||||
const result = await client.executeWithRetry('workflow-id', {
|
||||
@@ -186,11 +186,11 @@ const result = await client.executeWithRetry('workflow-id', {
|
||||
|
||||
**Retourne :** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
|
||||
La logique de nouvelle tentative utilise un backoff exponentiel (1s → 2s → 4s → 8s...) avec une variation aléatoire de ±25 % pour éviter l'effet de rafale. Si l'API fournit un en-tête `retry-after`, celui-ci sera utilisé à la place.
|
||||
La logique de nouvelle tentative utilise un backoff exponentiel (1s → 2s → 4s → 8s...) avec une variation aléatoire de ±25 % pour éviter l'effet de horde. Si l'API fournit un en-tête `retry-after`, celui-ci sera utilisé à la place.
|
||||
|
||||
##### getRateLimitInfo()
|
||||
|
||||
Obtient les informations actuelles sur les limites de débit à partir de la dernière réponse de l'API.
|
||||
Obtenir les informations actuelles de limitation de débit à partir de la dernière réponse de l'API.
|
||||
|
||||
```typescript
|
||||
const rateLimitInfo = client.getRateLimitInfo();
|
||||
@@ -205,7 +205,7 @@ if (rateLimitInfo) {
|
||||
|
||||
##### getUsageLimits()
|
||||
|
||||
Obtient les limites d'utilisation actuelles et les informations de quota pour votre compte.
|
||||
Obtenir les limites d'utilisation actuelles et les informations de quota pour votre compte.
|
||||
|
||||
```typescript
|
||||
const limits = await client.getUsageLimits();
|
||||
@@ -247,7 +247,7 @@ console.log('Plan:', limits.usage.plan);
|
||||
|
||||
##### setApiKey()
|
||||
|
||||
Met à jour la clé API.
|
||||
Mettre à jour la clé API.
|
||||
|
||||
```typescript
|
||||
client.setApiKey('new-api-key');
|
||||
@@ -255,7 +255,7 @@ client.setApiKey('new-api-key');
|
||||
|
||||
##### setBaseUrl()
|
||||
|
||||
Met à jour l'URL de base.
|
||||
Mettre à jour l'URL de base.
|
||||
|
||||
```typescript
|
||||
client.setBaseUrl('https://my-custom-domain.com');
|
||||
@@ -356,7 +356,7 @@ class SimStudioError extends Error {
|
||||
|
||||
**Codes d'erreur courants :**
|
||||
- `UNAUTHORIZED` : Clé API invalide
|
||||
- `TIMEOUT` : Délai d'attente de la requête dépassé
|
||||
- `TIMEOUT` : Délai d'attente dépassé
|
||||
- `RATE_LIMIT_EXCEEDED` : Limite de débit dépassée
|
||||
- `USAGE_LIMIT_EXCEEDED` : Limite d'utilisation dépassée
|
||||
- `EXECUTION_ERROR` : Échec de l'exécution du workflow
|
||||
@@ -501,7 +501,7 @@ Configurez le client en utilisant des variables d'environnement :
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Intégration avec Express de Node.js
|
||||
### Intégration avec Node.js Express
|
||||
|
||||
Intégration avec un serveur Express.js :
|
||||
|
||||
@@ -604,26 +604,105 @@ async function executeClientSideWorkflow() {
|
||||
});
|
||||
|
||||
console.log('Workflow result:', result);
|
||||
|
||||
|
||||
// Update UI with result
|
||||
document.getElementById('result')!.textContent =
|
||||
document.getElementById('result')!.textContent =
|
||||
JSON.stringify(result.output, null, 2);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach to button click
|
||||
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
|
||||
```
|
||||
|
||||
### Téléchargement de fichiers
|
||||
|
||||
Les objets File sont automatiquement détectés et convertis au format base64. Incluez-les dans votre entrée sous le nom de champ correspondant au format d'entrée du déclencheur API de votre workflow.
|
||||
|
||||
Le SDK convertit les objets File dans ce format :
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: 'file',
|
||||
data: 'data:mime/type;base64,base64data',
|
||||
name: 'filename',
|
||||
mime: 'mime/type'
|
||||
}
|
||||
```
|
||||
|
||||
Alternativement, vous pouvez fournir manuellement des fichiers en utilisant le format URL :
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: 'url',
|
||||
data: 'https://example.com/file.pdf',
|
||||
name: 'file.pdf',
|
||||
mime: 'application/pdf'
|
||||
}
|
||||
```
|
||||
|
||||
<Tabs items={['Browser', 'Node.js']}>
|
||||
<Tab value="Browser">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
|
||||
});
|
||||
|
||||
// From file input
|
||||
async function handleFileUpload(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const files = Array.from(input.files || []);
|
||||
|
||||
// Include files under the field name from your API trigger's input format
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
documents: files, // Must match your workflow's "files" field name
|
||||
instructions: 'Analyze these documents'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Result:', result);
|
||||
}
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="Node.js">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
import fs from 'fs';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.SIM_API_KEY!
|
||||
});
|
||||
|
||||
// Read file and create File object
|
||||
const fileBuffer = fs.readFileSync('./document.pdf');
|
||||
const file = new File([fileBuffer], 'document.pdf', {
|
||||
type: 'application/pdf'
|
||||
});
|
||||
|
||||
// Include files under the field name from your API trigger's input format
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
documents: [file], // Must match your workflow's "files" field name
|
||||
query: 'Summarize this document'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Callout type="warning">
|
||||
Lors de l'utilisation du SDK dans le navigateur, veillez à ne pas exposer de clés API sensibles. Envisagez d'utiliser un proxy backend ou des clés API publiques avec des permissions limitées.
|
||||
Lorsque vous utilisez le SDK dans le navigateur, faites attention à ne pas exposer des clés API sensibles. Envisagez d'utiliser un proxy backend ou des clés API publiques avec des permissions limitées.
|
||||
</Callout>
|
||||
|
||||
### Exemple de hook React
|
||||
|
||||
Créer un hook React personnalisé pour l'exécution de workflow :
|
||||
Créez un hook React personnalisé pour l'exécution du workflow :
|
||||
|
||||
```typescript
|
||||
import { useState, useCallback } from 'react';
|
||||
@@ -699,9 +778,9 @@ function WorkflowComponent() {
|
||||
}
|
||||
```
|
||||
|
||||
### Exécution asynchrone de workflow
|
||||
### Exécution asynchrone du workflow
|
||||
|
||||
Exécuter des workflows de manière asynchrone pour les tâches de longue durée :
|
||||
Exécutez des workflows de manière asynchrone pour les tâches de longue durée :
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient, AsyncExecutionResult } from 'simstudio-ts-sdk';
|
||||
@@ -750,7 +829,7 @@ executeAsync();
|
||||
|
||||
### Limitation de débit et nouvelle tentative
|
||||
|
||||
Gérer automatiquement les limites de débit avec backoff exponentiel :
|
||||
Gérez automatiquement les limites de débit avec un backoff exponentiel :
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
|
||||
@@ -786,9 +865,9 @@ async function executeWithRetryHandling() {
|
||||
}
|
||||
```
|
||||
|
||||
### Surveillance d'utilisation
|
||||
### Surveillance de l'utilisation
|
||||
|
||||
Surveiller l'utilisation et les limites de votre compte :
|
||||
Surveillez l'utilisation et les limites de votre compte :
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -814,28 +893,28 @@ async function checkUsage() {
|
||||
console.log(' Resets at:', limits.rateLimit.async.resetAt);
|
||||
console.log(' Is limited:', limits.rateLimit.async.isLimited);
|
||||
|
||||
console.log('\n=== Utilisation ===');
|
||||
console.log('Coût de la période actuelle : ' + limits.usage.currentPeriodCost.toFixed(2) + ' $');
|
||||
console.log('Limite : ' + limits.usage.limit.toFixed(2) + ' $');
|
||||
console.log('Forfait :', limits.usage.plan);
|
||||
console.log('\n=== Usage ===');
|
||||
console.log('Current period cost: $' + 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('Utilisation : ' + percentUsed.toFixed(1) + ' %');
|
||||
console.log('Usage: ' + percentUsed.toFixed(1) + '%');
|
||||
|
||||
if (percentUsed > 80) {
|
||||
console.warn('⚠️ Attention : vous approchez de votre limite d\'utilisation !');
|
||||
console.warn('⚠️ Warning: You are approaching your usage limit!');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erreur lors de la vérification de l\'utilisation :', error);
|
||||
console.error('Error checking usage:', error);
|
||||
}
|
||||
}
|
||||
|
||||
checkUsage();
|
||||
```
|
||||
|
||||
### Exécution de flux de travail avec streaming
|
||||
### Exécution de workflow en streaming
|
||||
|
||||
Exécutez des flux de travail avec des réponses en streaming en temps réel :
|
||||
Exécutez des workflows avec des réponses en streaming en temps réel :
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -846,40 +925,35 @@ const client = new SimStudioClient({
|
||||
|
||||
async function executeWithStreaming() {
|
||||
try {
|
||||
// Activer le streaming pour des sorties de blocs spécifiques
|
||||
// Enable streaming for specific block outputs
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: { message: 'Compter jusqu'à cinq' },
|
||||
input: { message: 'Count to five' },
|
||||
stream: true,
|
||||
selectedOutputs: ['agent1.content'] // Utiliser le format blockName.attribute
|
||||
selectedOutputs: ['agent1.content'] // Use blockName.attribute format
|
||||
});
|
||||
|
||||
console.log('Résultat du workflow :', result);
|
||||
console.log('Workflow result:', result);
|
||||
} catch (error) {
|
||||
console.error('Erreur :', error);
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
The streaming response follows the Server-Sent Events (SSE) format:
|
||||
La réponse en streaming suit le format Server-Sent Events (SSE) :
|
||||
|
||||
```
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", deux"}
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"}
|
||||
|
||||
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
|
||||
data: [DONE]
|
||||
|
||||
```
|
||||
|
||||
**React Streaming Example:**
|
||||
**Exemple de streaming avec React :**
|
||||
|
||||
```
|
||||
|
||||
typescript
|
||||
```typescript
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
function StreamingWorkflow() {
|
||||
@@ -941,44 +1015,43 @@ function StreamingWorkflow() {
|
||||
return (
|
||||
<div>
|
||||
<button onClick={executeStreaming} disabled={loading}>
|
||||
{loading ? 'Génération en cours...' : 'Démarrer le streaming'}
|
||||
{loading ? 'Generating...' : 'Start Streaming'}
|
||||
</button>
|
||||
<div style={{ whiteSpace: 'pre-wrap' }}>{output}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Getting Your API Key
|
||||
## Obtenir votre clé API
|
||||
|
||||
<Steps>
|
||||
<Step title="Log in to Sim">
|
||||
Navigate to [Sim](https://sim.ai) and log in to your account.
|
||||
<Step title="Connectez-vous à Sim">
|
||||
Accédez à [Sim](https://sim.ai) et connectez-vous à votre compte.
|
||||
</Step>
|
||||
<Step title="Open your workflow">
|
||||
Navigate to the workflow you want to execute programmatically.
|
||||
<Step title="Ouvrez votre workflow">
|
||||
Accédez au workflow que vous souhaitez exécuter par programmation.
|
||||
</Step>
|
||||
<Step title="Deploy your workflow">
|
||||
Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.
|
||||
<Step title="Déployez votre workflow">
|
||||
Cliquez sur "Déployer" pour déployer votre workflow s'il n'a pas encore été déployé.
|
||||
</Step>
|
||||
<Step title="Create or select an API key">
|
||||
During the deployment process, select or create an API key.
|
||||
<Step title="Créez ou sélectionnez une clé API">
|
||||
Pendant le processus de déploiement, sélectionnez ou créez une clé API.
|
||||
</Step>
|
||||
<Step title="Copy the API key">
|
||||
Copy the API key to use in your TypeScript/JavaScript application.
|
||||
<Step title="Copiez la clé API">
|
||||
Copiez la clé API pour l'utiliser dans votre application TypeScript/JavaScript.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Callout type="warning">
|
||||
Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management.
|
||||
Gardez votre clé API en sécurité et ne la publiez jamais dans un système de contrôle de version. Utilisez des variables d'environnement ou une gestion sécurisée de configuration.
|
||||
</Callout>
|
||||
|
||||
## Requirements
|
||||
## Prérequis
|
||||
|
||||
- Node.js 16+
|
||||
- TypeScript 5.0+ (for TypeScript projects)
|
||||
- TypeScript 5.0+ (pour les projets TypeScript)
|
||||
|
||||
## License
|
||||
## Licence
|
||||
|
||||
Apache-2.0
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
title: Guardrails
|
||||
title: ガードレール
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
@@ -8,213 +8,213 @@ 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.
|
||||
ガードレールブロックは、複数の検証タイプに対してコンテンツをチェックすることで、AIワークフローを検証し保護します。データ品質の確保、ハルシネーション(幻覚)の防止、個人情報の検出、フォーマット要件の強制などをワークフローに組み込む前に行います。
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Image
|
||||
src="/static/blocks/guardrails.png"
|
||||
alt="Guardrails Block"
|
||||
alt="ガードレールブロック"
|
||||
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
|
||||
<strong>JSON構造の検証</strong>:パース前にLLM出力が有効なJSONであることを確認
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Match Regex Patterns</strong>: Verify content matches specific formats (emails, phone numbers, URLs, etc.)
|
||||
<strong>正規表現パターンの一致</strong>:コンテンツが特定のフォーマット(メール、電話番号、URLなど)に一致するか確認
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Detect Hallucinations</strong>: Use RAG + LLM scoring to validate AI outputs against knowledge base content
|
||||
<strong>ハルシネーション(幻覚)の検出</strong>:RAG + LLMスコアリングを使用してAI出力をナレッジベースコンテンツと照合して検証
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Detect PII</strong>: Identify and optionally mask personally identifiable information across 40+ entity types
|
||||
<strong>個人情報の検出</strong>:40種類以上のエンティティタイプにわたる個人を特定できる情報を識別し、オプションでマスク処理
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Validation Types
|
||||
## 検証タイプ
|
||||
|
||||
### JSON Validation
|
||||
### JSON検証
|
||||
|
||||
Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed.
|
||||
コンテンツが適切にフォーマットされたJSONであることを検証します。構造化されたLLM出力を安全にパースできることを確認するのに最適です。
|
||||
|
||||
**Use Cases:**
|
||||
- Validate JSON responses from Agent blocks before parsing
|
||||
- Ensure API payloads are properly formatted
|
||||
- Check structured data integrity
|
||||
**ユースケース:**
|
||||
- パース前にエージェントブロックからのJSON応答を検証
|
||||
- APIペイロードが適切にフォーマットされていることを確認
|
||||
- 構造化データの整合性をチェック
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if valid JSON, `false` otherwise
|
||||
- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...")
|
||||
**出力:**
|
||||
- `passed`: 有効なJSONの場合は`true`、それ以外は`false`
|
||||
- `error`: 検証が失敗した場合のエラーメッセージ(例:「無効なJSON:予期しないトークン...」)
|
||||
|
||||
### 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
|
||||
**ユースケース:**
|
||||
- メールアドレスの検証
|
||||
- 電話番号フォーマットのチェック
|
||||
- URLやカスタム識別子の確認
|
||||
- 特定のテキストパターンの強制
|
||||
|
||||
**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)
|
||||
**設定:**
|
||||
- **正規表現パターン**:一致させる正規表現(例:メールの場合は`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if content matches pattern, `false` otherwise
|
||||
- `error`: Error message if validation fails
|
||||
**出力:**
|
||||
- `passed`: コンテンツがパターンに一致する場合は `true`、それ以外の場合は `false`
|
||||
- `error`: 検証が失敗した場合のエラーメッセージ
|
||||
|
||||
### Hallucination Detection
|
||||
### 幻覚検出
|
||||
|
||||
Uses Retrieval-Augmented Generation (RAG) with LLM scoring to detect when AI-generated content contradicts or isn't grounded in your knowledge base.
|
||||
検索拡張生成(RAG)とLLMスコアリングを使用して、AI生成コンテンツがナレッジベースと矛盾している場合や、ナレッジベースに根拠がない場合を検出します。
|
||||
|
||||
**How It Works:**
|
||||
1. Queries your knowledge base for relevant context
|
||||
2. Sends both the AI output and retrieved context to an LLM
|
||||
3. LLM assigns a confidence score (0-10 scale)
|
||||
- **0** = Full hallucination (completely ungrounded)
|
||||
- **10** = Fully grounded (completely supported by knowledge base)
|
||||
4. Validation passes if score ≥ threshold (default: 3)
|
||||
**仕組み:**
|
||||
1. 関連するコンテキストについてナレッジベースに問い合わせます
|
||||
2. AI出力と取得したコンテキストの両方をLLMに送信します
|
||||
3. LLMが信頼度スコア(0〜10のスケール)を割り当てます
|
||||
- **0** = 完全な幻覚(まったく根拠なし)
|
||||
- **10** = 完全に根拠あり(ナレッジベースで完全にサポートされている)
|
||||
4. スコアが閾値以上(デフォルト:3)であれば検証に合格します
|
||||
|
||||
**Configuration:**
|
||||
- **Knowledge Base**: Select from your existing knowledge bases
|
||||
- **Model**: Choose LLM for scoring (requires strong reasoning - GPT-4o, Claude 3.7 Sonnet recommended)
|
||||
- **API Key**: Authentication for selected LLM provider (auto-hidden for hosted/Ollama models)
|
||||
- **Confidence Threshold**: Minimum score to pass (0-10, default: 3)
|
||||
- **Top K** (Advanced): Number of knowledge base chunks to retrieve (default: 10)
|
||||
**設定:**
|
||||
- **ナレッジベース**: 既存のナレッジベースから選択
|
||||
- **モデル**: スコアリング用のLLMを選択(強力な推論能力が必要 - GPT-4o、Claude 3.7 Sonnetを推奨)
|
||||
- **APIキー**: 選択したLLMプロバイダーの認証(ホスト型/Ollamaモデルでは自動的に非表示)
|
||||
- **信頼度閾値**: 合格するための最小スコア(0〜10、デフォルト:3)
|
||||
- **Top K**(詳細設定): 取得するナレッジベースのチャンク数(デフォルト:10)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if confidence score ≥ threshold
|
||||
- `score`: Confidence score (0-10)
|
||||
- `reasoning`: LLM's explanation for the score
|
||||
- `error`: Error message if validation fails
|
||||
**出力:**
|
||||
- `passed`: 信頼度スコアが閾値以上の場合は `true`
|
||||
- `score`: 信頼度スコア(0〜10)
|
||||
- `reasoning`: スコアに対するLLMの説明
|
||||
- `error`: 検証が失敗した場合のエラーメッセージ
|
||||
|
||||
**Use Cases:**
|
||||
- Validate Agent responses against documentation
|
||||
- Ensure customer support answers are factually accurate
|
||||
- Verify generated content matches source material
|
||||
- Quality control for RAG applications
|
||||
**ユースケース:**
|
||||
- エージェントの応答をドキュメントに対して検証
|
||||
- カスタマーサポートの回答が事実に基づいていることを確認
|
||||
- 生成されたコンテンツがソース資料と一致することを確認
|
||||
- RAGアプリケーションの品質管理
|
||||
|
||||
### PII Detection
|
||||
### PII検出
|
||||
|
||||
Detects personally identifiable information using Microsoft Presidio. Supports 40+ entity types across multiple countries and languages.
|
||||
Microsoft Presidioを使用して個人を特定できる情報を検出します。複数の国や言語にわたる40以上のエンティティタイプをサポートしています。
|
||||
|
||||
<div className="mx-auto w-3/5 overflow-hidden rounded-lg">
|
||||
<Video src="guardrails.mp4" width={500} height={350} />
|
||||
</div>
|
||||
|
||||
**How It Works:**
|
||||
1. Scans content for PII entities using pattern matching and NLP
|
||||
2. Returns detected entities with locations and confidence scores
|
||||
3. Optionally masks detected PII in the output
|
||||
**仕組み:**
|
||||
1. パターンマッチングとNLPを使用してコンテンツ内のPIIエンティティをスキャンします
|
||||
2. 検出されたエンティティの位置と信頼度スコアを返します
|
||||
3. オプションで出力内の検出されたPIIをマスクします
|
||||
|
||||
**Configuration:**
|
||||
- **PII Types to Detect**: Select from grouped categories via modal selector
|
||||
- **Common**: Person name, Email, Phone, Credit card, IP address, etc.
|
||||
- **USA**: SSN, Driver's license, Passport, etc.
|
||||
- **UK**: NHS number, National insurance number
|
||||
- **Spain**: NIF, NIE, CIF
|
||||
- **Italy**: Fiscal code, Driver's license, VAT code
|
||||
- **Poland**: PESEL, NIP, REGON
|
||||
- **Singapore**: NRIC/FIN, UEN
|
||||
- **Australia**: ABN, ACN, TFN, Medicare
|
||||
- **India**: Aadhaar, PAN, Passport, Voter number
|
||||
- **Mode**:
|
||||
- **Detect**: Only identify PII (default)
|
||||
- **Mask**: Replace detected PII with masked values
|
||||
- **Language**: Detection language (default: English)
|
||||
**設定:**
|
||||
- **検出するPIIタイプ**: モーダルセレクターからグループ化されたカテゴリーを選択
|
||||
- **一般**: 個人名、メールアドレス、電話番号、クレジットカード、IPアドレスなど
|
||||
- **アメリカ**: 社会保障番号、運転免許証、パスポートなど
|
||||
- **イギリス**: NHS番号、国民保険番号
|
||||
- **スペイン**: NIF、NIE、CIF
|
||||
- **イタリア**: 納税者番号、運転免許証、VAT番号
|
||||
- **ポーランド**: PESEL、NIP、REGON
|
||||
- **シンガポール**: NRIC/FIN、UEN
|
||||
- **オーストラリア**: ABN、ACN、TFN、メディケア
|
||||
- **インド**: Aadhaar、PAN、パスポート、有権者番号
|
||||
- **モード**:
|
||||
- **検出**: PIIの識別のみ(デフォルト)
|
||||
- **マスク**: 検出されたPIIをマスク値に置き換え
|
||||
- **言語**: 検出言語(デフォルト:英語)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `false` if any selected PII types are detected
|
||||
- `detectedEntities`: Array of detected PII with type, location, and confidence
|
||||
- `maskedText`: Content with PII masked (only if mode = "Mask")
|
||||
- `error`: Error message if validation fails
|
||||
**出力:**
|
||||
- `passed`: 選択したPIIタイプが検出された場合は `false`
|
||||
- `detectedEntities`: タイプ、位置、信頼度を含む検出されたPIIの配列
|
||||
- `maskedText`: PIIがマスクされたコンテンツ(モード = "Mask"の場合のみ)
|
||||
- `error`: 検証が失敗した場合のエラーメッセージ
|
||||
|
||||
**Use Cases:**
|
||||
- Block content containing sensitive personal information
|
||||
- Mask PII before logging or storing data
|
||||
- Compliance with GDPR, HIPAA, and other privacy regulations
|
||||
- Sanitize user inputs before processing
|
||||
**ユースケース:**
|
||||
- 機密性の高い個人情報を含むコンテンツのブロック
|
||||
- データのログ記録や保存前のPIIマスキング
|
||||
- GDPR、HIPAAなどのプライバシー規制への準拠
|
||||
- 処理前のユーザー入力のサニタイズ
|
||||
|
||||
## Configuration
|
||||
## 設定
|
||||
|
||||
### Content to Validate
|
||||
### 検証するコンテンツ
|
||||
|
||||
The input content to validate. This typically comes from:
|
||||
- Agent block outputs: `<agent.content>`
|
||||
- Function block results: `<function.output>`
|
||||
- API responses: `<api.output>`
|
||||
- Any other block output
|
||||
検証する入力コンテンツ。通常、以下から取得されます:
|
||||
- エージェントブロックの出力: `<agent.content>`
|
||||
- ファンクションブロックの結果: `<function.output>`
|
||||
- APIレスポンス: `<api.output>`
|
||||
- その他のブロック出力
|
||||
|
||||
### Validation Type
|
||||
### 検証タイプ
|
||||
|
||||
Choose from four validation types:
|
||||
- **Valid JSON**: Check if content is properly formatted JSON
|
||||
- **Regex Match**: Verify content matches a regex pattern
|
||||
- **Hallucination Check**: Validate against knowledge base with LLM scoring
|
||||
- **PII Detection**: Detect and optionally mask personally identifiable information
|
||||
4つの検証タイプから選択:
|
||||
- **有効なJSON**: コンテンツが適切にフォーマットされたJSONかどうかを確認
|
||||
- **正規表現マッチ**: コンテンツが正規表現パターンに一致するか検証
|
||||
- **幻覚チェック**: LLMスコアリングによる知識ベースとの検証
|
||||
- **PII検出**: 個人を特定できる情報の検出と任意のマスキング
|
||||
|
||||
## Outputs
|
||||
## 出力
|
||||
|
||||
All validation types return:
|
||||
すべての検証タイプは以下を返します:
|
||||
|
||||
- **`<guardrails.passed>`**: Boolean indicating if validation passed
|
||||
- **`<guardrails.validationType>`**: The type of validation performed
|
||||
- **`<guardrails.input>`**: The original input that was validated
|
||||
- **`<guardrails.error>`**: Error message if validation failed (optional)
|
||||
- **`<guardrails.passed>`**: 検証が成功したかどうかを示すブール値
|
||||
- **`<guardrails.validationType>`**: 実行された検証のタイプ
|
||||
- **`<guardrails.input>`**: 検証された元の入力
|
||||
- **`<guardrails.error>`**: 検証が失敗した場合のエラーメッセージ(オプション)
|
||||
|
||||
Additional outputs by type:
|
||||
タイプ別の追加出力:
|
||||
|
||||
**Hallucination Check:**
|
||||
- **`<guardrails.score>`**: Confidence score (0-10)
|
||||
- **`<guardrails.reasoning>`**: LLM's explanation
|
||||
**幻覚チェック:**
|
||||
- **`<guardrails.score>`**: 信頼度スコア(0〜10)
|
||||
- **`<guardrails.reasoning>`**: LLMの説明
|
||||
|
||||
**PII Detection:**
|
||||
- **`<guardrails.detectedEntities>`**: Array of detected PII entities
|
||||
- **`<guardrails.maskedText>`**: Content with PII masked (if mode = "Mask")
|
||||
**PII検出:**
|
||||
- **`<guardrails.detectedEntities>`**: 検出されたPIIエンティティの配列
|
||||
- **`<guardrails.maskedText>`**: PIIがマスクされたコンテンツ(モード = "Mask"の場合)
|
||||
|
||||
## Example Use Cases
|
||||
## 使用例
|
||||
|
||||
### Validate JSON Before Parsing
|
||||
### パース前にJSONを検証する
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Ensure Agent output is valid JSON</h4>
|
||||
<h4 className="font-medium">シナリオ:エージェントの出力が有効なJSONであることを確認する</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent generates structured JSON response</li>
|
||||
<li>Guardrails validates JSON format</li>
|
||||
<li>Condition block checks `<guardrails.passed>`</li>
|
||||
<li>If passed → Parse and use data, If failed → Retry or handle error</li>
|
||||
<li>エージェントが構造化されたJSON応答を生成</li>
|
||||
<li>ガードレールがJSON形式を検証</li>
|
||||
<li>条件ブロックが`<guardrails.passed>`をチェック</li>
|
||||
<li>成功した場合→データを解析して使用、失敗した場合→再試行またはエラー処理</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
### Prevent Hallucinations
|
||||
### 幻覚を防止する
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Validate customer support responses</h4>
|
||||
<h4 className="font-medium">シナリオ:カスタマーサポートの回答を検証する</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent generates response to customer question</li>
|
||||
<li>Guardrails checks against support documentation knowledge base</li>
|
||||
<li>If confidence score ≥ 3 → Send response</li>
|
||||
<li>If confidence score \< 3 → Flag for human review</li>
|
||||
<li>エージェントが顧客の質問に対する回答を生成</li>
|
||||
<li>ガードレールがサポートドキュメントのナレッジベースと照合</li>
|
||||
<li>信頼度スコアが3以上→回答を送信</li>
|
||||
<li>信頼度スコアが3未満→人間によるレビューにフラグを立てる</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
### Block PII in User Inputs
|
||||
### ユーザー入力のPIIをブロックする
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Sanitize user-submitted content</h4>
|
||||
<h4 className="font-medium">シナリオ:ユーザー提出コンテンツを無害化する</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>User submits form with text content</li>
|
||||
<li>Guardrails detects PII (emails, phone numbers, SSN, etc.)</li>
|
||||
<li>If PII detected → Reject submission or mask sensitive data</li>
|
||||
<li>If no PII → Process normally</li>
|
||||
<li>ユーザーがテキストコンテンツを含むフォームを提出</li>
|
||||
<li>ガードレールがPII(メール、電話番号、社会保障番号など)を検出</li>
|
||||
<li>PIIが検出された場合→提出を拒否または機密データをマスク</li>
|
||||
<li>PIIがない場合→通常通り処理</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
@@ -222,30 +222,29 @@ Additional outputs by type:
|
||||
<Video src="guardrails-example.mp4" width={500} height={350} />
|
||||
</div>
|
||||
|
||||
### Validate Email Format
|
||||
### メール形式を検証する
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Check email address format</h4>
|
||||
<h4 className="font-medium">シナリオ:メールアドレス形式をチェックする</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent extracts email from text</li>
|
||||
<li>Guardrails validates with regex pattern</li>
|
||||
<li>If valid → Use email for notification</li>
|
||||
<li>If invalid → Request correction</li>
|
||||
<li>エージェントがテキストからメールを抽出</li>
|
||||
<li>ガードレールが正規表現パターンで検証</li>
|
||||
<li>有効な場合→メールを通知に使用</li>
|
||||
<li>無効な場合→修正を要求</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
## Best Practices
|
||||
## ベストプラクティス
|
||||
|
||||
- **Chain with Condition blocks**: Use `<guardrails.passed>` to branch workflow logic based on validation results
|
||||
- **Use JSON validation before parsing**: Always validate JSON structure before attempting to parse LLM outputs
|
||||
- **Choose appropriate PII types**: Only select the PII entity types relevant to your use case for better performance
|
||||
- **Set reasonable confidence thresholds**: For hallucination detection, adjust threshold based on your accuracy requirements (higher = stricter)
|
||||
- **Use strong models for hallucination detection**: GPT-4o or Claude 3.7 Sonnet provide more accurate confidence scoring
|
||||
- **Mask PII for logging**: Use "Mask" mode when you need to log or store content that may contain PII
|
||||
- **Test regex patterns**: Validate your regex patterns thoroughly before deploying to production
|
||||
- **Monitor validation failures**: Track `<guardrails.error>` messages to identify common validation issues
|
||||
- **条件ブロックと連携する**: `<guardrails.passed>` を使用して検証結果に基づいてワークフローのロジックを分岐させる
|
||||
- **JSONの解析前に検証する**: LLM出力を解析する前に、必ずJSON構造を検証する
|
||||
- **適切なPIIタイプを選択する**: パフォーマンス向上のため、ユースケースに関連するPIIエンティティタイプのみを選択する
|
||||
- **適切な信頼度しきい値を設定する**: 幻覚検出では、精度要件に基づいてしきい値を調整する(高いほど厳格)
|
||||
- **幻覚検出には高性能モデルを使用する**: GPT-4oまたはClaude 3.7 Sonnetは、より正確な信頼度スコアリングを提供する
|
||||
- **ログ記録のためにPIIをマスクする**: PIIを含む可能性のあるコンテンツをログに記録または保存する必要がある場合は、「マスク」モードを使用する
|
||||
- **正規表現パターンをテストする**: 本番環境にデプロイする前に、正規表現パターンを徹底的に検証する
|
||||
- **検証失敗を監視する**: `<guardrails.error>` メッセージを追跡して、一般的な検証の問題を特定する
|
||||
|
||||
<Callout type="info">
|
||||
Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical.
|
||||
ガードレールの検証はワークフロー内で同期的に行われます。レイテンシーが重要な場合は、幻覚検出にはより高速なモデル(GPT-4o-miniなど)を選択してください。
|
||||
</Callout>
|
||||
|
||||
|
||||
@@ -7,10 +7,10 @@ import { Card, Cards } from 'fumadocs-ui/components/card'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
Sim用の公式TypeScript/JavaScript SDKは、完全な型安全性を提供し、Node.jsとブラウザ環境の両方をサポートしています。これにより、Node.jsアプリケーション、Webアプリケーション、その他のJavaScript環境からプログラムによってワークフローを実行することができます。
|
||||
Simの公式TypeScript/JavaScript SDKは完全な型安全性を提供し、Node.jsとブラウザ環境の両方をサポートしています。これにより、Node.jsアプリケーション、Webアプリケーション、その他のJavaScript環境からプログラムでワークフローを実行することができます。
|
||||
|
||||
<Callout type="info">
|
||||
TypeScript SDKは、完全な型安全性、非同期実行サポート、指数バックオフによる自動レート制限、使用状況追跡を提供します。
|
||||
TypeScript SDKは完全な型安全性、非同期実行サポート、指数バックオフによる自動レート制限、使用状況追跡を提供します。
|
||||
</Callout>
|
||||
|
||||
## インストール
|
||||
@@ -43,7 +43,7 @@ Sim用の公式TypeScript/JavaScript SDKは、完全な型安全性を提供し
|
||||
|
||||
## クイックスタート
|
||||
|
||||
以下は、始めるための簡単な例です:
|
||||
以下は簡単な使用例です:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -96,12 +96,12 @@ const result = await client.executeWorkflow('workflow-id', {
|
||||
- `input` (any): ワークフローに渡す入力データ
|
||||
- `timeout` (number): タイムアウト(ミリ秒)(デフォルト: 30000)
|
||||
- `stream` (boolean): ストリーミングレスポンスを有効にする(デフォルト: false)
|
||||
- `selectedOutputs` (string[]): `blockName.attribute`形式でストリーミングするブロック出力(例: `["agent1.content"]`)
|
||||
- `selectedOutputs` (string[]): `blockName.attribute` 形式でストリーミングするブロック出力(例: `["agent1.content"]`)
|
||||
- `async` (boolean): 非同期実行(デフォルト: false)
|
||||
|
||||
**戻り値:** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
|
||||
`async: true`の場合、ポーリング用のタスクIDをすぐに返します。それ以外の場合は、完了を待ちます。
|
||||
`async: true` の場合、ポーリング用のタスクIDをすぐに返します。それ以外の場合は、完了を待ちます。
|
||||
|
||||
##### getWorkflowStatus()
|
||||
|
||||
@@ -161,7 +161,7 @@ if (status.status === 'completed') {
|
||||
|
||||
##### executeWithRetry()
|
||||
|
||||
レート制限エラー時に指数バックオフを使用して自動的に再試行するワークフロー実行。
|
||||
指数バックオフを使用してレート制限エラー時に自動的に再試行するワークフロー実行。
|
||||
|
||||
```typescript
|
||||
const result = await client.executeWithRetry('workflow-id', {
|
||||
@@ -177,7 +177,7 @@ const result = await client.executeWithRetry('workflow-id', {
|
||||
|
||||
**パラメータ:**
|
||||
- `workflowId` (string): 実行するワークフローのID
|
||||
- `options` (ExecutionOptions, オプション): `executeWorkflow()`と同じ
|
||||
- `options` (ExecutionOptions, オプション): `executeWorkflow()` と同じ
|
||||
- `retryOptions` (RetryOptions, オプション):
|
||||
- `maxRetries` (number): 最大再試行回数(デフォルト: 3)
|
||||
- `initialDelay` (number): 初期遅延(ミリ秒)(デフォルト: 1000)
|
||||
@@ -186,7 +186,7 @@ const result = await client.executeWithRetry('workflow-id', {
|
||||
|
||||
**戻り値:** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
|
||||
再試行ロジックは、サンダリングハード問題を防ぐために±25%のジッターを含む指数バックオフ(1秒→2秒→4秒→8秒...)を使用します。APIが`retry-after`ヘッダーを提供する場合、代わりにそれが使用されます。
|
||||
リトライロジックは指数バックオフ(1秒 → 2秒 → 4秒 → 8秒...)を使用し、サンダリングハード問題を防ぐために±25%のジッターを適用します。APIが `retry-after` ヘッダーを提供する場合、代わりにそれが使用されます。
|
||||
|
||||
##### getRateLimitInfo()
|
||||
|
||||
@@ -306,7 +306,7 @@ interface WorkflowStatus {
|
||||
}
|
||||
```
|
||||
|
||||
### RateLimitInfo
|
||||
### レート制限情報
|
||||
|
||||
```typescript
|
||||
interface RateLimitInfo {
|
||||
@@ -317,7 +317,7 @@ interface RateLimitInfo {
|
||||
}
|
||||
```
|
||||
|
||||
### UsageLimits
|
||||
### 使用制限
|
||||
|
||||
```typescript
|
||||
interface UsageLimits {
|
||||
@@ -345,7 +345,7 @@ interface UsageLimits {
|
||||
}
|
||||
```
|
||||
|
||||
### SimStudioError
|
||||
### SimStudioエラー
|
||||
|
||||
```typescript
|
||||
class SimStudioError extends Error {
|
||||
@@ -356,10 +356,10 @@ class SimStudioError extends Error {
|
||||
|
||||
**一般的なエラーコード:**
|
||||
- `UNAUTHORIZED`: 無効なAPIキー
|
||||
- `TIMEOUT`: リクエストがタイムアウトしました
|
||||
- `RATE_LIMIT_EXCEEDED`: レート制限を超えました
|
||||
- `USAGE_LIMIT_EXCEEDED`: 使用制限を超えました
|
||||
- `EXECUTION_ERROR`: ワークフローの実行に失敗しました
|
||||
- `TIMEOUT`: リクエストタイムアウト
|
||||
- `RATE_LIMIT_EXCEEDED`: レート制限超過
|
||||
- `USAGE_LIMIT_EXCEEDED`: 使用制限超過
|
||||
- `EXECUTION_ERROR`: ワークフロー実行失敗
|
||||
|
||||
## 例
|
||||
|
||||
@@ -376,7 +376,7 @@ class SimStudioError extends Error {
|
||||
入力データでワークフローを実行します。
|
||||
</Step>
|
||||
<Step title="結果の処理">
|
||||
実行結果を処理し、エラーがあれば対処します。
|
||||
実行結果を処理し、エラーを適切に扱います。
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
@@ -462,8 +462,8 @@ async function executeWithErrorHandling() {
|
||||
|
||||
環境変数を使用してクライアントを設定します:
|
||||
|
||||
<Tabs items={['Development', 'Production']}>
|
||||
<Tab value="Development">
|
||||
<Tabs items={['開発環境', '本番環境']}>
|
||||
<Tab value="開発環境">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -481,7 +481,7 @@ async function executeWithErrorHandling() {
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="Production">
|
||||
<Tab value="本番環境">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -501,7 +501,7 @@ async function executeWithErrorHandling() {
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Node.js Express統合
|
||||
### Node.js Expressとの統合
|
||||
|
||||
Express.jsサーバーとの統合:
|
||||
|
||||
@@ -545,7 +545,7 @@ app.listen(3000, () => {
|
||||
|
||||
### Next.js APIルート
|
||||
|
||||
Next.js APIルートでの使用:
|
||||
Next.js APIルートでの使用方法:
|
||||
|
||||
```typescript
|
||||
// pages/api/workflow.ts or app/api/workflow/route.ts
|
||||
@@ -584,7 +584,7 @@ export default async function handler(
|
||||
|
||||
### ブラウザでの使用
|
||||
|
||||
ブラウザでの使用(適切なCORS設定が必要):
|
||||
ブラウザでの使用方法(適切なCORS設定が必要):
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -604,26 +604,105 @@ async function executeClientSideWorkflow() {
|
||||
});
|
||||
|
||||
console.log('Workflow result:', result);
|
||||
|
||||
|
||||
// Update UI with result
|
||||
document.getElementById('result')!.textContent =
|
||||
document.getElementById('result')!.textContent =
|
||||
JSON.stringify(result.output, null, 2);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach to button click
|
||||
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
|
||||
```
|
||||
|
||||
### ファイルアップロード
|
||||
|
||||
Fileオブジェクトは自動的に検出され、base64形式に変換されます。ワークフローのAPIトリガー入力形式に一致するフィールド名で入力に含めてください。
|
||||
|
||||
SDKはFileオブジェクトを以下の形式に変換します:
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: 'file',
|
||||
data: 'data:mime/type;base64,base64data',
|
||||
name: 'filename',
|
||||
mime: 'mime/type'
|
||||
}
|
||||
```
|
||||
|
||||
または、URL形式を使用して手動でファイルを提供することもできます:
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: 'url',
|
||||
data: 'https://example.com/file.pdf',
|
||||
name: 'file.pdf',
|
||||
mime: 'application/pdf'
|
||||
}
|
||||
```
|
||||
|
||||
<Tabs items={['Browser', 'Node.js']}>
|
||||
<Tab value="Browser">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
|
||||
});
|
||||
|
||||
// From file input
|
||||
async function handleFileUpload(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const files = Array.from(input.files || []);
|
||||
|
||||
// Include files under the field name from your API trigger's input format
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
documents: files, // Must match your workflow's "files" field name
|
||||
instructions: 'Analyze these documents'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Result:', result);
|
||||
}
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="Node.js">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
import fs from 'fs';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.SIM_API_KEY!
|
||||
});
|
||||
|
||||
// Read file and create File object
|
||||
const fileBuffer = fs.readFileSync('./document.pdf');
|
||||
const file = new File([fileBuffer], 'document.pdf', {
|
||||
type: 'application/pdf'
|
||||
});
|
||||
|
||||
// Include files under the field name from your API trigger's input format
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
documents: [file], // Must match your workflow's "files" field name
|
||||
query: 'Summarize this document'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Callout type="warning">
|
||||
ブラウザでSDKを使用する場合、機密性の高いAPIキーを公開しないよう注意してください。バックエンドプロキシや権限が制限された公開APIキーの使用を検討してください。
|
||||
</Callout>
|
||||
|
||||
### Reactフックの例
|
||||
|
||||
ワークフロー実行用のカスタムReactフックを作成:
|
||||
ワークフロー実行用のカスタムReactフックを作成する:
|
||||
|
||||
```typescript
|
||||
import { useState, useCallback } from 'react';
|
||||
@@ -701,7 +780,7 @@ function WorkflowComponent() {
|
||||
|
||||
### 非同期ワークフロー実行
|
||||
|
||||
長時間実行タスク向けに非同期でワークフローを実行:
|
||||
長時間実行されるタスクのためにワークフローを非同期で実行する:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient, AsyncExecutionResult } from 'simstudio-ts-sdk';
|
||||
@@ -750,7 +829,7 @@ executeAsync();
|
||||
|
||||
### レート制限とリトライ
|
||||
|
||||
指数バックオフによるレート制限の自動処理:
|
||||
指数バックオフを使用して自動的にレート制限を処理する:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
|
||||
@@ -786,9 +865,9 @@ async function executeWithRetryHandling() {
|
||||
}
|
||||
```
|
||||
|
||||
### 使用状況モニタリング
|
||||
### 使用状況のモニタリング
|
||||
|
||||
アカウントの使用状況と制限のモニタリング:
|
||||
アカウントの使用状況と制限をモニタリングします:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -815,11 +894,27 @@ async function checkUsage() {
|
||||
console.log(' Is limited:', limits.rateLimit.async.isLimited);
|
||||
|
||||
console.log('\n=== Usage ===');
|
||||
console.log('Current period cost:
|
||||
console.log('Current period cost: $' + limits.usage.currentPeriodCost.toFixed(2));
|
||||
console.log('Limit: $' + limits.usage.limit.toFixed(2));
|
||||
console.log('Plan:', limits.usage.plan);
|
||||
|
||||
### Streaming Workflow Execution
|
||||
const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
|
||||
console.log('Usage: ' + percentUsed.toFixed(1) + '%');
|
||||
|
||||
Execute workflows with real-time streaming responses:
|
||||
if (percentUsed > 80) {
|
||||
console.warn('⚠️ Warning: You are approaching your usage limit!');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking usage:', error);
|
||||
}
|
||||
}
|
||||
|
||||
checkUsage();
|
||||
```
|
||||
|
||||
### ワークフローのストリーミング実行
|
||||
|
||||
リアルタイムのストリーミングレスポンスでワークフローを実行します:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -830,21 +925,21 @@ const client = new SimStudioClient({
|
||||
|
||||
async function executeWithStreaming() {
|
||||
try {
|
||||
// 特定のブロック出力のストリーミングを有効化
|
||||
// Enable streaming for specific block outputs
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: { message: 'Count to five' },
|
||||
stream: true,
|
||||
selectedOutputs: ['agent1.content'] // blockName.attribute形式を使用
|
||||
selectedOutputs: ['agent1.content'] // Use blockName.attribute format
|
||||
});
|
||||
|
||||
console.log('ワークフロー結果:', result);
|
||||
console.log('Workflow result:', result);
|
||||
} catch (error) {
|
||||
console.error('エラー:', error);
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The streaming response follows the Server-Sent Events (SSE) format:
|
||||
ストリーミングレスポンスはServer-Sent Events(SSE)形式に従います:
|
||||
|
||||
```
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
@@ -856,7 +951,7 @@ data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
**React Streaming Example:**
|
||||
**Reactストリーミングの例:**
|
||||
|
||||
```typescript
|
||||
import { useState, useEffect } from 'react';
|
||||
@@ -928,36 +1023,35 @@ function StreamingWorkflow() {
|
||||
}
|
||||
```
|
||||
|
||||
## Getting Your API Key
|
||||
## APIキーの取得
|
||||
|
||||
<Steps>
|
||||
<Step title="Log in to Sim">
|
||||
Navigate to [Sim](https://sim.ai) and log in to your account.
|
||||
<Step title="Simにログイン">
|
||||
[Sim](https://sim.ai)に移動してアカウントにログインします。
|
||||
</Step>
|
||||
<Step title="Open your workflow">
|
||||
Navigate to the workflow you want to execute programmatically.
|
||||
<Step title="ワークフローを開く">
|
||||
プログラムで実行したいワークフローに移動します。
|
||||
</Step>
|
||||
<Step title="Deploy your workflow">
|
||||
Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.
|
||||
<Step title="ワークフローをデプロイする">
|
||||
まだデプロイされていない場合は、「デプロイ」をクリックしてワークフローをデプロイします。
|
||||
</Step>
|
||||
<Step title="Create or select an API key">
|
||||
During the deployment process, select or create an API key.
|
||||
<Step title="APIキーを作成または選択する">
|
||||
デプロイプロセス中に、APIキーを選択または作成します。
|
||||
</Step>
|
||||
<Step title="Copy the API key">
|
||||
Copy the API key to use in your TypeScript/JavaScript application.
|
||||
<Step title="APIキーをコピーする">
|
||||
TypeScript/JavaScriptアプリケーションで使用するAPIキーをコピーします。
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Callout type="warning">
|
||||
Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management.
|
||||
APIキーは安全に保管し、バージョン管理システムにコミットしないでください。環境変数や安全な設定管理を使用してください。
|
||||
</Callout>
|
||||
|
||||
## Requirements
|
||||
## 要件
|
||||
|
||||
- Node.js 16+
|
||||
- TypeScript 5.0+ (for TypeScript projects)
|
||||
|
||||
## License
|
||||
- Node.js 16以上
|
||||
- TypeScript 5.0以上(TypeScriptプロジェクトの場合)
|
||||
|
||||
## ライセンス
|
||||
|
||||
Apache-2.0
|
||||
|
||||
@@ -8,213 +8,213 @@ 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.
|
||||
Guardrails 模块通过针对多种验证类型检查内容,验证并保护您的 AI 工作流。在内容进入工作流之前,确保数据质量、防止幻觉、检测 PII(个人身份信息)并强制执行格式要求。
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Image
|
||||
src="/static/blocks/guardrails.png"
|
||||
alt="Guardrails Block"
|
||||
alt="Guardrails 模块"
|
||||
width={500}
|
||||
height={350}
|
||||
className="my-6"
|
||||
/>
|
||||
</div>
|
||||
|
||||
## Overview
|
||||
## 概述
|
||||
|
||||
The Guardrails block enables you to:
|
||||
Guardrails 模块使您能够:
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
<strong>Validate JSON Structure</strong>: Ensure LLM outputs are valid JSON before parsing
|
||||
<strong>验证 JSON 结构</strong>:确保 LLM 输出在解析之前是有效的 JSON
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Match Regex Patterns</strong>: Verify content matches specific formats (emails, phone numbers, URLs, etc.)
|
||||
<strong>匹配正则表达式模式</strong>:验证内容是否符合特定格式(如电子邮件、电话号码、URL 等)
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Detect Hallucinations</strong>: Use RAG + LLM scoring to validate AI outputs against knowledge base content
|
||||
<strong>检测幻觉</strong>:使用 RAG + LLM 评分验证 AI 输出是否符合知识库内容
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Detect PII</strong>: Identify and optionally mask personally identifiable information across 40+ entity types
|
||||
<strong>检测 PII</strong>:识别并可选择性地屏蔽 40 多种实体类型的个人身份信息
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Validation Types
|
||||
## 验证类型
|
||||
|
||||
### JSON Validation
|
||||
### JSON 验证
|
||||
|
||||
Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed.
|
||||
验证内容是否为正确格式的 JSON。非常适合确保结构化的 LLM 输出可以安全解析。
|
||||
|
||||
**Use Cases:**
|
||||
- Validate JSON responses from Agent blocks before parsing
|
||||
- Ensure API payloads are properly formatted
|
||||
- Check structured data integrity
|
||||
**使用场景:**
|
||||
- 在解析之前验证来自 Agent 模块的 JSON 响应
|
||||
- 确保 API 负载格式正确
|
||||
- 检查结构化数据的完整性
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if valid JSON, `false` otherwise
|
||||
- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...")
|
||||
**输出:**
|
||||
- `passed`:如果是有效的 JSON,则为 `true`,否则为 `false`
|
||||
- `error`:如果验证失败,则为错误消息(例如,“无效的 JSON:意外的标记...”)
|
||||
|
||||
### 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
|
||||
**使用场景:**
|
||||
- 验证电子邮件地址
|
||||
- 检查电话号码格式
|
||||
- 验证 URL 或自定义标识符
|
||||
- 强制执行特定文本模式
|
||||
|
||||
**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)
|
||||
**配置:**
|
||||
- **正则表达式模式**:要匹配的正则表达式(例如,电子邮件的 `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if content matches pattern, `false` otherwise
|
||||
- `error`: Error message if validation fails
|
||||
**输出:**
|
||||
- `passed`:如果内容符合模式,则为 `true`,否则为 `false`
|
||||
- `error`:如果验证失败,则显示错误信息
|
||||
|
||||
### Hallucination Detection
|
||||
### 幻觉检测
|
||||
|
||||
Uses Retrieval-Augmented Generation (RAG) with LLM scoring to detect when AI-generated content contradicts or isn't grounded in your knowledge base.
|
||||
使用基于检索增强生成 (RAG) 的方法,并结合 LLM 评分,检测 AI 生成的内容是否与您的知识库相矛盾或不相关。
|
||||
|
||||
**How It Works:**
|
||||
1. Queries your knowledge base for relevant context
|
||||
2. Sends both the AI output and retrieved context to an LLM
|
||||
3. LLM assigns a confidence score (0-10 scale)
|
||||
- **0** = Full hallucination (completely ungrounded)
|
||||
- **10** = Fully grounded (completely supported by knowledge base)
|
||||
4. Validation passes if score ≥ threshold (default: 3)
|
||||
**工作原理:**
|
||||
1. 查询您的知识库以获取相关上下文
|
||||
2. 将 AI 输出和检索到的上下文发送到 LLM
|
||||
3. LLM 分配一个置信评分(0-10 分制)
|
||||
- **0** = 完全幻觉(完全无依据)
|
||||
- **10** = 完全有依据(完全由知识库支持)
|
||||
4. 如果评分 ≥ 阈值(默认值:3),验证通过
|
||||
|
||||
**Configuration:**
|
||||
- **Knowledge Base**: Select from your existing knowledge bases
|
||||
- **Model**: Choose LLM for scoring (requires strong reasoning - GPT-4o, Claude 3.7 Sonnet recommended)
|
||||
- **API Key**: Authentication for selected LLM provider (auto-hidden for hosted/Ollama models)
|
||||
- **Confidence Threshold**: Minimum score to pass (0-10, default: 3)
|
||||
- **Top K** (Advanced): Number of knowledge base chunks to retrieve (default: 10)
|
||||
**配置:**
|
||||
- **知识库**:从现有知识库中选择
|
||||
- **模型**:选择用于评分的 LLM(需要强大的推理能力,推荐 GPT-4o、Claude 3.7 Sonnet)
|
||||
- **API 密钥**:所选 LLM 提供商的身份验证(托管/Ollama 模型自动隐藏)
|
||||
- **置信阈值**:通过验证的最低评分(0-10,默认值:3)
|
||||
- **Top K**(高级):检索的知识库块数量(默认值:10)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `true` if confidence score ≥ threshold
|
||||
- `score`: Confidence score (0-10)
|
||||
- `reasoning`: LLM's explanation for the score
|
||||
- `error`: Error message if validation fails
|
||||
**输出:**
|
||||
- `passed`:如果置信评分 ≥ 阈值,则为 `true`
|
||||
- `score`:置信评分(0-10)
|
||||
- `reasoning`:LLM 对评分的解释
|
||||
- `error`:如果验证失败,则显示错误信息
|
||||
|
||||
**Use Cases:**
|
||||
- Validate Agent responses against documentation
|
||||
- Ensure customer support answers are factually accurate
|
||||
- Verify generated content matches source material
|
||||
- Quality control for RAG applications
|
||||
**使用场景:**
|
||||
- 验证代理响应是否符合文档
|
||||
- 确保客户支持回答的事实准确性
|
||||
- 验证生成的内容是否与源材料匹配
|
||||
- RAG 应用的质量控制
|
||||
|
||||
### PII Detection
|
||||
### PII 检测
|
||||
|
||||
Detects personally identifiable information using Microsoft Presidio. Supports 40+ entity types across multiple countries and languages.
|
||||
使用 Microsoft Presidio 检测个人身份信息 (PII)。支持 40 多种实体类型,覆盖多个国家和语言。
|
||||
|
||||
<div className="mx-auto w-3/5 overflow-hidden rounded-lg">
|
||||
<Video src="guardrails.mp4" width={500} height={350} />
|
||||
</div>
|
||||
|
||||
**How It Works:**
|
||||
1. Scans content for PII entities using pattern matching and NLP
|
||||
2. Returns detected entities with locations and confidence scores
|
||||
3. Optionally masks detected PII in the output
|
||||
**工作原理:**
|
||||
1. 使用模式匹配和 NLP 扫描内容中的 PII 实体
|
||||
2. 返回检测到的实体及其位置和置信评分
|
||||
3. 可选择在输出中屏蔽检测到的 PII
|
||||
|
||||
**Configuration:**
|
||||
- **PII Types to Detect**: Select from grouped categories via modal selector
|
||||
- **Common**: Person name, Email, Phone, Credit card, IP address, etc.
|
||||
- **USA**: SSN, Driver's license, Passport, etc.
|
||||
- **UK**: NHS number, National insurance number
|
||||
- **Spain**: NIF, NIE, CIF
|
||||
- **Italy**: Fiscal code, Driver's license, VAT code
|
||||
- **Poland**: PESEL, NIP, REGON
|
||||
- **Singapore**: NRIC/FIN, UEN
|
||||
- **Australia**: ABN, ACN, TFN, Medicare
|
||||
- **India**: Aadhaar, PAN, Passport, Voter number
|
||||
- **Mode**:
|
||||
- **Detect**: Only identify PII (default)
|
||||
- **Mask**: Replace detected PII with masked values
|
||||
- **Language**: Detection language (default: English)
|
||||
**配置:**
|
||||
- **要检测的 PII 类型**:通过模态选择器从分组类别中选择
|
||||
- **常见**:姓名、电子邮件、电话、信用卡、IP 地址等
|
||||
- **美国**:社会安全号码 (SSN)、驾驶执照、护照等
|
||||
- **英国**:NHS 编号、国家保险号码
|
||||
- **西班牙**:NIF、NIE、CIF
|
||||
- **意大利**:税号、驾驶执照、增值税号
|
||||
- **波兰**:PESEL、NIP、REGON
|
||||
- **新加坡**:NRIC/FIN、UEN
|
||||
- **澳大利亚**:ABN、ACN、TFN、Medicare
|
||||
- **印度**:Aadhaar、PAN、护照、选民编号
|
||||
- **模式:**
|
||||
- **检测**:仅识别 PII(默认)
|
||||
- **掩码**:将检测到的 PII 替换为掩码值
|
||||
- **语言:**检测语言(默认:英语)
|
||||
|
||||
**Output:**
|
||||
- `passed`: `false` if any selected PII types are detected
|
||||
- `detectedEntities`: Array of detected PII with type, location, and confidence
|
||||
- `maskedText`: Content with PII masked (only if mode = "Mask")
|
||||
- `error`: Error message if validation fails
|
||||
**输出:**
|
||||
- `passed`:如果检测到任何选定的 PII 类型
|
||||
- `false`:检测到的 PII 数组,包括类型、位置和置信度
|
||||
- `detectedEntities`:带有 PII 掩码的内容(仅当模式为 "掩码" 时)
|
||||
- `maskedText`:如果验证失败的错误消息
|
||||
|
||||
**Use Cases:**
|
||||
- Block content containing sensitive personal information
|
||||
- Mask PII before logging or storing data
|
||||
- Compliance with GDPR, HIPAA, and other privacy regulations
|
||||
- Sanitize user inputs before processing
|
||||
**使用场景:**
|
||||
- 阻止包含敏感个人信息的内容
|
||||
- 在记录或存储数据之前对 PII 进行掩码
|
||||
- 符合 GDPR、HIPAA 和其他隐私法规
|
||||
- 在处理之前清理用户输入
|
||||
|
||||
## Configuration
|
||||
## 配置
|
||||
|
||||
### Content to Validate
|
||||
### 要验证的内容
|
||||
|
||||
The input content to validate. This typically comes from:
|
||||
- Agent block outputs: `<agent.content>`
|
||||
- Function block results: `<function.output>`
|
||||
- API responses: `<api.output>`
|
||||
- Any other block output
|
||||
要验证的输入内容。通常来自:
|
||||
- 代理块输出:`<agent.content>`
|
||||
- 功能块结果:`<function.output>`
|
||||
- API 响应:`<api.output>`
|
||||
- 任何其他块输出
|
||||
|
||||
### Validation Type
|
||||
### 验证类型
|
||||
|
||||
Choose from four validation types:
|
||||
- **Valid JSON**: Check if content is properly formatted JSON
|
||||
- **Regex Match**: Verify content matches a regex pattern
|
||||
- **Hallucination Check**: Validate against knowledge base with LLM scoring
|
||||
- **PII Detection**: Detect and optionally mask personally identifiable information
|
||||
从四种验证类型中选择:
|
||||
- **有效 JSON**:检查内容是否为正确格式的 JSON
|
||||
- **正则表达式匹配**:验证内容是否匹配正则表达式模式
|
||||
- **幻觉检查**:通过 LLM 评分与知识库验证
|
||||
- **PII 检测**:检测并可选地掩码个人身份信息
|
||||
|
||||
## Outputs
|
||||
## 输出
|
||||
|
||||
All validation types return:
|
||||
所有验证类型返回:
|
||||
|
||||
- **`<guardrails.passed>`**: Boolean indicating if validation passed
|
||||
- **`<guardrails.validationType>`**: The type of validation performed
|
||||
- **`<guardrails.input>`**: The original input that was validated
|
||||
- **`<guardrails.error>`**: Error message if validation failed (optional)
|
||||
- **`<guardrails.passed>`**:布尔值,指示验证是否通过
|
||||
- **`<guardrails.validationType>`**:执行的验证类型
|
||||
- **`<guardrails.input>`**:被验证的原始输入
|
||||
- **`<guardrails.error>`**:如果验证失败的错误信息(可选)
|
||||
|
||||
Additional outputs by type:
|
||||
按类型的附加输出:
|
||||
|
||||
**Hallucination Check:**
|
||||
- **`<guardrails.score>`**: Confidence score (0-10)
|
||||
- **`<guardrails.reasoning>`**: LLM's explanation
|
||||
**幻觉检查:**
|
||||
- **`<guardrails.score>`**:置信分数(0-10)
|
||||
- **`<guardrails.reasoning>`**:LLM 的解释
|
||||
|
||||
**PII Detection:**
|
||||
- **`<guardrails.detectedEntities>`**: Array of detected PII entities
|
||||
- **`<guardrails.maskedText>`**: Content with PII masked (if mode = "Mask")
|
||||
**PII 检测:**
|
||||
- **`<guardrails.detectedEntities>`**:检测到的 PII 实体数组
|
||||
- **`<guardrails.maskedText>`**:已屏蔽 PII 的内容(如果模式为 "Mask")
|
||||
|
||||
## Example Use Cases
|
||||
## 示例用例
|
||||
|
||||
### Validate JSON Before Parsing
|
||||
### 在解析前验证 JSON
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Ensure Agent output is valid JSON</h4>
|
||||
<h4 className="font-medium">场景:确保代理输出为有效的 JSON</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent generates structured JSON response</li>
|
||||
<li>Guardrails validates JSON format</li>
|
||||
<li>Condition block checks `<guardrails.passed>`</li>
|
||||
<li>If passed → Parse and use data, If failed → Retry or handle error</li>
|
||||
<li>代理生成结构化的 JSON 响应</li>
|
||||
<li>Guardrails 验证 JSON 格式</li>
|
||||
<li>条件块检查 `<guardrails.passed>`</li>
|
||||
<li>如果通过 → 解析并使用数据,如果失败 → 重试或处理错误</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
### Prevent Hallucinations
|
||||
### 防止幻觉
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Validate customer support responses</h4>
|
||||
<h4 className="font-medium">场景:验证客户支持响应</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent generates response to customer question</li>
|
||||
<li>Guardrails checks against support documentation knowledge base</li>
|
||||
<li>If confidence score ≥ 3 → Send response</li>
|
||||
<li>If confidence score \< 3 → Flag for human review</li>
|
||||
<li>代理生成对客户问题的响应</li>
|
||||
<li>Guardrails 根据支持文档知识库进行检查</li>
|
||||
<li>如果置信分数 ≥ 3 → 发送响应</li>
|
||||
<li>如果置信分数 \< 3 → 标记为人工审核</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
### Block PII in User Inputs
|
||||
### 阻止用户输入中的 PII
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Sanitize user-submitted content</h4>
|
||||
<h4 className="font-medium">场景:清理用户提交的内容</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>User submits form with text content</li>
|
||||
<li>Guardrails detects PII (emails, phone numbers, SSN, etc.)</li>
|
||||
<li>If PII detected → Reject submission or mask sensitive data</li>
|
||||
<li>If no PII → Process normally</li>
|
||||
<li>用户提交带有文本内容的表单</li>
|
||||
<li>Guardrails 检测 PII(电子邮件、电话号码、社会安全号码等)</li>
|
||||
<li>如果检测到 PII → 拒绝提交或屏蔽敏感数据</li>
|
||||
<li>如果没有 PII → 正常处理</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
@@ -222,30 +222,29 @@ Additional outputs by type:
|
||||
<Video src="guardrails-example.mp4" width={500} height={350} />
|
||||
</div>
|
||||
|
||||
### Validate Email Format
|
||||
### 验证电子邮件格式
|
||||
|
||||
<div className="mb-4 rounded-md border p-4">
|
||||
<h4 className="font-medium">Scenario: Check email address format</h4>
|
||||
<h4 className="font-medium">场景:检查电子邮件地址格式</h4>
|
||||
<ol className="list-decimal pl-5 text-sm">
|
||||
<li>Agent extracts email from text</li>
|
||||
<li>Guardrails validates with regex pattern</li>
|
||||
<li>If valid → Use email for notification</li>
|
||||
<li>If invalid → Request correction</li>
|
||||
<li>代理从文本中提取电子邮件</li>
|
||||
<li>Guardrails 使用正则表达式模式进行验证</li>
|
||||
<li>如果有效 → 使用电子邮件进行通知</li>
|
||||
<li>如果无效 → 请求更正</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
## Best Practices
|
||||
## 最佳实践
|
||||
|
||||
- **Chain with Condition blocks**: Use `<guardrails.passed>` to branch workflow logic based on validation results
|
||||
- **Use JSON validation before parsing**: Always validate JSON structure before attempting to parse LLM outputs
|
||||
- **Choose appropriate PII types**: Only select the PII entity types relevant to your use case for better performance
|
||||
- **Set reasonable confidence thresholds**: For hallucination detection, adjust threshold based on your accuracy requirements (higher = stricter)
|
||||
- **Use strong models for hallucination detection**: GPT-4o or Claude 3.7 Sonnet provide more accurate confidence scoring
|
||||
- **Mask PII for logging**: Use "Mask" mode when you need to log or store content that may contain PII
|
||||
- **Test regex patterns**: Validate your regex patterns thoroughly before deploying to production
|
||||
- **Monitor validation failures**: Track `<guardrails.error>` messages to identify common validation issues
|
||||
- **与条件块链式使用**:使用 `<guardrails.passed>` 根据验证结果分支工作流逻辑
|
||||
- **在解析前使用 JSON 验证**:在尝试解析 LLM 输出之前,始终验证 JSON 结构
|
||||
- **选择合适的 PII 类型**:仅选择与您的用例相关的 PII 实体类型以获得更好的性能
|
||||
- **设置合理的置信度阈值**:对于幻觉检测,根据您的准确性要求调整阈值(越高 = 越严格)
|
||||
- **使用强大的模型进行幻觉检测**:GPT-4o 或 Claude 3.7 Sonnet 提供更准确的置信度评分
|
||||
- **对日志中的 PII 进行掩码**:当需要记录或存储可能包含 PII 的内容时,使用“掩码”模式
|
||||
- **测试正则表达式模式**:在部署到生产环境之前,彻底验证您的正则表达式模式
|
||||
- **监控验证失败**:跟踪 `<guardrails.error>` 消息以识别常见的验证问题
|
||||
|
||||
<Callout type="info">
|
||||
Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical.
|
||||
Guardrails 验证在您的工作流中同步进行。对于幻觉检测,如果延迟至关重要,请选择更快的模型(如 GPT-4o-mini)。
|
||||
</Callout>
|
||||
|
||||
|
||||
@@ -7,10 +7,10 @@ import { Card, Cards } from 'fumadocs-ui/components/card'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
Sim 的官方 TypeScript/JavaScript SDK 提供完整的类型安全,支持 Node.js 和浏览器环境,允许您从 Node.js 应用程序、Web 应用程序和其他 JavaScript 环境中以编程方式执行工作流。
|
||||
Sim 的官方 TypeScript/JavaScript SDK 提供完整的类型安全性,并支持 Node.js 和浏览器环境,允许您从 Node.js 应用程序、Web 应用程序和其他 JavaScript 环境中以编程方式执行工作流。
|
||||
|
||||
<Callout type="info">
|
||||
TypeScript SDK 提供完整的类型安全、异步执行支持、带有指数回退的自动速率限制以及使用跟踪。
|
||||
TypeScript SDK 提供完整的类型安全性、异步执行支持、带有指数回退的自动速率限制以及使用情况跟踪。
|
||||
</Callout>
|
||||
|
||||
## 安装
|
||||
@@ -74,14 +74,14 @@ new SimStudioClient(config: SimStudioConfig)
|
||||
```
|
||||
|
||||
**配置:**
|
||||
- `config.apiKey` (字符串): 您的 Sim API 密钥
|
||||
- `config.baseUrl` (字符串,可选): Sim API 的基础 URL(默认为 `https://sim.ai`)
|
||||
- `config.apiKey` (string):您的 Sim API 密钥
|
||||
- `config.baseUrl` (string,可选):Sim API 的基础 URL(默认为 `https://sim.ai`)
|
||||
|
||||
#### 方法
|
||||
|
||||
##### executeWorkflow()
|
||||
|
||||
执行带有可选输入数据的工作流。
|
||||
使用可选的输入数据执行工作流。
|
||||
|
||||
```typescript
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
@@ -91,13 +91,13 @@ const result = await client.executeWorkflow('workflow-id', {
|
||||
```
|
||||
|
||||
**参数:**
|
||||
- `workflowId` (字符串): 要执行的工作流的 ID
|
||||
- `options` (ExecutionOptions,可选):
|
||||
- `input` (任意类型): 传递给工作流的输入数据
|
||||
- `timeout` (数字): 超时时间(以毫秒为单位,默认值:30000)
|
||||
- `stream` (布尔值): 启用流式响应(默认值:false)
|
||||
- `selectedOutputs` (字符串数组): 以 `blockName.attribute` 格式阻止流中的输出(例如,`["agent1.content"]`)
|
||||
- `async` (布尔值): 异步执行(默认值:false)
|
||||
- `workflowId`(字符串):要执行的工作流的 ID
|
||||
- `options`(ExecutionOptions,可选):
|
||||
- `input`(任意类型):传递给工作流的输入数据
|
||||
- `timeout`(数字):超时时间(以毫秒为单位,默认值:30000)
|
||||
- `stream`(布尔值):启用流式响应(默认值:false)
|
||||
- `selectedOutputs`(字符串数组):以 `blockName.attribute` 格式流式传输的块输出(例如,`["agent1.content"]`)
|
||||
- `async`(布尔值):异步执行(默认值:false)
|
||||
|
||||
**返回值:** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
|
||||
@@ -113,13 +113,13 @@ console.log('Is deployed:', status.isDeployed);
|
||||
```
|
||||
|
||||
**参数:**
|
||||
- `workflowId` (字符串): 工作流的 ID
|
||||
- `workflowId`(字符串):工作流的 ID
|
||||
|
||||
**返回值:** `Promise<WorkflowStatus>`
|
||||
|
||||
##### validateWorkflow()
|
||||
|
||||
验证工作流是否已准备好执行。
|
||||
验证工作流是否准备好执行。
|
||||
|
||||
```typescript
|
||||
const isReady = await client.validateWorkflow('workflow-id');
|
||||
@@ -129,7 +129,7 @@ if (isReady) {
|
||||
```
|
||||
|
||||
**参数:**
|
||||
- `workflowId` (字符串): 工作流的 ID
|
||||
- `workflowId`(字符串):工作流的 ID
|
||||
|
||||
**返回值:** `Promise<boolean>`
|
||||
|
||||
@@ -146,22 +146,22 @@ if (status.status === 'completed') {
|
||||
```
|
||||
|
||||
**参数:**
|
||||
- `taskId` (字符串): 异步执行返回的任务 ID
|
||||
- `taskId`(字符串):异步执行返回的任务 ID
|
||||
|
||||
**返回值:** `Promise<JobStatus>`
|
||||
|
||||
**响应字段:**
|
||||
- `success` (布尔值): 请求是否成功
|
||||
- `taskId` (字符串): 任务 ID
|
||||
- `status` (字符串): 可能的值包括 `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
|
||||
- `metadata` (对象): 包含 `startedAt`, `completedAt` 和 `duration`
|
||||
- `output` (任意类型,可选): 工作流输出(完成时)
|
||||
- `error` (任意类型,可选): 错误详情(失败时)
|
||||
- `estimatedDuration` (数字,可选): 估计持续时间(以毫秒为单位,处理中/排队时)
|
||||
- `success`(布尔值):请求是否成功
|
||||
- `taskId`(字符串):任务 ID
|
||||
- `status`(字符串):以下之一 `'queued'`、`'processing'`、`'completed'`、`'failed'`、`'cancelled'`
|
||||
- `metadata`(对象):包含 `startedAt`、`completedAt` 和 `duration`
|
||||
- `output`(任意类型,可选):工作流输出(完成时)
|
||||
- `error`(任意类型,可选):错误详情(失败时)
|
||||
- `estimatedDuration`(数字,可选):估计持续时间(以毫秒为单位,处理中/排队时)
|
||||
|
||||
##### executeWithRetry()
|
||||
|
||||
使用指数退避机制,在遇到速率限制错误时自动重试执行工作流。
|
||||
使用指数退避自动重试速率限制错误的工作流执行。
|
||||
|
||||
```typescript
|
||||
const result = await client.executeWithRetry('workflow-id', {
|
||||
@@ -186,11 +186,11 @@ const result = await client.executeWithRetry('workflow-id', {
|
||||
|
||||
**返回值:** `Promise<WorkflowExecutionResult | AsyncExecutionResult>`
|
||||
|
||||
重试逻辑使用指数退避(1秒 → 2秒 → 4秒 → 8秒...),并带有 ±25% 的抖动以防止蜂拥效应。如果 API 提供了 `retry-after` 头,则会使用该头。
|
||||
重试逻辑使用指数退避(1 秒 → 2 秒 → 4 秒 → 8 秒...)并带有 ±25% 的抖动,以防止惊群效应。如果 API 提供了 `retry-after` 标头,则会使用该标头。
|
||||
|
||||
##### getRateLimitInfo()
|
||||
|
||||
从上一次 API 响应中获取当前速率限制信息。
|
||||
从上一次 API 响应中获取当前的速率限制信息。
|
||||
|
||||
```typescript
|
||||
const rateLimitInfo = client.getRateLimitInfo();
|
||||
@@ -604,26 +604,105 @@ async function executeClientSideWorkflow() {
|
||||
});
|
||||
|
||||
console.log('Workflow result:', result);
|
||||
|
||||
|
||||
// Update UI with result
|
||||
document.getElementById('result')!.textContent =
|
||||
document.getElementById('result')!.textContent =
|
||||
JSON.stringify(result.output, null, 2);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach to button click
|
||||
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
|
||||
```
|
||||
|
||||
### 文件上传
|
||||
|
||||
文件对象会被自动检测并转换为 base64 格式。将它们包含在输入中,字段名称需与工作流的 API 触发输入格式匹配。
|
||||
|
||||
SDK 将文件对象转换为以下格式:
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: 'file',
|
||||
data: 'data:mime/type;base64,base64data',
|
||||
name: 'filename',
|
||||
mime: 'mime/type'
|
||||
}
|
||||
```
|
||||
|
||||
或者,您可以使用 URL 格式手动提供文件:
|
||||
|
||||
```typescript
|
||||
{
|
||||
type: 'url',
|
||||
data: 'https://example.com/file.pdf',
|
||||
name: 'file.pdf',
|
||||
mime: 'application/pdf'
|
||||
}
|
||||
```
|
||||
|
||||
<Tabs items={['浏览器', 'Node.js']}>
|
||||
<Tab value="浏览器">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
|
||||
});
|
||||
|
||||
// From file input
|
||||
async function handleFileUpload(event: Event) {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const files = Array.from(input.files || []);
|
||||
|
||||
// Include files under the field name from your API trigger's input format
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
documents: files, // Must match your workflow's "files" field name
|
||||
instructions: 'Analyze these documents'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Result:', result);
|
||||
}
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="Node.js">
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
import fs from 'fs';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.SIM_API_KEY!
|
||||
});
|
||||
|
||||
// Read file and create File object
|
||||
const fileBuffer = fs.readFileSync('./document.pdf');
|
||||
const file = new File([fileBuffer], 'document.pdf', {
|
||||
type: 'application/pdf'
|
||||
});
|
||||
|
||||
// Include files under the field name from your API trigger's input format
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
documents: [file], // Must match your workflow's "files" field name
|
||||
query: 'Summarize this document'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Callout type="warning">
|
||||
在浏览器中使用 SDK 时,请注意不要暴露敏感的 API 密钥。建议使用后端代理或具有有限权限的公共 API 密钥。
|
||||
</Callout>
|
||||
|
||||
### React Hook 示例
|
||||
|
||||
为工作流执行创建自定义 React hook:
|
||||
为工作流执行创建一个自定义 React hook:
|
||||
|
||||
```typescript
|
||||
import { useState, useCallback } from 'react';
|
||||
@@ -815,11 +894,27 @@ async function checkUsage() {
|
||||
console.log(' Is limited:', limits.rateLimit.async.isLimited);
|
||||
|
||||
console.log('\n=== Usage ===');
|
||||
console.log('Current period cost:
|
||||
console.log('Current period cost: $' + limits.usage.currentPeriodCost.toFixed(2));
|
||||
console.log('Limit: $' + limits.usage.limit.toFixed(2));
|
||||
console.log('Plan:', limits.usage.plan);
|
||||
|
||||
### Streaming Workflow Execution
|
||||
const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
|
||||
console.log('Usage: ' + percentUsed.toFixed(1) + '%');
|
||||
|
||||
Execute workflows with real-time streaming responses:
|
||||
if (percentUsed > 80) {
|
||||
console.warn('⚠️ Warning: You are approaching your usage limit!');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking usage:', error);
|
||||
}
|
||||
}
|
||||
|
||||
checkUsage();
|
||||
```
|
||||
|
||||
### 流式工作流执行
|
||||
|
||||
通过实时流式响应执行工作流:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
@@ -830,21 +925,21 @@ const client = new SimStudioClient({
|
||||
|
||||
async function executeWithStreaming() {
|
||||
try {
|
||||
// 为特定的块输出启用流式传输
|
||||
// Enable streaming for specific block outputs
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: { message: 'Count to five' },
|
||||
stream: true,
|
||||
selectedOutputs: ['agent1.content'] // 使用 blockName.attribute 格式
|
||||
selectedOutputs: ['agent1.content'] // Use blockName.attribute format
|
||||
});
|
||||
|
||||
console.log('工作流结果:', result);
|
||||
console.log('Workflow result:', result);
|
||||
} catch (error) {
|
||||
console.error('错误:', error);
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The streaming response follows the Server-Sent Events (SSE) format:
|
||||
流式响应遵循服务器发送事件 (SSE) 格式:
|
||||
|
||||
```
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
@@ -856,7 +951,7 @@ data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
**React Streaming Example:**
|
||||
**React 流式示例:**
|
||||
|
||||
```typescript
|
||||
import { useState, useEffect } from 'react';
|
||||
@@ -869,16 +964,16 @@ function StreamingWorkflow() {
|
||||
setLoading(true);
|
||||
setOutput('');
|
||||
|
||||
// 重要提示:请从您的后端服务器发起此 API 调用,而不是从浏览器发起
|
||||
// 切勿在客户端代码中暴露您的 API 密钥
|
||||
// IMPORTANT: Make this API call from your backend server, not the browser
|
||||
// Never expose your API key in client-side code
|
||||
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! // 仅限服务器端环境变量
|
||||
'X-API-Key': process.env.SIM_API_KEY! // Server-side environment variable only
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message: '生成一个故事',
|
||||
message: 'Generate a story',
|
||||
stream: true,
|
||||
selectedOutputs: ['agent1.content']
|
||||
})
|
||||
@@ -907,10 +1002,10 @@ function StreamingWorkflow() {
|
||||
if (parsed.chunk) {
|
||||
setOutput(prev => prev + parsed.chunk);
|
||||
} else if (parsed.event === 'done') {
|
||||
console.log('执行完成:', parsed.metadata);
|
||||
console.log('Execution complete:', parsed.metadata);
|
||||
}
|
||||
} catch (e) {
|
||||
// 跳过无效的 JSON
|
||||
// Skip invalid JSON
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -920,7 +1015,7 @@ function StreamingWorkflow() {
|
||||
return (
|
||||
<div>
|
||||
<button onClick={executeStreaming} disabled={loading}>
|
||||
{loading ? '生成中...' : '开始流式处理'}
|
||||
{loading ? 'Generating...' : 'Start Streaming'}
|
||||
</button>
|
||||
<div style={{ whiteSpace: 'pre-wrap' }}>{output}</div>
|
||||
</div>
|
||||
@@ -928,34 +1023,34 @@ function StreamingWorkflow() {
|
||||
}
|
||||
```
|
||||
|
||||
## Getting Your API Key
|
||||
## 获取您的 API 密钥
|
||||
|
||||
<Steps>
|
||||
<Step title="Log in to Sim">
|
||||
Navigate to [Sim](https://sim.ai) and log in to your account.
|
||||
<Step title="登录到 Sim">
|
||||
访问 [Sim](https://sim.ai) 并登录到您的账户。
|
||||
</Step>
|
||||
<Step title="Open your workflow">
|
||||
Navigate to the workflow you want to execute programmatically.
|
||||
<Step title="打开您的工作流">
|
||||
导航到您想要以编程方式执行的工作流。
|
||||
</Step>
|
||||
<Step title="Deploy your workflow">
|
||||
Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.
|
||||
<Step title="部署您的工作流">
|
||||
如果尚未部署,请点击“部署”以部署您的工作流。
|
||||
</Step>
|
||||
<Step title="Create or select an API key">
|
||||
During the deployment process, select or create an API key.
|
||||
<Step title="创建或选择一个 API 密钥">
|
||||
在部署过程中,选择或创建一个 API 密钥。
|
||||
</Step>
|
||||
<Step title="Copy the API key">
|
||||
Copy the API key to use in your TypeScript/JavaScript application.
|
||||
<Step title="复制 API 密钥">
|
||||
复制 API 密钥以在您的 TypeScript/JavaScript 应用程序中使用。
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Callout type="warning">
|
||||
Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management.
|
||||
请确保您的 API 密钥安全,切勿将其提交到版本控制中。使用环境变量或安全配置管理。
|
||||
</Callout>
|
||||
|
||||
## Requirements
|
||||
## 要求
|
||||
|
||||
- Node.js 16+
|
||||
- TypeScript 5.0+ (for TypeScript projects)
|
||||
- TypeScript 5.0+(适用于 TypeScript 项目)
|
||||
|
||||
## 许可证
|
||||
|
||||
|
||||
@@ -11,8 +11,7 @@
|
||||
"content/docs/[locale]/*.mdx",
|
||||
"content/docs/[locale]/*/*.mdx",
|
||||
"content/docs/[locale]/*/*/*.mdx"
|
||||
],
|
||||
"exclude": ["content/docs/[locale]/sdks/*.mdx"]
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2397,72 +2397,33 @@ checksums:
|
||||
content/110: 652b35852355ef0a9e0d7b634639cfc9
|
||||
content/111: 7afd8cd395c8e63bb1ede3538307de54
|
||||
content/112: 3304a33dfb626c6e2267c062e8956a9d
|
||||
content/113: eea7828d6d712dc31d150bd438284b8a
|
||||
content/114: 72a2b6306511832781715e503f0442d8
|
||||
content/115: fe19a895e0b360386bfefc269ca596a5
|
||||
content/116: d1bab8ec5a51a9da5464eb47e2a16b50
|
||||
content/117: f4b91b5931dff5faaa26581272e51b61
|
||||
content/118: 8f2d6066da0f1958aa55c6191f0a5be1
|
||||
content/119: 2a1c4e0626d1a10a59ae80490435f1c6
|
||||
content/120: a74834b7a623c3f5cc323d3ceeb5415f
|
||||
content/121: f9da331cf341b7abe9fa4f1f021bb2ce
|
||||
content/122: 006b642e4072cd86730b41503906c267
|
||||
content/123: 4570f2c71f19c1a89aa15c62abea2a6b
|
||||
content/124: bbb4874da742521d5e07d05e17056a3a
|
||||
content/125: 35f33ebf126b4a967bccf057d990d8ea
|
||||
content/126: 519f8d2ed7a62f11b58f924d05a1bdf4
|
||||
content/127: 711f65ba5fbbc9204591770be00c0b76
|
||||
content/128: d1bab8ec5a51a9da5464eb47e2a16b50
|
||||
content/129: 9a2604ebbc848ffc92920e7ca9a1f5d5
|
||||
content/130: 2d9792d07b8887ecb00b4bddaa77760d
|
||||
content/131: 67c60dcbdcb96ec99abda80aed195a39
|
||||
content/132: cd7923b20a896061bd8b437607a456ab
|
||||
content/133: 6497acadfafd123e6501104bc339cb0b
|
||||
content/134: 8d345f55098ed7fe8a79bfcd52780f56
|
||||
content/135: 7f2808ae7cc39c74fa1ea2e023e16db8
|
||||
content/136: 88f2cd0696cc8d78dc4b04549b26c13b
|
||||
content/137: d1bab8ec5a51a9da5464eb47e2a16b50
|
||||
content/138: 4760068730805bd746ad2b7abae14be7
|
||||
content/139: 363a11a70ad2991f43e5c645343d24b1
|
||||
content/140: 76193afa096b6017eb981461fbd0af36
|
||||
content/141: 0e297ada3c58c15adbac6ede74fec86b
|
||||
content/142: 08c8a11473671bde84d82b265f8f70cc
|
||||
content/143: d1bab8ec5a51a9da5464eb47e2a16b50
|
||||
content/144: ac1580a83d54361553916f1518ca3eff
|
||||
content/145: a10c4dc3ab88bfa976836d5a2fd21168
|
||||
content/146: e7ac414081f94d0ea1f36ef434392bb2
|
||||
content/147: 5235c1c6fe2a3956c0b55c2d1827fb98
|
||||
content/148: 074894d66efb4d36737a0735278e41cb
|
||||
content/149: e5aa4e76b5d89aa3c2cda5255443eccd
|
||||
content/150: b41c367dfb1527280df6c09bd32e626c
|
||||
content/151: a5b2b0cf64941e8e962724a5728a5071
|
||||
content/152: 08c8a11473671bde84d82b265f8f70cc
|
||||
content/153: d1bab8ec5a51a9da5464eb47e2a16b50
|
||||
content/154: da658275cc81a20f9cf7e4c66c7af1e3
|
||||
content/155: d87f098de2239cceabdb02513ec754c0
|
||||
content/156: 642e60a6fc14e6cca105684b0bc778fa
|
||||
content/157: 41775a7801766af4164c8d93674e6cb2
|
||||
content/158: 3afc03a5ab1dc9db2bfa092b0ac4826a
|
||||
content/159: 18ddfcaf2be4a6f1d9819407dad9ce7c
|
||||
content/160: 0d9a26fefe257a86593e24043e803357
|
||||
content/161: 7ec562abd07f7db290d6f2accea4cd2d
|
||||
content/162: ee8b87f59db1c578b95ad0198df084b7
|
||||
content/163: 4603578d6b314b662f45564a34ca430d
|
||||
content/164: cf4c97eb254d0bd6ea6633344621c2c2
|
||||
content/165: 7b4640989fab002039936156f857eb21
|
||||
content/166: 65ca9f08745b47b4cce8ea8247d043bf
|
||||
content/167: 162b4180611ff0a53b782e4dc8109293
|
||||
content/168: 6b367a189eb53cb198e3666023def89c
|
||||
content/169: dbb2125cefcf618849600c1eccae8a64
|
||||
content/170: 04eedda0da3767b06e6017c559e05414
|
||||
content/171: 077ed20dc3e9d5664e20d2814825cbdf
|
||||
content/172: a88260a5b5e23da73e4534376adeb193
|
||||
content/173: e5e2329cdc226186fe9d44767528a4a0
|
||||
content/174: 1773624e9ac3d5132b505894ef51977e
|
||||
content/175: d62c9575cc66feec7589fba95c9f7aee
|
||||
content/176: 7af652c5407ae7e156ab27b21a4f26d3
|
||||
content/177: ecd571818ddf3d31b08b80a25958a662
|
||||
content/178: 7dcdf2fbf3fce3f94987046506e12a9b
|
||||
content/113: bf1afa789fdfa5815faaf43574341e90
|
||||
content/114: 5f2fe55d098d4e4f438af595708b2280
|
||||
content/115: 41b8f7cf8899a0e92e255a3f845f9584
|
||||
content/116: 61ddd890032078ffd2da931b1d153b6d
|
||||
content/117: 7873aa7487bc3e8a4826d65c1760a4a0
|
||||
content/118: 98182d9aabe14d5bad43a5ee76a75eab
|
||||
content/119: 2bdb01e4bcb08b1d99f192acf8e2fba7
|
||||
content/120: 7079d9c00b1e1882c329b7e9b8f74552
|
||||
content/121: 0f9d65eaf6e8de43c3d5fa7e62bc838d
|
||||
content/122: 58c8e9d2d0ac37efd958203b8fbc8193
|
||||
content/123: 7859d36a7a6d0122c0818b28ee29aa3e
|
||||
content/124: ce185e7b041b8f95ebc11370d3e0aad9
|
||||
content/125: 55c6b58dc7516918e8bfde837235ff52
|
||||
content/126: 41c2bb95317d7c0421817a2b1a68cc09
|
||||
content/127: 4c95f9fa55f698f220577380dff95011
|
||||
content/128: 9ef273d776aada1b2cff3452f08ff985
|
||||
content/129: 100e12673551d4ceb5b906b1b9c65059
|
||||
content/130: ce253674cd7c49320203cda2bdd3685b
|
||||
content/131: 8910afcea8c205a28256eb30de6a1f26
|
||||
content/132: 4d7ad757d2c70fdff7834146d38dddd8
|
||||
content/133: a88260a5b5e23da73e4534376adeb193
|
||||
content/134: e5e2329cdc226186fe9d44767528a4a0
|
||||
content/135: 1773624e9ac3d5132b505894ef51977e
|
||||
content/136: d62c9575cc66feec7589fba95c9f7aee
|
||||
content/137: 7af652c5407ae7e156ab27b21a4f26d3
|
||||
content/138: ecd571818ddf3d31b08b80a25958a662
|
||||
content/139: 7dcdf2fbf3fce3f94987046506e12a9b
|
||||
27578f1315b6f1b7418d5e0d6042722e:
|
||||
meta/title: 8c555594662512e95f28e20d3880f186
|
||||
content/0: 9218a2e190598690d0fc5c27c30f01bb
|
||||
|
||||
Reference in New Issue
Block a user