diff --git a/apps/docs/content/docs/de/execution/costs.mdx b/apps/docs/content/docs/de/execution/costs.mdx
index 385ebd6699..d83a02cba2 100644
--- a/apps/docs/content/docs/de/execution/costs.mdx
+++ b/apps/docs/content/docs/de/execution/costs.mdx
@@ -170,17 +170,49 @@ Verschiedene Abonnementpläne haben unterschiedliche Nutzungslimits:
| **Team** | $500 (gepoolt) | 50 sync, 100 async |
| **Enterprise** | Individuell | Individuell |
+## Abrechnungsmodell
+
+Sim verwendet ein **Basisabonnement + Mehrverbrauch** Abrechnungsmodell:
+
+### Wie es funktioniert
+
+**Pro-Plan (20 $/Monat):**
+- Monatliches Abonnement beinhaltet 20 $ Nutzung
+- Nutzung unter 20 $ → Keine zusätzlichen Kosten
+- Nutzung über 20 $ → Zahlung des Mehrverbrauchs am Monatsende
+- Beispiel: 35 $ Nutzung = 20 $ (Abonnement) + 15 $ (Mehrverbrauch)
+
+**Team-Plan (40 $/Nutzer/Monat):**
+- Gemeinsame Nutzung für alle Teammitglieder
+- Mehrverbrauch wird aus der Gesamtnutzung des Teams berechnet
+- Organisationsinhaber erhält eine Rechnung
+
+**Enterprise-Pläne:**
+- Fester monatlicher Preis, kein Mehrverbrauch
+- Individuelle Nutzungslimits gemäß Vereinbarung
+
+### Schwellenwertabrechnung
+
+Wenn der nicht abgerechnete Mehrverbrauch 50 $ erreicht, berechnet Sim automatisch den gesamten nicht abgerechneten Betrag.
+
+**Beispiel:**
+- Tag 10: 70 $ Mehrverbrauch → Sofortige Abrechnung von 70 $
+- Tag 15: Zusätzliche 35 $ Nutzung (insgesamt 105 $) → Bereits abgerechnet, keine Aktion
+- Tag 20: Weitere 50 $ Nutzung (insgesamt 155 $, 85 $ nicht abgerechnet) → Sofortige Abrechnung von 85 $
+
+Dies verteilt hohe Mehrverbrauchskosten über den Monat, anstatt eine große Rechnung am Periodenende zu stellen.
+
## Best Practices für Kostenmanagement
1. **Regelmäßig überwachen**: Prüfen Sie Ihr Nutzungs-Dashboard häufig, um Überraschungen zu vermeiden
2. **Budgets festlegen**: Nutzen Sie Planlimits als Leitplanken für Ihre Ausgaben
3. **Workflows optimieren**: Überprüfen Sie kostenintensive Ausführungen und optimieren Sie Prompts oder Modellauswahl
-4. **Passende Modelle verwenden**: Stimmen Sie die Modellkomplexität auf die Aufgabenanforderungen ab
+4. **Passende Modelle verwenden**: Passen Sie die Modellkomplexität an die Aufgabenanforderungen an
5. **Ähnliche Aufgaben bündeln**: Kombinieren Sie wenn möglich mehrere Anfragen, um den Overhead zu reduzieren
## Nächste Schritte
- Überprüfen Sie Ihre aktuelle Nutzung unter [Einstellungen → Abonnement](https://sim.ai/settings/subscription)
- Erfahren Sie mehr über [Logging](/execution/logging), um Ausführungsdetails zu verfolgen
-- Erkunden Sie die [Externe API](/execution/api) für programmatische Kostenüberwachung
-- Sehen Sie sich [Workflow-Optimierungstechniken](/blocks) an, um Kosten zu reduzieren
\ No newline at end of file
+- Erkunden Sie die [externe API](/execution/api) für programmatische Kostenüberwachung
+- Sehen Sie sich [Workflow-Optimierungstechniken](/blocks) zur Kostenreduzierung an
\ No newline at end of file
diff --git a/apps/docs/content/docs/de/sdks/python.mdx b/apps/docs/content/docs/de/sdks/python.mdx
index 368010f430..c185733f85 100644
--- a/apps/docs/content/docs/de/sdks/python.mdx
+++ b/apps/docs/content/docs/de/sdks/python.mdx
@@ -387,7 +387,7 @@ Behandeln Sie verschiedene Fehlertypen, die während der Workflow-Ausführung au
from simstudio import SimStudioClient, SimStudioError
import os
-client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
def execute_with_error_handling():
try:
@@ -600,7 +600,7 @@ Führe Workflows mit Echtzeit-Streaming-Antworten aus:
from simstudio import SimStudioClient
import os
-client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
def execute_with_streaming():
"""Execute workflow with streaming enabled."""
diff --git a/apps/docs/content/docs/de/sdks/typescript.mdx b/apps/docs/content/docs/de/sdks/typescript.mdx
index 55e36ce7e2..a72ff0c7c3 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() {
@@ -926,6 +933,7 @@ function StreamingWorkflow() {
);
}
+
```
## Getting Your API Key
@@ -961,7 +969,9 @@ function StreamingWorkflow() {
The SDK is written in TypeScript and provides full type safety:
-```typescript
+```
+
+typescript
import {
SimStudioClient,
WorkflowExecutionResult,
@@ -987,4 +997,296 @@ const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
## License
+Apache-2.0
+
+ 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)
+
+## TypeScript Support
+
+The SDK is written in TypeScript and provides full type safety:
+
+```typescript
+import {
+ SimStudioClient,
+ WorkflowExecutionResult,
+ WorkflowStatus,
+ SimStudioError
+} from 'simstudio-ts-sdk';
+
+// Typsichere Client-Initialisierung
+const client: SimStudioClient = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+// Typsichere Workflow-Ausführung
+const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
+ input: {
+ message: 'Hallo, TypeScript!'
+ }
+});
+
+// Typsichere Statusprüfung
+const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
+```
+
+## License
+
+Apache-2.0 + limits.usage.limit.toFixed(2));
+ console.log('Plan:', limits.usage.plan);
+
+ const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
+ console.log('Usage: ' + percentUsed.toFixed(1) + '%');
+
+ 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';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+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'] // Use blockName.attribute format
+ });
+
+ console.log('Workflow result:', result);
+ } catch (error) {
+ console.error('Error:', error);
+ }
+}
+```
+
+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":", two"}
+
+data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
+
+data: [DONE]
+```
+
+**React Streaming-Beispiel:**
+
+```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}
+
+ );
+}
+```
+
+## Ihren API-Schlüssel erhalten
+
+
+
+ Navigieren Sie zu [Sim](https://sim.ai) und melden Sie sich bei Ihrem Konto an.
+
+
+ Navigieren Sie zu dem Workflow, den Sie programmatisch ausführen möchten.
+
+
+ Klicken Sie auf "Deploy", um Ihren Workflow zu deployen, falls dies noch nicht geschehen ist.
+
+
+ Wählen Sie während des Deployment-Prozesses einen API-Schlüssel aus oder erstellen Sie einen neuen.
+
+
+ Kopieren Sie den API-Schlüssel zur Verwendung in Ihrer 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)
+
+## TypeScript-Unterstützung
+
+Das SDK ist in TypeScript geschrieben und bietet vollständige Typsicherheit:
+
+```typescript
+import {
+ SimStudioClient,
+ WorkflowExecutionResult,
+ WorkflowStatus,
+ SimStudioError
+} from 'simstudio-ts-sdk';
+
+// Type-safe client initialization
+const client: SimStudioClient = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+// Type-safe workflow execution
+const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
+ input: {
+ message: 'Hello, TypeScript!'
+ }
+});
+
+// Type-safe status checking
+const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
+```
+
+## Lizenz
+
Apache-2.0
\ No newline at end of file
diff --git a/apps/docs/content/docs/en/execution/costs.mdx b/apps/docs/content/docs/en/execution/costs.mdx
index 890af4b1c5..d35423c409 100644
--- a/apps/docs/content/docs/en/execution/costs.mdx
+++ b/apps/docs/content/docs/en/execution/costs.mdx
@@ -166,6 +166,38 @@ Different subscription plans have different usage limits:
| **Team** | $500 (pooled) | 50 sync, 100 async |
| **Enterprise** | Custom | Custom |
+## Billing Model
+
+Sim uses a **base subscription + overage** billing model:
+
+### How It Works
+
+**Pro Plan ($20/month):**
+- Monthly subscription includes $20 of usage
+- Usage under $20 → No additional charges
+- Usage over $20 → Pay the overage at month end
+- Example: $35 usage = $20 (subscription) + $15 (overage)
+
+**Team Plan ($40/seat/month):**
+- Pooled usage across all team members
+- Overage calculated from total team usage
+- Organization owner receives one bill
+
+**Enterprise Plans:**
+- Fixed monthly price, no overages
+- Custom usage limits per agreement
+
+### Threshold Billing
+
+When unbilled overage reaches $50, Sim automatically bills the full unbilled amount.
+
+**Example:**
+- Day 10: $70 overage → Bill $70 immediately
+- Day 15: Additional $35 usage ($105 total) → Already billed, no action
+- Day 20: Another $50 usage ($155 total, $85 unbilled) → Bill $85 immediately
+
+This spreads large overage charges throughout the month instead of one large bill at period end.
+
## Cost Management Best Practices
1. **Monitor Regularly**: Check your usage dashboard frequently to avoid surprises
diff --git a/apps/docs/content/docs/es/execution/costs.mdx b/apps/docs/content/docs/es/execution/costs.mdx
index 78daf6600b..40468da241 100644
--- a/apps/docs/content/docs/es/execution/costs.mdx
+++ b/apps/docs/content/docs/es/execution/costs.mdx
@@ -170,17 +170,49 @@ Los diferentes planes de suscripción tienen diferentes límites de uso:
| **Equipo** | $500 (agrupado) | 50 síncronos, 100 asíncronos |
| **Empresa** | Personalizado | Personalizado |
+## Modelo de facturación
+
+Sim utiliza un modelo de facturación de **suscripción base + excedente**:
+
+### Cómo funciona
+
+**Plan Pro (20$/mes):**
+- La suscripción mensual incluye 20$ de uso
+- Uso por debajo de 20$ → Sin cargos adicionales
+- Uso por encima de 20$ → Paga el excedente al final del mes
+- Ejemplo: 35$ de uso = 20$ (suscripción) + 15$ (excedente)
+
+**Plan Team (40$/usuario/mes):**
+- Uso compartido entre todos los miembros del equipo
+- El excedente se calcula a partir del uso total del equipo
+- El propietario de la organización recibe una única factura
+
+**Planes Enterprise:**
+- Precio mensual fijo, sin excedentes
+- Límites de uso personalizados según el acuerdo
+
+### Facturación por umbrales
+
+Cuando el excedente no facturado alcanza los 50$, Sim factura automáticamente el importe total no facturado.
+
+**Ejemplo:**
+- Día 10: 70$ de excedente → Factura inmediata de 70$
+- Día 15: 35$ adicionales de uso (105$ en total) → Ya facturado, sin acción
+- Día 20: Otros 50$ de uso (155$ en total, 85$ sin facturar) → Factura inmediata de 85$
+
+Esto distribuye los cargos grandes por excedente a lo largo del mes en lugar de una factura grande al final del período.
+
## Mejores prácticas para la gestión de costos
-1. **Monitorear regularmente**: Revisa tu panel de uso frecuentemente para evitar sorpresas
-2. **Establecer presupuestos**: Utiliza los límites del plan como guías para tu gasto
-3. **Optimizar flujos de trabajo**: Revisa las ejecuciones de alto costo y optimiza los prompts o la selección de modelos
-4. **Usar modelos apropiados**: Ajusta la complejidad del modelo a los requisitos de la tarea
-5. **Agrupar tareas similares**: Combina múltiples solicitudes cuando sea posible para reducir la sobrecarga
+1. **Monitoreo regular**: Revisa tu panel de uso con frecuencia para evitar sorpresas
+2. **Establece presupuestos**: Utiliza los límites del plan como guía para tu gasto
+3. **Optimiza flujos de trabajo**: Revisa las ejecuciones de alto costo y optimiza los prompts o la selección de modelos
+4. **Usa modelos apropiados**: Ajusta la complejidad del modelo a los requisitos de la tarea
+5. **Agrupa tareas similares**: Combina múltiples solicitudes cuando sea posible para reducir la sobrecarga
## Próximos pasos
- Revisa tu uso actual en [Configuración → Suscripción](https://sim.ai/settings/subscription)
- Aprende sobre [Registro](/execution/logging) para seguir los detalles de ejecución
-- Explora la [API externa](/execution/api) para monitoreo programático de costos
+- Explora la [API externa](/execution/api) para el monitoreo programático de costos
- Consulta las [técnicas de optimización de flujo de trabajo](/blocks) para reducir costos
\ No newline at end of file
diff --git a/apps/docs/content/docs/es/sdks/python.mdx b/apps/docs/content/docs/es/sdks/python.mdx
index 2edb110394..75b4f3777a 100644
--- a/apps/docs/content/docs/es/sdks/python.mdx
+++ b/apps/docs/content/docs/es/sdks/python.mdx
@@ -609,7 +609,7 @@ Ejecuta flujos de trabajo con respuestas en tiempo real:
from simstudio import SimStudioClient
import os
-client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
def execute_with_streaming():
"""Execute workflow with streaming enabled."""
diff --git a/apps/docs/content/docs/es/sdks/typescript.mdx b/apps/docs/content/docs/es/sdks/typescript.mdx
index fca8a9805f..fee55cec30 100644
--- a/apps/docs/content/docs/es/sdks/typescript.mdx
+++ b/apps/docs/content/docs/es/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:', 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"}
@@ -854,11 +858,14 @@ data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", dos"}
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
data: [DONE]
+
```
**React Streaming Example:**
-```typescript
+```
+
+typescript
import { useState, useEffect } from 'react';
function StreamingWorkflow() {
@@ -926,6 +933,7 @@ function StreamingWorkflow() {
);
}
+
```
## Getting Your API Key
@@ -961,7 +969,9 @@ function StreamingWorkflow() {
The SDK is written in TypeScript and provides full type safety:
-```typescript
+```
+
+typescript
import {
SimStudioClient,
WorkflowExecutionResult,
@@ -987,5 +997,296 @@ const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
## License
+Apache-2.0
+
+ 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('Ejecución completada:', parsed.metadata);
+ }
+ } catch (e) {
+ // Omitir JSON inválido
+ }
+ }
+ }
+ }
+ };
+
+ 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)
+
+## TypeScript Support
+
+The SDK is written in TypeScript and provides full type safety:
+
+```typescript
+import {
+ SimStudioClient,
+ WorkflowExecutionResult,
+ WorkflowStatus,
+ SimStudioError
+} from 'simstudio-ts-sdk';
+
+// Inicialización del cliente con seguridad de tipos
+const client: SimStudioClient = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+// Ejecución de flujo de trabajo con seguridad de tipos
+const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
+ input: {
+ message: 'Hola, TypeScript!'
+ }
+});
+
+// Verificación de estado con seguridad de tipos
+const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
+```
+
+## License
+
+Apache-2.0 + limits.usage.limit.toFixed(2));
+ console.log('Plan:', limits.usage.plan);
+
+ const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
+ console.log('Usage: ' + percentUsed.toFixed(1) + '%');
+
+ if (percentUsed > 80) {
+ console.warn('⚠️ Warning: You are approaching your usage limit!');
+ }
+ } catch (error) {
+ console.error('Error checking usage:', error);
+ }
+}
+
+checkUsage();
+```
+
+### Ejecución de flujo de trabajo en streaming
+
+Ejecuta flujos de trabajo con respuestas en tiempo real:
+
+```typescript
+import { SimStudioClient } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+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'] // Use blockName.attribute format
+ });
+
+ console.log('Workflow result:', result);
+ } catch (error) {
+ console.error('Error:', error);
+ }
+}
+```
+
+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":", two"}
+
+data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
+
+data: [DONE]
+```
+
+**Ejemplo de streaming en React:**
+
+```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}
+
+ );
+}
+```
+
+## 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 "Desplegar" 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)
+
+## Soporte para TypeScript
+
+El SDK está escrito en TypeScript y proporciona seguridad de tipos completa:
+
+```typescript
+import {
+ SimStudioClient,
+ WorkflowExecutionResult,
+ WorkflowStatus,
+ SimStudioError
+} from 'simstudio-ts-sdk';
+
+// Type-safe client initialization
+const client: SimStudioClient = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+// Type-safe workflow execution
+const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
+ input: {
+ message: 'Hello, TypeScript!'
+ }
+});
+
+// Type-safe status checking
+const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
+```
+
+## Licencia
Apache-2.0
diff --git a/apps/docs/content/docs/fr/execution/costs.mdx b/apps/docs/content/docs/fr/execution/costs.mdx
index 7ab7b0099f..6ccd8b0f92 100644
--- a/apps/docs/content/docs/fr/execution/costs.mdx
+++ b/apps/docs/content/docs/fr/execution/costs.mdx
@@ -170,17 +170,49 @@ Les différents forfaits d'abonnement ont des limites d'utilisation différentes
| **Équipe** | 500 $ (mutualisé) | 50 sync, 100 async |
| **Entreprise** | Personnalisé | Personnalisé |
+## Modèle de facturation
+
+Sim utilise un modèle de facturation **abonnement de base + dépassement** :
+
+### Comment ça fonctionne
+
+**Forfait Pro (20 €/mois) :**
+- L'abonnement mensuel inclut 20 € d'utilisation
+- Utilisation inférieure à 20 € → Pas de frais supplémentaires
+- Utilisation supérieure à 20 € → Paiement du dépassement en fin de mois
+- Exemple : 35 € d'utilisation = 20 € (abonnement) + 15 € (dépassement)
+
+**Forfait Équipe (40 €/utilisateur/mois) :**
+- Utilisation mutualisée entre tous les membres de l'équipe
+- Dépassement calculé sur l'utilisation totale de l'équipe
+- Le propriétaire de l'organisation reçoit une seule facture
+
+**Forfaits Entreprise :**
+- Prix mensuel fixe, sans dépassements
+- Limites d'utilisation personnalisées selon l'accord
+
+### Facturation par seuil
+
+Lorsque le dépassement non facturé atteint 50 €, Sim facture automatiquement le montant total non facturé.
+
+**Exemple :**
+- Jour 10 : 70 € de dépassement → Facturation immédiate de 70 €
+- Jour 15 : 35 € d'utilisation supplémentaire (105 € au total) → Déjà facturé, aucune action
+- Jour 20 : 50 € d'utilisation supplémentaire (155 € au total, 85 € non facturés) → Facturation immédiate de 85 €
+
+Cela répartit les frais de dépassement importants tout au long du mois au lieu d'une seule grosse facture en fin de période.
+
## Meilleures pratiques de gestion des coûts
-1. **Surveillez régulièrement** : vérifiez fréquemment votre tableau de bord d'utilisation pour éviter les surprises
-2. **Définissez des budgets** : utilisez les limites du plan comme garde-fous pour vos dépenses
-3. **Optimisez les flux de travail** : examinez les exécutions à coût élevé et optimisez les prompts ou la sélection de modèles
-4. **Utilisez des modèles appropriés** : adaptez la complexité du modèle aux exigences de la tâche
-5. **Regroupez les tâches similaires** : combinez plusieurs requêtes lorsque c'est possible pour réduire les frais généraux
+1. **Surveillance régulière** : Vérifiez fréquemment votre tableau de bord d'utilisation pour éviter les surprises
+2. **Définir des budgets** : Utilisez les limites du forfait comme garde-fous pour vos dépenses
+3. **Optimiser les flux de travail** : Examinez les exécutions à coût élevé et optimisez les prompts ou la sélection de modèles
+4. **Utiliser les modèles appropriés** : Adaptez la complexité du modèle aux exigences de la tâche
+5. **Regrouper les tâches similaires** : Combinez plusieurs requêtes lorsque c'est possible pour réduire les frais généraux
## Prochaines étapes
-- Examinez votre utilisation actuelle dans [Paramètres → Abonnement](https://sim.ai/settings/subscription)
-- Apprenez-en plus sur la [Journalisation](/execution/logging) pour suivre les détails d'exécution
+- Consultez votre utilisation actuelle dans [Paramètres → Abonnement](https://sim.ai/settings/subscription)
+- Découvrez la [Journalisation](/execution/logging) pour suivre les détails d'exécution
- Explorez l'[API externe](/execution/api) pour la surveillance programmatique des coûts
-- Découvrez les [techniques d'optimisation de flux de travail](/blocks) pour réduire les coûts
\ No newline at end of file
+- Consultez les [techniques d'optimisation des flux de travail](/blocks) pour réduire les coûts
\ No newline at end of file
diff --git a/apps/docs/content/docs/fr/sdks/python.mdx b/apps/docs/content/docs/fr/sdks/python.mdx
index faf5f4b203..d3a8f11dcc 100644
--- a/apps/docs/content/docs/fr/sdks/python.mdx
+++ b/apps/docs/content/docs/fr/sdks/python.mdx
@@ -387,7 +387,7 @@ Gérez différents types d'erreurs qui peuvent survenir pendant l'exécution du
from simstudio import SimStudioClient, SimStudioError
import os
-client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
def execute_with_error_handling():
try:
@@ -433,7 +433,7 @@ Exécutez plusieurs workflows efficacement :
from simstudio import SimStudioClient
import os
-client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
def execute_workflows_batch(workflow_data_pairs):
"""Execute multiple workflows with different input data."""
@@ -609,7 +609,7 @@ Exécutez des workflows avec des réponses en streaming en temps réel :
from simstudio import SimStudioClient
import os
-client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
def execute_with_streaming():
"""Execute workflow with streaming enabled."""
diff --git a/apps/docs/content/docs/fr/sdks/typescript.mdx b/apps/docs/content/docs/fr/sdks/typescript.mdx
index ca572c346e..35efab136c 100644
--- a/apps/docs/content/docs/fr/sdks/typescript.mdx
+++ b/apps/docs/content/docs/fr/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('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"}
@@ -854,11 +858,14 @@ data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", deux"}
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
data: [DONE]
+
```
**React Streaming Example:**
-```typescript
+```
+
+typescript
import { useState, useEffect } from 'react';
function StreamingWorkflow() {
@@ -926,6 +933,7 @@ function StreamingWorkflow() {
);
}
+
```
## Getting Your API Key
@@ -961,7 +969,9 @@ function StreamingWorkflow() {
The SDK is written in TypeScript and provides full type safety:
-```typescript
+```
+
+typescript
import {
SimStudioClient,
WorkflowExecutionResult,
@@ -987,5 +997,296 @@ const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
## License
+Apache-2.0
+
+ 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('Exécution terminée :', parsed.metadata);
+ }
+ } catch (e) {
+ // Ignorer le JSON invalide
+ }
+ }
+ }
+ }
+ };
+
+ 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)
+
+## TypeScript Support
+
+The SDK is written in TypeScript and provides full type safety:
+
+```typescript
+import {
+ SimStudioClient,
+ WorkflowExecutionResult,
+ WorkflowStatus,
+ SimStudioError
+} from 'simstudio-ts-sdk';
+
+// Initialisation du client avec typage sécurisé
+const client: SimStudioClient = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+// Exécution de workflow avec typage sécurisé
+const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
+ input: {
+ message: 'Hello, TypeScript!'
+ }
+});
+
+// Vérification de statut avec typage sécurisé
+const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
+```
+
+## License
+
+Apache-2.0 + limits.usage.limit.toFixed(2));
+ console.log('Plan:', limits.usage.plan);
+
+ const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
+ console.log('Usage: ' + percentUsed.toFixed(1) + '%');
+
+ if (percentUsed > 80) {
+ console.warn('⚠️ Warning: You are approaching your usage limit!');
+ }
+ } catch (error) {
+ console.error('Error checking usage:', error);
+ }
+}
+
+checkUsage();
+```
+
+### Exécution de workflow en streaming
+
+Exécutez des workflows 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 {
+ // Enable streaming for specific block outputs
+ const result = await client.executeWorkflow('workflow-id', {
+ input: { message: 'Count to five' },
+ stream: true,
+ selectedOutputs: ['agent1.content'] // Use blockName.attribute format
+ });
+
+ console.log('Workflow result:', result);
+ } catch (error) {
+ console.error('Error:', error);
+ }
+}
+```
+
+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":", two"}
+
+data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
+
+data: [DONE]
+```
+
+**Exemple de streaming avec React :**
+
+```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}
+
+ );
+}
+```
+
+## 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 sécurisée et ne la soumettez jamais au contrôle de version. Utilisez des variables d'environnement ou une gestion de configuration sécurisée.
+
+
+## Prérequis
+
+- Node.js 16+
+- TypeScript 5.0+ (pour les projets TypeScript)
+
+## Support TypeScript
+
+Le SDK est écrit en TypeScript et offre une sécurité de typage complète :
+
+```typescript
+import {
+ SimStudioClient,
+ WorkflowExecutionResult,
+ WorkflowStatus,
+ SimStudioError
+} from 'simstudio-ts-sdk';
+
+// Type-safe client initialization
+const client: SimStudioClient = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+// Type-safe workflow execution
+const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
+ input: {
+ message: 'Hello, TypeScript!'
+ }
+});
+
+// Type-safe status checking
+const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
+```
+
+## Licence
Apache-2.0
diff --git a/apps/docs/content/docs/ja/execution/costs.mdx b/apps/docs/content/docs/ja/execution/costs.mdx
index 6f83172d2b..c991c42c8e 100644
--- a/apps/docs/content/docs/ja/execution/costs.mdx
+++ b/apps/docs/content/docs/ja/execution/costs.mdx
@@ -170,17 +170,49 @@ curl -X GET -H "X-API-Key: YOUR_API_KEY" -H "Content-Type: application/json" htt
| **チーム** | $500(プール) | 50同期、100非同期 |
| **エンタープライズ** | カスタム | カスタム |
+## 課金モデル
+
+Simは**基本サブスクリプション + 超過分**の課金モデルを使用しています:
+
+### 仕組み
+
+**Proプラン(月額$20):**
+- 月額サブスクリプションには$20分の使用量が含まれます
+- 使用量が$20未満 → 追加料金なし
+- 使用量が$20を超える → 月末に超過分を支払い
+- 例:$35の使用量 = $20(サブスクリプション)+ $15(超過分)
+
+**チームプラン(月額$40/シート):**
+- チームメンバー全体でプールされた使用量
+- チーム全体の使用量から超過分を計算
+- 組織のオーナーが一括で請求を受ける
+
+**エンタープライズプラン:**
+- 固定月額料金、超過料金なし
+- 契約に基づくカスタム使用制限
+
+### しきい値課金
+
+未請求の超過分が$50に達すると、Simは自動的に未請求の全額を請求します。
+
+**例:**
+- 10日目:$70の超過分 → 即時に$70を請求
+- 15日目:追加$35の使用(合計$105)→ すでに請求済み、アクションなし
+- 20日目:さらに$50の使用(合計$155、未請求$85)→ 即時に$85を請求
+
+これにより、期間終了時に大きな請求が一度にくるのではなく、月を通じて大きな超過料金が分散されます。
+
## コスト管理のベストプラクティス
-1. **定期的な監視**: 予期せぬ事態を避けるため、使用状況ダッシュボードを頻繁に確認する
-2. **予算の設定**: プランの制限を支出のガードレールとして使用する
-3. **ワークフローの最適化**: コストの高い実行を見直し、プロンプトやモデル選択を最適化する
-4. **適切なモデルの使用**: タスクの要件に合わせてモデルの複雑さを選択する
-5. **類似タスクのバッチ処理**: 可能な場合は複数のリクエストを組み合わせてオーバーヘッドを削減する
+1. **定期的な監視**:予想外の事態を避けるため、使用量ダッシュボードを頻繁にチェック
+2. **予算設定**:支出の目安としてプラン制限を活用
+3. **ワークフローの最適化**:高コストの実行を見直し、プロンプトやモデル選択を最適化
+4. **適切なモデルの使用**:タスク要件にモデルの複雑さを合わせる
+5. **類似タスクのバッチ処理**:オーバーヘッドを減らすために可能な場合は複数のリクエストを組み合わせる
## 次のステップ
-- [設定 → サブスクリプション](https://sim.ai/settings/subscription)で現在の使用状況を確認する
+- [設定 → サブスクリプション](https://sim.ai/settings/subscription)で現在の使用状況を確認
- 実行詳細を追跡するための[ロギング](/execution/logging)について学ぶ
-- プログラムによるコスト監視のための[外部API](/execution/api)を探索する
-- コスト削減のための[ワークフロー最適化テクニック](/blocks)をチェックする
\ No newline at end of file
+- プログラムによるコスト監視のための[外部API](/execution/api)を探索
+- コスト削減のための[ワークフロー最適化テクニック](/blocks)をチェック
\ No newline at end of file
diff --git a/apps/docs/content/docs/ja/sdks/python.mdx b/apps/docs/content/docs/ja/sdks/python.mdx
index b667a9f3d8..39fa75470d 100644
--- a/apps/docs/content/docs/ja/sdks/python.mdx
+++ b/apps/docs/content/docs/ja/sdks/python.mdx
@@ -433,7 +433,7 @@ with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
from simstudio import SimStudioClient
import os
-client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
def execute_workflows_batch(workflow_data_pairs):
"""Execute multiple workflows with different input data."""
@@ -660,7 +660,7 @@ def stream_workflow():
'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
headers={
'Content-Type': 'application/json',
- 'X-API-Key': os.getenv('SIM_API_KEY')
+ 'X-API-Key': os.getenv('SIM_API_KEY')
},
json={
'message': 'Generate a story',
diff --git a/apps/docs/content/docs/ja/sdks/typescript.mdx b/apps/docs/content/docs/ja/sdks/typescript.mdx
index 785f60b29d..9499403712 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() {
@@ -926,6 +933,7 @@ function StreamingWorkflow() {
);
}
+
```
## Getting Your API Key
@@ -961,7 +969,9 @@ function StreamingWorkflow() {
The SDK is written in TypeScript and provides full type safety:
-```typescript
+```
+
+typescript
import {
SimStudioClient,
WorkflowExecutionResult,
@@ -987,5 +997,296 @@ const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
## License
+Apache-2.0
+
+ 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)
+
+## TypeScript Support
+
+The SDK is written in TypeScript and provides full type safety:
+
+```typescript
+import {
+ SimStudioClient,
+ WorkflowExecutionResult,
+ WorkflowStatus,
+ SimStudioError
+} from 'simstudio-ts-sdk';
+
+// 型安全なクライアント初期化
+const client: SimStudioClient = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+// 型安全なワークフロー実行
+const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
+ input: {
+ message: 'Hello, TypeScript!'
+ }
+});
+
+// 型安全なステータス確認
+const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
+```
+
+## License
+
+Apache-2.0 + limits.usage.limit.toFixed(2));
+ console.log('Plan:', limits.usage.plan);
+
+ const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
+ console.log('Usage: ' + percentUsed.toFixed(1) + '%');
+
+ 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';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+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'] // Use blockName.attribute format
+ });
+
+ console.log('Workflow result:', result);
+ } catch (error) {
+ console.error('Error:', error);
+ }
+}
+```
+
+ストリーミングレスポンスはServer-Sent Events(SSE)形式に従います:
+
+```
+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ストリーミング例:**
+
+```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}
+
+ );
+}
+```
+
+## APIキーの取得方法
+
+
+
+ [Sim](https://sim.ai)に移動してアカウントにログインします。
+
+
+ プログラムで実行したいワークフローに移動します。
+
+
+ まだデプロイされていない場合は、「デプロイ」をクリックしてワークフローをデプロイします。
+
+
+ デプロイプロセス中に、APIキーを選択または作成します。
+
+
+ TypeScript/JavaScriptアプリケーションで使用するAPIキーをコピーします。
+
+
+
+
+ APIキーは安全に保管し、バージョン管理システムにコミットしないでください。環境変数や安全な設定管理を使用してください。
+
+
+## 要件
+
+- Node.js 16以上
+- TypeScript 5.0以上(TypeScriptプロジェクトの場合)
+
+## TypeScriptサポート
+
+このSDKはTypeScriptで書かれており、完全な型安全性を提供します:
+
+```typescript
+import {
+ SimStudioClient,
+ WorkflowExecutionResult,
+ WorkflowStatus,
+ SimStudioError
+} from 'simstudio-ts-sdk';
+
+// Type-safe client initialization
+const client: SimStudioClient = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+// Type-safe workflow execution
+const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
+ input: {
+ message: 'Hello, TypeScript!'
+ }
+});
+
+// Type-safe status checking
+const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
+```
+
+## ライセンス
Apache-2.0
diff --git a/apps/docs/content/docs/zh/execution/costs.mdx b/apps/docs/content/docs/zh/execution/costs.mdx
index 4ada972604..00e2b3387f 100644
--- a/apps/docs/content/docs/zh/execution/costs.mdx
+++ b/apps/docs/content/docs/zh/execution/costs.mdx
@@ -170,11 +170,43 @@ curl -X GET -H "X-API-Key: YOUR_API_KEY" -H "Content-Type: application/json" htt
| **团队** | $500(池化) | 50 同步, 100 异步 |
| **企业** | 自定义 | 自定义 |
+## 计费模式
+
+Sim 使用 **基础订阅 + 超额** 的计费模式:
+
+### 工作原理
+
+**专业计划($20/月):**
+- 月订阅包含 $20 的使用额度
+- 使用低于 $20 → 无额外费用
+- 使用超过 $20 → 月底支付超额部分
+- 示例:$35 的使用 = $20(订阅)+ $15(超额)
+
+**团队计划($40/人/月):**
+- 团队成员共享使用额度
+- 超额费用根据团队总使用量计算
+- 组织所有者收到一张账单
+
+**企业计划:**
+- 固定月费,无超额费用
+- 根据协议定制使用限制
+
+### 阈值计费
+
+当未结算的超额费用达到 $50 时,Sim 会自动结算全部未结算金额。
+
+**示例:**
+- 第 10 天:$70 超额 → 立即结算 $70
+- 第 15 天:额外使用 $35(总计 $105)→ 已结算,无需操作
+- 第 20 天:再使用 $50(总计 $155,未结算 $85)→ 立即结算 $85
+
+这可以将大额超额费用分散到整个月,而不是在周期末一次性结算。
+
## 成本管理最佳实践
-1. **定期监控**:经常检查您的使用仪表板,避免意外情况
-2. **设置预算**:使用计划限制作为支出控制的护栏
-3. **优化工作流程**:审查高成本的执行情况,优化提示或模型选择
+1. **定期监控**:经常检查您的使用仪表板,避免意外
+2. **设定预算**:使用计划限制作为支出控制的参考
+3. **优化工作流程**:审查高成本的执行,优化提示或模型选择
4. **使用合适的模型**:根据任务需求匹配模型复杂度
5. **批量处理相似任务**:尽可能合并多个请求以减少开销
diff --git a/apps/docs/content/docs/zh/sdks/python.mdx b/apps/docs/content/docs/zh/sdks/python.mdx
index 8ca6874295..5a59d69d70 100644
--- a/apps/docs/content/docs/zh/sdks/python.mdx
+++ b/apps/docs/content/docs/zh/sdks/python.mdx
@@ -433,7 +433,7 @@ with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
from simstudio import SimStudioClient
import os
-client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
def execute_workflows_batch(workflow_data_pairs):
"""Execute multiple workflows with different input data."""
@@ -660,7 +660,7 @@ def stream_workflow():
'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
headers={
'Content-Type': 'application/json',
- 'X-API-Key': os.getenv('SIM_API_KEY')
+ 'X-API-Key': os.getenv('SIM_API_KEY')
},
json={
'message': 'Generate a story',
diff --git a/apps/docs/content/docs/zh/sdks/typescript.mdx b/apps/docs/content/docs/zh/sdks/typescript.mdx
index ba56120459..427bb105f6 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() {
@@ -926,6 +933,114 @@ function StreamingWorkflow() {
);
}
+
+```
+
+## 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)
+
+## TypeScript Support
+
+The SDK is written in TypeScript and provides full type safety:
+
+```
+
+typescript
+import {
+ SimStudioClient,
+ WorkflowExecutionResult,
+ WorkflowStatus,
+ SimStudioError
+} from 'simstudio-ts-sdk';
+
+// 类型安全的客户端初始化
+const client: SimStudioClient = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+// 类型安全的工作流执行
+const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
+ input: {
+ message: '你好,TypeScript!'
+ }
+});
+
+// 类型安全的状态检查
+const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
+```
+
+## 许可证
+
+Apache-2.0
+
+ 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('执行完成:', parsed.metadata);
+ }
+ } catch (e) {
+ // 跳过无效的 JSON
+ }
+ }
+ }
+ }
+ };
+
+ return (
+