diff --git a/apps/docs/content/docs/de/sdks/python.mdx b/apps/docs/content/docs/de/sdks/python.mdx
index cb07899431..368010f430 100644
--- a/apps/docs/content/docs/de/sdks/python.mdx
+++ b/apps/docs/content/docs/de/sdks/python.mdx
@@ -10,7 +10,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
Das offizielle Python SDK für Sim ermöglicht es Ihnen, Workflows programmatisch aus Ihren Python-Anwendungen mithilfe des offiziellen Python SDKs auszuführen.
- Das Python SDK unterstützt Python 3.8+ und bietet synchrone Workflow-Ausführung. Alle Workflow-Ausführungen sind derzeit synchron.
+ Das Python SDK unterstützt Python 3.8+ mit asynchroner Ausführungsunterstützung, automatischer Ratenbegrenzung mit exponentiellem Backoff und Nutzungsverfolgung.
## Installation
@@ -74,12 +74,17 @@ result = client.execute_workflow(
- `workflow_id` (str): Die ID des auszuführenden Workflows
- `input_data` (dict, optional): Eingabedaten, die an den Workflow übergeben werden
- `timeout` (float, optional): Timeout in Sekunden (Standard: 30.0)
+- `stream` (bool, optional): Streaming-Antworten aktivieren (Standard: False)
+- `selected_outputs` (list[str], optional): Block-Ausgaben, die im `blockName.attribute`Format gestreamt werden sollen (z.B. `["agent1.content"]`)
+- `async_execution` (bool, optional): Asynchron ausführen (Standard: False)
-**Rückgabewert:** `WorkflowExecutionResult`
+**Rückgabe:** `WorkflowExecutionResult | AsyncExecutionResult`
+
+Wenn `async_execution=True`, wird sofort mit einer Task-ID zum Abfragen zurückgegeben. Andernfalls wird auf den Abschluss gewartet.
##### get_workflow_status()
-Ruft den Status eines Workflows ab (Deployment-Status usw.).
+Den Status eines Workflows abrufen (Bereitstellungsstatus usw.).
```python
status = client.get_workflow_status("workflow-id")
@@ -93,7 +98,7 @@ print("Is deployed:", status.is_deployed)
##### validate_workflow()
-Überprüft, ob ein Workflow für die Ausführung bereit ist.
+Überprüfen, ob ein Workflow für die Ausführung bereit ist.
```python
is_ready = client.validate_workflow("workflow-id")
@@ -107,28 +112,118 @@ if is_ready:
**Rückgabe:** `bool`
-##### execute_workflow_sync()
+##### get_job_status()
-
- Derzeit ist diese Methode identisch mit `execute_workflow()`, da alle Ausführungen synchron sind. Diese Methode wird für zukünftige Kompatibilität bereitgestellt, wenn asynchrone Ausführung hinzugefügt wird.
-
+Den Status einer asynchronen Job-Ausführung abrufen.
+
+```python
+status = client.get_job_status("task-id-from-async-execution")
+print("Status:", status["status"]) # 'queued', 'processing', 'completed', 'failed'
+if status["status"] == "completed":
+ print("Output:", status["output"])
+```
+
+**Parameter:**
+- `task_id` (str): Die Task-ID, die von der asynchronen Ausführung zurückgegeben wurde
+
+**Rückgabe:** `Dict[str, Any]`
-Führt einen Workflow aus (derzeit synchron, identisch mit `execute_workflow()`).
+**Antwortfelder:**
+- `success` (bool): Ob die Anfrage erfolgreich war
+- `taskId` (str): Die Task-ID
+- `status` (str): Einer der Werte `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
+- `metadata` (dict): Enthält `startedAt`, `completedAt` und `duration`
+- `output` (any, optional): Die Workflow-Ausgabe (wenn abgeschlossen)
+- `error` (any, optional): Fehlerdetails (wenn fehlgeschlagen)
+- `estimatedDuration` (int, optional): Geschätzte Dauer in Millisekunden (wenn in Bearbeitung/in Warteschlange)
+
+##### execute_with_retry()
+
+Einen Workflow mit automatischer Wiederholung bei Ratenbegrenzungsfehlern unter Verwendung von exponentiellem Backoff ausführen.
```python
-result = client.execute_workflow_sync(
+result = client.execute_with_retry(
"workflow-id",
- input_data={"data": "some input"},
- timeout=60.0
+ input_data={"message": "Hello"},
+ timeout=30.0,
+ max_retries=3, # Maximum number of retries
+ initial_delay=1.0, # Initial delay in seconds
+ max_delay=30.0, # Maximum delay in seconds
+ backoff_multiplier=2.0 # Exponential backoff multiplier
)
```
**Parameter:**
- `workflow_id` (str): Die ID des auszuführenden Workflows
- `input_data` (dict, optional): Eingabedaten, die an den Workflow übergeben werden
-- `timeout` (float): Timeout für die initiale Anfrage in Sekunden
+- `timeout` (float, optional): Timeout in Sekunden
+- `stream` (bool, optional): Streaming-Antworten aktivieren
+- `selected_outputs` (list, optional): Block-Ausgaben zum Streamen
+- `async_execution` (bool, optional): Asynchron ausführen
+- `max_retries` (int, optional): Maximale Anzahl von Wiederholungen (Standard: 3)
+- `initial_delay` (float, optional): Anfängliche Verzögerung in Sekunden (Standard: 1.0)
+- `max_delay` (float, optional): Maximale Verzögerung in Sekunden (Standard: 30.0)
+- `backoff_multiplier` (float, optional): Backoff-Multiplikator (Standard: 2.0)
+
+**Rückgabewert:** `WorkflowExecutionResult | AsyncExecutionResult`
+
+Die Wiederholungslogik verwendet exponentielles Backoff (1s → 2s → 4s → 8s...) mit ±25% Jitter, um den Thundering-Herd-Effekt zu vermeiden. Wenn die API einen `retry-after` Header bereitstellt, wird dieser stattdessen verwendet.
+
+##### get_rate_limit_info()
+
+Ruft die aktuellen Rate-Limit-Informationen aus der letzten API-Antwort ab.
+
+```python
+rate_limit_info = client.get_rate_limit_info()
+if rate_limit_info:
+ print("Limit:", rate_limit_info.limit)
+ print("Remaining:", rate_limit_info.remaining)
+ print("Reset:", datetime.fromtimestamp(rate_limit_info.reset))
+```
-**Rückgabe:** `WorkflowExecutionResult`
+**Rückgabewert:** `RateLimitInfo | None`
+
+##### get_usage_limits()
+
+Ruft aktuelle Nutzungslimits und Kontingentinformationen für dein Konto ab.
+
+```python
+limits = client.get_usage_limits()
+print("Sync requests remaining:", limits.rate_limit["sync"]["remaining"])
+print("Async requests remaining:", limits.rate_limit["async"]["remaining"])
+print("Current period cost:", limits.usage["currentPeriodCost"])
+print("Plan:", limits.usage["plan"])
+```
+
+**Rückgabewert:** `UsageLimits`
+
+**Antwortstruktur:**
+
+```python
+{
+ "success": bool,
+ "rateLimit": {
+ "sync": {
+ "isLimited": bool,
+ "limit": int,
+ "remaining": int,
+ "resetAt": str
+ },
+ "async": {
+ "isLimited": bool,
+ "limit": int,
+ "remaining": int,
+ "resetAt": str
+ },
+ "authType": str # 'api' or 'manual'
+ },
+ "usage": {
+ "currentPeriodCost": float,
+ "limit": float,
+ "plan": str # e.g., 'free', 'pro'
+ }
+}
+```
##### set_api_key()
@@ -170,6 +265,18 @@ class WorkflowExecutionResult:
total_duration: Optional[float] = None
```
+### AsyncExecutionResult
+
+```python
+@dataclass
+class AsyncExecutionResult:
+ success: bool
+ task_id: str
+ status: str # 'queued'
+ created_at: str
+ links: Dict[str, str] # e.g., {"status": "/api/jobs/{taskId}"}
+```
+
### WorkflowStatus
```python
@@ -181,6 +288,27 @@ class WorkflowStatus:
needs_redeployment: bool = False
```
+### RateLimitInfo
+
+```python
+@dataclass
+class RateLimitInfo:
+ limit: int
+ remaining: int
+ reset: int
+ retry_after: Optional[int] = None
+```
+
+### UsageLimits
+
+```python
+@dataclass
+class UsageLimits:
+ success: bool
+ rate_limit: Dict[str, Any]
+ usage: Dict[str, Any]
+```
+
### SimStudioError
```python
@@ -191,6 +319,13 @@ class SimStudioError(Exception):
self.status = status
```
+**Häufige Fehlercodes:**
+- `UNAUTHORIZED`: Ungültiger API-Schlüssel
+- `TIMEOUT`: Zeitüberschreitung bei der Anfrage
+- `RATE_LIMIT_EXCEEDED`: Ratengrenze überschritten
+- `USAGE_LIMIT_EXCEEDED`: Nutzungsgrenze überschritten
+- `EXECUTION_ERROR`: Workflow-Ausführung fehlgeschlagen
+
## Beispiele
### Grundlegende Workflow-Ausführung
@@ -252,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:
@@ -279,16 +414,7 @@ def execute_with_error_handling():
Verwenden Sie den Client als Kontextmanager, um die Ressourcenbereinigung automatisch zu handhaben:
-```python
-from simstudio import SimStudioClient
-import os
-
-# Using context manager to automatically close the session
-with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
- result = client.execute_workflow("workflow-id")
- print("Result:", result)
-# Session is automatically closed here
-```
+---CODE-PLACEHOLDER-ef99d3dd509e04865d5b6b0e0e03d3f8---
### Batch-Workflow-Ausführung
@@ -298,7 +424,7 @@ Führen Sie mehrere Workflows effizient 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_workflows_batch(workflow_data_pairs):
"""Execute multiple workflows with different input data."""
@@ -339,9 +465,233 @@ for result in results:
print(f"Workflow {result['workflow_id']}: {'Success' if result['success'] else 'Failed'}")
```
+### Asynchrone Workflow-Ausführung
+
+Führen Sie Workflows asynchron für lang laufende Aufgaben aus:
+
+```python
+import os
+import time
+from simstudio import SimStudioClient
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_async():
+ try:
+ # Start async execution
+ result = client.execute_workflow(
+ "workflow-id",
+ input_data={"data": "large dataset"},
+ async_execution=True # Execute asynchronously
+ )
+
+ # Check if result is an async execution
+ if hasattr(result, 'task_id'):
+ print(f"Task ID: {result.task_id}")
+ print(f"Status endpoint: {result.links['status']}")
+
+ # Poll for completion
+ status = client.get_job_status(result.task_id)
+
+ while status["status"] in ["queued", "processing"]:
+ print(f"Current status: {status['status']}")
+ time.sleep(2) # Wait 2 seconds
+ status = client.get_job_status(result.task_id)
+
+ if status["status"] == "completed":
+ print("Workflow completed!")
+ print(f"Output: {status['output']}")
+ print(f"Duration: {status['metadata']['duration']}")
+ else:
+ print(f"Workflow failed: {status['error']}")
+
+ except Exception as error:
+ print(f"Error: {error}")
+
+execute_async()
+```
+
+### Rate-Limiting und Wiederholungsversuche
+
+Behandle Rate-Limits automatisch mit exponentiellem Backoff:
+
+```python
+import os
+from simstudio import SimStudioClient, SimStudioError
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_with_retry_handling():
+ try:
+ # Automatically retries on rate limit
+ result = client.execute_with_retry(
+ "workflow-id",
+ input_data={"message": "Process this"},
+ max_retries=5,
+ initial_delay=1.0,
+ max_delay=60.0,
+ backoff_multiplier=2.0
+ )
+
+ print(f"Success: {result}")
+ except SimStudioError as error:
+ if error.code == "RATE_LIMIT_EXCEEDED":
+ print("Rate limit exceeded after all retries")
+
+ # Check rate limit info
+ rate_limit_info = client.get_rate_limit_info()
+ if rate_limit_info:
+ from datetime import datetime
+ reset_time = datetime.fromtimestamp(rate_limit_info.reset)
+ print(f"Rate limit resets at: {reset_time}")
+
+execute_with_retry_handling()
+```
+
+### Nutzungsüberwachung
+
+Überwache deine Kontonutzung und -limits:
+
+```python
+import os
+from simstudio import SimStudioClient
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def check_usage():
+ try:
+ limits = client.get_usage_limits()
+
+ print("=== Rate Limits ===")
+ print("Sync requests:")
+ print(f" Limit: {limits.rate_limit['sync']['limit']}")
+ print(f" Remaining: {limits.rate_limit['sync']['remaining']}")
+ print(f" Resets at: {limits.rate_limit['sync']['resetAt']}")
+ print(f" Is limited: {limits.rate_limit['sync']['isLimited']}")
+
+ print("\nAsync requests:")
+ print(f" Limit: {limits.rate_limit['async']['limit']}")
+ print(f" Remaining: {limits.rate_limit['async']['remaining']}")
+ print(f" Resets at: {limits.rate_limit['async']['resetAt']}")
+ print(f" Is limited: {limits.rate_limit['async']['isLimited']}")
+
+ print("\n=== Usage ===")
+ print(f"Current period cost: ${limits.usage['currentPeriodCost']:.2f}")
+ print(f"Limit: ${limits.usage['limit']:.2f}")
+ print(f"Plan: {limits.usage['plan']}")
+
+ percent_used = (limits.usage['currentPeriodCost'] / limits.usage['limit']) * 100
+ print(f"Usage: {percent_used:.1f}%")
+
+ if percent_used > 80:
+ print("⚠️ Warning: You are approaching your usage limit!")
+
+ except Exception as error:
+ print(f"Error checking usage: {error}")
+
+check_usage()
+```
+
+### Streaming-Workflow-Ausführung
+
+Führe Workflows mit Echtzeit-Streaming-Antworten aus:
+
+```python
+from simstudio import SimStudioClient
+import os
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_with_streaming():
+ """Execute workflow with streaming enabled."""
+ try:
+ # Enable streaming for specific block outputs
+ result = client.execute_workflow(
+ "workflow-id",
+ input_data={"message": "Count to five"},
+ stream=True,
+ selected_outputs=["agent1.content"] # Use blockName.attribute format
+ )
+
+ print("Workflow result:", result)
+ except Exception as error:
+ print("Error:", error)
+
+execute_with_streaming()
+```
+
+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]
+```
+
+**Flask-Streaming-Beispiel:**
+
+```python
+from flask import Flask, Response, stream_with_context
+import requests
+import json
+import os
+
+app = Flask(__name__)
+
+@app.route('/stream-workflow')
+def stream_workflow():
+ """Stream workflow execution to the client."""
+
+ def generate():
+ response = requests.post(
+ 'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
+ headers={
+ 'Content-Type': 'application/json',
+ 'X-API-Key': os.getenv('SIM_API_KEY')
+ },
+ json={
+ 'message': 'Generate a story',
+ 'stream': True,
+ 'selectedOutputs': ['agent1.content']
+ },
+ stream=True
+ )
+
+ for line in response.iter_lines():
+ if line:
+ decoded_line = line.decode('utf-8')
+ if decoded_line.startswith('data: '):
+ data = decoded_line[6:] # Remove 'data: ' prefix
+
+ if data == '[DONE]':
+ break
+
+ try:
+ parsed = json.loads(data)
+ if 'chunk' in parsed:
+ yield f"data: {json.dumps(parsed)}\n\n"
+ elif parsed.get('event') == 'done':
+ yield f"data: {json.dumps(parsed)}\n\n"
+ print("Execution complete:", parsed.get('metadata'))
+ except json.JSONDecodeError:
+ pass
+
+ return Response(
+ stream_with_context(generate()),
+ mimetype='text/event-stream'
+ )
+
+if __name__ == '__main__':
+ app.run(debug=True)
+```
+
### Umgebungskonfiguration
-Konfigurieren Sie den Client mit Umgebungsvariablen:
+Konfiguriere den Client mit Umgebungsvariablen:
@@ -352,7 +702,7 @@ Konfigurieren Sie den Client mit Umgebungsvariablen:
# Development configuration
client = SimStudioClient(
- api_key=os.getenv("SIM_API_KEY"),
+ api_key=os.getenv("SIM_API_KEY")
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
)
```
@@ -382,19 +732,19 @@ Konfigurieren Sie den Client mit Umgebungsvariablen:
- Navigieren Sie zu [Sim](https://sim.ai) und melden Sie sich bei Ihrem Konto an.
+ Navigiere zu [Sim](https://sim.ai) und melde dich bei deinem Konto an.
-
- Navigieren Sie zu dem Workflow, den Sie programmatisch ausführen möchten.
+
+ Navigiere zu dem Workflow, den du programmatisch ausführen möchtest.
-
- Klicken Sie auf "Deploy", um Ihren Workflow bereitzustellen, falls dies noch nicht geschehen ist.
+
+ Klicke auf "Deploy", um deinen Workflow zu deployen, falls dies noch nicht geschehen ist.
-
- Wählen Sie während des Bereitstellungsprozesses einen API-Schlüssel aus oder erstellen Sie einen neuen.
+
+ Wähle während des Deployment-Prozesses einen API-Schlüssel aus oder erstelle einen neuen.
-
- Kopieren Sie den API-Schlüssel zur Verwendung in Ihrer Python-Anwendung.
+
+ Kopiere den API-Schlüssel zur Verwendung in deiner Python-Anwendung.
diff --git a/apps/docs/content/docs/de/sdks/typescript.mdx b/apps/docs/content/docs/de/sdks/typescript.mdx
index c25c2843e3..55e36ce7e2 100644
--- a/apps/docs/content/docs/de/sdks/typescript.mdx
+++ b/apps/docs/content/docs/de/sdks/typescript.mdx
@@ -7,10 +7,10 @@ import { Card, Cards } from 'fumadocs-ui/components/card'
import { Step, Steps } from 'fumadocs-ui/components/steps'
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
-Das offizielle TypeScript/JavaScript SDK für Sim bietet vollständige Typsicherheit und unterstützt sowohl Node.js- als auch Browser-Umgebungen, sodass Sie Workflows programmatisch aus Ihren Node.js-Anwendungen, Webanwendungen und anderen JavaScript-Umgebungen ausführen können. Alle Workflow-Ausführungen sind derzeit synchron.
+Das offizielle TypeScript/JavaScript SDK für Sim bietet vollständige Typsicherheit und unterstützt sowohl Node.js- als auch Browser-Umgebungen, sodass Sie Workflows programmatisch aus Ihren Node.js-Anwendungen, Webanwendungen und anderen JavaScript-Umgebungen ausführen können.
- Das TypeScript SDK bietet vollständige Typsicherheit und unterstützt sowohl Node.js- als auch Browser-Umgebungen. Alle Workflow-Ausführungen sind derzeit synchron.
+ Das TypeScript SDK bietet vollständige Typsicherheit, Unterstützung für asynchrone Ausführung, automatische Ratenbegrenzung mit exponentiellem Backoff und Nutzungsverfolgung.
## Installation
@@ -95,8 +95,13 @@ const result = await client.executeWorkflow('workflow-id', {
- `options` (ExecutionOptions, optional):
- `input` (any): Eingabedaten, die an den Workflow übergeben werden
- `timeout` (number): Timeout in Millisekunden (Standard: 30000)
+ - `stream` (boolean): Streaming-Antworten aktivieren (Standard: false)
+ - `selectedOutputs` (string[]): Block-Ausgaben, die im `blockName.attribute`Format gestreamt werden sollen (z.B. `["agent1.content"]`)
+ - `async` (boolean): Asynchron ausführen (Standard: false)
-**Rückgabewert:** `Promise`
+**Rückgabe:** `Promise`
+
+Wenn `async: true`, wird sofort mit einer Task-ID zum Abfragen zurückgegeben. Andernfalls wird auf den Abschluss gewartet.
##### getWorkflowStatus()
@@ -110,7 +115,7 @@ console.log('Is deployed:', status.isDeployed);
**Parameter:**
- `workflowId` (string): Die ID des Workflows
-**Rückgabewert:** `Promise`
+**Rückgabe:** `Promise`
##### validateWorkflow()
@@ -126,34 +131,123 @@ if (isReady) {
**Parameter:**
- `workflowId` (string): Die ID des Workflows
-**Rückgabewert:** `Promise`
+**Rückgabe:** `Promise`
-##### executeWorkflowSync()
+##### getJobStatus()
-
- Derzeit ist diese Methode identisch mit `executeWorkflow()`, da alle Ausführungen synchron sind. Diese Methode wird für zukünftige Kompatibilität bereitgestellt, wenn asynchrone Ausführung hinzugefügt wird.
-
+Den Status einer asynchronen Job-Ausführung abrufen.
+
+```typescript
+const status = await client.getJobStatus('task-id-from-async-execution');
+console.log('Status:', status.status); // 'queued', 'processing', 'completed', 'failed'
+if (status.status === 'completed') {
+ console.log('Output:', status.output);
+}
+```
+
+**Parameter:**
+- `taskId` (string): Die Task-ID, die von der asynchronen Ausführung zurückgegeben wurde
+
+**Rückgabe:** `Promise`
+
+**Antwortfelder:**
+- `success` (boolean): Ob die Anfrage erfolgreich war
+- `taskId` (string): Die Task-ID
+- `status` (string): Einer der Werte `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
+- `metadata` (object): Enthält `startedAt`, `completedAt` und `duration`
+- `output` (any, optional): Die Workflow-Ausgabe (wenn abgeschlossen)
+- `error` (any, optional): Fehlerdetails (wenn fehlgeschlagen)
+- `estimatedDuration` (number, optional): Geschätzte Dauer in Millisekunden (wenn in Bearbeitung/in der Warteschlange)
-Einen Workflow ausführen (derzeit synchron, identisch mit `executeWorkflow()`).
+##### executeWithRetry()
+
+Führt einen Workflow mit automatischer Wiederholung bei Ratenlimitfehlern unter Verwendung von exponentiellem Backoff aus.
```typescript
-const result = await client.executeWorkflowSync('workflow-id', {
- input: { data: 'some input' },
- timeout: 60000
+const result = await client.executeWithRetry('workflow-id', {
+ input: { message: 'Hello' },
+ timeout: 30000
+}, {
+ maxRetries: 3, // Maximum number of retries
+ initialDelay: 1000, // Initial delay in ms (1 second)
+ maxDelay: 30000, // Maximum delay in ms (30 seconds)
+ backoffMultiplier: 2 // Exponential backoff multiplier
});
```
**Parameter:**
- `workflowId` (string): Die ID des auszuführenden Workflows
-- `options` (ExecutionOptions, optional):
- - `input` (any): Eingabedaten, die an den Workflow übergeben werden
- - `timeout` (number): Timeout für die initiale Anfrage in Millisekunden
+- `options` (ExecutionOptions, optional): Gleich wie `executeWorkflow()`
+- `retryOptions` (RetryOptions, optional):
+ - `maxRetries` (number): Maximale Anzahl von Wiederholungen (Standard: 3)
+ - `initialDelay` (number): Anfängliche Verzögerung in ms (Standard: 1000)
+ - `maxDelay` (number): Maximale Verzögerung in ms (Standard: 30000)
+ - `backoffMultiplier` (number): Backoff-Multiplikator (Standard: 2)
+
+**Rückgabewert:** `Promise`
+
+Die Wiederholungslogik verwendet exponentiellen Backoff (1s → 2s → 4s → 8s...) mit ±25% Jitter, um den Thundering-Herd-Effekt zu vermeiden. Wenn die API einen `retry-after`Header bereitstellt, wird dieser stattdessen verwendet.
-**Rückgabewert:** `Promise`
+##### getRateLimitInfo()
+
+Ruft die aktuellen Ratenlimit-Informationen aus der letzten API-Antwort ab.
+
+```typescript
+const rateLimitInfo = client.getRateLimitInfo();
+if (rateLimitInfo) {
+ console.log('Limit:', rateLimitInfo.limit);
+ console.log('Remaining:', rateLimitInfo.remaining);
+ console.log('Reset:', new Date(rateLimitInfo.reset * 1000));
+}
+```
+
+**Rückgabewert:** `RateLimitInfo | null`
+
+##### getUsageLimits()
+
+Ruft aktuelle Nutzungslimits und Kontingentinformationen für Ihr Konto ab.
+
+```typescript
+const limits = await client.getUsageLimits();
+console.log('Sync requests remaining:', limits.rateLimit.sync.remaining);
+console.log('Async requests remaining:', limits.rateLimit.async.remaining);
+console.log('Current period cost:', limits.usage.currentPeriodCost);
+console.log('Plan:', limits.usage.plan);
+```
+
+**Rückgabewert:** `Promise`
+
+**Antwortstruktur:**
+
+```typescript
+{
+ success: boolean
+ rateLimit: {
+ sync: {
+ isLimited: boolean
+ limit: number
+ remaining: number
+ resetAt: string
+ }
+ async: {
+ isLimited: boolean
+ limit: number
+ remaining: number
+ resetAt: string
+ }
+ authType: string // 'api' or 'manual'
+ }
+ usage: {
+ currentPeriodCost: number
+ limit: number
+ plan: string // e.g., 'free', 'pro'
+ }
+}
+```
##### setApiKey()
-Den API-Schlüssel aktualisieren.
+Aktualisiert den API-Schlüssel.
```typescript
client.setApiKey('new-api-key');
@@ -161,7 +255,7 @@ client.setApiKey('new-api-key');
##### setBaseUrl()
-Die Basis-URL aktualisieren.
+Aktualisiert die Basis-URL.
```typescript
client.setBaseUrl('https://my-custom-domain.com');
@@ -187,6 +281,20 @@ interface WorkflowExecutionResult {
}
```
+### AsyncExecutionResult
+
+```typescript
+interface AsyncExecutionResult {
+ success: boolean;
+ taskId: string;
+ status: 'queued';
+ createdAt: string;
+ links: {
+ status: string; // e.g., "/api/jobs/{taskId}"
+ };
+}
+```
+
### WorkflowStatus
```typescript
@@ -198,6 +306,45 @@ interface WorkflowStatus {
}
```
+### RateLimitInfo
+
+```typescript
+interface RateLimitInfo {
+ limit: number;
+ remaining: number;
+ reset: number;
+ retryAfter?: number;
+}
+```
+
+### UsageLimits
+
+```typescript
+interface UsageLimits {
+ success: boolean;
+ rateLimit: {
+ sync: {
+ isLimited: boolean;
+ limit: number;
+ remaining: number;
+ resetAt: string;
+ };
+ async: {
+ isLimited: boolean;
+ limit: number;
+ remaining: number;
+ resetAt: string;
+ };
+ authType: string;
+ };
+ usage: {
+ currentPeriodCost: number;
+ limit: number;
+ plan: string;
+ };
+}
+```
+
### SimStudioError
```typescript
@@ -207,6 +354,13 @@ class SimStudioError extends Error {
}
```
+**Häufige Fehlercodes:**
+- `UNAUTHORIZED`: Ungültiger API-Schlüssel
+- `TIMEOUT`: Zeitüberschreitung der Anfrage
+- `RATE_LIMIT_EXCEEDED`: Ratengrenze überschritten
+- `USAGE_LIMIT_EXCEEDED`: Nutzungsgrenze überschritten
+- `EXECUTION_ERROR`: Workflow-Ausführung fehlgeschlagen
+
## Beispiele
### Grundlegende Workflow-Ausführung
@@ -467,16 +621,16 @@ document.getElementById('executeBtn')?.addEventListener('click', executeClientSi
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.
-### React Hook Beispiel
+### React Hook-Beispiel
-Erstellen Sie einen benutzerdefinierten React Hook für die Workflow-Ausführung:
+Erstellen eines benutzerdefinierten React-Hooks für die Workflow-Ausführung:
```typescript
import { useState, useCallback } from 'react';
import { SimStudioClient, WorkflowExecutionResult } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
- apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
+ apiKey: process.env.SIM_API_KEY!
});
interface UseWorkflowResult {
@@ -532,7 +686,7 @@ function WorkflowComponent() {
-
+
{error &&
Error: {error.message}
}
{result && (
@@ -545,38 +699,267 @@ function WorkflowComponent() {
}
```
-## Ihren API-Schlüssel erhalten
+### Asynchrone Workflow-Ausführung
+
+Führen Sie Workflows asynchron für lang laufende Aufgaben aus:
+
+```typescript
+import { SimStudioClient, AsyncExecutionResult } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function executeAsync() {
+ try {
+ // Start async execution
+ const result = await client.executeWorkflow('workflow-id', {
+ input: { data: 'large dataset' },
+ async: true // Execute asynchronously
+ });
+
+ // Check if result is an async execution
+ if ('taskId' in result) {
+ console.log('Task ID:', result.taskId);
+ console.log('Status endpoint:', result.links.status);
+
+ // Poll for completion
+ 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
+ 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);
+ } else {
+ console.error('Workflow failed:', status.error);
+ }
+ }
+ } catch (error) {
+ console.error('Error:', error);
+ }
+}
+
+executeAsync();
+```
+
+### Rate-Limiting und Wiederholungsversuche
+
+Automatische Behandlung von Rate-Limits mit exponentiellem Backoff:
+
+```typescript
+import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function executeWithRetryHandling() {
+ try {
+ // Automatically retries on rate limit
+ const result = await client.executeWithRetry('workflow-id', {
+ input: { message: 'Process this' }
+ }, {
+ maxRetries: 5,
+ initialDelay: 1000,
+ maxDelay: 60000,
+ backoffMultiplier: 2
+ });
+
+ console.log('Success:', result);
+ } catch (error) {
+ if (error instanceof SimStudioError && error.code === 'RATE_LIMIT_EXCEEDED') {
+ console.error('Rate limit exceeded after all retries');
+
+ // Check rate limit info
+ const rateLimitInfo = client.getRateLimitInfo();
+ if (rateLimitInfo) {
+ console.log('Rate limit resets at:', new Date(rateLimitInfo.reset * 1000));
+ }
+ }
+ }
+}
+```
+
+### Nutzungsüberwachung
+
+Überwachen Sie Ihre Kontonutzung und -limits:
+
+```typescript
+import { SimStudioClient } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function checkUsage() {
+ try {
+ const limits = await client.getUsageLimits();
+
+ console.log('=== 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('\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);
+
+ console.log('\n=== Usage ===');
+ console.log('Current period cost:
+
+### Streaming Workflow Execution
+
+Execute workflows with real-time streaming responses:
+
+```typescript
+import { SimStudioClient } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function executeWithStreaming() {
+ try {
+ // Streaming für bestimmte Block-Ausgaben aktivieren
+ const result = await client.executeWorkflow('workflow-id', {
+ input: { message: 'Count to five' },
+ stream: true,
+ selectedOutputs: ['agent1.content'] // Format blockName.attribute verwenden
+ });
+
+ console.log('Workflow-Ergebnis:', result);
+ } catch (error) {
+ console.error('Fehler:', error);
+ }
+}
+```
+
+The streaming response follows the Server-Sent Events (SSE) format:
+
+```
+data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
+
+data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", zwei"}
+
+data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
+
+data: [DONE]
+```
+
+**React Streaming Example:**
+
+```typescript
+import { useState, useEffect } from 'react';
+
+function StreamingWorkflow() {
+ const [output, setOutput] = useState('');
+ const [loading, setLoading] = useState(false);
+
+ const executeStreaming = async () => {
+ setLoading(true);
+ setOutput('');
+
+ // WICHTIG: Führen Sie diesen API-Aufruf von Ihrem Backend-Server aus, nicht vom Browser
+ // Setzen Sie niemals Ihren API-Schlüssel im Client-seitigen Code frei
+ const response = await fetch('https://sim.ai/api/workflows/WORKFLOW_ID/execute', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-API-Key': process.env.SIM_API_KEY! // Nur serverseitige Umgebungsvariable
+ },
+ body: JSON.stringify({
+ message: '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('Ausführung abgeschlossen:', parsed.metadata);
+ }
+ } catch (e) {
+ // Ungültiges JSON überspringen
+ }
+ }
+ }
+ }
+ };
+
+ return (
+
+
+
{output}
+
+ );
+}
+```
+
+## Getting Your API Key
-
- Navigieren Sie zu [Sim](https://sim.ai) und melden Sie sich bei Ihrem Konto an.
+
+ Navigate to [Sim](https://sim.ai) and log in to your account.
-
- Navigieren Sie zu dem Workflow, den Sie programmatisch ausführen möchten.
+
+ Navigate to the workflow you want to execute programmatically.
-
- Klicken Sie auf "Deploy", um Ihren Workflow zu deployen, falls dies noch nicht geschehen ist.
+
+ Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.
-
- Wählen Sie während des Deployment-Prozesses einen API-Schlüssel aus oder erstellen Sie einen neuen.
+
+ During the deployment process, select or create an API key.
-
- Kopieren Sie den API-Schlüssel zur Verwendung in Ihrer TypeScript/JavaScript-Anwendung.
+
+ Copy the API key to use in your TypeScript/JavaScript application.
- Halten Sie Ihren API-Schlüssel sicher und committen Sie ihn niemals in die Versionskontrolle. Verwenden Sie Umgebungsvariablen oder sicheres Konfigurationsmanagement.
+ Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management.
-## Anforderungen
+## Requirements
- Node.js 16+
-- TypeScript 5.0+ (für TypeScript-Projekte)
+- TypeScript 5.0+ (for TypeScript projects)
-## TypeScript-Unterstützung
+## TypeScript Support
-Das SDK ist in TypeScript geschrieben und bietet vollständige Typsicherheit:
+The SDK is written in TypeScript and provides full type safety:
```typescript
import {
@@ -586,22 +969,22 @@ import {
SimStudioError
} from 'simstudio-ts-sdk';
-// Type-safe client initialization
+// Typsichere Client-Initialisierung
const client: SimStudioClient = new SimStudioClient({
apiKey: process.env.SIM_API_KEY!
});
-// Type-safe workflow execution
+// Typsichere Workflow-Ausführung
const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
input: {
message: 'Hello, TypeScript!'
}
});
-// Type-safe status checking
+// Typsichere Statusprüfung
const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
```
-## Lizenz
+## License
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 ccdd8eff9b..8dab4cfb38 100644
--- a/apps/docs/content/docs/de/triggers/api.mdx
+++ b/apps/docs/content/docs/de/triggers/api.mdx
@@ -38,14 +38,92 @@ curl -X POST \
Erfolgreiche Antworten geben das serialisierte Ausführungsergebnis vom Executor zurück. Fehler zeigen Validierungs-, Authentifizierungs- oder Workflow-Fehler an.
-## Ausgabe-Referenz
+## 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.
+
+### Anfrageparameter
+
+Fügen Sie diese Parameter hinzu, um Streaming zu aktivieren:
+
+- `stream` - Auf `true` setzen, 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)
+- Blocknamen sind nicht case-sensitive und Leerzeichen werden ignoriert
+
+### Beispielanfrage
+
+```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": "Count to five",
+ "stream": true,
+ "selectedOutputs": ["agent1.content"]
+ }'
+```
+
+### Antwortformat
+
+Streaming-Antworten verwenden das Server-Sent Events (SSE) Format:
+
+```
+data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
+
+data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"}
+
+data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", three"}
+
+data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
+
+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
+- **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"]
+ }'
+```
+
+Das Feld `blockId` in jedem Chunk ermöglicht es Ihnen, die Ausgabe zum richtigen UI-Element zu leiten:
+
+```
+data: {"blockId":"agent1-uuid","chunk":"Processing..."}
+
+data: {"blockId":"agent2-uuid","chunk":"Analyzing..."}
+
+data: {"blockId":"agent1-uuid","chunk":" complete"}
+```
+
+## Ausgabereferenz
| Referenz | Beschreibung |
|-----------|-------------|
| `` | Im Eingabeformat definiertes Feld |
| `` | Gesamter strukturierter Anfragekörper |
-Wenn kein Eingabeformat definiert ist, stellt der Executor das rohe JSON nur unter `` bereit.
+Wenn kein Eingabeformat definiert ist, stellt der Executor das rohe JSON nur 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/en/sdks/python.mdx b/apps/docs/content/docs/en/sdks/python.mdx
index 8655f76d87..b31351e2a4 100644
--- a/apps/docs/content/docs/en/sdks/python.mdx
+++ b/apps/docs/content/docs/en/sdks/python.mdx
@@ -348,7 +348,7 @@ class SimStudioError(Exception):
import os
from simstudio import SimStudioClient
-client = SimStudioClient(api_key=os.getenv("SIM_API_KEY
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
def run_workflow():
try:
@@ -386,7 +386,7 @@ Handle different types of errors that may occur during workflow execution:
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:
@@ -432,7 +432,7 @@ Execute multiple workflows efficiently:
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."""
@@ -608,7 +608,7 @@ Execute workflows with real-time streaming responses:
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."""
@@ -659,7 +659,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/en/sdks/typescript.mdx b/apps/docs/content/docs/en/sdks/typescript.mdx
index 9f9b620026..1e8ea8782a 100644
--- a/apps/docs/content/docs/en/sdks/typescript.mdx
+++ b/apps/docs/content/docs/en/sdks/typescript.mdx
@@ -992,4 +992,4 @@ const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
## License
-Apache-2.0
\ No newline at end of file
+Apache-2.0
diff --git a/apps/docs/content/docs/es/sdks/python.mdx b/apps/docs/content/docs/es/sdks/python.mdx
index c915b0d114..2edb110394 100644
--- a/apps/docs/content/docs/es/sdks/python.mdx
+++ b/apps/docs/content/docs/es/sdks/python.mdx
@@ -10,7 +10,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
El SDK oficial de Python para Sim te permite ejecutar flujos de trabajo programáticamente desde tus aplicaciones Python utilizando el SDK oficial de Python.
- El SDK de Python es compatible con Python 3.8+ y proporciona ejecución sincrónica de flujos de trabajo. Todas las ejecuciones de flujos de trabajo son actualmente sincrónicas.
+ El SDK de Python es compatible con Python 3.8+ con soporte para ejecución asíncrona, limitación automática de velocidad con retroceso exponencial y seguimiento de uso.
## Instalación
@@ -74,12 +74,17 @@ result = client.execute_workflow(
- `workflow_id` (str): El ID del flujo de trabajo a ejecutar
- `input_data` (dict, opcional): Datos de entrada para pasar al flujo de trabajo
- `timeout` (float, opcional): Tiempo de espera en segundos (predeterminado: 30.0)
+- `stream` (bool, opcional): Habilitar respuestas en streaming (predeterminado: False)
+- `selected_outputs` (list[str], opcional): Salidas de bloque para transmitir en formato `blockName.attribute` (p. ej., `["agent1.content"]`)
+- `async_execution` (bool, opcional): Ejecutar de forma asíncrona (predeterminado: False)
-**Devuelve:** `WorkflowExecutionResult`
+**Devuelve:** `WorkflowExecutionResult | AsyncExecutionResult`
+
+Cuando `async_execution=True`, devuelve inmediatamente un ID de tarea para sondeo. De lo contrario, espera a que se complete.
##### get_workflow_status()
-Obtiene el estado de un flujo de trabajo (estado de implementación, etc.).
+Obtener el estado de un flujo de trabajo (estado de implementación, etc.).
```python
status = client.get_workflow_status("workflow-id")
@@ -93,7 +98,7 @@ print("Is deployed:", status.is_deployed)
##### validate_workflow()
-Valida que un flujo de trabajo esté listo para su ejecución.
+Validar que un flujo de trabajo está listo para su ejecución.
```python
is_ready = client.validate_workflow("workflow-id")
@@ -107,28 +112,118 @@ if is_ready:
**Devuelve:** `bool`
-##### execute_workflow_sync()
+##### get_job_status()
-
- Actualmente, este método es idéntico a `execute_workflow()` ya que todas las ejecuciones son síncronas. Este método se proporciona para compatibilidad futura cuando se añada la ejecución asíncrona.
-
+Obtener el estado de una ejecución de trabajo asíncrono.
+
+```python
+status = client.get_job_status("task-id-from-async-execution")
+print("Status:", status["status"]) # 'queued', 'processing', 'completed', 'failed'
+if status["status"] == "completed":
+ print("Output:", status["output"])
+```
+
+**Parámetros:**
+- `task_id` (str): El ID de tarea devuelto de la ejecución asíncrona
+
+**Devuelve:** `Dict[str, Any]`
-Ejecuta un flujo de trabajo (actualmente síncrono, igual que `execute_workflow()`).
+**Campos de respuesta:**
+- `success` (bool): Si la solicitud fue exitosa
+- `taskId` (str): El ID de la tarea
+- `status` (str): Uno de `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
+- `metadata` (dict): Contiene `startedAt`, `completedAt`, y `duration`
+- `output` (any, opcional): La salida del flujo de trabajo (cuando se completa)
+- `error` (any, opcional): Detalles del error (cuando falla)
+- `estimatedDuration` (int, opcional): Duración estimada en milisegundos (cuando está procesando/en cola)
+
+##### execute_with_retry()
+
+Ejecutar un flujo de trabajo con reintento automático en errores de límite de velocidad usando retroceso exponencial.
```python
-result = client.execute_workflow_sync(
+result = client.execute_with_retry(
"workflow-id",
- input_data={"data": "some input"},
- timeout=60.0
+ input_data={"message": "Hello"},
+ timeout=30.0,
+ max_retries=3, # Maximum number of retries
+ initial_delay=1.0, # Initial delay in seconds
+ max_delay=30.0, # Maximum delay in seconds
+ backoff_multiplier=2.0 # Exponential backoff multiplier
)
```
**Parámetros:**
- `workflow_id` (str): El ID del flujo de trabajo a ejecutar
- `input_data` (dict, opcional): Datos de entrada para pasar al flujo de trabajo
-- `timeout` (float): Tiempo de espera para la solicitud inicial en segundos
+- `timeout` (float, opcional): Tiempo de espera en segundos
+- `stream` (bool, opcional): Habilitar respuestas en streaming
+- `selected_outputs` (list, opcional): Salidas de bloque para transmitir
+- `async_execution` (bool, opcional): Ejecutar de forma asíncrona
+- `max_retries` (int, opcional): Número máximo de reintentos (predeterminado: 3)
+- `initial_delay` (float, opcional): Retraso inicial en segundos (predeterminado: 1.0)
+- `max_delay` (float, opcional): Retraso máximo en segundos (predeterminado: 30.0)
+- `backoff_multiplier` (float, opcional): Multiplicador de retroceso (predeterminado: 2.0)
+
+**Devuelve:** `WorkflowExecutionResult | AsyncExecutionResult`
+
+La lógica de reintento utiliza retroceso exponencial (1s → 2s → 4s → 8s...) con fluctuación de ±25% para evitar el efecto de manada. Si la API proporciona un encabezado `retry-after`, se utilizará en su lugar.
+
+##### get_rate_limit_info()
+
+Obtiene la información actual del límite de tasa de la última respuesta de la API.
+
+```python
+rate_limit_info = client.get_rate_limit_info()
+if rate_limit_info:
+ print("Limit:", rate_limit_info.limit)
+ print("Remaining:", rate_limit_info.remaining)
+ print("Reset:", datetime.fromtimestamp(rate_limit_info.reset))
+```
+
+**Devuelve:** `RateLimitInfo | None`
+
+##### get_usage_limits()
-**Devuelve:** `WorkflowExecutionResult`
+Obtiene los límites de uso actuales y la información de cuota para tu cuenta.
+
+```python
+limits = client.get_usage_limits()
+print("Sync requests remaining:", limits.rate_limit["sync"]["remaining"])
+print("Async requests remaining:", limits.rate_limit["async"]["remaining"])
+print("Current period cost:", limits.usage["currentPeriodCost"])
+print("Plan:", limits.usage["plan"])
+```
+
+**Devuelve:** `UsageLimits`
+
+**Estructura de respuesta:**
+
+```python
+{
+ "success": bool,
+ "rateLimit": {
+ "sync": {
+ "isLimited": bool,
+ "limit": int,
+ "remaining": int,
+ "resetAt": str
+ },
+ "async": {
+ "isLimited": bool,
+ "limit": int,
+ "remaining": int,
+ "resetAt": str
+ },
+ "authType": str # 'api' or 'manual'
+ },
+ "usage": {
+ "currentPeriodCost": float,
+ "limit": float,
+ "plan": str # e.g., 'free', 'pro'
+ }
+}
+```
##### set_api_key()
@@ -170,6 +265,18 @@ class WorkflowExecutionResult:
total_duration: Optional[float] = None
```
+### AsyncExecutionResult
+
+```python
+@dataclass
+class AsyncExecutionResult:
+ success: bool
+ task_id: str
+ status: str # 'queued'
+ created_at: str
+ links: Dict[str, str] # e.g., {"status": "/api/jobs/{taskId}"}
+```
+
### WorkflowStatus
```python
@@ -181,6 +288,27 @@ class WorkflowStatus:
needs_redeployment: bool = False
```
+### RateLimitInfo
+
+```python
+@dataclass
+class RateLimitInfo:
+ limit: int
+ remaining: int
+ reset: int
+ retry_after: Optional[int] = None
+```
+
+### UsageLimits
+
+```python
+@dataclass
+class UsageLimits:
+ success: bool
+ rate_limit: Dict[str, Any]
+ usage: Dict[str, Any]
+```
+
### SimStudioError
```python
@@ -191,6 +319,13 @@ class SimStudioError(Exception):
self.status = status
```
+**Códigos de error comunes:**
+- `UNAUTHORIZED`: Clave API inválida
+- `TIMEOUT`: Tiempo de espera agotado
+- `RATE_LIMIT_EXCEEDED`: Límite de tasa excedido
+- `USAGE_LIMIT_EXCEEDED`: Límite de uso excedido
+- `EXECUTION_ERROR`: Ejecución del flujo de trabajo fallida
+
## Ejemplos
### Ejecución básica de flujo de trabajo
@@ -205,8 +340,8 @@ class SimStudioError(Exception):
Ejecuta el flujo de trabajo con tus datos de entrada.
-
- Procesa el resultado de la ejecución y maneja cualquier error.
+
+ Procesa el resultado de la ejecución y gestiona cualquier error.
@@ -275,9 +410,9 @@ def execute_with_error_handling():
raise
```
-### Uso del administrador de contexto
+### Uso del gestor de contexto
-Usa el cliente como un administrador de contexto para manejar automáticamente la limpieza de recursos:
+Usa el cliente como un gestor de contexto para manejar automáticamente la limpieza de recursos:
```python
from simstudio import SimStudioClient
@@ -290,7 +425,7 @@ with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
# Session is automatically closed here
```
-### Ejecución por lotes de flujos de trabajo
+### Ejecución de flujos de trabajo por lotes
Ejecuta múltiples flujos de trabajo de manera eficiente:
@@ -298,7 +433,7 @@ Ejecuta múltiples flujos de trabajo de manera eficiente:
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."""
@@ -339,6 +474,230 @@ for result in results:
print(f"Workflow {result['workflow_id']}: {'Success' if result['success'] else 'Failed'}")
```
+### Ejecución asíncrona de flujos de trabajo
+
+Ejecuta flujos de trabajo de forma asíncrona para tareas de larga duración:
+
+```python
+import os
+import time
+from simstudio import SimStudioClient
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_async():
+ try:
+ # Start async execution
+ result = client.execute_workflow(
+ "workflow-id",
+ input_data={"data": "large dataset"},
+ async_execution=True # Execute asynchronously
+ )
+
+ # Check if result is an async execution
+ if hasattr(result, 'task_id'):
+ print(f"Task ID: {result.task_id}")
+ print(f"Status endpoint: {result.links['status']}")
+
+ # Poll for completion
+ status = client.get_job_status(result.task_id)
+
+ while status["status"] in ["queued", "processing"]:
+ print(f"Current status: {status['status']}")
+ time.sleep(2) # Wait 2 seconds
+ status = client.get_job_status(result.task_id)
+
+ if status["status"] == "completed":
+ print("Workflow completed!")
+ print(f"Output: {status['output']}")
+ print(f"Duration: {status['metadata']['duration']}")
+ else:
+ print(f"Workflow failed: {status['error']}")
+
+ except Exception as error:
+ print(f"Error: {error}")
+
+execute_async()
+```
+
+### Límite de tasa y reintentos
+
+Maneja los límites de tasa automáticamente con retroceso exponencial:
+
+```python
+import os
+from simstudio import SimStudioClient, SimStudioError
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_with_retry_handling():
+ try:
+ # Automatically retries on rate limit
+ result = client.execute_with_retry(
+ "workflow-id",
+ input_data={"message": "Process this"},
+ max_retries=5,
+ initial_delay=1.0,
+ max_delay=60.0,
+ backoff_multiplier=2.0
+ )
+
+ print(f"Success: {result}")
+ except SimStudioError as error:
+ if error.code == "RATE_LIMIT_EXCEEDED":
+ print("Rate limit exceeded after all retries")
+
+ # Check rate limit info
+ rate_limit_info = client.get_rate_limit_info()
+ if rate_limit_info:
+ from datetime import datetime
+ reset_time = datetime.fromtimestamp(rate_limit_info.reset)
+ print(f"Rate limit resets at: {reset_time}")
+
+execute_with_retry_handling()
+```
+
+### Monitoreo de uso
+
+Monitorea el uso de tu cuenta y sus límites:
+
+```python
+import os
+from simstudio import SimStudioClient
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def check_usage():
+ try:
+ limits = client.get_usage_limits()
+
+ print("=== Rate Limits ===")
+ print("Sync requests:")
+ print(f" Limit: {limits.rate_limit['sync']['limit']}")
+ print(f" Remaining: {limits.rate_limit['sync']['remaining']}")
+ print(f" Resets at: {limits.rate_limit['sync']['resetAt']}")
+ print(f" Is limited: {limits.rate_limit['sync']['isLimited']}")
+
+ print("\nAsync requests:")
+ print(f" Limit: {limits.rate_limit['async']['limit']}")
+ print(f" Remaining: {limits.rate_limit['async']['remaining']}")
+ print(f" Resets at: {limits.rate_limit['async']['resetAt']}")
+ print(f" Is limited: {limits.rate_limit['async']['isLimited']}")
+
+ print("\n=== Usage ===")
+ print(f"Current period cost: ${limits.usage['currentPeriodCost']:.2f}")
+ print(f"Limit: ${limits.usage['limit']:.2f}")
+ print(f"Plan: {limits.usage['plan']}")
+
+ percent_used = (limits.usage['currentPeriodCost'] / limits.usage['limit']) * 100
+ print(f"Usage: {percent_used:.1f}%")
+
+ if percent_used > 80:
+ print("⚠️ Warning: You are approaching your usage limit!")
+
+ except Exception as error:
+ print(f"Error checking usage: {error}")
+
+check_usage()
+```
+
+### Ejecución de flujo de trabajo en streaming
+
+Ejecuta flujos de trabajo con respuestas en tiempo real:
+
+```python
+from simstudio import SimStudioClient
+import os
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_with_streaming():
+ """Execute workflow with streaming enabled."""
+ try:
+ # Enable streaming for specific block outputs
+ result = client.execute_workflow(
+ "workflow-id",
+ input_data={"message": "Count to five"},
+ stream=True,
+ selected_outputs=["agent1.content"] # Use blockName.attribute format
+ )
+
+ print("Workflow result:", result)
+ except Exception as error:
+ print("Error:", error)
+
+execute_with_streaming()
+```
+
+La respuesta en streaming sigue el formato de 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]
+```
+
+**Ejemplo de streaming con Flask:**
+
+```python
+from flask import Flask, Response, stream_with_context
+import requests
+import json
+import os
+
+app = Flask(__name__)
+
+@app.route('/stream-workflow')
+def stream_workflow():
+ """Stream workflow execution to the client."""
+
+ def generate():
+ response = requests.post(
+ 'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
+ headers={
+ 'Content-Type': 'application/json',
+ 'X-API-Key': os.getenv('SIM_API_KEY')
+ },
+ json={
+ 'message': 'Generate a story',
+ 'stream': True,
+ 'selectedOutputs': ['agent1.content']
+ },
+ stream=True
+ )
+
+ for line in response.iter_lines():
+ if line:
+ decoded_line = line.decode('utf-8')
+ if decoded_line.startswith('data: '):
+ data = decoded_line[6:] # Remove 'data: ' prefix
+
+ if data == '[DONE]':
+ break
+
+ try:
+ parsed = json.loads(data)
+ if 'chunk' in parsed:
+ yield f"data: {json.dumps(parsed)}\n\n"
+ elif parsed.get('event') == 'done':
+ yield f"data: {json.dumps(parsed)}\n\n"
+ print("Execution complete:", parsed.get('metadata'))
+ except json.JSONDecodeError:
+ pass
+
+ return Response(
+ stream_with_context(generate()),
+ mimetype='text/event-stream'
+ )
+
+if __name__ == '__main__':
+ app.run(debug=True)
+```
+
### Configuración del entorno
Configura el cliente usando variables de entorno:
@@ -352,7 +711,7 @@ Configura el cliente usando variables de entorno:
# Development configuration
client = SimStudioClient(
- api_key=os.getenv("SIM_API_KEY"),
+ api_key=os.getenv("SIM_API_KEY")
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
)
```
diff --git a/apps/docs/content/docs/es/sdks/typescript.mdx b/apps/docs/content/docs/es/sdks/typescript.mdx
index 91af813326..fca8a9805f 100644
--- a/apps/docs/content/docs/es/sdks/typescript.mdx
+++ b/apps/docs/content/docs/es/sdks/typescript.mdx
@@ -7,10 +7,10 @@ import { Card, Cards } from 'fumadocs-ui/components/card'
import { Step, Steps } from 'fumadocs-ui/components/steps'
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
-El SDK oficial de TypeScript/JavaScript para Sim proporciona seguridad de tipos completa y es compatible tanto con entornos Node.js como con navegadores, lo que te permite ejecutar flujos de trabajo de forma programática desde tus aplicaciones Node.js, aplicaciones web y otros entornos JavaScript. Todas las ejecuciones de flujos de trabajo son actualmente síncronas.
+El SDK oficial de TypeScript/JavaScript para Sim proporciona seguridad de tipos completa y es compatible tanto con entornos Node.js como de navegador, lo que te permite ejecutar flujos de trabajo programáticamente desde tus aplicaciones Node.js, aplicaciones web y otros entornos JavaScript.
- El SDK de TypeScript proporciona seguridad de tipos completa y es compatible tanto con entornos Node.js como con navegadores. Todas las ejecuciones de flujos de trabajo son actualmente síncronas.
+ El SDK de TypeScript proporciona seguridad de tipos completa, soporte para ejecución asíncrona, limitación automática de velocidad con retroceso exponencial y seguimiento de uso.
## Instalación
@@ -95,8 +95,13 @@ const result = await client.executeWorkflow('workflow-id', {
- `options` (ExecutionOptions, opcional):
- `input` (any): Datos de entrada para pasar al flujo de trabajo
- `timeout` (number): Tiempo de espera en milisegundos (predeterminado: 30000)
+ - `stream` (boolean): Habilitar respuestas en streaming (predeterminado: false)
+ - `selectedOutputs` (string[]): Bloquear salidas para transmitir en formato `blockName.attribute` (por ejemplo, `["agent1.content"]`)
+ - `async` (boolean): Ejecutar de forma asíncrona (predeterminado: false)
-**Devuelve:** `Promise`
+**Devuelve:** `Promise`
+
+Cuando `async: true`, devuelve inmediatamente un ID de tarea para sondeo. De lo contrario, espera a que se complete.
##### getWorkflowStatus()
@@ -128,32 +133,121 @@ if (isReady) {
**Devuelve:** `Promise`
-##### executeWorkflowSync()
+##### getJobStatus()
-
- Actualmente, este método es idéntico a `executeWorkflow()` ya que todas las ejecuciones son síncronas. Este método se proporciona para compatibilidad futura cuando se añada la ejecución asíncrona.
-
+Obtener el estado de una ejecución de trabajo asíncrono.
+
+```typescript
+const status = await client.getJobStatus('task-id-from-async-execution');
+console.log('Status:', status.status); // 'queued', 'processing', 'completed', 'failed'
+if (status.status === 'completed') {
+ console.log('Output:', status.output);
+}
+```
+
+**Parámetros:**
+- `taskId` (string): El ID de tarea devuelto de la ejecución asíncrona
+
+**Devuelve:** `Promise`
+
+**Campos de respuesta:**
+- `success` (boolean): Si la solicitud fue exitosa
+- `taskId` (string): El ID de la tarea
+- `status` (string): Uno de `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
+- `metadata` (object): Contiene `startedAt`, `completedAt`, y `duration`
+- `output` (any, opcional): La salida del flujo de trabajo (cuando se completa)
+- `error` (any, opcional): Detalles del error (cuando falla)
+- `estimatedDuration` (number, opcional): Duración estimada en milisegundos (cuando está procesando/en cola)
-Ejecutar un flujo de trabajo (actualmente síncrono, igual que `executeWorkflow()`).
+##### executeWithRetry()
+
+Ejecuta un flujo de trabajo con reintento automático en errores de límite de tasa utilizando retroceso exponencial.
```typescript
-const result = await client.executeWorkflowSync('workflow-id', {
- input: { data: 'some input' },
- timeout: 60000
+const result = await client.executeWithRetry('workflow-id', {
+ input: { message: 'Hello' },
+ timeout: 30000
+}, {
+ maxRetries: 3, // Maximum number of retries
+ initialDelay: 1000, // Initial delay in ms (1 second)
+ maxDelay: 30000, // Maximum delay in ms (30 seconds)
+ backoffMultiplier: 2 // Exponential backoff multiplier
});
```
**Parámetros:**
- `workflowId` (string): El ID del flujo de trabajo a ejecutar
-- `options` (ExecutionOptions, opcional):
- - `input` (any): Datos de entrada para pasar al flujo de trabajo
- - `timeout` (number): Tiempo de espera para la solicitud inicial en milisegundos
+- `options` (ExecutionOptions, opcional): Igual que `executeWorkflow()`
+- `retryOptions` (RetryOptions, opcional):
+ - `maxRetries` (number): Número máximo de reintentos (predeterminado: 3)
+ - `initialDelay` (number): Retraso inicial en ms (predeterminado: 1000)
+ - `maxDelay` (number): Retraso máximo en ms (predeterminado: 30000)
+ - `backoffMultiplier` (number): Multiplicador de retroceso (predeterminado: 2)
+
+**Devuelve:** `Promise`
+
+La lógica de reintento utiliza retroceso exponencial (1s → 2s → 4s → 8s...) con fluctuación de ±25% para evitar el efecto de manada. Si la API proporciona una cabecera `retry-after`, se utilizará en su lugar.
+
+##### getRateLimitInfo()
+
+Obtiene la información actual del límite de tasa de la última respuesta de la API.
+
+```typescript
+const rateLimitInfo = client.getRateLimitInfo();
+if (rateLimitInfo) {
+ console.log('Limit:', rateLimitInfo.limit);
+ console.log('Remaining:', rateLimitInfo.remaining);
+ console.log('Reset:', new Date(rateLimitInfo.reset * 1000));
+}
+```
+
+**Devuelve:** `RateLimitInfo | null`
+
+##### getUsageLimits()
-**Devuelve:** `Promise`
+Obtiene los límites de uso actuales y la información de cuota para tu cuenta.
+
+```typescript
+const limits = await client.getUsageLimits();
+console.log('Sync requests remaining:', limits.rateLimit.sync.remaining);
+console.log('Async requests remaining:', limits.rateLimit.async.remaining);
+console.log('Current period cost:', limits.usage.currentPeriodCost);
+console.log('Plan:', limits.usage.plan);
+```
+
+**Devuelve:** `Promise`
+
+**Estructura de respuesta:**
+
+```typescript
+{
+ success: boolean
+ rateLimit: {
+ sync: {
+ isLimited: boolean
+ limit: number
+ remaining: number
+ resetAt: string
+ }
+ async: {
+ isLimited: boolean
+ limit: number
+ remaining: number
+ resetAt: string
+ }
+ authType: string // 'api' or 'manual'
+ }
+ usage: {
+ currentPeriodCost: number
+ limit: number
+ plan: string // e.g., 'free', 'pro'
+ }
+}
+```
##### setApiKey()
-Actualizar la clave API.
+Actualiza la clave API.
```typescript
client.setApiKey('new-api-key');
@@ -161,7 +255,7 @@ client.setApiKey('new-api-key');
##### setBaseUrl()
-Actualizar la URL base.
+Actualiza la URL base.
```typescript
client.setBaseUrl('https://my-custom-domain.com');
@@ -187,6 +281,20 @@ interface WorkflowExecutionResult {
}
```
+### AsyncExecutionResult
+
+```typescript
+interface AsyncExecutionResult {
+ success: boolean;
+ taskId: string;
+ status: 'queued';
+ createdAt: string;
+ links: {
+ status: string; // e.g., "/api/jobs/{taskId}"
+ };
+}
+```
+
### WorkflowStatus
```typescript
@@ -198,6 +306,45 @@ interface WorkflowStatus {
}
```
+### RateLimitInfo
+
+```typescript
+interface RateLimitInfo {
+ limit: number;
+ remaining: number;
+ reset: number;
+ retryAfter?: number;
+}
+```
+
+### UsageLimits
+
+```typescript
+interface UsageLimits {
+ success: boolean;
+ rateLimit: {
+ sync: {
+ isLimited: boolean;
+ limit: number;
+ remaining: number;
+ resetAt: string;
+ };
+ async: {
+ isLimited: boolean;
+ limit: number;
+ remaining: number;
+ resetAt: string;
+ };
+ authType: string;
+ };
+ usage: {
+ currentPeriodCost: number;
+ limit: number;
+ plan: string;
+ };
+}
+```
+
### SimStudioError
```typescript
@@ -207,6 +354,13 @@ class SimStudioError extends Error {
}
```
+**Códigos de error comunes:**
+- `UNAUTHORIZED`: Clave API inválida
+- `TIMEOUT`: Tiempo de espera agotado
+- `RATE_LIMIT_EXCEEDED`: Límite de tasa excedido
+- `USAGE_LIMIT_EXCEEDED`: Límite de uso excedido
+- `EXECUTION_ERROR`: Ejecución del flujo de trabajo fallida
+
## Ejemplos
### Ejecución básica de flujo de trabajo
@@ -216,13 +370,13 @@ class SimStudioError extends Error {
Configura el SimStudioClient con tu clave API.
- Comprueba si el flujo de trabajo está implementado y listo para su ejecución.
+ Comprueba si el flujo de trabajo está desplegado y listo para su ejecución.
Ejecuta el flujo de trabajo con tus datos de entrada.
-
- Procesa el resultado de la ejecución y maneja cualquier error.
+
+ Procesa el resultado de la ejecución y gestiona cualquier error.
@@ -349,7 +503,7 @@ Configura el cliente usando variables de entorno:
### Integración con Express de Node.js
-Integración con un servidor Express.js:
+Integra con un servidor Express.js:
```typescript
import express from 'express';
@@ -430,7 +584,7 @@ export default async function handler(
### Uso del navegador
-Uso en el navegador (con la configuración CORS adecuada):
+Uso en el navegador (con configuración CORS adecuada):
```typescript
import { SimStudioClient } from 'simstudio-ts-sdk';
@@ -469,14 +623,14 @@ document.getElementById('executeBtn')?.addEventListener('click', executeClientSi
### Ejemplo de hook de React
-Crea un hook personalizado de React para la ejecución del flujo de trabajo:
+Crea un hook personalizado de React para la ejecución de flujos de trabajo:
```typescript
import { useState, useCallback } from 'react';
import { SimStudioClient, WorkflowExecutionResult } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
- apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
+ apiKey: process.env.SIM_API_KEY!
});
interface UseWorkflowResult {
@@ -532,7 +686,7 @@ function WorkflowComponent() {
-
+
{error &&
Error: {error.message}
}
{result && (
@@ -545,38 +699,267 @@ function WorkflowComponent() {
}
```
-## Obtener tu clave API
+### Ejecución asíncrona de flujos de trabajo
+
+Ejecuta flujos de trabajo de forma asíncrona para tareas de larga duración:
+
+```typescript
+import { SimStudioClient, AsyncExecutionResult } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function executeAsync() {
+ try {
+ // Start async execution
+ const result = await client.executeWorkflow('workflow-id', {
+ input: { data: 'large dataset' },
+ async: true // Execute asynchronously
+ });
+
+ // Check if result is an async execution
+ if ('taskId' in result) {
+ console.log('Task ID:', result.taskId);
+ console.log('Status endpoint:', result.links.status);
+
+ // Poll for completion
+ 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
+ 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);
+ } else {
+ console.error('Workflow failed:', status.error);
+ }
+ }
+ } catch (error) {
+ console.error('Error:', error);
+ }
+}
+
+executeAsync();
+```
+
+### Límite de tasa y reintentos
+
+Maneja límites de tasa automáticamente con retroceso exponencial:
+
+```typescript
+import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function executeWithRetryHandling() {
+ try {
+ // Automatically retries on rate limit
+ const result = await client.executeWithRetry('workflow-id', {
+ input: { message: 'Process this' }
+ }, {
+ maxRetries: 5,
+ initialDelay: 1000,
+ maxDelay: 60000,
+ backoffMultiplier: 2
+ });
+
+ console.log('Success:', result);
+ } catch (error) {
+ if (error instanceof SimStudioError && error.code === 'RATE_LIMIT_EXCEEDED') {
+ console.error('Rate limit exceeded after all retries');
+
+ // Check rate limit info
+ const rateLimitInfo = client.getRateLimitInfo();
+ if (rateLimitInfo) {
+ console.log('Rate limit resets at:', new Date(rateLimitInfo.reset * 1000));
+ }
+ }
+ }
+}
+```
+
+### Monitoreo de uso
+
+Monitorea el uso de tu cuenta y sus límites:
+
+```typescript
+import { SimStudioClient } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function checkUsage() {
+ try {
+ const limits = await client.getUsageLimits();
+
+ console.log('=== 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('\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);
+
+ console.log('\n=== Usage ===');
+ console.log('Current period cost:
+
+### Streaming Workflow Execution
+
+Execute workflows with real-time streaming responses:
+
+```typescript
+import { SimStudioClient } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function executeWithStreaming() {
+ try {
+ // Habilita streaming para salidas de bloques específicos
+ const result = await client.executeWorkflow('workflow-id', {
+ input: { message: 'Count to five' },
+ stream: true,
+ selectedOutputs: ['agent1.content'] // Usa el formato blockName.attribute
+ });
+
+ console.log('Resultado del flujo de trabajo:', result);
+ } catch (error) {
+ console.error('Error:', error);
+ }
+}
+```
+
+The streaming response follows the Server-Sent Events (SSE) format:
+
+```
+data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
+
+data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", dos"}
+
+data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
+
+data: [DONE]
+```
+
+**React Streaming Example:**
+
+```typescript
+import { useState, useEffect } from 'react';
+
+function StreamingWorkflow() {
+ const [output, setOutput] = useState('');
+ const [loading, setLoading] = useState(false);
+
+ const executeStreaming = async () => {
+ setLoading(true);
+ setOutput('');
+
+ // IMPORTANT: Make this API call from your backend server, not the browser
+ // Never expose your API key in client-side code
+ const response = await fetch('https://sim.ai/api/workflows/WORKFLOW_ID/execute', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-API-Key': process.env.SIM_API_KEY! // Server-side environment variable only
+ },
+ body: JSON.stringify({
+ message: 'Generate a story',
+ stream: true,
+ selectedOutputs: ['agent1.content']
+ })
+ });
+
+ const reader = response.body?.getReader();
+ const decoder = new TextDecoder();
+
+ while (reader) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ const chunk = decoder.decode(value);
+ const lines = chunk.split('\n\n');
+
+ for (const line of lines) {
+ if (line.startsWith('data: ')) {
+ const data = line.slice(6);
+ if (data === '[DONE]') {
+ setLoading(false);
+ break;
+ }
+
+ try {
+ const parsed = JSON.parse(data);
+ if (parsed.chunk) {
+ setOutput(prev => prev + parsed.chunk);
+ } else if (parsed.event === 'done') {
+ console.log('Execution complete:', parsed.metadata);
+ }
+ } catch (e) {
+ // Skip invalid JSON
+ }
+ }
+ }
+ }
+ };
+
+ return (
+
+
+
{output}
+
+ );
+}
+```
+
+## Getting Your API Key
-
- Navega a [Sim](https://sim.ai) e inicia sesión en tu cuenta.
+
+ Navigate to [Sim](https://sim.ai) and log in to your account.
-
- Navega al flujo de trabajo que quieres ejecutar programáticamente.
+
+ Navigate to the workflow you want to execute programmatically.
-
- Haz clic en "Deploy" para desplegar tu flujo de trabajo si aún no ha sido desplegado.
+
+ Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.
-
- Durante el proceso de despliegue, selecciona o crea una clave API.
+
+ During the deployment process, select or create an API key.
-
- Copia la clave API para usarla en tu aplicación TypeScript/JavaScript.
+
+ Copy the API key to use in your TypeScript/JavaScript application.
- Mantén tu clave API segura y nunca la incluyas en el control de versiones. Usa variables de entorno o gestión de configuración segura.
+ Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management.
-## Requisitos
+## Requirements
- Node.js 16+
-- TypeScript 5.0+ (para proyectos TypeScript)
+- TypeScript 5.0+ (for TypeScript projects)
-## Soporte para TypeScript
+## TypeScript Support
-El SDK está escrito en TypeScript y proporciona seguridad de tipos completa:
+The SDK is written in TypeScript and provides full type safety:
```typescript
import {
@@ -594,7 +977,7 @@ const client: SimStudioClient = new SimStudioClient({
// Type-safe workflow execution
const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
input: {
- message: 'Hello, TypeScript!'
+ message: '¡Hola, TypeScript!'
}
});
@@ -602,6 +985,7 @@ const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-i
const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
```
-## Licencia
+## License
+
-Apache-2.0
\ No newline at end of file
+Apache-2.0
diff --git a/apps/docs/content/docs/es/triggers/api.mdx b/apps/docs/content/docs/es/triggers/api.mdx
index c05facd2a4..09ecda8971 100644
--- a/apps/docs/content/docs/es/triggers/api.mdx
+++ b/apps/docs/content/docs/es/triggers/api.mdx
@@ -38,15 +38,93 @@ curl -X POST \
Las respuestas exitosas devuelven el resultado de ejecución serializado del Ejecutor. Los errores muestran fallos de validación, autenticación o flujo de trabajo.
+## 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.
+
+### Parámetros de solicitud
+
+Añade estos parámetros para habilitar el streaming:
+
+- `stream` - Establece a `true` para habilitar el streaming de eventos enviados por el servidor (SSE)
+- `selectedOutputs` - Array de salidas de bloques para transmitir (p. ej., `["agent1.content"]`)
+
+### Formato de salida de bloque
+
+Usa el formato `blockName.attribute` para especificar qué salidas de bloques 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
+
+### Ejemplo de solicitud
+
+```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": "Count to five",
+ "stream": true,
+ "selectedOutputs": ["agent1.content"]
+ }'
+```
+
+### Formato de respuesta
+
+Las respuestas en streaming utilizan 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: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", three"}
+
+data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
+
+data: [DONE]
+```
+
+Cada evento incluye:
+- **Fragmentos de 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
+
+### 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:
+
+```
+data: {"blockId":"agent1-uuid","chunk":"Processing..."}
+
+data: {"blockId":"agent2-uuid","chunk":"Analyzing..."}
+
+data: {"blockId":"agent1-uuid","chunk":" complete"}
+```
+
## Referencia de salida
| Referencia | Descripción |
|-----------|-------------|
-| `` | Campo definido en el Formato de Entrada |
-| `` | Cuerpo completo estructurado de la solicitud |
+| `` | Campo definido en el formato de entrada |
+| `` | Cuerpo de solicitud estructurado completo |
-Si no se define un Formato de Entrada, el ejecutor expone el JSON sin procesar solo en ``.
+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 realizar cambios para que el punto de conexión se mantenga actualizado.
+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.
diff --git a/apps/docs/content/docs/fr/sdks/python.mdx b/apps/docs/content/docs/fr/sdks/python.mdx
index e72bf1911c..faf5f4b203 100644
--- a/apps/docs/content/docs/fr/sdks/python.mdx
+++ b/apps/docs/content/docs/fr/sdks/python.mdx
@@ -10,7 +10,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
Le SDK Python officiel pour Sim vous permet d'exécuter des workflows de manière programmatique à partir de vos applications Python en utilisant le SDK Python officiel.
- Le SDK Python prend en charge Python 3.8+ et fournit une exécution synchrone des workflows. Toutes les exécutions de workflow sont actuellement synchrones.
+ Le SDK Python prend en charge Python 3.8+ avec support d'exécution asynchrone, limitation automatique du débit avec backoff exponentiel, et suivi d'utilisation.
## Installation
@@ -71,11 +71,16 @@ result = client.execute_workflow(
```
**Paramètres :**
-- `workflow_id` (str) : L'ID du workflow à exécuter
+- `workflow_id` (str) : L'identifiant du workflow à exécuter
- `input_data` (dict, facultatif) : Données d'entrée à transmettre au workflow
-- `timeout` (float, facultatif) : Délai d'attente en secondes (par défaut : 30.0)
+- `timeout` (float, facultatif) : Délai d'expiration en secondes (par défaut : 30.0)
+- `stream` (bool, facultatif) : Activer les réponses en streaming (par défaut : False)
+- `selected_outputs` (list[str], facultatif) : Sorties de blocs à diffuser au format `blockName.attribute` (par exemple, `["agent1.content"]`)
+- `async_execution` (bool, facultatif) : Exécuter de manière asynchrone (par défaut : False)
+
+**Retourne :** `WorkflowExecutionResult | AsyncExecutionResult`
-**Retourne :** `WorkflowExecutionResult`
+Lorsque `async_execution=True`, retourne immédiatement un identifiant de tâche pour l'interrogation. Sinon, attend la fin de l'exécution.
##### get_workflow_status()
@@ -87,13 +92,13 @@ print("Is deployed:", status.is_deployed)
```
**Paramètres :**
-- `workflow_id` (str) : L'ID du workflow
+- `workflow_id` (str) : L'identifiant du workflow
**Retourne :** `WorkflowStatus`
##### validate_workflow()
-Valide qu'un workflow est prêt pour l'exécution.
+Valider qu'un workflow est prêt pour l'exécution.
```python
is_ready = client.validate_workflow("workflow-id")
@@ -107,32 +112,122 @@ if is_ready:
**Retourne :** `bool`
-##### execute_workflow_sync()
+##### get_job_status()
-
- Actuellement, cette méthode est identique à `execute_workflow()` puisque toutes les exécutions sont synchrones. Cette méthode est fournie pour une compatibilité future lorsque l'exécution asynchrone sera ajoutée.
-
+Obtenir le statut d'une exécution de tâche asynchrone.
+
+```python
+status = client.get_job_status("task-id-from-async-execution")
+print("Status:", status["status"]) # 'queued', 'processing', 'completed', 'failed'
+if status["status"] == "completed":
+ print("Output:", status["output"])
+```
+
+**Paramètres :**
+- `task_id` (str) : L'identifiant de tâche retourné par l'exécution asynchrone
+
+**Retourne :** `Dict[str, Any]`
+
+**Champs de réponse :**
+- `success` (bool) : Si la requête a réussi
+- `taskId` (str) : L'identifiant de la tâche
+- `status` (str) : L'un des états suivants : `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
+- `metadata` (dict) : Contient `startedAt`, `completedAt`, et `duration`
+- `output` (any, facultatif) : La sortie du workflow (une fois terminé)
+- `error` (any, facultatif) : Détails de l'erreur (en cas d'échec)
+- `estimatedDuration` (int, facultatif) : Durée estimée en millisecondes (lors du traitement/mise en file d'attente)
-Exécute un workflow (actuellement synchrone, identique à `execute_workflow()`).
+##### execute_with_retry()
+
+Exécuter un workflow avec réessai automatique en cas d'erreurs de limitation de débit, en utilisant un backoff exponentiel.
```python
-result = client.execute_workflow_sync(
+result = client.execute_with_retry(
"workflow-id",
- input_data={"data": "some input"},
- timeout=60.0
+ input_data={"message": "Hello"},
+ timeout=30.0,
+ max_retries=3, # Maximum number of retries
+ initial_delay=1.0, # Initial delay in seconds
+ max_delay=30.0, # Maximum delay in seconds
+ backoff_multiplier=2.0 # Exponential backoff multiplier
)
```
**Paramètres :**
- `workflow_id` (str) : L'identifiant du workflow à exécuter
- `input_data` (dict, facultatif) : Données d'entrée à transmettre au workflow
-- `timeout` (float) : Délai d'attente pour la requête initiale en secondes
+- `timeout` (float, facultatif) : Délai d'expiration en secondes
+- `stream` (bool, facultatif) : Activer les réponses en streaming
+- `selected_outputs` (list, facultatif) : Sorties de blocs à diffuser
+- `async_execution` (bool, facultatif) : Exécuter de manière asynchrone
+- `max_retries` (int, facultatif) : Nombre maximum de tentatives (par défaut : 3)
+- `initial_delay` (float, facultatif) : Délai initial en secondes (par défaut : 1.0)
+- `max_delay` (float, facultatif) : Délai maximum en secondes (par défaut : 30.0)
+- `backoff_multiplier` (float, facultatif) : Multiplicateur de backoff (par défaut : 2.0)
+
+**Retourne :** `WorkflowExecutionResult | AsyncExecutionResult`
-**Retourne :** `WorkflowExecutionResult`
+La logique de nouvelle tentative utilise un backoff exponentiel (1s → 2s → 4s → 8s...) avec une variation aléatoire de ±25% pour éviter l'effet de horde. Si l'API fournit un en-tête `retry-after`, celui-ci sera utilisé à la place.
+
+##### get_rate_limit_info()
+
+Obtenir les informations actuelles sur les limites de débit à partir de la dernière réponse de l'API.
+
+```python
+rate_limit_info = client.get_rate_limit_info()
+if rate_limit_info:
+ print("Limit:", rate_limit_info.limit)
+ print("Remaining:", rate_limit_info.remaining)
+ print("Reset:", datetime.fromtimestamp(rate_limit_info.reset))
+```
+
+**Retourne :** `RateLimitInfo | None`
+
+##### get_usage_limits()
+
+Obtenir les limites d'utilisation actuelles et les informations de quota pour votre compte.
+
+```python
+limits = client.get_usage_limits()
+print("Sync requests remaining:", limits.rate_limit["sync"]["remaining"])
+print("Async requests remaining:", limits.rate_limit["async"]["remaining"])
+print("Current period cost:", limits.usage["currentPeriodCost"])
+print("Plan:", limits.usage["plan"])
+```
+
+**Retourne :** `UsageLimits`
+
+**Structure de la réponse :**
+
+```python
+{
+ "success": bool,
+ "rateLimit": {
+ "sync": {
+ "isLimited": bool,
+ "limit": int,
+ "remaining": int,
+ "resetAt": str
+ },
+ "async": {
+ "isLimited": bool,
+ "limit": int,
+ "remaining": int,
+ "resetAt": str
+ },
+ "authType": str # 'api' or 'manual'
+ },
+ "usage": {
+ "currentPeriodCost": float,
+ "limit": float,
+ "plan": str # e.g., 'free', 'pro'
+ }
+}
+```
##### set_api_key()
-Met à jour la clé API.
+Mettre à jour la clé API.
```python
client.set_api_key("new-api-key")
@@ -140,7 +235,7 @@ client.set_api_key("new-api-key")
##### set_base_url()
-Met à jour l'URL de base.
+Mettre à jour l'URL de base.
```python
client.set_base_url("https://my-custom-domain.com")
@@ -148,7 +243,7 @@ client.set_base_url("https://my-custom-domain.com")
##### close()
-Ferme la session HTTP sous-jacente.
+Fermer la session HTTP sous-jacente.
```python
client.close()
@@ -170,6 +265,18 @@ class WorkflowExecutionResult:
total_duration: Optional[float] = None
```
+### AsyncExecutionResult
+
+```python
+@dataclass
+class AsyncExecutionResult:
+ success: bool
+ task_id: str
+ status: str # 'queued'
+ created_at: str
+ links: Dict[str, str] # e.g., {"status": "/api/jobs/{taskId}"}
+```
+
### WorkflowStatus
```python
@@ -181,6 +288,27 @@ class WorkflowStatus:
needs_redeployment: bool = False
```
+### RateLimitInfo
+
+```python
+@dataclass
+class RateLimitInfo:
+ limit: int
+ remaining: int
+ reset: int
+ retry_after: Optional[int] = None
+```
+
+### UsageLimits
+
+```python
+@dataclass
+class UsageLimits:
+ success: bool
+ rate_limit: Dict[str, Any]
+ usage: Dict[str, Any]
+```
+
### SimStudioError
```python
@@ -191,19 +319,26 @@ class SimStudioError(Exception):
self.status = status
```
+**Codes d'erreur courants :**
+- `UNAUTHORIZED` : Clé API invalide
+- `TIMEOUT` : Délai d'attente de la requête dépassé
+- `RATE_LIMIT_EXCEEDED` : Limite de débit dépassée
+- `USAGE_LIMIT_EXCEEDED` : Limite d'utilisation dépassée
+- `EXECUTION_ERROR` : Échec de l'exécution du workflow
+
## Exemples
-### Exécution de flux de travail basique
+### Exécution basique d'un workflow
Configurez le SimStudioClient avec votre clé API.
-
- Vérifiez si le flux de travail est déployé et prêt pour l'exécution.
+
+ Vérifiez si le workflow est déployé et prêt pour l'exécution.
-
- Lancez le flux de travail avec vos données d'entrée.
+
+ Lancez le workflow avec vos données d'entrée.
Traitez le résultat de l'exécution et gérez les éventuelles erreurs.
@@ -246,13 +381,13 @@ run_workflow()
### Gestion des erreurs
-Gérez différents types d'erreurs qui peuvent survenir pendant l'exécution du flux de travail :
+Gérez différents types d'erreurs qui peuvent survenir pendant l'exécution du workflow :
```python
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:
@@ -290,9 +425,9 @@ with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
# Session is automatically closed here
```
-### Exécution de flux de travail par lots
+### Exécution de workflows par lots
-Exécutez plusieurs flux de travail efficacement :
+Exécutez plusieurs workflows efficacement :
```python
from simstudio import SimStudioClient
@@ -339,6 +474,230 @@ for result in results:
print(f"Workflow {result['workflow_id']}: {'Success' if result['success'] else 'Failed'}")
```
+### Exécution asynchrone de workflow
+
+Exécutez des workflows de manière asynchrone pour les tâches de longue durée :
+
+```python
+import os
+import time
+from simstudio import SimStudioClient
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_async():
+ try:
+ # Start async execution
+ result = client.execute_workflow(
+ "workflow-id",
+ input_data={"data": "large dataset"},
+ async_execution=True # Execute asynchronously
+ )
+
+ # Check if result is an async execution
+ if hasattr(result, 'task_id'):
+ print(f"Task ID: {result.task_id}")
+ print(f"Status endpoint: {result.links['status']}")
+
+ # Poll for completion
+ status = client.get_job_status(result.task_id)
+
+ while status["status"] in ["queued", "processing"]:
+ print(f"Current status: {status['status']}")
+ time.sleep(2) # Wait 2 seconds
+ status = client.get_job_status(result.task_id)
+
+ if status["status"] == "completed":
+ print("Workflow completed!")
+ print(f"Output: {status['output']}")
+ print(f"Duration: {status['metadata']['duration']}")
+ else:
+ print(f"Workflow failed: {status['error']}")
+
+ except Exception as error:
+ print(f"Error: {error}")
+
+execute_async()
+```
+
+### Limitation de débit et nouvelle tentative
+
+Gérez les limites de débit automatiquement avec un retrait exponentiel :
+
+```python
+import os
+from simstudio import SimStudioClient, SimStudioError
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_with_retry_handling():
+ try:
+ # Automatically retries on rate limit
+ result = client.execute_with_retry(
+ "workflow-id",
+ input_data={"message": "Process this"},
+ max_retries=5,
+ initial_delay=1.0,
+ max_delay=60.0,
+ backoff_multiplier=2.0
+ )
+
+ print(f"Success: {result}")
+ except SimStudioError as error:
+ if error.code == "RATE_LIMIT_EXCEEDED":
+ print("Rate limit exceeded after all retries")
+
+ # Check rate limit info
+ rate_limit_info = client.get_rate_limit_info()
+ if rate_limit_info:
+ from datetime import datetime
+ reset_time = datetime.fromtimestamp(rate_limit_info.reset)
+ print(f"Rate limit resets at: {reset_time}")
+
+execute_with_retry_handling()
+```
+
+### Surveillance de l'utilisation
+
+Surveillez l'utilisation et les limites de votre compte :
+
+```python
+import os
+from simstudio import SimStudioClient
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def check_usage():
+ try:
+ limits = client.get_usage_limits()
+
+ print("=== Rate Limits ===")
+ print("Sync requests:")
+ print(f" Limit: {limits.rate_limit['sync']['limit']}")
+ print(f" Remaining: {limits.rate_limit['sync']['remaining']}")
+ print(f" Resets at: {limits.rate_limit['sync']['resetAt']}")
+ print(f" Is limited: {limits.rate_limit['sync']['isLimited']}")
+
+ print("\nAsync requests:")
+ print(f" Limit: {limits.rate_limit['async']['limit']}")
+ print(f" Remaining: {limits.rate_limit['async']['remaining']}")
+ print(f" Resets at: {limits.rate_limit['async']['resetAt']}")
+ print(f" Is limited: {limits.rate_limit['async']['isLimited']}")
+
+ print("\n=== Usage ===")
+ print(f"Current period cost: ${limits.usage['currentPeriodCost']:.2f}")
+ print(f"Limit: ${limits.usage['limit']:.2f}")
+ print(f"Plan: {limits.usage['plan']}")
+
+ percent_used = (limits.usage['currentPeriodCost'] / limits.usage['limit']) * 100
+ print(f"Usage: {percent_used:.1f}%")
+
+ if percent_used > 80:
+ print("⚠️ Warning: You are approaching your usage limit!")
+
+ except Exception as error:
+ print(f"Error checking usage: {error}")
+
+check_usage()
+```
+
+### Exécution de workflow en streaming
+
+Exécutez des workflows avec des réponses en streaming en temps réel :
+
+```python
+from simstudio import SimStudioClient
+import os
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_with_streaming():
+ """Execute workflow with streaming enabled."""
+ try:
+ # Enable streaming for specific block outputs
+ result = client.execute_workflow(
+ "workflow-id",
+ input_data={"message": "Count to five"},
+ stream=True,
+ selected_outputs=["agent1.content"] # Use blockName.attribute format
+ )
+
+ print("Workflow result:", result)
+ except Exception as error:
+ print("Error:", error)
+
+execute_with_streaming()
+```
+
+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 Flask :**
+
+```python
+from flask import Flask, Response, stream_with_context
+import requests
+import json
+import os
+
+app = Flask(__name__)
+
+@app.route('/stream-workflow')
+def stream_workflow():
+ """Stream workflow execution to the client."""
+
+ def generate():
+ response = requests.post(
+ 'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
+ headers={
+ 'Content-Type': 'application/json',
+ 'X-API-Key': os.getenv('SIM_API_KEY')
+ },
+ json={
+ 'message': 'Generate a story',
+ 'stream': True,
+ 'selectedOutputs': ['agent1.content']
+ },
+ stream=True
+ )
+
+ for line in response.iter_lines():
+ if line:
+ decoded_line = line.decode('utf-8')
+ if decoded_line.startswith('data: '):
+ data = decoded_line[6:] # Remove 'data: ' prefix
+
+ if data == '[DONE]':
+ break
+
+ try:
+ parsed = json.loads(data)
+ if 'chunk' in parsed:
+ yield f"data: {json.dumps(parsed)}\n\n"
+ elif parsed.get('event') == 'done':
+ yield f"data: {json.dumps(parsed)}\n\n"
+ print("Execution complete:", parsed.get('metadata'))
+ except json.JSONDecodeError:
+ pass
+
+ return Response(
+ stream_with_context(generate()),
+ mimetype='text/event-stream'
+ )
+
+if __name__ == '__main__':
+ app.run(debug=True)
+```
+
### Configuration de l'environnement
Configurez le client en utilisant des variables d'environnement :
@@ -352,7 +711,7 @@ Configurez le client en utilisant des variables d'environnement :
# Development configuration
client = SimStudioClient(
- api_key=os.getenv("SIM_API_KEY"),
+ api_key=os.getenv("SIM_API_KEY")
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
)
```
@@ -378,17 +737,17 @@ Configurez le client en utilisant des variables d'environnement :
-## Obtenir votre clé API
+## Obtention de votre clé API
Accédez à [Sim](https://sim.ai) et connectez-vous à votre compte.
-
- Naviguez vers le flux de travail que vous souhaitez exécuter par programmation.
+
+ Accédez au workflow que vous souhaitez exécuter par programmation.
-
- Cliquez sur "Déployer" pour déployer votre flux de travail s'il n'a pas encore été déployé.
+
+ 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.
diff --git a/apps/docs/content/docs/fr/sdks/typescript.mdx b/apps/docs/content/docs/fr/sdks/typescript.mdx
index 1dec62fbd7..ca572c346e 100644
--- a/apps/docs/content/docs/fr/sdks/typescript.mdx
+++ b/apps/docs/content/docs/fr/sdks/typescript.mdx
@@ -7,10 +7,10 @@ import { Card, Cards } from 'fumadocs-ui/components/card'
import { Step, Steps } from 'fumadocs-ui/components/steps'
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
-Le SDK officiel TypeScript/JavaScript pour Sim offre une sécurité de type complète et prend en charge les environnements Node.js et navigateur, vous permettant d'exécuter des workflows de manière programmatique depuis vos applications Node.js, applications web et autres environnements JavaScript. Toutes les exécutions de workflow sont actuellement synchrones.
+Le SDK officiel TypeScript/JavaScript pour Sim offre une sécurité de type complète et prend en charge les environnements Node.js et navigateur, vous permettant d'exécuter des workflows par programmation depuis vos applications Node.js, applications web et autres environnements JavaScript.
- Le SDK TypeScript offre une sécurité de type complète et prend en charge les environnements Node.js et navigateur. Toutes les exécutions de workflow sont actuellement synchrones.
+ Le SDK TypeScript offre une sécurité de type complète, la prise en charge de l'exécution asynchrone, une limitation automatique du débit avec backoff exponentiel et le suivi d'utilisation.
## Installation
@@ -91,12 +91,17 @@ const result = await client.executeWorkflow('workflow-id', {
```
**Paramètres :**
-- `workflowId` (string) : L'identifiant du workflow à exécuter
-- `options` (ExecutionOptions, facultatif) :
+- `workflowId` (string) : L'ID du workflow à exécuter
+- `options` (ExecutionOptions, optionnel) :
- `input` (any) : Données d'entrée à transmettre au workflow
- `timeout` (number) : Délai d'expiration en millisecondes (par défaut : 30000)
+ - `stream` (boolean) : Activer les réponses en streaming (par défaut : false)
+ - `selectedOutputs` (string[]) : Bloquer les sorties à diffuser au format `blockName.attribute` (par exemple, `["agent1.content"]`)
+ - `async` (boolean) : Exécuter de manière asynchrone (par défaut : false)
+
+**Retourne :** `Promise`
-**Retourne :** `Promise`
+Lorsque `async: true`, retourne immédiatement avec un ID de tâche pour l'interrogation. Sinon, attend la fin de l'exécution.
##### getWorkflowStatus()
@@ -108,7 +113,7 @@ console.log('Is deployed:', status.isDeployed);
```
**Paramètres :**
-- `workflowId` (string) : L'identifiant du workflow
+- `workflowId` (string) : L'ID du workflow
**Retourne :** `Promise`
@@ -124,36 +129,125 @@ if (isReady) {
```
**Paramètres :**
-- `workflowId` (string) : L'identifiant du workflow
+- `workflowId` (string) : L'ID du workflow
**Retourne :** `Promise`
-##### executeWorkflowSync()
+##### getJobStatus()
-
- Actuellement, cette méthode est identique à `executeWorkflow()` puisque toutes les exécutions sont synchrones. Cette méthode est fournie pour une compatibilité future lorsque l'exécution asynchrone sera ajoutée.
-
+Obtenir le statut d'une exécution de tâche asynchrone.
+
+```typescript
+const status = await client.getJobStatus('task-id-from-async-execution');
+console.log('Status:', status.status); // 'queued', 'processing', 'completed', 'failed'
+if (status.status === 'completed') {
+ console.log('Output:', status.output);
+}
+```
+
+**Paramètres :**
+- `taskId` (string) : L'ID de tâche retourné par l'exécution asynchrone
+
+**Retourne :** `Promise`
-Exécuter un workflow (actuellement synchrone, identique à `executeWorkflow()`).
+**Champs de réponse :**
+- `success` (boolean) : Indique si la requête a réussi
+- `taskId` (string) : L'ID de la tâche
+- `status` (string) : L'un des statuts suivants : `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
+- `metadata` (object) : Contient `startedAt`, `completedAt`, et `duration`
+- `output` (any, optionnel) : La sortie du workflow (une fois terminé)
+- `error` (any, optionnel) : Détails de l'erreur (en cas d'échec)
+- `estimatedDuration` (number, optionnel) : Durée estimée en millisecondes (lorsqu'en traitement/en file d'attente)
+
+##### executeWithRetry()
+
+Exécute un workflow avec une nouvelle tentative automatique en cas d'erreurs de limite de débit en utilisant un backoff exponentiel.
```typescript
-const result = await client.executeWorkflowSync('workflow-id', {
- input: { data: 'some input' },
- timeout: 60000
+const result = await client.executeWithRetry('workflow-id', {
+ input: { message: 'Hello' },
+ timeout: 30000
+}, {
+ maxRetries: 3, // Maximum number of retries
+ initialDelay: 1000, // Initial delay in ms (1 second)
+ maxDelay: 30000, // Maximum delay in ms (30 seconds)
+ backoffMultiplier: 2 // Exponential backoff multiplier
});
```
**Paramètres :**
- `workflowId` (string) : L'identifiant du workflow à exécuter
-- `options` (ExecutionOptions, facultatif) :
- - `input` (any) : Données d'entrée à transmettre au workflow
- - `timeout` (number) : Délai d'expiration pour la requête initiale en millisecondes
+- `options` (ExecutionOptions, facultatif) : Identique à `executeWorkflow()`
+- `retryOptions` (RetryOptions, facultatif) :
+ - `maxRetries` (number) : Nombre maximum de tentatives (par défaut : 3)
+ - `initialDelay` (number) : Délai initial en ms (par défaut : 1000)
+ - `maxDelay` (number) : Délai maximum en ms (par défaut : 30000)
+ - `backoffMultiplier` (number) : Multiplicateur de backoff (par défaut : 2)
+
+**Retourne :** `Promise`
+
+La logique de nouvelle tentative utilise un backoff exponentiel (1s → 2s → 4s → 8s...) avec une variation aléatoire de ±25 % pour éviter l'effet de rafale. Si l'API fournit un en-tête `retry-after`, celui-ci sera utilisé à la place.
+
+##### getRateLimitInfo()
+
+Obtient les informations actuelles sur les limites de débit à partir de la dernière réponse de l'API.
+
+```typescript
+const rateLimitInfo = client.getRateLimitInfo();
+if (rateLimitInfo) {
+ console.log('Limit:', rateLimitInfo.limit);
+ console.log('Remaining:', rateLimitInfo.remaining);
+ console.log('Reset:', new Date(rateLimitInfo.reset * 1000));
+}
+```
+
+**Retourne :** `RateLimitInfo | null`
+
+##### getUsageLimits()
-**Retourne :** `Promise`
+Obtient les limites d'utilisation actuelles et les informations de quota pour votre compte.
+
+```typescript
+const limits = await client.getUsageLimits();
+console.log('Sync requests remaining:', limits.rateLimit.sync.remaining);
+console.log('Async requests remaining:', limits.rateLimit.async.remaining);
+console.log('Current period cost:', limits.usage.currentPeriodCost);
+console.log('Plan:', limits.usage.plan);
+```
+
+**Retourne :** `Promise`
+
+**Structure de la réponse :**
+
+```typescript
+{
+ success: boolean
+ rateLimit: {
+ sync: {
+ isLimited: boolean
+ limit: number
+ remaining: number
+ resetAt: string
+ }
+ async: {
+ isLimited: boolean
+ limit: number
+ remaining: number
+ resetAt: string
+ }
+ authType: string // 'api' or 'manual'
+ }
+ usage: {
+ currentPeriodCost: number
+ limit: number
+ plan: string // e.g., 'free', 'pro'
+ }
+}
+```
##### setApiKey()
-Mettre à jour la clé API.
+Met à jour la clé API.
```typescript
client.setApiKey('new-api-key');
@@ -161,7 +255,7 @@ client.setApiKey('new-api-key');
##### setBaseUrl()
-Mettre à jour l'URL de base.
+Met à jour l'URL de base.
```typescript
client.setBaseUrl('https://my-custom-domain.com');
@@ -187,6 +281,20 @@ interface WorkflowExecutionResult {
}
```
+### AsyncExecutionResult
+
+```typescript
+interface AsyncExecutionResult {
+ success: boolean;
+ taskId: string;
+ status: 'queued';
+ createdAt: string;
+ links: {
+ status: string; // e.g., "/api/jobs/{taskId}"
+ };
+}
+```
+
### WorkflowStatus
```typescript
@@ -198,6 +306,45 @@ interface WorkflowStatus {
}
```
+### RateLimitInfo
+
+```typescript
+interface RateLimitInfo {
+ limit: number;
+ remaining: number;
+ reset: number;
+ retryAfter?: number;
+}
+```
+
+### UsageLimits
+
+```typescript
+interface UsageLimits {
+ success: boolean;
+ rateLimit: {
+ sync: {
+ isLimited: boolean;
+ limit: number;
+ remaining: number;
+ resetAt: string;
+ };
+ async: {
+ isLimited: boolean;
+ limit: number;
+ remaining: number;
+ resetAt: string;
+ };
+ authType: string;
+ };
+ usage: {
+ currentPeriodCost: number;
+ limit: number;
+ plan: string;
+ };
+}
+```
+
### SimStudioError
```typescript
@@ -207,9 +354,16 @@ class SimStudioError extends Error {
}
```
+**Codes d'erreur courants :**
+- `UNAUTHORIZED` : Clé API invalide
+- `TIMEOUT` : Délai d'attente de la requête dépassé
+- `RATE_LIMIT_EXCEEDED` : Limite de débit dépassée
+- `USAGE_LIMIT_EXCEEDED` : Limite d'utilisation dépassée
+- `EXECUTION_ERROR` : Échec de l'exécution du workflow
+
## Exemples
-### Exécution de workflow basique
+### Exécution basique d'un workflow
@@ -469,14 +623,14 @@ document.getElementById('executeBtn')?.addEventListener('click', executeClientSi
### Exemple de hook React
-Créez un hook React personnalisé pour l'exécution du workflow :
+Créer un hook React personnalisé pour l'exécution de workflow :
```typescript
import { useState, useCallback } from 'react';
import { SimStudioClient, WorkflowExecutionResult } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
- apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
+ apiKey: process.env.SIM_API_KEY!
});
interface UseWorkflowResult {
@@ -532,7 +686,7 @@ function WorkflowComponent() {
-
+
{error &&
Error: {error.message}
}
{result && (
@@ -545,38 +699,267 @@ function WorkflowComponent() {
}
```
-## Obtenir votre clé API
+### Exécution asynchrone de workflow
+
+Exécuter des workflows de manière asynchrone pour les tâches de longue durée :
+
+```typescript
+import { SimStudioClient, AsyncExecutionResult } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function executeAsync() {
+ try {
+ // Start async execution
+ const result = await client.executeWorkflow('workflow-id', {
+ input: { data: 'large dataset' },
+ async: true // Execute asynchronously
+ });
+
+ // Check if result is an async execution
+ if ('taskId' in result) {
+ console.log('Task ID:', result.taskId);
+ console.log('Status endpoint:', result.links.status);
+
+ // Poll for completion
+ 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
+ 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);
+ } else {
+ console.error('Workflow failed:', status.error);
+ }
+ }
+ } catch (error) {
+ console.error('Error:', error);
+ }
+}
+
+executeAsync();
+```
+
+### Limitation de débit et nouvelle tentative
+
+Gérer automatiquement les limites de débit avec backoff exponentiel :
+
+```typescript
+import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function executeWithRetryHandling() {
+ try {
+ // Automatically retries on rate limit
+ const result = await client.executeWithRetry('workflow-id', {
+ input: { message: 'Process this' }
+ }, {
+ maxRetries: 5,
+ initialDelay: 1000,
+ maxDelay: 60000,
+ backoffMultiplier: 2
+ });
+
+ console.log('Success:', result);
+ } catch (error) {
+ if (error instanceof SimStudioError && error.code === 'RATE_LIMIT_EXCEEDED') {
+ console.error('Rate limit exceeded after all retries');
+
+ // Check rate limit info
+ const rateLimitInfo = client.getRateLimitInfo();
+ if (rateLimitInfo) {
+ console.log('Rate limit resets at:', new Date(rateLimitInfo.reset * 1000));
+ }
+ }
+ }
+}
+```
+
+### Surveillance d'utilisation
+
+Surveiller l'utilisation et les limites de votre compte :
+
+```typescript
+import { SimStudioClient } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function checkUsage() {
+ try {
+ const limits = await client.getUsageLimits();
+
+ console.log('=== 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('\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);
+
+ console.log('\n=== Usage ===');
+ console.log('Current period cost:
+
+### Streaming Workflow Execution
+
+Execute workflows with real-time streaming responses:
+
+```typescript
+import { SimStudioClient } from 'simstudio-ts-sdk';
+
+const client = new SimStudioClient({
+ apiKey: process.env.SIM_API_KEY!
+});
+
+async function executeWithStreaming() {
+ try {
+ // Activer le streaming pour des sorties de blocs spécifiques
+ const result = await client.executeWorkflow('workflow-id', {
+ input: { message: 'Compter jusqu'à cinq' },
+ stream: true,
+ selectedOutputs: ['agent1.content'] // Utiliser le format blockName.attribute
+ });
+
+ console.log('Résultat du workflow :', result);
+ } catch (error) {
+ console.error('Erreur :', error);
+ }
+}
+```
+
+The streaming response follows the Server-Sent Events (SSE) format:
+
+```
+data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
+
+data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", deux"}
+
+data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
+
+data: [DONE]
+```
+
+**React Streaming Example:**
+
+```typescript
+import { useState, useEffect } from 'react';
+
+function StreamingWorkflow() {
+ const [output, setOutput] = useState('');
+ const [loading, setLoading] = useState(false);
+
+ const executeStreaming = async () => {
+ setLoading(true);
+ setOutput('');
+
+ // IMPORTANT: Make this API call from your backend server, not the browser
+ // Never expose your API key in client-side code
+ const response = await fetch('https://sim.ai/api/workflows/WORKFLOW_ID/execute', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-API-Key': process.env.SIM_API_KEY! // Server-side environment variable only
+ },
+ body: JSON.stringify({
+ message: 'Generate a story',
+ stream: true,
+ selectedOutputs: ['agent1.content']
+ })
+ });
+
+ const reader = response.body?.getReader();
+ const decoder = new TextDecoder();
+
+ while (reader) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ const chunk = decoder.decode(value);
+ const lines = chunk.split('\n\n');
+
+ for (const line of lines) {
+ if (line.startsWith('data: ')) {
+ const data = line.slice(6);
+ if (data === '[DONE]') {
+ setLoading(false);
+ break;
+ }
+
+ try {
+ const parsed = JSON.parse(data);
+ if (parsed.chunk) {
+ setOutput(prev => prev + parsed.chunk);
+ } else if (parsed.event === 'done') {
+ console.log('Execution complete:', parsed.metadata);
+ }
+ } catch (e) {
+ // Skip invalid JSON
+ }
+ }
+ }
+ }
+ };
+
+ return (
+
+
+
{output}
+
+ );
+}
+```
+
+## Getting Your API Key
-
- Accédez à [Sim](https://sim.ai) et connectez-vous à votre compte.
+
+ Navigate to [Sim](https://sim.ai) and log in to your account.
-
- Accédez au workflow que vous souhaitez exécuter par programmation.
+
+ Navigate to the workflow you want to execute programmatically.
-
- Cliquez sur « Déployer » pour déployer votre workflow s'il n'a pas encore été déployé.
+
+ Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.
-
- Pendant le processus de déploiement, sélectionnez ou créez une clé API.
+
+ During the deployment process, select or create an API key.
-
- Copiez la clé API à utiliser dans votre application TypeScript/JavaScript.
+
+ Copy the API key to use in your TypeScript/JavaScript application.
- Gardez votre clé API en sécurité et ne la soumettez jamais au contrôle de version. Utilisez des variables d'environnement ou une gestion de configuration sécurisée.
+ Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management.
-## Prérequis
+## Requirements
- Node.js 16+
-- TypeScript 5.0+ (pour les projets TypeScript)
+- TypeScript 5.0+ (for TypeScript projects)
-## Support TypeScript
+## TypeScript Support
-Le SDK est écrit en TypeScript et offre une sécurité de type complète :
+The SDK is written in TypeScript and provides full type safety:
```typescript
import {
@@ -594,7 +977,7 @@ const client: SimStudioClient = new SimStudioClient({
// Type-safe workflow execution
const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
input: {
- message: 'Hello, TypeScript!'
+ message: 'Bonjour, TypeScript !'
}
});
@@ -602,6 +985,7 @@ const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-i
const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
```
-## Licence
+## License
+
-Apache-2.0
\ No newline at end of file
+Apache-2.0
diff --git a/apps/docs/content/docs/fr/triggers/api.mdx b/apps/docs/content/docs/fr/triggers/api.mdx
index bac2d9ab95..978ec55610 100644
--- a/apps/docs/content/docs/fr/triggers/api.mdx
+++ b/apps/docs/content/docs/fr/triggers/api.mdx
@@ -38,6 +38,84 @@ curl -X POST \
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.
+## 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.
+
+### 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"]`)
+
+### 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"`)
+- Les noms de blocs ne sont pas sensibles à la casse et les espaces sont ignorés
+
+### Exemple de requête
+
+```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": "Count to five",
+ "stream": true,
+ "selectedOutputs": ["agent1.content"]
+ }'
+```
+
+### Format de réponse
+
+Les réponses en streaming utilisent 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: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", three"}
+
+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é
+- **Événement final** : `{"event": "done", ...}` - Métadonnées d'exécution et résultats complets
+- **Terminateur** : `[DONE]` - Signale la fin du flux
+
+### Streaming de plusieurs blocs
+
+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"]
+ }'
+```
+
+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"}
+```
+
## Référence des sorties
| Référence | Description |
diff --git a/apps/docs/content/docs/ja/sdks/python.mdx b/apps/docs/content/docs/ja/sdks/python.mdx
index debb8bac3c..b667a9f3d8 100644
--- a/apps/docs/content/docs/ja/sdks/python.mdx
+++ b/apps/docs/content/docs/ja/sdks/python.mdx
@@ -10,7 +10,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
Simの公式Python SDKを使用すると、公式Python SDKを使用してPythonアプリケーションからプログラムでワークフローを実行できます。
- Python SDKはPython 3.8以上をサポートし、同期的なワークフロー実行を提供します。現在、すべてのワークフロー実行は同期的です。
+ Python SDKはPython 3.8以上をサポートし、非同期実行、指数バックオフによる自動レート制限、使用状況追跡機能を提供します。
## インストール
@@ -70,12 +70,17 @@ result = client.execute_workflow(
)
```
-**パラメータ:**
+**パラメータ:**
- `workflow_id` (str): 実行するワークフローのID
- `input_data` (dict, オプション): ワークフローに渡す入力データ
-- `timeout` (float, オプション): タイムアウト(秒)(デフォルト:30.0)
+- `timeout` (float, オプション): タイムアウト(秒)(デフォルト: 30.0)
+- `stream` (bool, オプション): ストリーミングレスポンスを有効にする(デフォルト: False)
+- `selected_outputs` (list[str], オプション): `blockName.attribute`形式でストリーミングするブロック出力(例: `["agent1.content"]`)
+- `async_execution` (bool, オプション): 非同期実行(デフォルト: False)
+
+**戻り値:** `WorkflowExecutionResult | AsyncExecutionResult`
-**戻り値:** `WorkflowExecutionResult`
+`async_execution=True`の場合、ポーリング用のタスクIDをすぐに返します。それ以外の場合は、完了を待ちます。
##### get_workflow_status()
@@ -86,7 +91,7 @@ status = client.get_workflow_status("workflow-id")
print("Is deployed:", status.is_deployed)
```
-**パラメータ:**
+**パラメータ:**
- `workflow_id` (str): ワークフローのID
**戻り値:** `WorkflowStatus`
@@ -107,28 +112,118 @@ if is_ready:
**戻り値:** `bool`
-##### execute_workflow_sync()
+##### get_job_status()
-
- 現在、このメソッドは `execute_workflow()` と同一です。すべての実行は同期的に行われるためです。このメソッドは、将来的に非同期実行が追加された際の互換性のために提供されています。
-
+非同期ジョブ実行のステータスを取得します。
+
+```python
+status = client.get_job_status("task-id-from-async-execution")
+print("Status:", status["status"]) # 'queued', 'processing', 'completed', 'failed'
+if status["status"] == "completed":
+ print("Output:", status["output"])
+```
+
+**パラメータ:**
+- `task_id` (str): 非同期実行から返されたタスクID
+
+**戻り値:** `Dict[str, Any]`
+
+**レスポンスフィールド:**
+- `success` (bool): リクエストが成功したかどうか
+- `taskId` (str): タスクID
+- `status` (str): 次のいずれか: `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
+- `metadata` (dict): `startedAt`, `completedAt`, `duration`を含む
+- `output` (any, オプション): ワークフロー出力(完了時)
+- `error` (any, オプション): エラー詳細(失敗時)
+- `estimatedDuration` (int, オプション): 推定所要時間(ミリ秒)(処理中/キュー時)
-ワークフローを実行します(現在は同期的、`execute_workflow()` と同じ)。
+##### execute_with_retry()
+
+指数バックオフを使用してレート制限エラーで自動的に再試行するワークフロー実行。
```python
-result = client.execute_workflow_sync(
+result = client.execute_with_retry(
"workflow-id",
- input_data={"data": "some input"},
- timeout=60.0
+ input_data={"message": "Hello"},
+ timeout=30.0,
+ max_retries=3, # Maximum number of retries
+ initial_delay=1.0, # Initial delay in seconds
+ max_delay=30.0, # Maximum delay in seconds
+ backoff_multiplier=2.0 # Exponential backoff multiplier
)
```
**パラメータ:**
- `workflow_id` (str): 実行するワークフローのID
-- `input_data` (dict, optional): ワークフローに渡す入力データ
-- `timeout` (float): 初期リクエストのタイムアウト(秒)
+- `input_data` (dict, オプション): ワークフローに渡す入力データ
+- `timeout` (float, オプション): タイムアウト(秒)
+- `stream` (bool, オプション): ストリーミングレスポンスを有効にする
+- `selected_outputs` (list, オプション): ストリーミングするブロック出力
+- `async_execution` (bool, オプション): 非同期実行
+- `max_retries` (int, オプション): 最大再試行回数(デフォルト: 3)
+- `initial_delay` (float, オプション): 初期遅延(秒)(デフォルト: 1.0)
+- `max_delay` (float, オプション): 最大遅延(秒)(デフォルト: 30.0)
+- `backoff_multiplier` (float, オプション): バックオフ乗数(デフォルト: 2.0)
+
+**戻り値:** `WorkflowExecutionResult | AsyncExecutionResult`
+
+リトライロジックは、サンダリングハード問題を防ぐために±25%のジッターを伴う指数バックオフ(1秒→2秒→4秒→8秒...)を使用します。APIが `retry-after` ヘッダーを提供する場合、代わりにそれが使用されます。
-**戻り値:** `WorkflowExecutionResult`
+##### get_rate_limit_info()
+
+最後のAPIレスポンスから現在のレート制限情報を取得します。
+
+```python
+rate_limit_info = client.get_rate_limit_info()
+if rate_limit_info:
+ print("Limit:", rate_limit_info.limit)
+ print("Remaining:", rate_limit_info.remaining)
+ print("Reset:", datetime.fromtimestamp(rate_limit_info.reset))
+```
+
+**戻り値:** `RateLimitInfo | None`
+
+##### get_usage_limits()
+
+アカウントの現在の使用制限とクォータ情報を取得します。
+
+```python
+limits = client.get_usage_limits()
+print("Sync requests remaining:", limits.rate_limit["sync"]["remaining"])
+print("Async requests remaining:", limits.rate_limit["async"]["remaining"])
+print("Current period cost:", limits.usage["currentPeriodCost"])
+print("Plan:", limits.usage["plan"])
+```
+
+**戻り値:** `UsageLimits`
+
+**レスポンス構造:**
+
+```python
+{
+ "success": bool,
+ "rateLimit": {
+ "sync": {
+ "isLimited": bool,
+ "limit": int,
+ "remaining": int,
+ "resetAt": str
+ },
+ "async": {
+ "isLimited": bool,
+ "limit": int,
+ "remaining": int,
+ "resetAt": str
+ },
+ "authType": str # 'api' or 'manual'
+ },
+ "usage": {
+ "currentPeriodCost": float,
+ "limit": float,
+ "plan": str # e.g., 'free', 'pro'
+ }
+}
+```
##### set_api_key()
@@ -170,6 +265,18 @@ class WorkflowExecutionResult:
total_duration: Optional[float] = None
```
+### AsyncExecutionResult
+
+```python
+@dataclass
+class AsyncExecutionResult:
+ success: bool
+ task_id: str
+ status: str # 'queued'
+ created_at: str
+ links: Dict[str, str] # e.g., {"status": "/api/jobs/{taskId}"}
+```
+
### WorkflowStatus
```python
@@ -181,6 +288,27 @@ class WorkflowStatus:
needs_redeployment: bool = False
```
+### RateLimitInfo
+
+```python
+@dataclass
+class RateLimitInfo:
+ limit: int
+ remaining: int
+ reset: int
+ retry_after: Optional[int] = None
+```
+
+### UsageLimits
+
+```python
+@dataclass
+class UsageLimits:
+ success: bool
+ rate_limit: Dict[str, Any]
+ usage: Dict[str, Any]
+```
+
### SimStudioError
```python
@@ -191,6 +319,13 @@ class SimStudioError(Exception):
self.status = status
```
+**一般的なエラーコード:**
+- `UNAUTHORIZED`: 無効なAPIキー
+- `TIMEOUT`: リクエストがタイムアウトしました
+- `RATE_LIMIT_EXCEEDED`: レート制限を超えました
+- `USAGE_LIMIT_EXCEEDED`: 使用制限を超えました
+- `EXECUTION_ERROR`: ワークフローの実行に失敗しました
+
## 例
### 基本的なワークフロー実行
@@ -277,7 +412,7 @@ def execute_with_error_handling():
### コンテキストマネージャーの使用
-リソースのクリーンアップを自動的に処理するためにコンテキストマネージャーとしてクライアントを使用します:
+リソースのクリーンアップを自動的に処理するためにクライアントをコンテキストマネージャーとして使用します:
```python
from simstudio import SimStudioClient
@@ -339,6 +474,230 @@ for result in results:
print(f"Workflow {result['workflow_id']}: {'Success' if result['success'] else 'Failed'}")
```
+### 非同期ワークフロー実行
+
+長時間実行されるタスクのためにワークフローを非同期で実行します:
+
+```python
+import os
+import time
+from simstudio import SimStudioClient
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_async():
+ try:
+ # Start async execution
+ result = client.execute_workflow(
+ "workflow-id",
+ input_data={"data": "large dataset"},
+ async_execution=True # Execute asynchronously
+ )
+
+ # Check if result is an async execution
+ if hasattr(result, 'task_id'):
+ print(f"Task ID: {result.task_id}")
+ print(f"Status endpoint: {result.links['status']}")
+
+ # Poll for completion
+ status = client.get_job_status(result.task_id)
+
+ while status["status"] in ["queued", "processing"]:
+ print(f"Current status: {status['status']}")
+ time.sleep(2) # Wait 2 seconds
+ status = client.get_job_status(result.task_id)
+
+ if status["status"] == "completed":
+ print("Workflow completed!")
+ print(f"Output: {status['output']}")
+ print(f"Duration: {status['metadata']['duration']}")
+ else:
+ print(f"Workflow failed: {status['error']}")
+
+ except Exception as error:
+ print(f"Error: {error}")
+
+execute_async()
+```
+
+### レート制限とリトライ
+
+指数バックオフを使用して自動的にレート制限を処理します:
+
+```python
+import os
+from simstudio import SimStudioClient, SimStudioError
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_with_retry_handling():
+ try:
+ # Automatically retries on rate limit
+ result = client.execute_with_retry(
+ "workflow-id",
+ input_data={"message": "Process this"},
+ max_retries=5,
+ initial_delay=1.0,
+ max_delay=60.0,
+ backoff_multiplier=2.0
+ )
+
+ print(f"Success: {result}")
+ except SimStudioError as error:
+ if error.code == "RATE_LIMIT_EXCEEDED":
+ print("Rate limit exceeded after all retries")
+
+ # Check rate limit info
+ rate_limit_info = client.get_rate_limit_info()
+ if rate_limit_info:
+ from datetime import datetime
+ reset_time = datetime.fromtimestamp(rate_limit_info.reset)
+ print(f"Rate limit resets at: {reset_time}")
+
+execute_with_retry_handling()
+```
+
+### 使用状況モニタリング
+
+アカウントの使用状況と制限をモニタリングします:
+
+```python
+import os
+from simstudio import SimStudioClient
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def check_usage():
+ try:
+ limits = client.get_usage_limits()
+
+ print("=== Rate Limits ===")
+ print("Sync requests:")
+ print(f" Limit: {limits.rate_limit['sync']['limit']}")
+ print(f" Remaining: {limits.rate_limit['sync']['remaining']}")
+ print(f" Resets at: {limits.rate_limit['sync']['resetAt']}")
+ print(f" Is limited: {limits.rate_limit['sync']['isLimited']}")
+
+ print("\nAsync requests:")
+ print(f" Limit: {limits.rate_limit['async']['limit']}")
+ print(f" Remaining: {limits.rate_limit['async']['remaining']}")
+ print(f" Resets at: {limits.rate_limit['async']['resetAt']}")
+ print(f" Is limited: {limits.rate_limit['async']['isLimited']}")
+
+ print("\n=== Usage ===")
+ print(f"Current period cost: ${limits.usage['currentPeriodCost']:.2f}")
+ print(f"Limit: ${limits.usage['limit']:.2f}")
+ print(f"Plan: {limits.usage['plan']}")
+
+ percent_used = (limits.usage['currentPeriodCost'] / limits.usage['limit']) * 100
+ print(f"Usage: {percent_used:.1f}%")
+
+ if percent_used > 80:
+ print("⚠️ Warning: You are approaching your usage limit!")
+
+ except Exception as error:
+ print(f"Error checking usage: {error}")
+
+check_usage()
+```
+
+### ワークフローの実行ストリーミング
+
+リアルタイムのストリーミングレスポンスでワークフローを実行します:
+
+```python
+from simstudio import SimStudioClient
+import os
+
+client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
+
+def execute_with_streaming():
+ """Execute workflow with streaming enabled."""
+ try:
+ # Enable streaming for specific block outputs
+ result = client.execute_workflow(
+ "workflow-id",
+ input_data={"message": "Count to five"},
+ stream=True,
+ selected_outputs=["agent1.content"] # Use blockName.attribute format
+ )
+
+ print("Workflow result:", result)
+ except Exception as error:
+ print("Error:", error)
+
+execute_with_streaming()
+```
+
+ストリーミングレスポンスは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]
+```
+
+**Flaskストリーミングの例:**
+
+```python
+from flask import Flask, Response, stream_with_context
+import requests
+import json
+import os
+
+app = Flask(__name__)
+
+@app.route('/stream-workflow')
+def stream_workflow():
+ """Stream workflow execution to the client."""
+
+ def generate():
+ response = requests.post(
+ 'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
+ headers={
+ 'Content-Type': 'application/json',
+ 'X-API-Key': os.getenv('SIM_API_KEY')
+ },
+ json={
+ 'message': 'Generate a story',
+ 'stream': True,
+ 'selectedOutputs': ['agent1.content']
+ },
+ stream=True
+ )
+
+ for line in response.iter_lines():
+ if line:
+ decoded_line = line.decode('utf-8')
+ if decoded_line.startswith('data: '):
+ data = decoded_line[6:] # Remove 'data: ' prefix
+
+ if data == '[DONE]':
+ break
+
+ try:
+ parsed = json.loads(data)
+ if 'chunk' in parsed:
+ yield f"data: {json.dumps(parsed)}\n\n"
+ elif parsed.get('event') == 'done':
+ yield f"data: {json.dumps(parsed)}\n\n"
+ print("Execution complete:", parsed.get('metadata'))
+ except json.JSONDecodeError:
+ pass
+
+ return Response(
+ stream_with_context(generate()),
+ mimetype='text/event-stream'
+ )
+
+if __name__ == '__main__':
+ app.run(debug=True)
+```
+
### 環境設定
環境変数を使用してクライアントを設定します:
@@ -352,7 +711,7 @@ for result in results:
# Development configuration
client = SimStudioClient(
- api_key=os.getenv("SIM_API_KEY"),
+ api_key=os.getenv("SIM_API_KEY")
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
)
```
diff --git a/apps/docs/content/docs/ja/sdks/typescript.mdx b/apps/docs/content/docs/ja/sdks/typescript.mdx
index ea9bed31f5..785f60b29d 100644
--- a/apps/docs/content/docs/ja/sdks/typescript.mdx
+++ b/apps/docs/content/docs/ja/sdks/typescript.mdx
@@ -7,10 +7,10 @@ import { Card, Cards } from 'fumadocs-ui/components/card'
import { Step, Steps } from 'fumadocs-ui/components/steps'
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
-公式TypeScript/JavaScript SDKはSimのために完全な型安全性を提供し、Node.jsとブラウザ環境の両方をサポートしています。これにより、Node.jsアプリケーション、Webアプリケーション、その他のJavaScript環境からプログラムでワークフローを実行することができます。現在、すべてのワークフロー実行は同期的に行われます。
+Sim用の公式TypeScript/JavaScript SDKは、完全な型安全性を提供し、Node.jsとブラウザ環境の両方をサポートしています。これにより、Node.jsアプリケーション、Webアプリケーション、その他のJavaScript環境からプログラムによってワークフローを実行することができます。
- TypeScript SDKは完全な型安全性を提供し、Node.jsとブラウザ環境の両方をサポートしています。現在、すべてのワークフロー実行は同期的に行われます。
+ TypeScript SDKは、完全な型安全性、非同期実行サポート、指数バックオフによる自動レート制限、使用状況追跡を提供します。
## インストール
@@ -95,8 +95,13 @@ const result = await client.executeWorkflow('workflow-id', {
- `options` (ExecutionOptions, オプション):
- `input` (any): ワークフローに渡す入力データ
- `timeout` (number): タイムアウト(ミリ秒)(デフォルト: 30000)
+ - `stream` (boolean): ストリーミングレスポンスを有効にする(デフォルト: false)
+ - `selectedOutputs` (string[]): `blockName.attribute`形式でストリーミングするブロック出力(例: `["agent1.content"]`)
+ - `async` (boolean): 非同期実行(デフォルト: false)
-**戻り値:** `Promise`
+**戻り値:** `Promise`
+
+`async: true`の場合、ポーリング用のタスクIDをすぐに返します。それ以外の場合は、完了を待ちます。
##### getWorkflowStatus()
@@ -114,7 +119,7 @@ console.log('Is deployed:', status.isDeployed);
##### validateWorkflow()
-ワークフローが実行準備ができているか検証します。
+ワークフローが実行準備ができているかを検証します。
```typescript
const isReady = await client.validateWorkflow('workflow-id');
@@ -128,28 +133,117 @@ if (isReady) {
**戻り値:** `Promise`
-##### executeWorkflowSync()
+##### getJobStatus()
-
- 現在、このメソッドは `executeWorkflow()` と同一です。すべての実行は同期的に行われるためです。このメソッドは、将来的に非同期実行が追加された際の互換性のために提供されています。
-
+非同期ジョブ実行のステータスを取得します。
+
+```typescript
+const status = await client.getJobStatus('task-id-from-async-execution');
+console.log('Status:', status.status); // 'queued', 'processing', 'completed', 'failed'
+if (status.status === 'completed') {
+ console.log('Output:', status.output);
+}
+```
+
+**パラメータ:**
+- `taskId` (string): 非同期実行から返されたタスクID
+
+**戻り値:** `Promise`
+
+**レスポンスフィールド:**
+- `success` (boolean): リクエストが成功したかどうか
+- `taskId` (string): タスクID
+- `status` (string): 次のいずれか `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
+- `metadata` (object): `startedAt`, `completedAt`, および `duration` を含む
+- `output` (any, オプション): ワークフロー出力(完了時)
+- `error` (any, オプション): エラー詳細(失敗時)
+- `estimatedDuration` (number, オプション): 推定所要時間(ミリ秒)(処理中/キュー時)
-ワークフローを実行します(現在は同期的、`executeWorkflow()` と同じ)。
+##### executeWithRetry()
+
+レート制限エラー時に指数バックオフを使用して自動的に再試行するワークフロー実行。
```typescript
-const result = await client.executeWorkflowSync('workflow-id', {
- input: { data: 'some input' },
- timeout: 60000
+const result = await client.executeWithRetry('workflow-id', {
+ input: { message: 'Hello' },
+ timeout: 30000
+}, {
+ maxRetries: 3, // Maximum number of retries
+ initialDelay: 1000, // Initial delay in ms (1 second)
+ maxDelay: 30000, // Maximum delay in ms (30 seconds)
+ backoffMultiplier: 2 // Exponential backoff multiplier
});
```
**パラメータ:**
- `workflowId` (string): 実行するワークフローのID
-- `options` (ExecutionOptions, オプション):
- - `input` (any): ワークフローに渡す入力データ
- - `timeout` (number): 初期リクエストのタイムアウト(ミリ秒)
+- `options` (ExecutionOptions, オプション): `executeWorkflow()`と同じ
+- `retryOptions` (RetryOptions, オプション):
+ - `maxRetries` (number): 最大再試行回数(デフォルト: 3)
+ - `initialDelay` (number): 初期遅延(ミリ秒)(デフォルト: 1000)
+ - `maxDelay` (number): 最大遅延(ミリ秒)(デフォルト: 30000)
+ - `backoffMultiplier` (number): バックオフ乗数(デフォルト: 2)
+
+**戻り値:** `Promise`
+
+再試行ロジックは、サンダリングハード問題を防ぐために±25%のジッターを含む指数バックオフ(1秒→2秒→4秒→8秒...)を使用します。APIが`retry-after`ヘッダーを提供する場合、代わりにそれが使用されます。
+
+##### getRateLimitInfo()
+
+最後のAPIレスポンスから現在のレート制限情報を取得します。
+
+```typescript
+const rateLimitInfo = client.getRateLimitInfo();
+if (rateLimitInfo) {
+ console.log('Limit:', rateLimitInfo.limit);
+ console.log('Remaining:', rateLimitInfo.remaining);
+ console.log('Reset:', new Date(rateLimitInfo.reset * 1000));
+}
+```
+
+**戻り値:** `RateLimitInfo | null`
+
+##### getUsageLimits()
-**戻り値:** `Promise`
+アカウントの現在の使用制限とクォータ情報を取得します。
+
+```typescript
+const limits = await client.getUsageLimits();
+console.log('Sync requests remaining:', limits.rateLimit.sync.remaining);
+console.log('Async requests remaining:', limits.rateLimit.async.remaining);
+console.log('Current period cost:', limits.usage.currentPeriodCost);
+console.log('Plan:', limits.usage.plan);
+```
+
+**戻り値:** `Promise`
+
+**レスポンス構造:**
+
+```typescript
+{
+ success: boolean
+ rateLimit: {
+ sync: {
+ isLimited: boolean
+ limit: number
+ remaining: number
+ resetAt: string
+ }
+ async: {
+ isLimited: boolean
+ limit: number
+ remaining: number
+ resetAt: string
+ }
+ authType: string // 'api' or 'manual'
+ }
+ usage: {
+ currentPeriodCost: number
+ limit: number
+ plan: string // e.g., 'free', 'pro'
+ }
+}
+```
##### setApiKey()
@@ -167,7 +261,7 @@ client.setApiKey('new-api-key');
client.setBaseUrl('https://my-custom-domain.com');
```
-## 型
+## 型定義
### WorkflowExecutionResult
@@ -187,6 +281,20 @@ interface WorkflowExecutionResult {
}
```
+### AsyncExecutionResult
+
+```typescript
+interface AsyncExecutionResult {
+ success: boolean;
+ taskId: string;
+ status: 'queued';
+ createdAt: string;
+ links: {
+ status: string; // e.g., "/api/jobs/{taskId}"
+ };
+}
+```
+
### WorkflowStatus
```typescript
@@ -198,6 +306,45 @@ interface WorkflowStatus {
}
```
+### RateLimitInfo
+
+```typescript
+interface RateLimitInfo {
+ limit: number;
+ remaining: number;
+ reset: number;
+ retryAfter?: number;
+}
+```
+
+### UsageLimits
+
+```typescript
+interface UsageLimits {
+ success: boolean;
+ rateLimit: {
+ sync: {
+ isLimited: boolean;
+ limit: number;
+ remaining: number;
+ resetAt: string;
+ };
+ async: {
+ isLimited: boolean;
+ limit: number;
+ remaining: number;
+ resetAt: string;
+ };
+ authType: string;
+ };
+ usage: {
+ currentPeriodCost: number;
+ limit: number;
+ plan: string;
+ };
+}
+```
+
### SimStudioError
```typescript
@@ -207,9 +354,16 @@ class SimStudioError extends Error {
}
```
+**一般的なエラーコード:**
+- `UNAUTHORIZED`: 無効なAPIキー
+- `TIMEOUT`: リクエストがタイムアウトしました
+- `RATE_LIMIT_EXCEEDED`: レート制限を超えました
+- `USAGE_LIMIT_EXCEEDED`: 使用制限を超えました
+- `EXECUTION_ERROR`: ワークフローの実行に失敗しました
+
## 例
-### 基本的なワークフローの実行
+### 基本的なワークフロー実行
@@ -347,7 +501,7 @@ async function executeWithErrorHandling() {
-### Node.js Expressとの統合
+### Node.js Express統合
Express.jsサーバーとの統合:
@@ -430,7 +584,7 @@ export default async function handler(
### ブラウザでの使用
-ブラウザで使用する場合(適切なCORS設定が必要):
+ブラウザでの使用(適切なCORS設定が必要):
```typescript
import { SimStudioClient } from 'simstudio-ts-sdk';
@@ -464,7 +618,7 @@ document.getElementById('executeBtn')?.addEventListener('click', executeClientSi
```
- ブラウザでSDKを使用する際は、機密性の高いAPIキーを公開しないよう注意してください。バックエンドプロキシや権限が制限された公開APIキーの使用を検討してください。
+ ブラウザでSDKを使用する場合、機密性の高いAPIキーを公開しないよう注意してください。バックエンドプロキシや権限が制限された公開APIキーの使用を検討してください。
### Reactフックの例
@@ -476,7 +630,7 @@ import { useState, useCallback } from 'react';
import { SimStudioClient, WorkflowExecutionResult } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
- apiKey: process.env.NEXT_PUBLIC_SIM_API_KEY!
+ apiKey: process.env.SIM_API_KEY!
});
interface UseWorkflowResult {
@@ -532,7 +686,7 @@ function WorkflowComponent() {
-
+
{error &&