From 11e2a281de3d515f9590a5c97ead9fdef165f73b Mon Sep 17 00:00:00 2001 From: waleedlatif1 Date: Wed, 15 Oct 2025 01:38:34 +0000 Subject: [PATCH] feat(i18n): update translations --- .../content/docs/de/blocks/guardrails.mdx | 70 +++- apps/docs/content/docs/de/sdks/typescript.mdx | 206 +++++++++- .../content/docs/es/blocks/guardrails.mdx | 70 +++- apps/docs/content/docs/es/sdks/typescript.mdx | 371 +++++++++++++++++- .../content/docs/fr/blocks/guardrails.mdx | 70 +++- apps/docs/content/docs/fr/sdks/typescript.mdx | 371 +++++++++++++++++- .../content/docs/ja/blocks/guardrails.mdx | 70 +++- apps/docs/content/docs/ja/sdks/typescript.mdx | 205 +++++++++- .../content/docs/zh/blocks/guardrails.mdx | 70 +++- apps/docs/content/docs/zh/sdks/typescript.mdx | 206 +++++++++- 10 files changed, 1689 insertions(+), 20 deletions(-) diff --git a/apps/docs/content/docs/de/blocks/guardrails.mdx b/apps/docs/content/docs/de/blocks/guardrails.mdx index f2d6a95f8f1..382fd4f41af 100644 --- a/apps/docs/content/docs/de/blocks/guardrails.mdx +++ b/apps/docs/content/docs/de/blocks/guardrails.mdx @@ -65,7 +65,74 @@ Checks if content matches a specified regular expression pattern. - Enforce specific text patterns **Configuration:** -- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` for emails) +- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}--- +title: Guardrails +--- + +import { Callout } from 'fumadocs-ui/components/callout' +import { Step, Steps } from 'fumadocs-ui/components/steps' +import { Tab, Tabs } from 'fumadocs-ui/components/tabs' +import { Image } from '@/components/ui/image' +import { Video } from '@/components/ui/video' + +The Guardrails block validates and protects your AI workflows by checking content against multiple validation types. Ensure data quality, prevent hallucinations, detect PII, and enforce format requirements before content moves through your workflow. + +
+ Guardrails Block +
+ +## Overview + +The Guardrails block enables you to: + + + + Validate JSON Structure: Ensure LLM outputs are valid JSON before parsing + + + Match Regex Patterns: Verify content matches specific formats (emails, phone numbers, URLs, etc.) + + + Detect Hallucinations: Use RAG + LLM scoring to validate AI outputs against knowledge base content + + + Detect PII: Identify and optionally mask personally identifiable information across 40+ entity types + + + +## Validation Types + +### JSON Validation + +Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed. + +**Use Cases:** +- Validate JSON responses from Agent blocks before parsing +- Ensure API payloads are properly formatted +- Check structured data integrity + +**Output:** +- `passed`: `true` if valid JSON, `false` otherwise +- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...") + +### Regex Validation + +Checks if content matches a specified regular expression pattern. + +**Use Cases:** +- Validate email addresses +- Check phone number formats +- Verify URLs or custom identifiers +- Enforce specific text patterns + +**Configuration:** +- **Regex Pattern**: The regular expression to match against (e.g., for emails) **Output:** - `passed`: `true` if content matches pattern, `false` otherwise @@ -248,4 +315,3 @@ Additional outputs by type: Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical. - diff --git a/apps/docs/content/docs/de/sdks/typescript.mdx b/apps/docs/content/docs/de/sdks/typescript.mdx index 6cd1cafbfdf..9bc0c9df6d6 100644 --- a/apps/docs/content/docs/de/sdks/typescript.mdx +++ b/apps/docs/content/docs/de/sdks/typescript.mdx @@ -821,7 +821,9 @@ async function checkUsage() { Execute workflows with real-time streaming responses: -```typescript +``` + +typescript import { SimStudioClient } from 'simstudio-ts-sdk'; const client = new SimStudioClient({ @@ -842,11 +844,13 @@ async function executeWithStreaming() { console.error('Fehler:', error); } } + ``` The streaming response follows the Server-Sent Events (SSE) format: ``` + data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", zwei"} @@ -854,11 +858,14 @@ data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", zwei"} data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} data: [DONE] + ``` **React Streaming Example:** -```typescript +``` + +typescript import { useState, useEffect } from 'react'; function StreamingWorkflow() { @@ -959,4 +966,199 @@ function StreamingWorkflow() { ## License +Apache-2.0 + +typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function checkUsage() { + try { + const limits = await client.getUsageLimits(); + + console.log('=== Raten-Limits ==='); + console.log('Synchrone Anfragen:'); + console.log(' Limit:', limits.rateLimit.sync.limit); + console.log(' Verbleibend:', limits.rateLimit.sync.remaining); + console.log(' Zurückgesetzt um:', limits.rateLimit.sync.resetAt); + console.log(' Ist limitiert:', limits.rateLimit.sync.isLimited); + + console.log('\nAsynchrone Anfragen:'); + console.log(' Limit:', limits.rateLimit.async.limit); + console.log(' Verbleibend:', limits.rateLimit.async.remaining); + console.log(' Zurückgesetzt um:', limits.rateLimit.async.resetAt); + console.log(' Ist limitiert:', limits.rateLimit.async.isLimited); + + console.log('\n=== Nutzung ==='); + console.log('Kosten der aktuellen Periode: $' + limits.usage.currentPeriodCost.toFixed(2)); + console.log('Limit: $' + limits.usage.limit.toFixed(2)); + console.log('Plan:', limits.usage.plan); + + const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100; + console.log('Nutzung: ' + percentUsed.toFixed(1) + '%'); + + if (percentUsed > 80) { + console.warn('⚠️ Warnung: Sie nähern sich Ihrem Nutzungslimit!'); + } + } catch (error) { + console.error('Fehler bei der Überprüfung der Nutzung:', error); + } +} + +checkUsage(); + +``` + +### Streaming Workflow Execution + +Execute workflows with real-time streaming responses: + +``` + +typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // Streaming für bestimmte Block-Ausgaben aktivieren + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Zähle bis fünf' }, + stream: true, + selectedOutputs: ['agent1.content'] // Verwende das Format blockName.attribute + }); + + console.log('Workflow-Ergebnis:', result); + } catch (error) { + console.error('Fehler:', error); + } +} + +``` + +The streaming response follows the Server-Sent Events (SSE) format: + +``` + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"Eins"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", zwei"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] + +``` + +**React Streaming Example:** + +``` + +typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // WICHTIG: Führen Sie diesen API-Aufruf von Ihrem Backend-Server aus, nicht vom Browser + // Setzen Sie niemals Ihren API-Schlüssel in clientseitigem Code frei + const response = await fetch('https://sim.ai/api/workflows/WORKFLOW_ID/execute', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-API-Key': process.env.SIM_API_KEY! // Nur serverseitige Umgebungsvariable + }, + body: JSON.stringify({ + message: 'Generiere eine Geschichte', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## API-Schlüssel erhalten + + + + Navigiere zu [Sim](https://sim.ai) und melde dich in deinem Konto an. + + + Navigiere zu dem Workflow, den du programmatisch ausführen möchtest. + + + Klicke auf "Deploy", um deinen Workflow zu deployen, falls dies noch nicht geschehen ist. + + + Wähle während des Deployment-Prozesses einen API-Schlüssel aus oder erstelle einen neuen. + + + Kopiere den API-Schlüssel zur Verwendung in deiner TypeScript/JavaScript-Anwendung. + + + + + Halte deinen API-Schlüssel sicher und committe ihn niemals in die Versionskontrolle. Verwende Umgebungsvariablen oder sicheres Konfigurationsmanagement. + + +## Anforderungen + +- Node.js 16+ +- TypeScript 5.0+ (für TypeScript-Projekte) + +## Lizenz + Apache-2.0 \ No newline at end of file diff --git a/apps/docs/content/docs/es/blocks/guardrails.mdx b/apps/docs/content/docs/es/blocks/guardrails.mdx index f2d6a95f8f1..382fd4f41af 100644 --- a/apps/docs/content/docs/es/blocks/guardrails.mdx +++ b/apps/docs/content/docs/es/blocks/guardrails.mdx @@ -65,7 +65,74 @@ Checks if content matches a specified regular expression pattern. - Enforce specific text patterns **Configuration:** -- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` for emails) +- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}--- +title: Guardrails +--- + +import { Callout } from 'fumadocs-ui/components/callout' +import { Step, Steps } from 'fumadocs-ui/components/steps' +import { Tab, Tabs } from 'fumadocs-ui/components/tabs' +import { Image } from '@/components/ui/image' +import { Video } from '@/components/ui/video' + +The Guardrails block validates and protects your AI workflows by checking content against multiple validation types. Ensure data quality, prevent hallucinations, detect PII, and enforce format requirements before content moves through your workflow. + +
+ Guardrails Block +
+ +## Overview + +The Guardrails block enables you to: + + + + Validate JSON Structure: Ensure LLM outputs are valid JSON before parsing + + + Match Regex Patterns: Verify content matches specific formats (emails, phone numbers, URLs, etc.) + + + Detect Hallucinations: Use RAG + LLM scoring to validate AI outputs against knowledge base content + + + Detect PII: Identify and optionally mask personally identifiable information across 40+ entity types + + + +## Validation Types + +### JSON Validation + +Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed. + +**Use Cases:** +- Validate JSON responses from Agent blocks before parsing +- Ensure API payloads are properly formatted +- Check structured data integrity + +**Output:** +- `passed`: `true` if valid JSON, `false` otherwise +- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...") + +### Regex Validation + +Checks if content matches a specified regular expression pattern. + +**Use Cases:** +- Validate email addresses +- Check phone number formats +- Verify URLs or custom identifiers +- Enforce specific text patterns + +**Configuration:** +- **Regex Pattern**: The regular expression to match against (e.g., for emails) **Output:** - `passed`: `true` if content matches pattern, `false` otherwise @@ -248,4 +315,3 @@ Additional outputs by type: Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical. - diff --git a/apps/docs/content/docs/es/sdks/typescript.mdx b/apps/docs/content/docs/es/sdks/typescript.mdx index ae1d7ea53b4..101794bee08 100644 --- a/apps/docs/content/docs/es/sdks/typescript.mdx +++ b/apps/docs/content/docs/es/sdks/typescript.mdx @@ -815,8 +815,308 @@ async function checkUsage() { 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('Costo del período actual: + +### Ejecución de flujo de trabajo con streaming + +Ejecuta flujos de trabajo con respuestas en streaming en tiempo real: + +```typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // Habilita streaming para salidas de bloques específicos + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Count to five' }, + stream: true, + selectedOutputs: ['agent1.content'] // Usa el formato blockName.attribute + }); + + console.log('Resultado del flujo de trabajo:', result); + } catch (error) { + console.error('Error:', error); + } +} + +``` + +The streaming response follows the Server-Sent Events (SSE) format: + +``` + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", dos"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] + +``` + +**React Streaming Example:** + +``` + +typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // 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! // Server-side environment variable only + }, + body: JSON.stringify({ + message: 'Generate a story', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} + +``` + +## Getting Your API Key + + + + Navigate to [Sim](https://sim.ai) and log in to your account. + + + Navigate to the workflow you want to execute programmatically. + + + Click on "Deploy" to deploy your workflow if it hasn't been deployed yet. + + + During the deployment process, select or create an API key. + + + Copy the API key to use in your TypeScript/JavaScript application. + + + + + Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management. + + +## Requirements + +- Node.js 16+ +- TypeScript 5.0+ (for TypeScript projects) + +## License + +Apache-2.0 + limits.usage.currentPeriodCost.toFixed(2)); + console.log('Límite: + +### Ejecución de flujo de trabajo con streaming + +Ejecuta flujos de trabajo con respuestas en streaming en tiempo real: + +```typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // Habilita streaming para salidas de bloques específicos + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Count to five' }, + stream: true, + selectedOutputs: ['agent1.content'] // Usa el formato blockName.attribute + }); + + console.log('Resultado del flujo de trabajo:', result); + } catch (error) { + console.error('Error:', error); + } +} + +``` + +The streaming response follows the Server-Sent Events (SSE) format: + +``` + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", dos"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] + +``` + +**React Streaming Example:** + +``` + +typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // 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! // Server-side environment variable only + }, + body: JSON.stringify({ + message: 'Generate a story', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} + +``` + +## Getting Your API Key + + + + Navigate to [Sim](https://sim.ai) and log in to your account. + + + Navigate to the workflow you want to execute programmatically. + + + Click on "Deploy" to deploy your workflow if it hasn't been deployed yet. + + + During the deployment process, select or create an API key. + + + Copy the API key to use in your TypeScript/JavaScript application. + + + + + Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management. + + +## Requirements + +- Node.js 16+ +- TypeScript 5.0+ (for TypeScript projects) + +## License + +Apache-2.0 + limits.usage.limit.toFixed(2)); console.log('Plan:', limits.usage.plan); const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100; @@ -981,4 +1281,71 @@ function StreamingWorkflow() { ## License +Apache-2.0 + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## Obtener tu clave API + + + + Navega a [Sim](https://sim.ai) e inicia sesión en tu cuenta. + + + Navega al flujo de trabajo que quieres ejecutar programáticamente. + + + Haz clic en "Deploy" para desplegar tu flujo de trabajo si aún no ha sido desplegado. + + + Durante el proceso de despliegue, selecciona o crea una clave API. + + + Copia la clave API para usarla en tu aplicación TypeScript/JavaScript. + + + + + Mantén tu clave API segura y nunca la incluyas en el control de versiones. Utiliza variables de entorno o gestión de configuración segura. + + +## Requisitos + +- Node.js 16+ +- TypeScript 5.0+ (para proyectos TypeScript) + +## Licencia + Apache-2.0 \ No newline at end of file diff --git a/apps/docs/content/docs/fr/blocks/guardrails.mdx b/apps/docs/content/docs/fr/blocks/guardrails.mdx index f2d6a95f8f1..382fd4f41af 100644 --- a/apps/docs/content/docs/fr/blocks/guardrails.mdx +++ b/apps/docs/content/docs/fr/blocks/guardrails.mdx @@ -65,7 +65,74 @@ Checks if content matches a specified regular expression pattern. - Enforce specific text patterns **Configuration:** -- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` for emails) +- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}--- +title: Guardrails +--- + +import { Callout } from 'fumadocs-ui/components/callout' +import { Step, Steps } from 'fumadocs-ui/components/steps' +import { Tab, Tabs } from 'fumadocs-ui/components/tabs' +import { Image } from '@/components/ui/image' +import { Video } from '@/components/ui/video' + +The Guardrails block validates and protects your AI workflows by checking content against multiple validation types. Ensure data quality, prevent hallucinations, detect PII, and enforce format requirements before content moves through your workflow. + +
+ Guardrails Block +
+ +## Overview + +The Guardrails block enables you to: + + + + Validate JSON Structure: Ensure LLM outputs are valid JSON before parsing + + + Match Regex Patterns: Verify content matches specific formats (emails, phone numbers, URLs, etc.) + + + Detect Hallucinations: Use RAG + LLM scoring to validate AI outputs against knowledge base content + + + Detect PII: Identify and optionally mask personally identifiable information across 40+ entity types + + + +## Validation Types + +### JSON Validation + +Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed. + +**Use Cases:** +- Validate JSON responses from Agent blocks before parsing +- Ensure API payloads are properly formatted +- Check structured data integrity + +**Output:** +- `passed`: `true` if valid JSON, `false` otherwise +- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...") + +### Regex Validation + +Checks if content matches a specified regular expression pattern. + +**Use Cases:** +- Validate email addresses +- Check phone number formats +- Verify URLs or custom identifiers +- Enforce specific text patterns + +**Configuration:** +- **Regex Pattern**: The regular expression to match against (e.g., for emails) **Output:** - `passed`: `true` if content matches pattern, `false` otherwise @@ -248,4 +315,3 @@ Additional outputs by type: Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical. - diff --git a/apps/docs/content/docs/fr/sdks/typescript.mdx b/apps/docs/content/docs/fr/sdks/typescript.mdx index b023ed12acb..50dc3e5f7a7 100644 --- a/apps/docs/content/docs/fr/sdks/typescript.mdx +++ b/apps/docs/content/docs/fr/sdks/typescript.mdx @@ -815,8 +815,308 @@ async function checkUsage() { 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('Coût de la période actuelle : ' + limits.usage.currentPeriodCost.toFixed(2) + ' + +### Exécution de flux de travail avec streaming + +Exécutez des flux de travail avec des réponses en streaming en temps réel : + +```typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // Activer le streaming pour des sorties de blocs spécifiques + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Compter jusqu'à cinq' }, + stream: true, + selectedOutputs: ['agent1.content'] // Utiliser le format blockName.attribute + }); + + console.log('Résultat du workflow :', result); + } catch (error) { + console.error('Erreur :', error); + } +} + +``` + +The streaming response follows the Server-Sent Events (SSE) format: + +``` + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", deux"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] + +``` + +**React Streaming Example:** + +``` + +typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // 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! // Server-side environment variable only + }, + body: JSON.stringify({ + message: 'Generate a story', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} + +``` + +## Getting Your API Key + + + + Navigate to [Sim](https://sim.ai) and log in to your account. + + + Navigate to the workflow you want to execute programmatically. + + + Click on "Deploy" to deploy your workflow if it hasn't been deployed yet. + + + During the deployment process, select or create an API key. + + + Copy the API key to use in your TypeScript/JavaScript application. + + + + + Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management. + + +## Requirements + +- Node.js 16+ +- TypeScript 5.0+ (for TypeScript projects) + +## License + +Apache-2.0); + console.log('Limite : ' + limits.usage.limit.toFixed(2) + ' + +### Exécution de flux de travail avec streaming + +Exécutez des flux de travail avec des réponses en streaming en temps réel : + +```typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // Activer le streaming pour des sorties de blocs spécifiques + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Compter jusqu'à cinq' }, + stream: true, + selectedOutputs: ['agent1.content'] // Utiliser le format blockName.attribute + }); + + console.log('Résultat du workflow :', result); + } catch (error) { + console.error('Erreur :', error); + } +} + +``` + +The streaming response follows the Server-Sent Events (SSE) format: + +``` + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", deux"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] + +``` + +**React Streaming Example:** + +``` + +typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // 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! // Server-side environment variable only + }, + body: JSON.stringify({ + message: 'Generate a story', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} + +``` + +## Getting Your API Key + + + + Navigate to [Sim](https://sim.ai) and log in to your account. + + + Navigate to the workflow you want to execute programmatically. + + + Click on "Deploy" to deploy your workflow if it hasn't been deployed yet. + + + During the deployment process, select or create an API key. + + + Copy the API key to use in your TypeScript/JavaScript application. + + + + + Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management. + + +## Requirements + +- Node.js 16+ +- TypeScript 5.0+ (for TypeScript projects) + +## License + +Apache-2.0); console.log('Forfait :', limits.usage.plan); const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100; @@ -981,4 +1281,71 @@ function StreamingWorkflow() { ## License +Apache-2.0 + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## Obtenir votre clé API + + + + Accédez à [Sim](https://sim.ai) et connectez-vous à votre compte. + + + Accédez au workflow que vous souhaitez exécuter par programmation. + + + Cliquez sur « Déployer » pour déployer votre workflow s'il n'a pas encore été déployé. + + + Pendant le processus de déploiement, sélectionnez ou créez une clé API. + + + Copiez la clé API pour l'utiliser dans votre application TypeScript/JavaScript. + + + + + 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 la configuration. + + +## Prérequis + +- Node.js 16+ +- TypeScript 5.0+ (pour les projets TypeScript) + +## Licence + Apache-2.0 diff --git a/apps/docs/content/docs/ja/blocks/guardrails.mdx b/apps/docs/content/docs/ja/blocks/guardrails.mdx index f2d6a95f8f1..382fd4f41af 100644 --- a/apps/docs/content/docs/ja/blocks/guardrails.mdx +++ b/apps/docs/content/docs/ja/blocks/guardrails.mdx @@ -65,7 +65,74 @@ Checks if content matches a specified regular expression pattern. - Enforce specific text patterns **Configuration:** -- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` for emails) +- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}--- +title: Guardrails +--- + +import { Callout } from 'fumadocs-ui/components/callout' +import { Step, Steps } from 'fumadocs-ui/components/steps' +import { Tab, Tabs } from 'fumadocs-ui/components/tabs' +import { Image } from '@/components/ui/image' +import { Video } from '@/components/ui/video' + +The Guardrails block validates and protects your AI workflows by checking content against multiple validation types. Ensure data quality, prevent hallucinations, detect PII, and enforce format requirements before content moves through your workflow. + +
+ Guardrails Block +
+ +## Overview + +The Guardrails block enables you to: + + + + Validate JSON Structure: Ensure LLM outputs are valid JSON before parsing + + + Match Regex Patterns: Verify content matches specific formats (emails, phone numbers, URLs, etc.) + + + Detect Hallucinations: Use RAG + LLM scoring to validate AI outputs against knowledge base content + + + Detect PII: Identify and optionally mask personally identifiable information across 40+ entity types + + + +## Validation Types + +### JSON Validation + +Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed. + +**Use Cases:** +- Validate JSON responses from Agent blocks before parsing +- Ensure API payloads are properly formatted +- Check structured data integrity + +**Output:** +- `passed`: `true` if valid JSON, `false` otherwise +- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...") + +### Regex Validation + +Checks if content matches a specified regular expression pattern. + +**Use Cases:** +- Validate email addresses +- Check phone number formats +- Verify URLs or custom identifiers +- Enforce specific text patterns + +**Configuration:** +- **Regex Pattern**: The regular expression to match against (e.g., for emails) **Output:** - `passed`: `true` if content matches pattern, `false` otherwise @@ -248,4 +315,3 @@ Additional outputs by type: Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical. - diff --git a/apps/docs/content/docs/ja/sdks/typescript.mdx b/apps/docs/content/docs/ja/sdks/typescript.mdx index 06798a1a35b..683b46ea750 100644 --- a/apps/docs/content/docs/ja/sdks/typescript.mdx +++ b/apps/docs/content/docs/ja/sdks/typescript.mdx @@ -821,7 +821,9 @@ async function checkUsage() { Execute workflows with real-time streaming responses: -```typescript +``` + +typescript import { SimStudioClient } from 'simstudio-ts-sdk'; const client = new SimStudioClient({ @@ -842,11 +844,13 @@ async function executeWithStreaming() { console.error('エラー:', error); } } + ``` The streaming response follows the Server-Sent Events (SSE) format: ``` + data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} @@ -854,11 +858,14 @@ data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} data: [DONE] + ``` **React Streaming Example:** -```typescript +``` + +typescript import { useState, useEffect } from 'react'; function StreamingWorkflow() { @@ -959,5 +966,199 @@ function StreamingWorkflow() { ## License +Apache-2.0 + +typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function checkUsage() { + try { + const limits = await client.getUsageLimits(); + + console.log('=== 利用制限 ==='); + console.log('同期リクエスト:'); + console.log(' 制限:', limits.rateLimit.sync.limit); + console.log(' 残り:', limits.rateLimit.sync.remaining); + console.log(' リセット時間:', limits.rateLimit.sync.resetAt); + console.log(' 制限中:', limits.rateLimit.sync.isLimited); + + console.log('\n非同期リクエスト:'); + console.log(' 制限:', limits.rateLimit.async.limit); + console.log(' 残り:', limits.rateLimit.async.remaining); + console.log(' リセット時間:', limits.rateLimit.async.resetAt); + console.log(' 制限中:', limits.rateLimit.async.isLimited); + + console.log('\n=== 使用状況 ==='); + console.log('現在の期間のコスト: $' + limits.usage.currentPeriodCost.toFixed(2)); + console.log('上限: $' + limits.usage.limit.toFixed(2)); + console.log('プラン:', limits.usage.plan); + + const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100; + console.log('使用率: ' + percentUsed.toFixed(1) + '%'); + + if (percentUsed > 80) { + console.warn('⚠️ 警告: 使用制限に近づいています!'); + } + } catch (error) { + console.error('使用状況確認エラー:', error); + } +} + +checkUsage(); + +``` + +### Streaming Workflow Execution + +Execute workflows with real-time streaming responses: + +``` + +typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // 特定のブロック出力のストリーミングを有効化 + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Count to five' }, + stream: true, + selectedOutputs: ['agent1.content'] // blockName.attribute 形式を使用 + }); + + console.log('ワークフロー結果:', result); + } catch (error) { + console.error('エラー:', error); + } +} + +``` + +The streaming response follows the Server-Sent Events (SSE) format: + +``` + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] + +``` + +**React Streaming Example:** + +``` + +typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // 重要: このAPIコールはブラウザではなくバックエンドサーバーから行ってください + // クライアントサイドのコードにAPIキーを公開しないでください + 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! // サーバーサイドの環境変数のみ + }, + body: JSON.stringify({ + message: 'Generate a story', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## APIキーの取得方法 + + + + [Sim](https://sim.ai)に移動し、アカウントにログインします。 + + + プログラムで実行したいワークフローに移動します。 + + + まだデプロイされていない場合は、「デプロイ」をクリックしてワークフローをデプロイします。 + + + デプロイ処理中に、APIキーを選択または作成します。 + + + TypeScript/JavaScriptアプリケーションで使用するAPIキーをコピーします。 + + + + + APIキーは安全に保管し、バージョン管理システムにコミットしないでください。環境変数や安全な設定管理を使用してください。 + + +## 要件 + +- Node.js 16以上 +- TypeScript 5.0以上(TypeScriptプロジェクトの場合) + +## ライセンス Apache-2.0 diff --git a/apps/docs/content/docs/zh/blocks/guardrails.mdx b/apps/docs/content/docs/zh/blocks/guardrails.mdx index f2d6a95f8f1..382fd4f41af 100644 --- a/apps/docs/content/docs/zh/blocks/guardrails.mdx +++ b/apps/docs/content/docs/zh/blocks/guardrails.mdx @@ -65,7 +65,74 @@ Checks if content matches a specified regular expression pattern. - Enforce specific text patterns **Configuration:** -- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` for emails) +- **Regex Pattern**: The regular expression to match against (e.g., `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}--- +title: Guardrails +--- + +import { Callout } from 'fumadocs-ui/components/callout' +import { Step, Steps } from 'fumadocs-ui/components/steps' +import { Tab, Tabs } from 'fumadocs-ui/components/tabs' +import { Image } from '@/components/ui/image' +import { Video } from '@/components/ui/video' + +The Guardrails block validates and protects your AI workflows by checking content against multiple validation types. Ensure data quality, prevent hallucinations, detect PII, and enforce format requirements before content moves through your workflow. + +
+ Guardrails Block +
+ +## Overview + +The Guardrails block enables you to: + + + + Validate JSON Structure: Ensure LLM outputs are valid JSON before parsing + + + Match Regex Patterns: Verify content matches specific formats (emails, phone numbers, URLs, etc.) + + + Detect Hallucinations: Use RAG + LLM scoring to validate AI outputs against knowledge base content + + + Detect PII: Identify and optionally mask personally identifiable information across 40+ entity types + + + +## Validation Types + +### JSON Validation + +Validates that content is properly formatted JSON. Perfect for ensuring structured LLM outputs can be safely parsed. + +**Use Cases:** +- Validate JSON responses from Agent blocks before parsing +- Ensure API payloads are properly formatted +- Check structured data integrity + +**Output:** +- `passed`: `true` if valid JSON, `false` otherwise +- `error`: Error message if validation fails (e.g., "Invalid JSON: Unexpected token...") + +### Regex Validation + +Checks if content matches a specified regular expression pattern. + +**Use Cases:** +- Validate email addresses +- Check phone number formats +- Verify URLs or custom identifiers +- Enforce specific text patterns + +**Configuration:** +- **Regex Pattern**: The regular expression to match against (e.g., for emails) **Output:** - `passed`: `true` if content matches pattern, `false` otherwise @@ -248,4 +315,3 @@ Additional outputs by type: Guardrails validation happens synchronously in your workflow. For hallucination detection, choose faster models (like GPT-4o-mini) if latency is critical. - diff --git a/apps/docs/content/docs/zh/sdks/typescript.mdx b/apps/docs/content/docs/zh/sdks/typescript.mdx index 914499074f5..a1940f7e758 100644 --- a/apps/docs/content/docs/zh/sdks/typescript.mdx +++ b/apps/docs/content/docs/zh/sdks/typescript.mdx @@ -821,7 +821,9 @@ async function checkUsage() { Execute workflows with real-time streaming responses: -```typescript +``` + +typescript import { SimStudioClient } from 'simstudio-ts-sdk'; const client = new SimStudioClient({ @@ -842,11 +844,13 @@ async function executeWithStreaming() { console.error('错误:', error); } } + ``` The streaming response follows the Server-Sent Events (SSE) format: ``` + data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} @@ -854,11 +858,14 @@ data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} data: [DONE] + ``` **React Streaming Example:** -```typescript +``` + +typescript import { useState, useEffect } from 'react'; function StreamingWorkflow() { @@ -960,3 +967,198 @@ function StreamingWorkflow() { ## 许可证 Apache-2.0 + +typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function checkUsage() { + try { + const limits = await client.getUsageLimits(); + + console.log('=== 速率限制 ==='); + console.log('同步请求:'); + console.log(' 限制:', limits.rateLimit.sync.limit); + console.log(' 剩余:', limits.rateLimit.sync.remaining); + console.log(' 重置时间:', limits.rateLimit.sync.resetAt); + console.log(' 是否受限:', limits.rateLimit.sync.isLimited); + + console.log('\n异步请求:'); + console.log(' 限制:', limits.rateLimit.async.limit); + console.log(' 剩余:', limits.rateLimit.async.remaining); + console.log(' 重置时间:', limits.rateLimit.async.resetAt); + console.log(' 是否受限:', limits.rateLimit.async.isLimited); + + console.log('\n=== 使用情况 ==='); + console.log('当前周期费用: $' + limits.usage.currentPeriodCost.toFixed(2)); + console.log('限制: $' + limits.usage.limit.toFixed(2)); + console.log('计划:', limits.usage.plan); + + const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100; + console.log('使用率: ' + percentUsed.toFixed(1) + '%'); + + if (percentUsed > 80) { + console.warn('⚠️ 警告: 您的使用量接近限制!'); + } + } catch (error) { + console.error('检查使用情况时出错:', error); + } +} + +checkUsage(); + +``` + +### Streaming Workflow Execution + +Execute workflows with real-time streaming responses: + +``` + +typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // 为特定的块输出启用流式传输 + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Count to five' }, + stream: true, + selectedOutputs: ['agent1.content'] // 使用 blockName.attribute 格式 + }); + + console.log('工作流结果:', result); + } catch (error) { + console.error('错误:', error); + } +} + +``` + +The streaming response follows the Server-Sent Events (SSE) format: + +``` + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] + +``` + +**React Streaming Example:** + +``` + +typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // 重要: 请从您的后端服务器发起此 API 调用,而不是从浏览器 + // 切勿在客户端代码中暴露您的 API 密钥 + 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! // 仅限服务器端环境变量 + }, + body: JSON.stringify({ + message: '生成一个故事', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## 获取您的 API 密钥 + + + + 访问 [Sim](https://sim.ai) 并登录您的账户。 + + + 导航到您想要以编程方式执行的工作流。 + + + 点击“部署”以部署您的工作流(如果尚未部署)。 + + + 在部署过程中,选择或创建一个 API 密钥。 + + + 复制 API 密钥以在您的 TypeScript/JavaScript 应用程序中使用。 + + + + + 请确保您的 API 密钥安全,切勿将其提交到版本控制中。请使用环境变量或安全配置管理。 + + +## 要求 + +- Node.js 16+ +- TypeScript 5.0+(适用于 TypeScript 项目) + +## 许可证 + +Apache-2.0