diff --git a/apps/docs/content/docs/de/execution/costs.mdx b/apps/docs/content/docs/de/execution/costs.mdx
index 385ebd6699..5c77035b5a 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 $/Sitz/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. **Geeignete 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..c2a4f86550 100644
--- a/apps/docs/content/docs/de/sdks/typescript.mdx
+++ b/apps/docs/content/docs/de/sdks/typescript.mdx
@@ -604,28 +604,114 @@ async function executeClientSideWorkflow() {
});
console.log('Workflow result:', result);
-
+
// Update UI with result
- document.getElementById('result')!.textContent =
+ document.getElementById('result')!.textContent =
JSON.stringify(result.output, null, 2);
} catch (error) {
console.error('Error:', error);
}
}
+```
+
+### Datei-Upload
+
+Dateiobjekte werden automatisch erkannt und in das base64-Format konvertiert. Fügen Sie sie in Ihre Eingabe unter dem Feldnamen ein, der dem API-Trigger-Eingabeformat Ihres Workflows entspricht.
+
+Das SDK konvertiert Dateiobjekte in dieses Format:
+
+```typescript
+{
+ type: 'file',
+ data: 'data:mime/type;base64,base64data',
+ name: 'filename',
+ mime: 'mime/type'
+}
+```
+
+Alternativ können Sie Dateien manuell im URL-Format bereitstellen:
+
+```typescript
+{
+ type: 'url',
+ data: 'https://example.com/file.pdf',
+ name: 'file.pdf',
+ mime: 'application/pdf'
+}
+```
+
+
+
+
+ ```typescript
+ import { SimStudioClient } from 'simstudio-ts-sdk';
+
+ const client = new SimStudioClient({
+ apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
+ });
+
+ // From file input
+ async function handleFileUpload(event: Event) {
+ const input = event.target as HTMLInputElement;
+ const files = Array.from(input.files || []);
+
+ // Include files under the field name from your API trigger's input format
+ const result = await client.executeWorkflow('workflow-id', {
+ input: {
+ documents: files, // Must match your workflow's "files" field name
+ instructions: 'Analyze these documents'
+ }
+ });
+
+ console.log('Result:', result);
+ }
+ ```
+
+
+
+
+ ```typescript
+ import { SimStudioClient } from 'simstudio-ts-sdk';
+ import fs from 'fs';
+
+ const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+ });
+
+ // Read file and create File object
+ const fileBuffer = fs.readFileSync('./document.pdf');
+ const file = new File([fileBuffer], 'document.pdf', {
+ type: 'application/pdf'
+ });
+
+ // Include files under the field name from your API trigger's input format
+ const result = await client.executeWorkflow('workflow-id', {
+ input: {
+ documents: [file], // Must match your workflow's "files" field name
+ query: 'Summarize this document'
+ }
+ });
+ ```
+
+
+
-// Attach to button click
+// An Button-Klick anhängen
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
+
```
- Bei der Verwendung des SDK im Browser sollten Sie darauf achten, keine sensiblen API-Schlüssel offenzulegen. Erwägen Sie die Verwendung eines Backend-Proxys oder öffentlicher API-Schlüssel mit eingeschränkten Berechtigungen.
+ When using the SDK in the browser, be careful not to expose sensitive API keys. Consider using a backend proxy or public API keys with limited permissions.
-### React Hook-Beispiel
+### React Hook Example
-Erstellen eines benutzerdefinierten React-Hooks für die Workflow-Ausführung:
+Create a custom React hook for workflow execution:
-```typescript
+```
+
+typescript
import { useState, useCallback } from 'react';
import { SimStudioClient, WorkflowExecutionResult } from 'simstudio-ts-sdk';
@@ -671,7 +757,7 @@ export function useWorkflow(): UseWorkflowResult {
};
}
-// Usage in component
+// Verwendung in Komponente
function WorkflowComponent() {
const { result, loading, error, executeWorkflow } = useWorkflow();
@@ -684,26 +770,29 @@ function WorkflowComponent() {
return (
- {error &&
Error: {error.message}
}
+ {error &&
Fehler: {error.message}
}
{result && (
-
Result:
+
Ergebnis:
{JSON.stringify(result, null, 2)}
)}
);
}
+
```
-### Asynchrone Workflow-Ausführung
+### Async Workflow Execution
-Führen Sie Workflows asynchron für lang laufende Aufgaben aus:
+Execute workflows asynchronously for long-running tasks:
-```typescript
+```
+
+typescript
import { SimStudioClient, AsyncExecutionResult } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -712,47 +801,50 @@ const client = new SimStudioClient({
async function executeAsync() {
try {
- // Start async execution
+ // Starte asynchrone Ausführung
const result = await client.executeWorkflow('workflow-id', {
input: { data: 'large dataset' },
- async: true // Execute asynchronously
+ async: true // Asynchron ausführen
});
- // Check if result is an async execution
+ // Prüfe, ob das Ergebnis eine asynchrone Ausführung ist
if ('taskId' in result) {
console.log('Task ID:', result.taskId);
- console.log('Status endpoint:', result.links.status);
+ console.log('Status-Endpunkt:', result.links.status);
- // Poll for completion
+ // Abfragen bis zur Fertigstellung
let status = await client.getJobStatus(result.taskId);
while (status.status === 'queued' || status.status === 'processing') {
- console.log('Current status:', status.status);
- await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds
+ console.log('Aktueller Status:', status.status);
+ await new Promise(resolve => setTimeout(resolve, 2000)); // Warte 2 Sekunden
status = await client.getJobStatus(result.taskId);
}
if (status.status === 'completed') {
- console.log('Workflow completed!');
- console.log('Output:', status.output);
- console.log('Duration:', status.metadata.duration);
+ console.log('Workflow abgeschlossen!');
+ console.log('Ausgabe:', status.output);
+ console.log('Dauer:', status.metadata.duration);
} else {
- console.error('Workflow failed:', status.error);
+ console.error('Workflow fehlgeschlagen:', status.error);
}
}
} catch (error) {
- console.error('Error:', error);
+ console.error('Fehler:', error);
}
}
executeAsync();
+
```
-### Rate-Limiting und Wiederholungsversuche
+### Rate Limiting and Retry
-Automatische Behandlung von Rate-Limits mit exponentiellem Backoff:
+Handle rate limits automatically with exponential backoff:
-```typescript
+```
+
+typescript
import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -761,7 +853,7 @@ const client = new SimStudioClient({
async function executeWithRetryHandling() {
try {
- // Automatically retries on rate limit
+ // Wiederholt automatisch bei Rate-Limit
const result = await client.executeWithRetry('workflow-id', {
input: { message: 'Process this' }
}, {
@@ -771,26 +863,29 @@ async function executeWithRetryHandling() {
backoffMultiplier: 2
});
- console.log('Success:', result);
+ console.log('Erfolg:', result);
} catch (error) {
if (error instanceof SimStudioError && error.code === 'RATE_LIMIT_EXCEEDED') {
- console.error('Rate limit exceeded after all retries');
+ console.error('Rate-Limit nach allen Wiederholungsversuchen überschritten');
- // Check rate limit info
+ // Rate-Limit-Informationen prüfen
const rateLimitInfo = client.getRateLimitInfo();
if (rateLimitInfo) {
- console.log('Rate limit resets at:', new Date(rateLimitInfo.reset * 1000));
+ console.log('Rate-Limit wird zurückgesetzt um:', new Date(rateLimitInfo.reset * 1000));
}
}
}
}
+
```
-### Nutzungsüberwachung
+### Usage Monitoring
-Überwachen Sie Ihre Kontonutzung und -limits:
+Monitor your account usage and limits:
-```typescript
+```
+
+typescript
import { SimStudioClient } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -802,26 +897,45 @@ async function checkUsage() {
const limits = await client.getUsageLimits();
console.log('=== Rate Limits ===');
- console.log('Sync requests:');
+ console.log('Synchrone Anfragen:');
console.log(' Limit:', limits.rateLimit.sync.limit);
- console.log(' Remaining:', limits.rateLimit.sync.remaining);
- console.log(' Resets at:', limits.rateLimit.sync.resetAt);
- console.log(' Is limited:', limits.rateLimit.sync.isLimited);
+ 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('\nAsync requests:');
+ console.log('\nAsynchrone Anfragen:');
console.log(' Limit:', limits.rateLimit.async.limit);
- console.log(' Remaining:', limits.rateLimit.async.remaining);
- console.log(' Resets at:', limits.rateLimit.async.resetAt);
- console.log(' Is limited:', limits.rateLimit.async.isLimited);
+ 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=== Usage ===');
- console.log('Current period cost:
+ 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
+```
+
+typescript
import { SimStudioClient } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -830,11 +944,11 @@ const client = new SimStudioClient({
async function executeWithStreaming() {
try {
- // Streaming für bestimmte Block-Ausgaben aktivieren
+ // Streaming für bestimmte Block-Outputs aktivieren
const result = await client.executeWorkflow('workflow-id', {
- input: { message: 'Count to five' },
+ input: { message: 'Zähle bis fünf' },
stream: true,
- selectedOutputs: ['agent1.content'] // Format blockName.attribute verwenden
+ selectedOutputs: ['agent1.content'] // Verwende blockName.attribute Format
});
console.log('Workflow-Ergebnis:', result);
@@ -842,23 +956,28 @@ async function executeWithStreaming() {
console.error('Fehler:', error);
}
}
+
```
The streaming response follows the Server-Sent Events (SSE) format:
```
-data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
+
+data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"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
+```
+
+typescript
import { useState, useEffect } from 'react';
function StreamingWorkflow() {
@@ -878,7 +997,7 @@ function StreamingWorkflow() {
'X-API-Key': process.env.SIM_API_KEY! // Nur serverseitige Umgebungsvariable
},
body: JSON.stringify({
- message: 'Generate a story',
+ message: 'Generiere eine Geschichte',
stream: true,
selectedOutputs: ['agent1.content']
})
@@ -926,6 +1045,7 @@ function StreamingWorkflow() {
);
}
+
```
## Getting Your API Key
@@ -961,7 +1081,9 @@ function StreamingWorkflow() {
The SDK is written in TypeScript and provides full type safety:
-```typescript
+```
+
+typescript
import {
SimStudioClient,
WorkflowExecutionResult,
@@ -977,7 +1099,7 @@ const client: SimStudioClient = new SimStudioClient({
// Typsichere Workflow-Ausführung
const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
input: {
- message: 'Hello, TypeScript!'
+ message: 'Hallo, TypeScript!'
}
});
@@ -985,6 +1107,6 @@ const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-i
const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
```
-## License
+## Lizenz
Apache-2.0
\ No newline at end of file
diff --git a/apps/docs/content/docs/de/triggers/api.mdx b/apps/docs/content/docs/de/triggers/api.mdx
index 8dab4cfb38..c5990f52f8 100644
--- a/apps/docs/content/docs/de/triggers/api.mdx
+++ b/apps/docs/content/docs/de/triggers/api.mdx
@@ -22,9 +22,17 @@ Der API-Trigger stellt Ihren Workflow als sicheren HTTP-Endpunkt bereit. Senden
/>
-Fügen Sie für jeden Parameter ein Feld **Eingabeformat** hinzu. Die Ausgabeschlüssel zur Laufzeit spiegeln das Schema wider und sind auch unter `` verfügbar.
+Füge ein **Eingabeformat**-Feld für jeden Parameter hinzu. Unterstützte Typen:
-Manuelle Ausführungen im Editor verwenden die Spalte `value`, damit Sie testen können, ohne eine Anfrage zu senden. Während der Ausführung füllt der Resolver sowohl `` als auch `` aus.
+- **string** - Textwerte
+- **number** - Numerische Werte
+- **boolean** - Wahr/Falsch-Werte
+- **json** - JSON-Objekte
+- **files** - Datei-Uploads (Zugriff über ``, ``, usw.)
+
+Laufzeit-Ausgabeschlüssel spiegeln das Schema wider und sind unter `` verfügbar.
+
+Manuelle Ausführungen im Editor verwenden die Spalte `value`, damit du testen kannst, ohne eine Anfrage zu senden. Während der Ausführung füllt der Resolver sowohl `` als auch ``.
## Anfrage-Beispiel
@@ -40,22 +48,22 @@ Erfolgreiche Antworten geben das serialisierte Ausführungsergebnis vom Executor
## Streaming-Antworten
-Aktivieren Sie Echtzeit-Streaming, um Workflow-Ausgaben zu erhalten, während sie zeichen-für-zeichen generiert werden. Dies ist nützlich, um KI-Antworten progressiv für Benutzer anzuzeigen.
+Aktiviere Echtzeit-Streaming, um Workflow-Ausgaben während der Generierung zeichenweise zu erhalten. Dies ist nützlich, um KI-Antworten progressiv für Benutzer anzuzeigen.
-### Anfrageparameter
+### Anfrage-Parameter
-Fügen Sie diese Parameter hinzu, um Streaming zu aktivieren:
+Füge diese Parameter hinzu, um Streaming zu aktivieren:
-- `stream` - Auf `true` setzen, um Server-Sent Events (SSE) Streaming zu aktivieren
+- `stream` - Setze auf `true`, um Server-Sent Events (SSE) Streaming zu aktivieren
- `selectedOutputs` - Array von Block-Ausgaben zum Streamen (z.B. `["agent1.content"]`)
### Block-Ausgabeformat
-Verwenden Sie das `blockName.attribute` Format, um anzugeben, welche Block-Ausgaben gestreamt werden sollen:
-- Format: `"blockName.attribute"` (z.B. Wenn Sie den Inhalt des Agent 1-Blocks streamen möchten, würden Sie `"agent1.content"` verwenden)
+Verwende das Format `blockName.attribute`, um anzugeben, welche Block-Ausgaben gestreamt werden sollen:
+- Format: `"blockName.attribute"` (z.B. wenn du den Inhalt des Agent 1-Blocks streamen möchtest, würdest du `"agent1.content"` verwenden)
- Blocknamen sind nicht case-sensitive und Leerzeichen werden ignoriert
-### Beispielanfrage
+### Beispiel-Anfrage
```bash
curl -X POST \
@@ -86,44 +94,89 @@ data: [DONE]
```
Jedes Ereignis enthält:
-- **Streaming-Chunks**: `{"blockId": "...", "chunk": "text"}` - Echtzeit-Text während er generiert wird
-- **Abschlussereignis**: `{"event": "done", ...}` - Ausführungsmetadaten und vollständige Ergebnisse
+- **Streaming-Chunks**: `{"blockId": "...", "chunk": "text"}` - Echtzeit-Text während der Generierung
+- **Finales Ereignis**: `{"event": "done", ...}` - Ausführungsmetadaten und vollständige Ergebnisse
- **Terminator**: `[DONE]` - Signalisiert das Ende des Streams
### Streaming mehrerer Blöcke
Wenn `selectedOutputs` mehrere Blöcke enthält, zeigt jeder Chunk an, welcher Block ihn erzeugt hat:
-```bash
-curl -X POST \
- https://sim.ai/api/workflows/WORKFLOW_ID/execute \
- -H 'Content-Type: application/json' \
- -H 'X-API-Key: YOUR_KEY' \
- -d '{
- "message": "Process this request",
- "stream": true,
- "selectedOutputs": ["agent1.content", "agent2.content"]
- }'
+```json
+{
+ "type": "block",
+ "blockType": "text",
+ "text": "Dies ist ein Textblock"
+}
```
-Das Feld `blockId` in jedem Chunk ermöglicht es Ihnen, die Ausgabe zum richtigen UI-Element zu leiten:
+Das Feld `blockId` in jedem Chunk ermöglicht es, die Ausgabe an das richtige UI-Element zu leiten:
+```json
+{
+ "type": "block",
+ "blockType": "code",
+ "text": "console.log('Hallo Welt');"
+}
```
-data: {"blockId":"agent1-uuid","chunk":"Processing..."}
-data: {"blockId":"agent2-uuid","chunk":"Analyzing..."}
+## Ausgabe-Referenz
+
+| Referenz | Beschreibung |
+|-----------|-------------|
+| `` | Feld, das im Eingabeformat definiert ist |
+| `` | Gesamter strukturierter Anforderungstext |
-data: {"blockId":"agent1-uuid","chunk":" complete"}
+### Datei-Upload-Format
+
+Die API akzeptiert Dateien in zwei Formaten:
+
+**1. Base64-kodierte Dateien** (empfohlen für SDKs):
+
+```json
+{
+ "files": [{
+ "data": "iVBORw0KGgoAAAANSUhEUgAA...",
+ "name": "image.png",
+ "mime": "image/png"
+ }]
+}
```
-## Ausgabereferenz
+- Maximale Dateigröße: 20MB pro Datei
+- Dateien werden in den Cloud-Speicher hochgeladen und in UserFile-Objekte mit allen Eigenschaften umgewandelt
-| Referenz | Beschreibung |
-|-----------|-------------|
-| `` | Im Eingabeformat definiertes Feld |
-| `` | Gesamter strukturierter Anfragekörper |
+**2. Direkte URL-Referenzen**:
+
+```json
+{
+ "files": [{
+ "url": "https://example.com/image.png",
+ "name": "image.png",
+ "mime": "image/png"
+ }]
+}
+```
+
+- Die Datei wird nicht hochgeladen, die URL wird direkt weitergegeben
+- Nützlich für die Referenzierung bestehender Dateien
+
+### Datei-Eigenschaften
+
+Für Dateien können alle Eigenschaften abgerufen werden:
+
+| Eigenschaft | Beschreibung | Typ |
+|----------|-------------|------|
+| `` | Signierte Download-URL | string |
+| `` | Ursprünglicher Dateiname | string |
+| `` | Dateigröße in Bytes | number |
+| `` | MIME-Typ | string |
+| `` | Upload-Zeitstempel (ISO 8601) | string |
+| `` | URL-Ablaufzeitstempel (ISO 8601) | string |
+
+Für URL-referenzierte Dateien sind dieselben Eigenschaften verfügbar, mit Ausnahme von `uploadedAt` und `expiresAt`, da die Datei nicht in unseren Speicher hochgeladen wird.
-Wenn kein Eingabeformat definiert ist, stellt der Executor das rohe JSON nur unter `` zur Verfügung.
+Wenn kein Eingabeformat definiert ist, stellt der Executor nur das rohe JSON unter `` zur Verfügung.
Ein Workflow kann nur einen API-Trigger enthalten. Veröffentlichen Sie nach Änderungen eine neue Bereitstellung, damit der Endpunkt aktuell bleibt.
diff --git a/apps/docs/content/docs/de/triggers/chat.mdx b/apps/docs/content/docs/de/triggers/chat.mdx
index 129054a819..2349fc229f 100644
--- a/apps/docs/content/docs/de/triggers/chat.mdx
+++ b/apps/docs/content/docs/de/triggers/chat.mdx
@@ -24,20 +24,31 @@ Der Chat-Auslöser erstellt eine Konversationsschnittstelle für Ihren Workflow.
Der Auslöser schreibt drei Felder, auf die nachfolgende Blöcke verweisen können:
-| Referenz | Beschreibung |
-|-----------|-------------|
-| `` | Neueste Benutzernachricht |
-| `` | Konversations-Thread-ID |
-| `` | Optionale hochgeladene Dateien |
+| Referenz | Beschreibung | Typ |
+|-----------|-------------|------|
+| `` | Letzte Benutzernachricht | string |
+| `` | Konversations-Thread-ID | string |
+| `` | Optionale hochgeladene Dateien | files array |
-Dateien enthalten `name`, `mimeType` und einen signierten Download `url`.
+### Dateieigenschaften
+
+Zugriff auf einzelne Dateieigenschaften über Array-Indizierung:
+
+| Eigenschaft | Beschreibung | Typ |
+|----------|-------------|------|
+| `` | Signierte Download-URL | string |
+| `` | Ursprünglicher Dateiname | string |
+| `` | Dateigröße in Bytes | number |
+| `` | MIME-Typ | string |
+| `` | Upload-Zeitstempel (ISO 8601) | string |
+| `` | URL-Ablaufzeitstempel (ISO 8601) | string |
## Nutzungshinweise
-1. Fügen Sie einen Chat-Auslöser-Block pro Workflow hinzu.
+1. Fügen Sie einen Chat-Trigger-Block pro Workflow hinzu.
2. Stellen Sie den Workflow im Chat-Modus bereit.
-3. Teilen Sie den Bereitstellungslink – jede Antwort verwendet die Konversations-ID wieder, sodass der Workflow den Kontext beibehalten kann.
+3. Teilen Sie den Bereitstellungslink – jede Antwort verwendet dieselbe Konversations-ID, damit der Workflow den Kontext beibehalten kann.
-Der Builder blockiert mehrere Chat-Auslöser-Blöcke im selben Workflow.
+Der Builder blockiert mehrere Chat-Trigger-Blöcke im selben Workflow.
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..ebfb734663 100644
--- a/apps/docs/content/docs/es/sdks/typescript.mdx
+++ b/apps/docs/content/docs/es/sdks/typescript.mdx
@@ -604,28 +604,114 @@ async function executeClientSideWorkflow() {
});
console.log('Workflow result:', result);
-
+
// Update UI with result
- document.getElementById('result')!.textContent =
+ document.getElementById('result')!.textContent =
JSON.stringify(result.output, null, 2);
} catch (error) {
console.error('Error:', error);
}
}
+```
+
+### Carga de archivos
+
+Los objetos de archivo se detectan automáticamente y se convierten a formato base64. Inclúyelos en tu entrada bajo el nombre de campo que coincida con el formato de entrada del disparador API de tu flujo de trabajo.
+
+El SDK convierte los objetos File a este formato:
+
+```typescript
+{
+ type: 'file',
+ data: 'data:mime/type;base64,base64data',
+ name: 'filename',
+ mime: 'mime/type'
+}
+```
+
+Alternativamente, puedes proporcionar archivos manualmente usando el formato URL:
+
+```typescript
+{
+ type: 'url',
+ data: 'https://example.com/file.pdf',
+ name: 'file.pdf',
+ mime: 'application/pdf'
+}
+```
-// Attach to button click
+
+
+
+ ```typescript
+ import { SimStudioClient } from 'simstudio-ts-sdk';
+
+ const client = new SimStudioClient({
+ apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
+ });
+
+ // From file input
+ async function handleFileUpload(event: Event) {
+ const input = event.target as HTMLInputElement;
+ const files = Array.from(input.files || []);
+
+ // Include files under the field name from your API trigger's input format
+ const result = await client.executeWorkflow('workflow-id', {
+ input: {
+ documents: files, // Must match your workflow's "files" field name
+ instructions: 'Analyze these documents'
+ }
+ });
+
+ console.log('Result:', result);
+ }
+ ```
+
+
+
+
+ ```typescript
+ import { SimStudioClient } from 'simstudio-ts-sdk';
+ import fs from 'fs';
+
+ const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+ });
+
+ // Read file and create File object
+ const fileBuffer = fs.readFileSync('./document.pdf');
+ const file = new File([fileBuffer], 'document.pdf', {
+ type: 'application/pdf'
+ });
+
+ // Include files under the field name from your API trigger's input format
+ const result = await client.executeWorkflow('workflow-id', {
+ input: {
+ documents: [file], // Must match your workflow's "files" field name
+ query: 'Summarize this document'
+ }
+ });
+ ```
+
+
+
+
+// Adjuntar al clic del botón
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
+
```
- Cuando uses el SDK en el navegador, ten cuidado de no exponer claves API sensibles. Considera usar un proxy de backend o claves API públicas con permisos limitados.
+ When using the SDK in the browser, be careful not to expose sensitive API keys. Consider using a backend proxy or public API keys with limited permissions.
-### Ejemplo de hook de React
+### React Hook Example
-Crea un hook personalizado de React para la ejecución de flujos de trabajo:
+Create a custom React hook for workflow execution:
-```typescript
+```
+
+typescript
import { useState, useCallback } from 'react';
import { SimStudioClient, WorkflowExecutionResult } from 'simstudio-ts-sdk';
@@ -671,7 +757,7 @@ export function useWorkflow(): UseWorkflowResult {
};
}
-// Usage in component
+// Uso en componente
function WorkflowComponent() {
const { result, loading, error, executeWorkflow } = useWorkflow();
@@ -684,26 +770,29 @@ function WorkflowComponent() {
return (
{error &&
Error: {error.message}
}
{result && (
-
Result:
+
Resultado:
{JSON.stringify(result, null, 2)}
)}
);
}
+
```
-### Ejecución asíncrona de flujos de trabajo
+### Async Workflow Execution
-Ejecuta flujos de trabajo de forma asíncrona para tareas de larga duración:
+Execute workflows asynchronously for long-running tasks:
-```typescript
+```
+
+typescript
import { SimStudioClient, AsyncExecutionResult } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -712,32 +801,32 @@ const client = new SimStudioClient({
async function executeAsync() {
try {
- // Start async execution
+ // Iniciar ejecución asíncrona
const result = await client.executeWorkflow('workflow-id', {
input: { data: 'large dataset' },
- async: true // Execute asynchronously
+ async: true // Ejecutar de forma asíncrona
});
- // Check if result is an async execution
+ // Comprobar si el resultado es una ejecución asíncrona
if ('taskId' in result) {
- console.log('Task ID:', result.taskId);
- console.log('Status endpoint:', result.links.status);
+ console.log('ID de tarea:', result.taskId);
+ console.log('Endpoint de estado:', result.links.status);
- // Poll for completion
+ // Sondear hasta completar
let status = await client.getJobStatus(result.taskId);
while (status.status === 'queued' || status.status === 'processing') {
- console.log('Current status:', status.status);
- await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds
+ console.log('Estado actual:', status.status);
+ await new Promise(resolve => setTimeout(resolve, 2000)); // Esperar 2 segundos
status = await client.getJobStatus(result.taskId);
}
if (status.status === 'completed') {
- console.log('Workflow completed!');
- console.log('Output:', status.output);
- console.log('Duration:', status.metadata.duration);
+ console.log('¡Flujo de trabajo completado!');
+ console.log('Salida:', status.output);
+ console.log('Duración:', status.metadata.duration);
} else {
- console.error('Workflow failed:', status.error);
+ console.error('Flujo de trabajo fallido:', status.error);
}
}
} catch (error) {
@@ -746,13 +835,16 @@ async function executeAsync() {
}
executeAsync();
+
```
-### Límite de tasa y reintentos
+### Rate Limiting and Retry
-Maneja límites de tasa automáticamente con retroceso exponencial:
+Handle rate limits automatically with exponential backoff:
-```typescript
+```
+
+typescript
import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -761,7 +853,7 @@ const client = new SimStudioClient({
async function executeWithRetryHandling() {
try {
- // Automatically retries on rate limit
+ // Reintenta automáticamente en caso de límite de tasa
const result = await client.executeWithRetry('workflow-id', {
input: { message: 'Process this' }
}, {
@@ -771,26 +863,29 @@ async function executeWithRetryHandling() {
backoffMultiplier: 2
});
- console.log('Success:', result);
+ console.log('Éxito:', result);
} catch (error) {
if (error instanceof SimStudioError && error.code === 'RATE_LIMIT_EXCEEDED') {
- console.error('Rate limit exceeded after all retries');
+ console.error('Límite de tasa excedido después de todos los reintentos');
- // Check rate limit info
+ // Comprobar información del límite de tasa
const rateLimitInfo = client.getRateLimitInfo();
if (rateLimitInfo) {
- console.log('Rate limit resets at:', new Date(rateLimitInfo.reset * 1000));
+ console.log('El límite de tasa se restablece en:', new Date(rateLimitInfo.reset * 1000));
}
}
}
}
+
```
-### Monitoreo de uso
+### Usage Monitoring
-Monitorea el uso de tu cuenta y sus límites:
+Monitor your account usage and limits:
-```typescript
+```
+
+typescript
import { SimStudioClient } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -801,27 +896,46 @@ async function checkUsage() {
try {
const limits = await client.getUsageLimits();
- console.log('=== Rate Limits ===');
- console.log('Sync requests:');
- console.log(' Limit:', limits.rateLimit.sync.limit);
- console.log(' Remaining:', limits.rateLimit.sync.remaining);
- console.log(' Resets at:', limits.rateLimit.sync.resetAt);
- console.log(' Is limited:', limits.rateLimit.sync.isLimited);
+ console.log('=== Límites de tasa ===');
+ console.log('Solicitudes síncronas:');
+ console.log(' Límite:', limits.rateLimit.sync.limit);
+ console.log(' Restantes:', limits.rateLimit.sync.remaining);
+ console.log(' Se restablece en:', limits.rateLimit.sync.resetAt);
+ console.log(' Está limitado:', limits.rateLimit.sync.isLimited);
+
+ console.log('\nSolicitudes asíncronas:');
+ console.log(' Límite:', limits.rateLimit.async.limit);
+ console.log(' Restantes:', limits.rateLimit.async.remaining);
+ console.log(' Se restablece en:', limits.rateLimit.async.resetAt);
+ console.log(' Está limitado:', 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('Plan:', limits.usage.plan);
+
+ const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
+ console.log('Uso: ' + percentUsed.toFixed(1) + '%');
+
+ if (percentUsed > 80) {
+ console.warn('⚠️ Advertencia: ¡Estás acercándote a tu límite de uso!');
+ }
+ } catch (error) {
+ console.error('Error al verificar el uso:', error);
+ }
+}
- console.log('\nAsync requests:');
- console.log(' Limit:', limits.rateLimit.async.limit);
- console.log(' Remaining:', limits.rateLimit.async.remaining);
- console.log(' Resets at:', limits.rateLimit.async.resetAt);
- console.log(' Is limited:', limits.rateLimit.async.isLimited);
+checkUsage();
- console.log('\n=== Usage ===');
- console.log('Current period cost:
+```
### Streaming Workflow Execution
Execute workflows with real-time streaming responses:
-```typescript
+```
+
+typescript
import { SimStudioClient } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -830,11 +944,11 @@ const client = new SimStudioClient({
async function executeWithStreaming() {
try {
- // Habilita streaming para salidas de bloques específicos
+ // Habilitar streaming para salidas de bloques específicos
const result = await client.executeWorkflow('workflow-id', {
- input: { message: 'Count to five' },
+ input: { message: 'Cuenta hasta cinco' },
stream: true,
- selectedOutputs: ['agent1.content'] // Usa el formato blockName.attribute
+ selectedOutputs: ['agent1.content'] // Usar formato blockName.attribute
});
console.log('Resultado del flujo de trabajo:', result);
@@ -842,23 +956,28 @@ 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":"Uno"}
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() {
@@ -869,16 +988,16 @@ function StreamingWorkflow() {
setLoading(true);
setOutput('');
- // IMPORTANT: Make this API call from your backend server, not the browser
- // Never expose your API key in client-side code
+ // IMPORTANTE: Haz esta llamada API desde tu servidor backend, no desde el navegador
+ // Nunca expongas tu clave API en código del lado del cliente
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
+ 'X-API-Key': process.env.SIM_API_KEY! // Variable de entorno solo del lado del servidor
},
body: JSON.stringify({
- message: 'Generate a story',
+ message: 'Genera una historia',
stream: true,
selectedOutputs: ['agent1.content']
})
@@ -907,10 +1026,10 @@ function StreamingWorkflow() {
if (parsed.chunk) {
setOutput(prev => prev + parsed.chunk);
} else if (parsed.event === 'done') {
- console.log('Execution complete:', parsed.metadata);
+ console.log('Ejecución completa:', parsed.metadata);
}
} catch (e) {
- // Skip invalid JSON
+ // Omitir JSON inválido
}
}
}
@@ -926,6 +1045,7 @@ function StreamingWorkflow() {
);
}
+
```
## Getting Your API Key
@@ -961,7 +1081,9 @@ function StreamingWorkflow() {
The SDK is written in TypeScript and provides full type safety:
-```typescript
+```
+
+typescript
import {
SimStudioClient,
WorkflowExecutionResult,
@@ -969,23 +1091,22 @@ import {
SimStudioError
} from 'simstudio-ts-sdk';
-// Type-safe client initialization
+// Inicialización del cliente con seguridad de tipos
const client: SimStudioClient = new SimStudioClient({
apiKey: process.env.SIM_API_KEY!
});
-// Type-safe workflow execution
+// Ejecución de flujo de trabajo con seguridad de tipos
const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
input: {
message: '¡Hola, TypeScript!'
}
});
-// Type-safe status checking
+// Verificación de estado con seguridad de tipos
const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
```
-## License
-
+## Licencia
Apache-2.0
diff --git a/apps/docs/content/docs/es/triggers/api.mdx b/apps/docs/content/docs/es/triggers/api.mdx
index 09ecda8971..97163e3c1b 100644
--- a/apps/docs/content/docs/es/triggers/api.mdx
+++ b/apps/docs/content/docs/es/triggers/api.mdx
@@ -22,9 +22,17 @@ El disparador de API expone tu flujo de trabajo como un punto de conexión HTTP
/>
-Añade un campo de **Formato de entrada** para cada parámetro. Las claves de salida en tiempo de ejecución reflejan el esquema y también están disponibles bajo ``.
+Añade un campo de **Formato de entrada** para cada parámetro. Tipos admitidos:
-Las ejecuciones manuales en el editor utilizan la columna `value` para que puedas realizar pruebas sin enviar una solicitud. Durante la ejecución, el resolutor completa tanto `` como ``.
+- **string** - Valores de texto
+- **number** - Valores numéricos
+- **boolean** - Valores verdadero/falso
+- **json** - Objetos JSON
+- **files** - Carga de archivos (acceso mediante ``, ``, etc.)
+
+Las claves de salida en tiempo de ejecución reflejan el esquema y están disponibles bajo ``.
+
+Las ejecuciones manuales en el editor utilizan la columna `value` para que puedas realizar pruebas sin enviar una solicitud. Durante la ejecución, el resolutor completa tanto `` como ``.
## Ejemplo de solicitud
@@ -40,7 +48,7 @@ Las respuestas exitosas devuelven el resultado de ejecución serializado del Eje
## Respuestas en streaming
-Habilita el streaming en tiempo real para recibir la salida del flujo de trabajo a medida que se genera, carácter por carácter. Esto es útil para mostrar las respuestas de IA progresivamente a los usuarios.
+Habilita el streaming en tiempo real para recibir la salida del flujo de trabajo a medida que se genera, carácter por carácter. Esto es útil para mostrar respuestas de IA progresivamente a los usuarios.
### Parámetros de solicitud
@@ -51,7 +59,7 @@ Añade estos parámetros para habilitar el streaming:
### Formato de salida de bloque
-Usa el formato `blockName.attribute` para especificar qué salidas de bloques transmitir:
+Utiliza el formato `blockName.attribute` para especificar qué salidas de bloque transmitir:
- Formato: `"blockName.attribute"` (p. ej., si quieres transmitir el contenido del bloque Agente 1, usarías `"agent1.content"`)
- Los nombres de los bloques no distinguen entre mayúsculas y minúsculas y se ignoran los espacios
@@ -86,34 +94,30 @@ data: [DONE]
```
Cada evento incluye:
-- **Fragmentos de streaming**: `{"blockId": "...", "chunk": "text"}` - Texto en tiempo real a medida que se genera
+- **Fragmentos en streaming**: `{"blockId": "...", "chunk": "text"}` - Texto en tiempo real a medida que se genera
- **Evento final**: `{"event": "done", ...}` - Metadatos de ejecución y resultados completos
-- **Terminador**: `[DONE]` - Señala el fin del stream
+- **Terminador**: `[DONE]` - Indica el final del stream
### Streaming de múltiples bloques
Cuando `selectedOutputs` incluye múltiples bloques, cada fragmento indica qué bloque lo produjo:
-```bash
-curl -X POST \
- https://sim.ai/api/workflows/WORKFLOW_ID/execute \
- -H 'Content-Type: application/json' \
- -H 'X-API-Key: YOUR_KEY' \
- -d '{
- "message": "Process this request",
- "stream": true,
- "selectedOutputs": ["agent1.content", "agent2.content"]
- }'
-```
-
-El campo `blockId` en cada fragmento te permite dirigir la salida al elemento de UI correcto:
-
+```json
+{
+ "type": "block",
+ "blockType": "text",
+ "text": "Este es un bloque de texto"
+}
```
-data: {"blockId":"agent1-uuid","chunk":"Processing..."}
-data: {"blockId":"agent2-uuid","chunk":"Analyzing..."}
+El campo `blockId` en cada fragmento te permite dirigir la salida al elemento de interfaz correcto:
-data: {"blockId":"agent1-uuid","chunk":" complete"}
+```json
+{
+ "type": "block",
+ "blockType": "image",
+ "imageUrl": "https://example.com/image.jpg"
+}
```
## Referencia de salida
@@ -121,10 +125,56 @@ data: {"blockId":"agent1-uuid","chunk":" complete"}
| Referencia | Descripción |
|-----------|-------------|
| `` | Campo definido en el formato de entrada |
-| `` | Cuerpo de solicitud estructurado completo |
+| `` | Cuerpo completo de la solicitud estructurada |
+
+### Formato de carga de archivos
+
+La API acepta archivos en dos formatos:
+
+**1. Archivos codificados en Base64** (recomendado para SDKs):
+
+```json
+{
+ "files": [{
+ "name": "example.pdf",
+ "data": "JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvY..."
+ }]
+}
+```
+
+- Tamaño máximo de archivo: 20MB por archivo
+- Los archivos se suben al almacenamiento en la nube y se convierten en objetos UserFile con todas las propiedades
+
+**2. Referencias directas de URL**:
+
+```json
+{
+ "files": [{
+ "url": "https://example.com/document.pdf"
+ }]
+}
+```
+
+- El archivo no se sube, la URL se pasa directamente
+- Útil para referenciar archivos existentes
+
+### Propiedades de archivos
+
+Para archivos, accede a todas las propiedades:
+
+| Propiedad | Descripción | Tipo |
+|----------|-------------|------|
+| `` | URL de descarga firmada | string |
+| `` | Nombre original del archivo | string |
+| `` | Tamaño del archivo en bytes | number |
+| `` | Tipo MIME | string |
+| `` | Marca de tiempo de subida (ISO 8601) | string |
+| `` | Marca de tiempo de caducidad de URL (ISO 8601) | string |
+
+Para archivos referenciados por URL, las mismas propiedades están disponibles excepto `uploadedAt` y `expiresAt` ya que el archivo no se sube a nuestro almacenamiento.
Si no se define un formato de entrada, el ejecutor expone el JSON sin procesar solo en ``.
-Un flujo de trabajo puede contener solo un disparador de API. Publica una nueva implementación después de los cambios para que el endpoint se mantenga actualizado.
+Un flujo de trabajo solo puede contener un disparador de API. Publica una nueva implementación después de los cambios para que el punto de conexión se mantenga actualizado.
diff --git a/apps/docs/content/docs/es/triggers/chat.mdx b/apps/docs/content/docs/es/triggers/chat.mdx
index bfe4da9a7f..000926af9d 100644
--- a/apps/docs/content/docs/es/triggers/chat.mdx
+++ b/apps/docs/content/docs/es/triggers/chat.mdx
@@ -24,20 +24,31 @@ El disparador de Chat crea una interfaz conversacional para tu flujo de trabajo.
El disparador escribe tres campos que los bloques posteriores pueden referenciar:
-| Referencia | Descripción |
-|-----------|-------------|
-| `` | Último mensaje del usuario |
-| `` | ID del hilo de conversación |
-| `` | Archivos subidos opcionales |
+| Referencia | Descripción | Tipo |
+|-----------|-------------|------|
+| `` | Último mensaje del usuario | string |
+| `` | ID del hilo de conversación | string |
+| `` | Archivos subidos opcionales | array de archivos |
-Los archivos incluyen `name`, `mimeType`, y una descarga firmada `url`.
+### Propiedades de archivo
+
+Accede a las propiedades individuales de los archivos usando indexación de arrays:
+
+| Propiedad | Descripción | Tipo |
+|----------|-------------|------|
+| `` | URL de descarga firmada | string |
+| `` | Nombre original del archivo | string |
+| `` | Tamaño del archivo en bytes | number |
+| `` | Tipo MIME | string |
+| `` | Marca de tiempo de subida (ISO 8601) | string |
+| `` | Marca de tiempo de caducidad de la URL (ISO 8601) | string |
## Notas de uso
-1. Añade un bloque de Disparador de Chat por flujo de trabajo.
+1. Añade un bloque de Chat Trigger por flujo de trabajo.
2. Despliega el flujo de trabajo en modo chat.
3. Comparte el enlace de despliegue—cada respuesta reutiliza el ID de conversación para que el flujo de trabajo pueda mantener el contexto.
-El constructor bloquea múltiples bloques de Disparador de Chat en el mismo flujo de trabajo.
+El constructor bloquea múltiples bloques de Chat Trigger en el mismo flujo de trabajo.
diff --git a/apps/docs/content/docs/fr/execution/costs.mdx b/apps/docs/content/docs/fr/execution/costs.mdx
index 7ab7b0099f..ddace38cee 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..8c75e13f7e 100644
--- a/apps/docs/content/docs/fr/sdks/typescript.mdx
+++ b/apps/docs/content/docs/fr/sdks/typescript.mdx
@@ -604,28 +604,114 @@ async function executeClientSideWorkflow() {
});
console.log('Workflow result:', result);
-
+
// Update UI with result
- document.getElementById('result')!.textContent =
+ document.getElementById('result')!.textContent =
JSON.stringify(result.output, null, 2);
} catch (error) {
console.error('Error:', error);
}
}
+```
+
+### Téléchargement de fichier
+
+Les objets File sont automatiquement détectés et convertis au format base64. Incluez-les dans votre entrée sous le nom de champ correspondant au format d'entrée du déclencheur API de votre workflow.
+
+Le SDK convertit les objets File dans ce format :
+
+```typescript
+{
+ type: 'file',
+ data: 'data:mime/type;base64,base64data',
+ name: 'filename',
+ mime: 'mime/type'
+}
+```
+
+Alternativement, vous pouvez fournir manuellement des fichiers en utilisant le format URL :
+
+```typescript
+{
+ type: 'url',
+ data: 'https://example.com/file.pdf',
+ name: 'file.pdf',
+ mime: 'application/pdf'
+}
+```
+
+
+
+
+ ```typescript
+ import { SimStudioClient } from 'simstudio-ts-sdk';
+
+ const client = new SimStudioClient({
+ apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
+ });
+
+ // From file input
+ async function handleFileUpload(event: Event) {
+ const input = event.target as HTMLInputElement;
+ const files = Array.from(input.files || []);
+
+ // Include files under the field name from your API trigger's input format
+ const result = await client.executeWorkflow('workflow-id', {
+ input: {
+ documents: files, // Must match your workflow's "files" field name
+ instructions: 'Analyze these documents'
+ }
+ });
+
+ console.log('Result:', result);
+ }
+ ```
+
+
+
-// Attach to button click
+ ```typescript
+ import { SimStudioClient } from 'simstudio-ts-sdk';
+ import fs from 'fs';
+
+ const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+ });
+
+ // Read file and create File object
+ const fileBuffer = fs.readFileSync('./document.pdf');
+ const file = new File([fileBuffer], 'document.pdf', {
+ type: 'application/pdf'
+ });
+
+ // Include files under the field name from your API trigger's input format
+ const result = await client.executeWorkflow('workflow-id', {
+ input: {
+ documents: [file], // Must match your workflow's "files" field name
+ query: 'Summarize this document'
+ }
+ });
+ ```
+
+
+
+
+// Attacher au clic du bouton
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
+
```
- Lors de l'utilisation du SDK dans le navigateur, veillez à ne pas exposer de clés API sensibles. Envisagez d'utiliser un proxy backend ou des clés API publiques avec des permissions limitées.
+ When using the SDK in the browser, be careful not to expose sensitive API keys. Consider using a backend proxy or public API keys with limited permissions.
-### Exemple de hook React
+### React Hook Example
-Créer un hook React personnalisé pour l'exécution de workflow :
+Create a custom React hook for workflow execution:
-```typescript
+```
+
+typescript
import { useState, useCallback } from 'react';
import { SimStudioClient, WorkflowExecutionResult } from 'simstudio-ts-sdk';
@@ -671,7 +757,7 @@ export function useWorkflow(): UseWorkflowResult {
};
}
-// Usage in component
+// Utilisation dans un composant
function WorkflowComponent() {
const { result, loading, error, executeWorkflow } = useWorkflow();
@@ -684,26 +770,29 @@ function WorkflowComponent() {
return (
- {error &&
Error: {error.message}
}
+ {error &&
Erreur : {error.message}
}
{result && (
-
Result:
+
Résultat :
{JSON.stringify(result, null, 2)}
)}
);
}
+
```
-### Exécution asynchrone de workflow
+### Async Workflow Execution
-Exécuter des workflows de manière asynchrone pour les tâches de longue durée :
+Execute workflows asynchronously for long-running tasks:
-```typescript
+```
+
+typescript
import { SimStudioClient, AsyncExecutionResult } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -712,47 +801,50 @@ const client = new SimStudioClient({
async function executeAsync() {
try {
- // Start async execution
+ // Démarrer l'exécution asynchrone
const result = await client.executeWorkflow('workflow-id', {
input: { data: 'large dataset' },
- async: true // Execute asynchronously
+ async: true // Exécuter de manière asynchrone
});
- // Check if result is an async execution
+ // Vérifier si le résultat est une exécution asynchrone
if ('taskId' in result) {
- console.log('Task ID:', result.taskId);
- console.log('Status endpoint:', result.links.status);
+ console.log('ID de tâche :', result.taskId);
+ console.log('Point de terminaison de statut :', result.links.status);
- // Poll for completion
+ // Interroger pour vérifier l'achèvement
let status = await client.getJobStatus(result.taskId);
while (status.status === 'queued' || status.status === 'processing') {
- console.log('Current status:', status.status);
- await new Promise(resolve => setTimeout(resolve, 2000)); // Wait 2 seconds
+ console.log('Statut actuel :', status.status);
+ await new Promise(resolve => setTimeout(resolve, 2000)); // Attendre 2 secondes
status = await client.getJobStatus(result.taskId);
}
if (status.status === 'completed') {
- console.log('Workflow completed!');
- console.log('Output:', status.output);
- console.log('Duration:', status.metadata.duration);
+ console.log('Workflow terminé !');
+ console.log('Sortie :', status.output);
+ console.log('Durée :', status.metadata.duration);
} else {
- console.error('Workflow failed:', status.error);
+ console.error('Échec du workflow :', status.error);
}
}
} catch (error) {
- console.error('Error:', error);
+ console.error('Erreur :', error);
}
}
executeAsync();
+
```
-### Limitation de débit et nouvelle tentative
+### Rate Limiting and Retry
-Gérer automatiquement les limites de débit avec backoff exponentiel :
+Handle rate limits automatically with exponential backoff:
-```typescript
+```
+
+typescript
import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -761,7 +853,7 @@ const client = new SimStudioClient({
async function executeWithRetryHandling() {
try {
- // Automatically retries on rate limit
+ // Réessaie automatiquement en cas de limite de débit
const result = await client.executeWithRetry('workflow-id', {
input: { message: 'Process this' }
}, {
@@ -771,26 +863,29 @@ async function executeWithRetryHandling() {
backoffMultiplier: 2
});
- console.log('Success:', result);
+ console.log('Succès :', result);
} catch (error) {
if (error instanceof SimStudioError && error.code === 'RATE_LIMIT_EXCEEDED') {
- console.error('Rate limit exceeded after all retries');
+ console.error('Limite de débit dépassée après toutes les tentatives');
- // Check rate limit info
+ // Vérifier les informations de limite de débit
const rateLimitInfo = client.getRateLimitInfo();
if (rateLimitInfo) {
- console.log('Rate limit resets at:', new Date(rateLimitInfo.reset * 1000));
+ console.log('La limite de débit se réinitialise à :', new Date(rateLimitInfo.reset * 1000));
}
}
}
}
+
```
-### Surveillance d'utilisation
+### Usage Monitoring
-Surveiller l'utilisation et les limites de votre compte :
+Monitor your account usage and limits:
-```typescript
+```
+
+typescript
import { SimStudioClient } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -801,27 +896,46 @@ async function checkUsage() {
try {
const limits = await client.getUsageLimits();
- console.log('=== Rate Limits ===');
- console.log('Sync requests:');
- console.log(' Limit:', limits.rateLimit.sync.limit);
- console.log(' Remaining:', limits.rateLimit.sync.remaining);
- console.log(' Resets at:', limits.rateLimit.sync.resetAt);
- console.log(' Is limited:', limits.rateLimit.sync.isLimited);
+ console.log('=== Limites de débit ===');
+ console.log('Requêtes synchrones :');
+ console.log(' Limite :', limits.rateLimit.sync.limit);
+ console.log(' Restant :', limits.rateLimit.sync.remaining);
+ console.log(' Réinitialisation à :', limits.rateLimit.sync.resetAt);
+ console.log(' Est limité :', limits.rateLimit.sync.isLimited);
+
+ console.log('\nRequêtes asynchrones :');
+ console.log(' Limite :', limits.rateLimit.async.limit);
+ console.log(' Restant :', limits.rateLimit.async.remaining);
+ console.log(' Réinitialisation à :', limits.rateLimit.async.resetAt);
+ console.log(' Est limité :', limits.rateLimit.async.isLimited);
+
+ console.log('\n=== Utilisation ===');
+ console.log('Coût de la période actuelle : ' + limits.usage.currentPeriodCost.toFixed(2) + ' €');
+ console.log('Limite : ' + limits.usage.limit.toFixed(2) + ' €');
+ console.log('Forfait :', limits.usage.plan);
+
+ const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100;
+ console.log('Utilisation : ' + percentUsed.toFixed(1) + ' %');
+
+ if (percentUsed > 80) {
+ console.warn('⚠️ Attention : vous approchez de votre limite d'utilisation !');
+ }
+ } catch (error) {
+ console.error('Erreur lors de la vérification de l'utilisation :', error);
+ }
+}
- console.log('\nAsync requests:');
- console.log(' Limit:', limits.rateLimit.async.limit);
- console.log(' Remaining:', limits.rateLimit.async.remaining);
- console.log(' Resets at:', limits.rateLimit.async.resetAt);
- console.log(' Is limited:', limits.rateLimit.async.isLimited);
+checkUsage();
- console.log('\n=== Usage ===');
- console.log('Current period cost:
+```
### Streaming Workflow Execution
Execute workflows with real-time streaming responses:
-```typescript
+```
+
+typescript
import { SimStudioClient } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
@@ -842,23 +956,28 @@ 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":"Un"}
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() {
@@ -869,16 +988,16 @@ function StreamingWorkflow() {
setLoading(true);
setOutput('');
- // IMPORTANT: Make this API call from your backend server, not the browser
- // Never expose your API key in client-side code
+ // IMPORTANT : Effectuez cet appel API depuis votre serveur backend, pas depuis le navigateur
+ // N'exposez jamais votre clé API dans le code côté client
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
+ 'X-API-Key': process.env.SIM_API_KEY! // Variable d'environnement côté serveur uniquement
},
body: JSON.stringify({
- message: 'Generate a story',
+ message: 'Générer une histoire',
stream: true,
selectedOutputs: ['agent1.content']
})
@@ -907,10 +1026,10 @@ function StreamingWorkflow() {
if (parsed.chunk) {
setOutput(prev => prev + parsed.chunk);
} else if (parsed.event === 'done') {
- console.log('Execution complete:', parsed.metadata);
+ console.log('Exécution terminée :', parsed.metadata);
}
} catch (e) {
- // Skip invalid JSON
+ // Ignorer le JSON invalide
}
}
}
@@ -926,6 +1045,7 @@ function StreamingWorkflow() {
);
}
+
```
## Getting Your API Key
@@ -961,7 +1081,9 @@ function StreamingWorkflow() {
The SDK is written in TypeScript and provides full type safety:
-```typescript
+```
+
+typescript
import {
SimStudioClient,
WorkflowExecutionResult,
@@ -969,23 +1091,22 @@ import {
SimStudioError
} from 'simstudio-ts-sdk';
-// Type-safe client initialization
+// Initialisation du client avec typage
const client: SimStudioClient = new SimStudioClient({
apiKey: process.env.SIM_API_KEY!
});
-// Type-safe workflow execution
+// Exécution de workflow avec typage
const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
input: {
message: 'Bonjour, TypeScript !'
}
});
-// Type-safe status checking
+// Vérification de statut avec typage
const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
```
-## License
-
+## Licence
Apache-2.0
diff --git a/apps/docs/content/docs/fr/triggers/api.mdx b/apps/docs/content/docs/fr/triggers/api.mdx
index 978ec55610..fa95fb0fb6 100644
--- a/apps/docs/content/docs/fr/triggers/api.mdx
+++ b/apps/docs/content/docs/fr/triggers/api.mdx
@@ -22,9 +22,17 @@ Le déclencheur d'API expose votre flux de travail en tant que point de terminai
/>
-Ajoutez un champ **Format d'entrée** pour chaque paramètre. Les clés de sortie d'exécution reflètent le schéma et sont également disponibles sous ``.
+Ajoutez un champ **Format d'entrée** pour chaque paramètre. Types pris en charge :
-Les exécutions manuelles dans l'éditeur utilisent la colonne `value` pour que vous puissiez tester sans envoyer de requête. Pendant l'exécution, le résolveur remplit à la fois `` et ``.
+- **string** - Valeurs textuelles
+- **number** - Valeurs numériques
+- **boolean** - Valeurs vrai/faux
+- **json** - Objets JSON
+- **files** - Téléchargements de fichiers (accès via ``, ``, etc.)
+
+Les clés de sortie d'exécution reflètent le schéma et sont disponibles sous ``.
+
+Les exécutions manuelles dans l'éditeur utilisent la colonne `value` pour que vous puissiez tester sans envoyer de requête. Pendant l'exécution, le résolveur remplit à la fois `` et ``.
## Exemple de requête
@@ -36,23 +44,23 @@ curl -X POST \
-d '{"userId":"demo-user","maxTokens":1024}'
```
-Les réponses réussies renvoient le résultat d'exécution sérialisé de l'exécuteur. Les erreurs révèlent des problèmes de validation, d'authentification ou d'échec du workflow.
+Les réponses réussies renvoient le résultat d'exécution sérialisé de l'Exécuteur. Les erreurs révèlent des problèmes de validation, d'authentification ou d'échec de workflow.
## Réponses en streaming
-Activez le streaming en temps réel pour recevoir les résultats du workflow au fur et à mesure qu'ils sont générés, caractère par caractère. Cela est utile pour afficher progressivement les réponses de l'IA aux utilisateurs.
+Activez le streaming en temps réel pour recevoir la sortie du workflow au fur et à mesure qu'elle est générée, caractère par caractère. Cela est utile pour afficher progressivement les réponses d'IA aux utilisateurs.
### Paramètres de requête
Ajoutez ces paramètres pour activer le streaming :
- `stream` - Définissez à `true` pour activer le streaming Server-Sent Events (SSE)
-- `selectedOutputs` - Tableau des sorties de blocs à diffuser en streaming (par exemple, `["agent1.content"]`)
+- `selectedOutputs` - Tableau des sorties de bloc à diffuser en streaming (par ex., `["agent1.content"]`)
### Format de sortie de bloc
-Utilisez le format `blockName.attribute` pour spécifier quelles sorties de blocs diffuser en streaming :
-- Format : `"blockName.attribute"` (par exemple, si vous souhaitez diffuser en streaming le contenu du bloc Agent 1, vous utiliseriez `"agent1.content"`)
+Utilisez le format `blockName.attribute` pour spécifier quelles sorties de bloc diffuser en streaming :
+- Format : `"blockName.attribute"` (par ex., si vous souhaitez diffuser le contenu du bloc Agent 1, vous utiliseriez `"agent1.content"`)
- Les noms de blocs ne sont pas sensibles à la casse et les espaces sont ignorés
### Exemple de requête
@@ -85,8 +93,8 @@ data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
data: [DONE]
```
-Chaque événement comprend :
-- **Fragments en streaming** : `{"blockId": "...", "chunk": "text"}` - Texte en temps réel au fur et à mesure qu'il est généré
+Chaque événement inclut :
+- **Fragments en streaming** : `{"blockId": "...", "chunk": "text"}` - Texte en temps réel au fur et à mesure de sa génération
- **Événement final** : `{"event": "done", ...}` - Métadonnées d'exécution et résultats complets
- **Terminateur** : `[DONE]` - Signale la fin du flux
@@ -94,26 +102,22 @@ Chaque événement comprend :
Lorsque `selectedOutputs` inclut plusieurs blocs, chaque fragment indique quel bloc l'a produit :
-```bash
-curl -X POST \
- https://sim.ai/api/workflows/WORKFLOW_ID/execute \
- -H 'Content-Type: application/json' \
- -H 'X-API-Key: YOUR_KEY' \
- -d '{
- "message": "Process this request",
- "stream": true,
- "selectedOutputs": ["agent1.content", "agent2.content"]
- }'
+```json
+{
+ "type": "block",
+ "blockType": "text",
+ "text": "Voici une réponse en streaming"
+}
```
Le champ `blockId` dans chaque fragment vous permet d'acheminer la sortie vers l'élément d'interface utilisateur approprié :
-```
-data: {"blockId":"agent1-uuid","chunk":"Processing..."}
-
-data: {"blockId":"agent2-uuid","chunk":"Analyzing..."}
-
-data: {"blockId":"agent1-uuid","chunk":" complete"}
+```json
+{
+ "type": "block",
+ "blockType": "code",
+ "text": "console.log('Ceci est un bloc de code');"
+}
```
## Référence des sorties
@@ -121,10 +125,57 @@ data: {"blockId":"agent1-uuid","chunk":" complete"}
| Référence | Description |
|-----------|-------------|
| `` | Champ défini dans le format d'entrée |
-| `` | Corps de requête structuré complet |
+| `` | Corps complet de la requête structurée |
+
+### Format de téléchargement de fichiers
+
+L'API accepte les fichiers dans deux formats :
+
+**1. Fichiers encodés en Base64** (recommandé pour les SDK) :
+
+```json
+{
+ "file": {
+ "data": "data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp...",
+ "name": "document.pdf"
+ }
+}
+```
+
+- Taille maximale de fichier : 20 Mo par fichier
+- Les fichiers sont téléchargés vers le stockage cloud et convertis en objets UserFile avec toutes les propriétés
+
+**2. Références directes par URL** :
+
+```json
+{
+ "file": {
+ "url": "https://example.com/document.pdf",
+ "name": "document.pdf"
+ }
+}
+```
+
+- Le fichier n'est pas téléchargé, l'URL est transmise directement
+- Utile pour référencer des fichiers existants
+
+### Propriétés des fichiers
+
+Pour les fichiers, accédez à toutes les propriétés :
+
+| Propriété | Description | Type |
+|----------|-------------|------|
+| `` | URL de téléchargement signée | chaîne |
+| `` | Nom de fichier original | chaîne |
+| `` | Taille du fichier en octets | nombre |
+| `` | Type MIME | chaîne |
+| `` | Horodatage du téléchargement (ISO 8601) | chaîne |
+| `` | Horodatage d'expiration de l'URL (ISO 8601) | chaîne |
+
+Pour les fichiers référencés par URL, les mêmes propriétés sont disponibles à l'exception de `uploadedAt` et `expiresAt` puisque le fichier n'est pas téléchargé dans notre stockage.
Si aucun format d'entrée n'est défini, l'exécuteur expose uniquement le JSON brut à ``.
-Un workflow ne peut contenir qu'un seul déclencheur API. Publiez un nouveau déploiement après les modifications pour que le point de terminaison reste à jour.
+Un flux de travail ne peut contenir qu'un seul déclencheur d'API. Publiez un nouveau déploiement après les modifications pour que le point de terminaison reste à jour.
diff --git a/apps/docs/content/docs/fr/triggers/chat.mdx b/apps/docs/content/docs/fr/triggers/chat.mdx
index 56f04cb022..b7bc78122a 100644
--- a/apps/docs/content/docs/fr/triggers/chat.mdx
+++ b/apps/docs/content/docs/fr/triggers/chat.mdx
@@ -24,20 +24,31 @@ Le déclencheur de chat crée une interface conversationnelle pour votre flux de
Le déclencheur écrit trois champs que les blocs en aval peuvent référencer :
-| Référence | Description |
-|-----------|-------------|
-| `` | Dernier message de l'utilisateur |
-| `` | ID du fil de conversation |
-| `` | Fichiers téléchargés optionnels |
+| Référence | Description | Type |
+|-----------|-------------|------|
+| `` | Dernier message de l'utilisateur | string |
+| `` | ID du fil de conversation | string |
+| `` | Fichiers téléchargés optionnels | tableau de fichiers |
-Les fichiers incluent `name`, `mimeType`, et un `url` signé.
+### Propriétés des fichiers
+
+Accédez aux propriétés individuelles des fichiers en utilisant l'indexation de tableau :
+
+| Propriété | Description | Type |
+|----------|-------------|------|
+| `` | URL de téléchargement signée | string |
+| `` | Nom de fichier original | string |
+| `` | Taille du fichier en octets | number |
+| `` | Type MIME | string |
+| `` | Horodatage du téléchargement (ISO 8601) | string |
+| `` | Horodatage d'expiration de l'URL (ISO 8601) | string |
## Notes d'utilisation
-1. Ajoutez un bloc Déclencheur de chat par flux de travail.
-2. Déployez le flux de travail en mode chat.
-3. Partagez le lien de déploiement — chaque réponse réutilise l'ID de conversation pour que le flux de travail puisse conserver le contexte.
+1. Ajoutez un bloc Déclencheur de chat par workflow.
+2. Déployez le workflow en mode chat.
+3. Partagez le lien de déploiement — chaque réponse réutilise l'ID de conversation pour que le workflow puisse conserver le contexte.
-Le constructeur bloque plusieurs blocs Déclencheur de chat dans le même flux de travail.
+Le constructeur bloque plusieurs blocs Déclencheur de chat dans le même workflow.
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..cdb30b3869 100644
--- a/apps/docs/content/docs/ja/sdks/typescript.mdx
+++ b/apps/docs/content/docs/ja/sdks/typescript.mdx
@@ -604,28 +604,114 @@ async function executeClientSideWorkflow() {
});
console.log('Workflow result:', result);
-
+
// Update UI with result
- document.getElementById('result')!.textContent =
+ document.getElementById('result')!.textContent =
JSON.stringify(result.output, null, 2);
} catch (error) {
console.error('Error:', error);
}
}
+```
+
+### ファイルアップロード
+
+ファイルオブジェクトは自動的に検出され、base64形式に変換されます。ワークフローのAPIトリガー入力形式に一致するフィールド名で入力に含めてください。
+
+SDKはファイルオブジェクトを次の形式に変換します:
+
+```typescript
+{
+ type: 'file',
+ data: 'data:mime/type;base64,base64data',
+ name: 'filename',
+ mime: 'mime/type'
+}
+```
+
+または、URL形式を使用して手動でファイルを提供することもできます:
+
+```typescript
+{
+ type: 'url',
+ data: 'https://example.com/file.pdf',
+ name: 'file.pdf',
+ mime: 'application/pdf'
+}
+```
+
+
+
+
+ ```typescript
+ import { SimStudioClient } from 'simstudio-ts-sdk';
+
+ const client = new SimStudioClient({
+ apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
+ });
+
+ // From file input
+ async function handleFileUpload(event: Event) {
+ const input = event.target as HTMLInputElement;
+ const files = Array.from(input.files || []);
+
+ // Include files under the field name from your API trigger's input format
+ const result = await client.executeWorkflow('workflow-id', {
+ input: {
+ documents: files, // Must match your workflow's "files" field name
+ instructions: 'Analyze these documents'
+ }
+ });
+
+ console.log('Result:', result);
+ }
+ ```
+
+
+
-// Attach to button click
+ ```typescript
+ import { SimStudioClient } from 'simstudio-ts-sdk';
+ import fs from 'fs';
+
+ const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+ });
+
+ // Read file and create File object
+ const fileBuffer = fs.readFileSync('./document.pdf');
+ const file = new File([fileBuffer], 'document.pdf', {
+ type: 'application/pdf'
+ });
+
+ // Include files under the field name from your API trigger's input format
+ const result = await client.executeWorkflow('workflow-id', {
+ input: {
+ documents: [file], // Must match your workflow's "files" field name
+ query: 'Summarize this document'
+ }
+ });
+ ```
+
+
+
+
+// ボタンクリックに接続
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
+
```
- ブラウザでSDKを使用する場合、機密性の高いAPIキーを公開しないよう注意してください。バックエンドプロキシや権限が制限された公開APIキーの使用を検討してください。
+ When using the SDK in the browser, be careful not to expose sensitive API keys. Consider using a backend proxy or public API keys with limited permissions.
-### Reactフックの例
+### React Hook Example
-ワークフロー実行用のカスタムReactフックを作成:
+Create a custom React hook for workflow execution:
-```typescript
+```
+
+typescript
import { useState, useCallback } from 'react';
import { SimStudioClient, WorkflowExecutionResult } from 'simstudio-ts-sdk';
@@ -671,7 +757,7 @@ export function useWorkflow(): UseWorkflowResult {
};
}
-// Usage in component
+// コンポーネントでの使用
function WorkflowComponent() {
const { result, loading, error, executeWorkflow } = useWorkflow();
@@ -684,26 +770,29 @@ function WorkflowComponent() {
return (