diff --git a/apps/docs/content/docs/de/execution/costs.mdx b/apps/docs/content/docs/de/execution/costs.mdx index 385ebd6699..d83a02cba2 100644 --- a/apps/docs/content/docs/de/execution/costs.mdx +++ b/apps/docs/content/docs/de/execution/costs.mdx @@ -170,17 +170,49 @@ Verschiedene Abonnementpläne haben unterschiedliche Nutzungslimits: | **Team** | $500 (gepoolt) | 50 sync, 100 async | | **Enterprise** | Individuell | Individuell | +## Abrechnungsmodell + +Sim verwendet ein **Basisabonnement + Mehrverbrauch** Abrechnungsmodell: + +### Wie es funktioniert + +**Pro-Plan (20 $/Monat):** +- Monatliches Abonnement beinhaltet 20 $ Nutzung +- Nutzung unter 20 $ → Keine zusätzlichen Kosten +- Nutzung über 20 $ → Zahlung des Mehrverbrauchs am Monatsende +- Beispiel: 35 $ Nutzung = 20 $ (Abonnement) + 15 $ (Mehrverbrauch) + +**Team-Plan (40 $/Nutzer/Monat):** +- Gemeinsame Nutzung für alle Teammitglieder +- Mehrverbrauch wird aus der Gesamtnutzung des Teams berechnet +- Organisationsinhaber erhält eine Rechnung + +**Enterprise-Pläne:** +- Fester monatlicher Preis, kein Mehrverbrauch +- Individuelle Nutzungslimits gemäß Vereinbarung + +### Schwellenwertabrechnung + +Wenn der nicht abgerechnete Mehrverbrauch 50 $ erreicht, berechnet Sim automatisch den gesamten nicht abgerechneten Betrag. + +**Beispiel:** +- Tag 10: 70 $ Mehrverbrauch → Sofortige Abrechnung von 70 $ +- Tag 15: Zusätzliche 35 $ Nutzung (insgesamt 105 $) → Bereits abgerechnet, keine Aktion +- Tag 20: Weitere 50 $ Nutzung (insgesamt 155 $, 85 $ nicht abgerechnet) → Sofortige Abrechnung von 85 $ + +Dies verteilt hohe Mehrverbrauchskosten über den Monat, anstatt eine große Rechnung am Periodenende zu stellen. + ## Best Practices für Kostenmanagement 1. **Regelmäßig überwachen**: Prüfen Sie Ihr Nutzungs-Dashboard häufig, um Überraschungen zu vermeiden 2. **Budgets festlegen**: Nutzen Sie Planlimits als Leitplanken für Ihre Ausgaben 3. **Workflows optimieren**: Überprüfen Sie kostenintensive Ausführungen und optimieren Sie Prompts oder Modellauswahl -4. **Passende Modelle verwenden**: Stimmen Sie die Modellkomplexität auf die Aufgabenanforderungen ab +4. **Passende Modelle verwenden**: Passen Sie die Modellkomplexität an die Aufgabenanforderungen an 5. **Ähnliche Aufgaben bündeln**: Kombinieren Sie wenn möglich mehrere Anfragen, um den Overhead zu reduzieren ## Nächste Schritte - Überprüfen Sie Ihre aktuelle Nutzung unter [Einstellungen → Abonnement](https://sim.ai/settings/subscription) - Erfahren Sie mehr über [Logging](/execution/logging), um Ausführungsdetails zu verfolgen -- Erkunden Sie die [Externe API](/execution/api) für programmatische Kostenüberwachung -- Sehen Sie sich [Workflow-Optimierungstechniken](/blocks) an, um Kosten zu reduzieren \ No newline at end of file +- Erkunden Sie die [externe API](/execution/api) für programmatische Kostenüberwachung +- Sehen Sie sich [Workflow-Optimierungstechniken](/blocks) zur Kostenreduzierung an \ No newline at end of file diff --git a/apps/docs/content/docs/de/sdks/python.mdx b/apps/docs/content/docs/de/sdks/python.mdx index 368010f430..c185733f85 100644 --- a/apps/docs/content/docs/de/sdks/python.mdx +++ b/apps/docs/content/docs/de/sdks/python.mdx @@ -387,7 +387,7 @@ Behandeln Sie verschiedene Fehlertypen, die während der Workflow-Ausführung au from simstudio import SimStudioClient, SimStudioError import os -client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) +client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) def execute_with_error_handling(): try: @@ -600,7 +600,7 @@ Führe Workflows mit Echtzeit-Streaming-Antworten aus: from simstudio import SimStudioClient import os -client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) +client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) def execute_with_streaming(): """Execute workflow with streaming enabled.""" diff --git a/apps/docs/content/docs/de/sdks/typescript.mdx b/apps/docs/content/docs/de/sdks/typescript.mdx index 55e36ce7e2..a72ff0c7c3 100644 --- a/apps/docs/content/docs/de/sdks/typescript.mdx +++ b/apps/docs/content/docs/de/sdks/typescript.mdx @@ -821,7 +821,9 @@ async function checkUsage() { Execute workflows with real-time streaming responses: -```typescript +``` + +typescript import { SimStudioClient } from 'simstudio-ts-sdk'; const client = new SimStudioClient({ @@ -842,11 +844,13 @@ async function executeWithStreaming() { console.error('Fehler:', error); } } + ``` The streaming response follows the Server-Sent Events (SSE) format: ``` + data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", zwei"} @@ -854,11 +858,14 @@ data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", zwei"} data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} data: [DONE] + ``` **React Streaming Example:** -```typescript +``` + +typescript import { useState, useEffect } from 'react'; function StreamingWorkflow() { @@ -926,6 +933,7 @@ function StreamingWorkflow() { ); } + ``` ## Getting Your API Key @@ -961,7 +969,9 @@ function StreamingWorkflow() { The SDK is written in TypeScript and provides full type safety: -```typescript +``` + +typescript import { SimStudioClient, WorkflowExecutionResult, @@ -987,4 +997,296 @@ const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); ## License +Apache-2.0 + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## Getting Your API Key + + + + Navigate to [Sim](https://sim.ai) and log in to your account. + + + Navigate to the workflow you want to execute programmatically. + + + Click on "Deploy" to deploy your workflow if it hasn't been deployed yet. + + + During the deployment process, select or create an API key. + + + Copy the API key to use in your TypeScript/JavaScript application. + + + + + Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management. + + +## Requirements + +- Node.js 16+ +- TypeScript 5.0+ (for TypeScript projects) + +## TypeScript Support + +The SDK is written in TypeScript and provides full type safety: + +```typescript +import { + SimStudioClient, + WorkflowExecutionResult, + WorkflowStatus, + SimStudioError +} from 'simstudio-ts-sdk'; + +// Typsichere Client-Initialisierung +const client: SimStudioClient = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +// Typsichere Workflow-Ausführung +const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', { + input: { + message: 'Hallo, TypeScript!' + } +}); + +// Typsichere Statusprüfung +const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); +``` + +## License + +Apache-2.0 + limits.usage.limit.toFixed(2)); + console.log('Plan:', limits.usage.plan); + + const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100; + console.log('Usage: ' + percentUsed.toFixed(1) + '%'); + + if (percentUsed > 80) { + console.warn('⚠️ Warning: You are approaching your usage limit!'); + } + } catch (error) { + console.error('Error checking usage:', error); + } +} + +checkUsage(); +``` + +### Streaming-Workflow-Ausführung + +Führen Sie Workflows mit Echtzeit-Streaming-Antworten aus: + +```typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // Enable streaming for specific block outputs + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Count to five' }, + stream: true, + selectedOutputs: ['agent1.content'] // Use blockName.attribute format + }); + + console.log('Workflow result:', result); + } catch (error) { + console.error('Error:', error); + } +} +``` + +Die Streaming-Antwort folgt dem Server-Sent Events (SSE) Format: + +``` +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] +``` + +**React Streaming-Beispiel:** + +```typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // IMPORTANT: Make this API call from your backend server, not the browser + // Never expose your API key in client-side code + const response = await fetch('https://sim.ai/api/workflows/WORKFLOW_ID/execute', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-API-Key': process.env.SIM_API_KEY! // Server-side environment variable only + }, + body: JSON.stringify({ + message: 'Generate a story', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## Ihren API-Schlüssel erhalten + + + + Navigieren Sie zu [Sim](https://sim.ai) und melden Sie sich bei Ihrem Konto an. + + + Navigieren Sie zu dem Workflow, den Sie programmatisch ausführen möchten. + + + Klicken Sie auf "Deploy", um Ihren Workflow zu deployen, falls dies noch nicht geschehen ist. + + + Wählen Sie während des Deployment-Prozesses einen API-Schlüssel aus oder erstellen Sie einen neuen. + + + Kopieren Sie den API-Schlüssel zur Verwendung in Ihrer TypeScript/JavaScript-Anwendung. + + + + + Halte deinen API-Schlüssel sicher und committe ihn niemals in die Versionskontrolle. Verwende Umgebungsvariablen oder sicheres Konfigurationsmanagement. + + +## Anforderungen + +- Node.js 16+ +- TypeScript 5.0+ (für TypeScript-Projekte) + +## TypeScript-Unterstützung + +Das SDK ist in TypeScript geschrieben und bietet vollständige Typsicherheit: + +```typescript +import { + SimStudioClient, + WorkflowExecutionResult, + WorkflowStatus, + SimStudioError +} from 'simstudio-ts-sdk'; + +// Type-safe client initialization +const client: SimStudioClient = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +// Type-safe workflow execution +const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', { + input: { + message: 'Hello, TypeScript!' + } +}); + +// Type-safe status checking +const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); +``` + +## Lizenz + Apache-2.0 \ No newline at end of file diff --git a/apps/docs/content/docs/en/execution/costs.mdx b/apps/docs/content/docs/en/execution/costs.mdx index 890af4b1c5..d35423c409 100644 --- a/apps/docs/content/docs/en/execution/costs.mdx +++ b/apps/docs/content/docs/en/execution/costs.mdx @@ -166,6 +166,38 @@ Different subscription plans have different usage limits: | **Team** | $500 (pooled) | 50 sync, 100 async | | **Enterprise** | Custom | Custom | +## Billing Model + +Sim uses a **base subscription + overage** billing model: + +### How It Works + +**Pro Plan ($20/month):** +- Monthly subscription includes $20 of usage +- Usage under $20 → No additional charges +- Usage over $20 → Pay the overage at month end +- Example: $35 usage = $20 (subscription) + $15 (overage) + +**Team Plan ($40/seat/month):** +- Pooled usage across all team members +- Overage calculated from total team usage +- Organization owner receives one bill + +**Enterprise Plans:** +- Fixed monthly price, no overages +- Custom usage limits per agreement + +### Threshold Billing + +When unbilled overage reaches $50, Sim automatically bills the full unbilled amount. + +**Example:** +- Day 10: $70 overage → Bill $70 immediately +- Day 15: Additional $35 usage ($105 total) → Already billed, no action +- Day 20: Another $50 usage ($155 total, $85 unbilled) → Bill $85 immediately + +This spreads large overage charges throughout the month instead of one large bill at period end. + ## Cost Management Best Practices 1. **Monitor Regularly**: Check your usage dashboard frequently to avoid surprises diff --git a/apps/docs/content/docs/es/execution/costs.mdx b/apps/docs/content/docs/es/execution/costs.mdx index 78daf6600b..40468da241 100644 --- a/apps/docs/content/docs/es/execution/costs.mdx +++ b/apps/docs/content/docs/es/execution/costs.mdx @@ -170,17 +170,49 @@ Los diferentes planes de suscripción tienen diferentes límites de uso: | **Equipo** | $500 (agrupado) | 50 síncronos, 100 asíncronos | | **Empresa** | Personalizado | Personalizado | +## Modelo de facturación + +Sim utiliza un modelo de facturación de **suscripción base + excedente**: + +### Cómo funciona + +**Plan Pro (20$/mes):** +- La suscripción mensual incluye 20$ de uso +- Uso por debajo de 20$ → Sin cargos adicionales +- Uso por encima de 20$ → Paga el excedente al final del mes +- Ejemplo: 35$ de uso = 20$ (suscripción) + 15$ (excedente) + +**Plan Team (40$/usuario/mes):** +- Uso compartido entre todos los miembros del equipo +- El excedente se calcula a partir del uso total del equipo +- El propietario de la organización recibe una única factura + +**Planes Enterprise:** +- Precio mensual fijo, sin excedentes +- Límites de uso personalizados según el acuerdo + +### Facturación por umbrales + +Cuando el excedente no facturado alcanza los 50$, Sim factura automáticamente el importe total no facturado. + +**Ejemplo:** +- Día 10: 70$ de excedente → Factura inmediata de 70$ +- Día 15: 35$ adicionales de uso (105$ en total) → Ya facturado, sin acción +- Día 20: Otros 50$ de uso (155$ en total, 85$ sin facturar) → Factura inmediata de 85$ + +Esto distribuye los cargos grandes por excedente a lo largo del mes en lugar de una factura grande al final del período. + ## Mejores prácticas para la gestión de costos -1. **Monitorear regularmente**: Revisa tu panel de uso frecuentemente para evitar sorpresas -2. **Establecer presupuestos**: Utiliza los límites del plan como guías para tu gasto -3. **Optimizar flujos de trabajo**: Revisa las ejecuciones de alto costo y optimiza los prompts o la selección de modelos -4. **Usar modelos apropiados**: Ajusta la complejidad del modelo a los requisitos de la tarea -5. **Agrupar tareas similares**: Combina múltiples solicitudes cuando sea posible para reducir la sobrecarga +1. **Monitoreo regular**: Revisa tu panel de uso con frecuencia para evitar sorpresas +2. **Establece presupuestos**: Utiliza los límites del plan como guía para tu gasto +3. **Optimiza flujos de trabajo**: Revisa las ejecuciones de alto costo y optimiza los prompts o la selección de modelos +4. **Usa modelos apropiados**: Ajusta la complejidad del modelo a los requisitos de la tarea +5. **Agrupa tareas similares**: Combina múltiples solicitudes cuando sea posible para reducir la sobrecarga ## Próximos pasos - Revisa tu uso actual en [Configuración → Suscripción](https://sim.ai/settings/subscription) - Aprende sobre [Registro](/execution/logging) para seguir los detalles de ejecución -- Explora la [API externa](/execution/api) para monitoreo programático de costos +- Explora la [API externa](/execution/api) para el monitoreo programático de costos - Consulta las [técnicas de optimización de flujo de trabajo](/blocks) para reducir costos \ No newline at end of file diff --git a/apps/docs/content/docs/es/sdks/python.mdx b/apps/docs/content/docs/es/sdks/python.mdx index 2edb110394..75b4f3777a 100644 --- a/apps/docs/content/docs/es/sdks/python.mdx +++ b/apps/docs/content/docs/es/sdks/python.mdx @@ -609,7 +609,7 @@ Ejecuta flujos de trabajo con respuestas en tiempo real: from simstudio import SimStudioClient import os -client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) +client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) def execute_with_streaming(): """Execute workflow with streaming enabled.""" diff --git a/apps/docs/content/docs/es/sdks/typescript.mdx b/apps/docs/content/docs/es/sdks/typescript.mdx index fca8a9805f..fee55cec30 100644 --- a/apps/docs/content/docs/es/sdks/typescript.mdx +++ b/apps/docs/content/docs/es/sdks/typescript.mdx @@ -821,7 +821,9 @@ async function checkUsage() { Execute workflows with real-time streaming responses: -```typescript +``` + +typescript import { SimStudioClient } from 'simstudio-ts-sdk'; const client = new SimStudioClient({ @@ -842,11 +844,13 @@ async function executeWithStreaming() { console.error('Error:', error); } } + ``` The streaming response follows the Server-Sent Events (SSE) format: ``` + data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", dos"} @@ -854,11 +858,14 @@ data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", dos"} data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} data: [DONE] + ``` **React Streaming Example:** -```typescript +``` + +typescript import { useState, useEffect } from 'react'; function StreamingWorkflow() { @@ -926,6 +933,7 @@ function StreamingWorkflow() { ); } + ``` ## Getting Your API Key @@ -961,7 +969,9 @@ function StreamingWorkflow() { The SDK is written in TypeScript and provides full type safety: -```typescript +``` + +typescript import { SimStudioClient, WorkflowExecutionResult, @@ -987,5 +997,296 @@ const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); ## License +Apache-2.0 + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Ejecución completada:', parsed.metadata); + } + } catch (e) { + // Omitir JSON inválido + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## Getting Your API Key + + + + Navigate to [Sim](https://sim.ai) and log in to your account. + + + Navigate to the workflow you want to execute programmatically. + + + Click on "Deploy" to deploy your workflow if it hasn't been deployed yet. + + + During the deployment process, select or create an API key. + + + Copy the API key to use in your TypeScript/JavaScript application. + + + + + Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management. + + +## Requirements + +- Node.js 16+ +- TypeScript 5.0+ (for TypeScript projects) + +## TypeScript Support + +The SDK is written in TypeScript and provides full type safety: + +```typescript +import { + SimStudioClient, + WorkflowExecutionResult, + WorkflowStatus, + SimStudioError +} from 'simstudio-ts-sdk'; + +// Inicialización del cliente con seguridad de tipos +const client: SimStudioClient = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +// Ejecución de flujo de trabajo con seguridad de tipos +const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', { + input: { + message: 'Hola, TypeScript!' + } +}); + +// Verificación de estado con seguridad de tipos +const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); +``` + +## License + +Apache-2.0 + limits.usage.limit.toFixed(2)); + console.log('Plan:', limits.usage.plan); + + const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100; + console.log('Usage: ' + percentUsed.toFixed(1) + '%'); + + if (percentUsed > 80) { + console.warn('⚠️ Warning: You are approaching your usage limit!'); + } + } catch (error) { + console.error('Error checking usage:', error); + } +} + +checkUsage(); +``` + +### Ejecución de flujo de trabajo en streaming + +Ejecuta flujos de trabajo con respuestas en tiempo real: + +```typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // Enable streaming for specific block outputs + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Count to five' }, + stream: true, + selectedOutputs: ['agent1.content'] // Use blockName.attribute format + }); + + console.log('Workflow result:', result); + } catch (error) { + console.error('Error:', error); + } +} +``` + +La respuesta en streaming sigue el formato de eventos enviados por el servidor (SSE): + +``` +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] +``` + +**Ejemplo de streaming en React:** + +```typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // IMPORTANT: Make this API call from your backend server, not the browser + // Never expose your API key in client-side code + const response = await fetch('https://sim.ai/api/workflows/WORKFLOW_ID/execute', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-API-Key': process.env.SIM_API_KEY! // Server-side environment variable only + }, + body: JSON.stringify({ + message: 'Generate a story', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## Obtener tu clave API + + + + Navega a [Sim](https://sim.ai) e inicia sesión en tu cuenta. + + + Navega al flujo de trabajo que quieres ejecutar programáticamente. + + + Haz clic en "Desplegar" para desplegar tu flujo de trabajo si aún no ha sido desplegado. + + + Durante el proceso de despliegue, selecciona o crea una clave API. + + + Copia la clave API para usarla en tu aplicación TypeScript/JavaScript. + + + + + Mantén tu clave API segura y nunca la incluyas en el control de versiones. Utiliza variables de entorno o gestión de configuración segura. + + +## Requisitos + +- Node.js 16+ +- TypeScript 5.0+ (para proyectos TypeScript) + +## Soporte para TypeScript + +El SDK está escrito en TypeScript y proporciona seguridad de tipos completa: + +```typescript +import { + SimStudioClient, + WorkflowExecutionResult, + WorkflowStatus, + SimStudioError +} from 'simstudio-ts-sdk'; + +// Type-safe client initialization +const client: SimStudioClient = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +// Type-safe workflow execution +const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', { + input: { + message: 'Hello, TypeScript!' + } +}); + +// Type-safe status checking +const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); +``` + +## Licencia Apache-2.0 diff --git a/apps/docs/content/docs/fr/execution/costs.mdx b/apps/docs/content/docs/fr/execution/costs.mdx index 7ab7b0099f..6ccd8b0f92 100644 --- a/apps/docs/content/docs/fr/execution/costs.mdx +++ b/apps/docs/content/docs/fr/execution/costs.mdx @@ -170,17 +170,49 @@ Les différents forfaits d'abonnement ont des limites d'utilisation différentes | **Équipe** | 500 $ (mutualisé) | 50 sync, 100 async | | **Entreprise** | Personnalisé | Personnalisé | +## Modèle de facturation + +Sim utilise un modèle de facturation **abonnement de base + dépassement** : + +### Comment ça fonctionne + +**Forfait Pro (20 €/mois) :** +- L'abonnement mensuel inclut 20 € d'utilisation +- Utilisation inférieure à 20 € → Pas de frais supplémentaires +- Utilisation supérieure à 20 € → Paiement du dépassement en fin de mois +- Exemple : 35 € d'utilisation = 20 € (abonnement) + 15 € (dépassement) + +**Forfait Équipe (40 €/utilisateur/mois) :** +- Utilisation mutualisée entre tous les membres de l'équipe +- Dépassement calculé sur l'utilisation totale de l'équipe +- Le propriétaire de l'organisation reçoit une seule facture + +**Forfaits Entreprise :** +- Prix mensuel fixe, sans dépassements +- Limites d'utilisation personnalisées selon l'accord + +### Facturation par seuil + +Lorsque le dépassement non facturé atteint 50 €, Sim facture automatiquement le montant total non facturé. + +**Exemple :** +- Jour 10 : 70 € de dépassement → Facturation immédiate de 70 € +- Jour 15 : 35 € d'utilisation supplémentaire (105 € au total) → Déjà facturé, aucune action +- Jour 20 : 50 € d'utilisation supplémentaire (155 € au total, 85 € non facturés) → Facturation immédiate de 85 € + +Cela répartit les frais de dépassement importants tout au long du mois au lieu d'une seule grosse facture en fin de période. + ## Meilleures pratiques de gestion des coûts -1. **Surveillez régulièrement** : vérifiez fréquemment votre tableau de bord d'utilisation pour éviter les surprises -2. **Définissez des budgets** : utilisez les limites du plan comme garde-fous pour vos dépenses -3. **Optimisez les flux de travail** : examinez les exécutions à coût élevé et optimisez les prompts ou la sélection de modèles -4. **Utilisez des modèles appropriés** : adaptez la complexité du modèle aux exigences de la tâche -5. **Regroupez les tâches similaires** : combinez plusieurs requêtes lorsque c'est possible pour réduire les frais généraux +1. **Surveillance régulière** : Vérifiez fréquemment votre tableau de bord d'utilisation pour éviter les surprises +2. **Définir des budgets** : Utilisez les limites du forfait comme garde-fous pour vos dépenses +3. **Optimiser les flux de travail** : Examinez les exécutions à coût élevé et optimisez les prompts ou la sélection de modèles +4. **Utiliser les modèles appropriés** : Adaptez la complexité du modèle aux exigences de la tâche +5. **Regrouper les tâches similaires** : Combinez plusieurs requêtes lorsque c'est possible pour réduire les frais généraux ## Prochaines étapes -- Examinez votre utilisation actuelle dans [Paramètres → Abonnement](https://sim.ai/settings/subscription) -- Apprenez-en plus sur la [Journalisation](/execution/logging) pour suivre les détails d'exécution +- Consultez votre utilisation actuelle dans [Paramètres → Abonnement](https://sim.ai/settings/subscription) +- Découvrez la [Journalisation](/execution/logging) pour suivre les détails d'exécution - Explorez l'[API externe](/execution/api) pour la surveillance programmatique des coûts -- Découvrez les [techniques d'optimisation de flux de travail](/blocks) pour réduire les coûts \ No newline at end of file +- Consultez les [techniques d'optimisation des flux de travail](/blocks) pour réduire les coûts \ No newline at end of file diff --git a/apps/docs/content/docs/fr/sdks/python.mdx b/apps/docs/content/docs/fr/sdks/python.mdx index faf5f4b203..d3a8f11dcc 100644 --- a/apps/docs/content/docs/fr/sdks/python.mdx +++ b/apps/docs/content/docs/fr/sdks/python.mdx @@ -387,7 +387,7 @@ Gérez différents types d'erreurs qui peuvent survenir pendant l'exécution du from simstudio import SimStudioClient, SimStudioError import os -client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) +client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) def execute_with_error_handling(): try: @@ -433,7 +433,7 @@ Exécutez plusieurs workflows efficacement : from simstudio import SimStudioClient import os -client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) +client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) def execute_workflows_batch(workflow_data_pairs): """Execute multiple workflows with different input data.""" @@ -609,7 +609,7 @@ Exécutez des workflows avec des réponses en streaming en temps réel : from simstudio import SimStudioClient import os -client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) +client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) def execute_with_streaming(): """Execute workflow with streaming enabled.""" diff --git a/apps/docs/content/docs/fr/sdks/typescript.mdx b/apps/docs/content/docs/fr/sdks/typescript.mdx index ca572c346e..35efab136c 100644 --- a/apps/docs/content/docs/fr/sdks/typescript.mdx +++ b/apps/docs/content/docs/fr/sdks/typescript.mdx @@ -821,7 +821,9 @@ async function checkUsage() { Execute workflows with real-time streaming responses: -```typescript +``` + +typescript import { SimStudioClient } from 'simstudio-ts-sdk'; const client = new SimStudioClient({ @@ -842,11 +844,13 @@ async function executeWithStreaming() { console.error('Erreur :', error); } } + ``` The streaming response follows the Server-Sent Events (SSE) format: ``` + data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", deux"} @@ -854,11 +858,14 @@ data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", deux"} data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} data: [DONE] + ``` **React Streaming Example:** -```typescript +``` + +typescript import { useState, useEffect } from 'react'; function StreamingWorkflow() { @@ -926,6 +933,7 @@ function StreamingWorkflow() { ); } + ``` ## Getting Your API Key @@ -961,7 +969,9 @@ function StreamingWorkflow() { The SDK is written in TypeScript and provides full type safety: -```typescript +``` + +typescript import { SimStudioClient, WorkflowExecutionResult, @@ -987,5 +997,296 @@ const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); ## License +Apache-2.0 + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Exécution terminée :', parsed.metadata); + } + } catch (e) { + // Ignorer le JSON invalide + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## Getting Your API Key + + + + Navigate to [Sim](https://sim.ai) and log in to your account. + + + Navigate to the workflow you want to execute programmatically. + + + Click on "Deploy" to deploy your workflow if it hasn't been deployed yet. + + + During the deployment process, select or create an API key. + + + Copy the API key to use in your TypeScript/JavaScript application. + + + + + Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management. + + +## Requirements + +- Node.js 16+ +- TypeScript 5.0+ (for TypeScript projects) + +## TypeScript Support + +The SDK is written in TypeScript and provides full type safety: + +```typescript +import { + SimStudioClient, + WorkflowExecutionResult, + WorkflowStatus, + SimStudioError +} from 'simstudio-ts-sdk'; + +// Initialisation du client avec typage sécurisé +const client: SimStudioClient = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +// Exécution de workflow avec typage sécurisé +const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', { + input: { + message: 'Hello, TypeScript!' + } +}); + +// Vérification de statut avec typage sécurisé +const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); +``` + +## License + +Apache-2.0 + limits.usage.limit.toFixed(2)); + console.log('Plan:', limits.usage.plan); + + const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100; + console.log('Usage: ' + percentUsed.toFixed(1) + '%'); + + if (percentUsed > 80) { + console.warn('⚠️ Warning: You are approaching your usage limit!'); + } + } catch (error) { + console.error('Error checking usage:', error); + } +} + +checkUsage(); +``` + +### Exécution de workflow en streaming + +Exécutez des workflows avec des réponses en streaming en temps réel : + +```typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // Enable streaming for specific block outputs + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Count to five' }, + stream: true, + selectedOutputs: ['agent1.content'] // Use blockName.attribute format + }); + + console.log('Workflow result:', result); + } catch (error) { + console.error('Error:', error); + } +} +``` + +La réponse en streaming suit le format Server-Sent Events (SSE) : + +``` +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] +``` + +**Exemple de streaming avec React :** + +```typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // IMPORTANT: Make this API call from your backend server, not the browser + // Never expose your API key in client-side code + const response = await fetch('https://sim.ai/api/workflows/WORKFLOW_ID/execute', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-API-Key': process.env.SIM_API_KEY! // Server-side environment variable only + }, + body: JSON.stringify({ + message: 'Generate a story', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## Obtenir votre clé API + + + + Accédez à [Sim](https://sim.ai) et connectez-vous à votre compte. + + + Accédez au workflow que vous souhaitez exécuter par programmation. + + + Cliquez sur « Déployer » pour déployer votre workflow s'il n'a pas encore été déployé. + + + Pendant le processus de déploiement, sélectionnez ou créez une clé API. + + + Copiez la clé API pour l'utiliser dans votre application TypeScript/JavaScript. + + + + + Gardez votre clé API sécurisée et ne la soumettez jamais au contrôle de version. Utilisez des variables d'environnement ou une gestion de configuration sécurisée. + + +## Prérequis + +- Node.js 16+ +- TypeScript 5.0+ (pour les projets TypeScript) + +## Support TypeScript + +Le SDK est écrit en TypeScript et offre une sécurité de typage complète : + +```typescript +import { + SimStudioClient, + WorkflowExecutionResult, + WorkflowStatus, + SimStudioError +} from 'simstudio-ts-sdk'; + +// Type-safe client initialization +const client: SimStudioClient = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +// Type-safe workflow execution +const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', { + input: { + message: 'Hello, TypeScript!' + } +}); + +// Type-safe status checking +const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); +``` + +## Licence Apache-2.0 diff --git a/apps/docs/content/docs/ja/execution/costs.mdx b/apps/docs/content/docs/ja/execution/costs.mdx index 6f83172d2b..c991c42c8e 100644 --- a/apps/docs/content/docs/ja/execution/costs.mdx +++ b/apps/docs/content/docs/ja/execution/costs.mdx @@ -170,17 +170,49 @@ curl -X GET -H "X-API-Key: YOUR_API_KEY" -H "Content-Type: application/json" htt | **チーム** | $500(プール) | 50同期、100非同期 | | **エンタープライズ** | カスタム | カスタム | +## 課金モデル + +Simは**基本サブスクリプション + 超過分**の課金モデルを使用しています: + +### 仕組み + +**Proプラン(月額$20):** +- 月額サブスクリプションには$20分の使用量が含まれます +- 使用量が$20未満 → 追加料金なし +- 使用量が$20を超える → 月末に超過分を支払い +- 例:$35の使用量 = $20(サブスクリプション)+ $15(超過分) + +**チームプラン(月額$40/シート):** +- チームメンバー全体でプールされた使用量 +- チーム全体の使用量から超過分を計算 +- 組織のオーナーが一括で請求を受ける + +**エンタープライズプラン:** +- 固定月額料金、超過料金なし +- 契約に基づくカスタム使用制限 + +### しきい値課金 + +未請求の超過分が$50に達すると、Simは自動的に未請求の全額を請求します。 + +**例:** +- 10日目:$70の超過分 → 即時に$70を請求 +- 15日目:追加$35の使用(合計$105)→ すでに請求済み、アクションなし +- 20日目:さらに$50の使用(合計$155、未請求$85)→ 即時に$85を請求 + +これにより、期間終了時に大きな請求が一度にくるのではなく、月を通じて大きな超過料金が分散されます。 + ## コスト管理のベストプラクティス -1. **定期的な監視**: 予期せぬ事態を避けるため、使用状況ダッシュボードを頻繁に確認する -2. **予算の設定**: プランの制限を支出のガードレールとして使用する -3. **ワークフローの最適化**: コストの高い実行を見直し、プロンプトやモデル選択を最適化する -4. **適切なモデルの使用**: タスクの要件に合わせてモデルの複雑さを選択する -5. **類似タスクのバッチ処理**: 可能な場合は複数のリクエストを組み合わせてオーバーヘッドを削減する +1. **定期的な監視**:予想外の事態を避けるため、使用量ダッシュボードを頻繁にチェック +2. **予算設定**:支出の目安としてプラン制限を活用 +3. **ワークフローの最適化**:高コストの実行を見直し、プロンプトやモデル選択を最適化 +4. **適切なモデルの使用**:タスク要件にモデルの複雑さを合わせる +5. **類似タスクのバッチ処理**:オーバーヘッドを減らすために可能な場合は複数のリクエストを組み合わせる ## 次のステップ -- [設定 → サブスクリプション](https://sim.ai/settings/subscription)で現在の使用状況を確認する +- [設定 → サブスクリプション](https://sim.ai/settings/subscription)で現在の使用状況を確認 - 実行詳細を追跡するための[ロギング](/execution/logging)について学ぶ -- プログラムによるコスト監視のための[外部API](/execution/api)を探索する -- コスト削減のための[ワークフロー最適化テクニック](/blocks)をチェックする \ No newline at end of file +- プログラムによるコスト監視のための[外部API](/execution/api)を探索 +- コスト削減のための[ワークフロー最適化テクニック](/blocks)をチェック \ No newline at end of file diff --git a/apps/docs/content/docs/ja/sdks/python.mdx b/apps/docs/content/docs/ja/sdks/python.mdx index b667a9f3d8..39fa75470d 100644 --- a/apps/docs/content/docs/ja/sdks/python.mdx +++ b/apps/docs/content/docs/ja/sdks/python.mdx @@ -433,7 +433,7 @@ with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client: from simstudio import SimStudioClient import os -client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) +client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) def execute_workflows_batch(workflow_data_pairs): """Execute multiple workflows with different input data.""" @@ -660,7 +660,7 @@ def stream_workflow(): 'https://sim.ai/api/workflows/WORKFLOW_ID/execute', headers={ 'Content-Type': 'application/json', - 'X-API-Key': os.getenv('SIM_API_KEY') + 'X-API-Key': os.getenv('SIM_API_KEY') }, json={ 'message': 'Generate a story', diff --git a/apps/docs/content/docs/ja/sdks/typescript.mdx b/apps/docs/content/docs/ja/sdks/typescript.mdx index 785f60b29d..9499403712 100644 --- a/apps/docs/content/docs/ja/sdks/typescript.mdx +++ b/apps/docs/content/docs/ja/sdks/typescript.mdx @@ -821,7 +821,9 @@ async function checkUsage() { Execute workflows with real-time streaming responses: -```typescript +``` + +typescript import { SimStudioClient } from 'simstudio-ts-sdk'; const client = new SimStudioClient({ @@ -842,11 +844,13 @@ async function executeWithStreaming() { console.error('エラー:', error); } } + ``` The streaming response follows the Server-Sent Events (SSE) format: ``` + data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} @@ -854,11 +858,14 @@ data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} data: [DONE] + ``` **React Streaming Example:** -```typescript +``` + +typescript import { useState, useEffect } from 'react'; function StreamingWorkflow() { @@ -926,6 +933,7 @@ function StreamingWorkflow() { ); } + ``` ## Getting Your API Key @@ -961,7 +969,9 @@ function StreamingWorkflow() { The SDK is written in TypeScript and provides full type safety: -```typescript +``` + +typescript import { SimStudioClient, WorkflowExecutionResult, @@ -987,5 +997,296 @@ const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); ## License +Apache-2.0 + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## Getting Your API Key + + + + Navigate to [Sim](https://sim.ai) and log in to your account. + + + Navigate to the workflow you want to execute programmatically. + + + Click on "Deploy" to deploy your workflow if it hasn't been deployed yet. + + + During the deployment process, select or create an API key. + + + Copy the API key to use in your TypeScript/JavaScript application. + + + + + Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management. + + +## Requirements + +- Node.js 16+ +- TypeScript 5.0+ (for TypeScript projects) + +## TypeScript Support + +The SDK is written in TypeScript and provides full type safety: + +```typescript +import { + SimStudioClient, + WorkflowExecutionResult, + WorkflowStatus, + SimStudioError +} from 'simstudio-ts-sdk'; + +// 型安全なクライアント初期化 +const client: SimStudioClient = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +// 型安全なワークフロー実行 +const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', { + input: { + message: 'Hello, TypeScript!' + } +}); + +// 型安全なステータス確認 +const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); +``` + +## License + +Apache-2.0 + limits.usage.limit.toFixed(2)); + console.log('Plan:', limits.usage.plan); + + const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100; + console.log('Usage: ' + percentUsed.toFixed(1) + '%'); + + if (percentUsed > 80) { + console.warn('⚠️ Warning: You are approaching your usage limit!'); + } + } catch (error) { + console.error('Error checking usage:', error); + } +} + +checkUsage(); +``` + +### ストリーミングワークフロー実行 + +リアルタイムストリーミングレスポンスでワークフローを実行します: + +```typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // Enable streaming for specific block outputs + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Count to five' }, + stream: true, + selectedOutputs: ['agent1.content'] // Use blockName.attribute format + }); + + console.log('Workflow result:', result); + } catch (error) { + console.error('Error:', error); + } +} +``` + +ストリーミングレスポンスはServer-Sent Events(SSE)形式に従います: + +``` +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] +``` + +**Reactストリーミング例:** + +```typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // IMPORTANT: Make this API call from your backend server, not the browser + // Never expose your API key in client-side code + const response = await fetch('https://sim.ai/api/workflows/WORKFLOW_ID/execute', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-API-Key': process.env.SIM_API_KEY! // Server-side environment variable only + }, + body: JSON.stringify({ + message: 'Generate a story', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## APIキーの取得方法 + + + + [Sim](https://sim.ai)に移動してアカウントにログインします。 + + + プログラムで実行したいワークフローに移動します。 + + + まだデプロイされていない場合は、「デプロイ」をクリックしてワークフローをデプロイします。 + + + デプロイプロセス中に、APIキーを選択または作成します。 + + + TypeScript/JavaScriptアプリケーションで使用するAPIキーをコピーします。 + + + + + APIキーは安全に保管し、バージョン管理システムにコミットしないでください。環境変数や安全な設定管理を使用してください。 + + +## 要件 + +- Node.js 16以上 +- TypeScript 5.0以上(TypeScriptプロジェクトの場合) + +## TypeScriptサポート + +このSDKはTypeScriptで書かれており、完全な型安全性を提供します: + +```typescript +import { + SimStudioClient, + WorkflowExecutionResult, + WorkflowStatus, + SimStudioError +} from 'simstudio-ts-sdk'; + +// Type-safe client initialization +const client: SimStudioClient = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +// Type-safe workflow execution +const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', { + input: { + message: 'Hello, TypeScript!' + } +}); + +// Type-safe status checking +const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); +``` + +## ライセンス Apache-2.0 diff --git a/apps/docs/content/docs/zh/execution/costs.mdx b/apps/docs/content/docs/zh/execution/costs.mdx index 4ada972604..00e2b3387f 100644 --- a/apps/docs/content/docs/zh/execution/costs.mdx +++ b/apps/docs/content/docs/zh/execution/costs.mdx @@ -170,11 +170,43 @@ curl -X GET -H "X-API-Key: YOUR_API_KEY" -H "Content-Type: application/json" htt | **团队** | $500(池化) | 50 同步, 100 异步 | | **企业** | 自定义 | 自定义 | +## 计费模式 + +Sim 使用 **基础订阅 + 超额** 的计费模式: + +### 工作原理 + +**专业计划($20/月):** +- 月订阅包含 $20 的使用额度 +- 使用低于 $20 → 无额外费用 +- 使用超过 $20 → 月底支付超额部分 +- 示例:$35 的使用 = $20(订阅)+ $15(超额) + +**团队计划($40/人/月):** +- 团队成员共享使用额度 +- 超额费用根据团队总使用量计算 +- 组织所有者收到一张账单 + +**企业计划:** +- 固定月费,无超额费用 +- 根据协议定制使用限制 + +### 阈值计费 + +当未结算的超额费用达到 $50 时,Sim 会自动结算全部未结算金额。 + +**示例:** +- 第 10 天:$70 超额 → 立即结算 $70 +- 第 15 天:额外使用 $35(总计 $105)→ 已结算,无需操作 +- 第 20 天:再使用 $50(总计 $155,未结算 $85)→ 立即结算 $85 + +这可以将大额超额费用分散到整个月,而不是在周期末一次性结算。 + ## 成本管理最佳实践 -1. **定期监控**:经常检查您的使用仪表板,避免意外情况 -2. **设置预算**:使用计划限制作为支出控制的护栏 -3. **优化工作流程**:审查高成本的执行情况,优化提示或模型选择 +1. **定期监控**:经常检查您的使用仪表板,避免意外 +2. **设定预算**:使用计划限制作为支出控制的参考 +3. **优化工作流程**:审查高成本的执行,优化提示或模型选择 4. **使用合适的模型**:根据任务需求匹配模型复杂度 5. **批量处理相似任务**:尽可能合并多个请求以减少开销 diff --git a/apps/docs/content/docs/zh/sdks/python.mdx b/apps/docs/content/docs/zh/sdks/python.mdx index 8ca6874295..5a59d69d70 100644 --- a/apps/docs/content/docs/zh/sdks/python.mdx +++ b/apps/docs/content/docs/zh/sdks/python.mdx @@ -433,7 +433,7 @@ with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client: from simstudio import SimStudioClient import os -client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) +client = SimStudioClient(api_key=os.getenv("SIM_API_KEY")) def execute_workflows_batch(workflow_data_pairs): """Execute multiple workflows with different input data.""" @@ -660,7 +660,7 @@ def stream_workflow(): 'https://sim.ai/api/workflows/WORKFLOW_ID/execute', headers={ 'Content-Type': 'application/json', - 'X-API-Key': os.getenv('SIM_API_KEY') + 'X-API-Key': os.getenv('SIM_API_KEY') }, json={ 'message': 'Generate a story', diff --git a/apps/docs/content/docs/zh/sdks/typescript.mdx b/apps/docs/content/docs/zh/sdks/typescript.mdx index ba56120459..427bb105f6 100644 --- a/apps/docs/content/docs/zh/sdks/typescript.mdx +++ b/apps/docs/content/docs/zh/sdks/typescript.mdx @@ -821,7 +821,9 @@ async function checkUsage() { Execute workflows with real-time streaming responses: -```typescript +``` + +typescript import { SimStudioClient } from 'simstudio-ts-sdk'; const client = new SimStudioClient({ @@ -842,11 +844,13 @@ async function executeWithStreaming() { console.error('错误:', error); } } + ``` The streaming response follows the Server-Sent Events (SSE) format: ``` + data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} @@ -854,11 +858,14 @@ data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} data: [DONE] + ``` **React Streaming Example:** -```typescript +``` + +typescript import { useState, useEffect } from 'react'; function StreamingWorkflow() { @@ -926,6 +933,114 @@ function StreamingWorkflow() { ); } + +``` + +## Getting Your API Key + + + + Navigate to [Sim](https://sim.ai) and log in to your account. + + + Navigate to the workflow you want to execute programmatically. + + + Click on "Deploy" to deploy your workflow if it hasn't been deployed yet. + + + During the deployment process, select or create an API key. + + + Copy the API key to use in your TypeScript/JavaScript application. + + + + + Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management. + + +## Requirements + +- Node.js 16+ +- TypeScript 5.0+ (for TypeScript projects) + +## TypeScript Support + +The SDK is written in TypeScript and provides full type safety: + +``` + +typescript +import { + SimStudioClient, + WorkflowExecutionResult, + WorkflowStatus, + SimStudioError +} from 'simstudio-ts-sdk'; + +// 类型安全的客户端初始化 +const client: SimStudioClient = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +// 类型安全的工作流执行 +const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', { + input: { + message: '你好,TypeScript!' + } +}); + +// 类型安全的状态检查 +const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); +``` + +## 许可证 + +Apache-2.0 + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('执行完成:', parsed.metadata); + } + } catch (e) { + // 跳过无效的 JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} ``` ## Getting Your API Key @@ -985,6 +1100,193 @@ const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-i const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); ``` +## License + +Apache-2.0 + limits.usage.limit.toFixed(2)); + console.log('Plan:', limits.usage.plan); + + const percentUsed = (limits.usage.currentPeriodCost / limits.usage.limit) * 100; + console.log('Usage: ' + percentUsed.toFixed(1) + '%'); + + if (percentUsed > 80) { + console.warn('⚠️ Warning: You are approaching your usage limit!'); + } + } catch (error) { + console.error('Error checking usage:', error); + } +} + +checkUsage(); +``` + +### 流式工作流执行 + +通过实时流式响应执行工作流: + +```typescript +import { SimStudioClient } from 'simstudio-ts-sdk'; + +const client = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +async function executeWithStreaming() { + try { + // Enable streaming for specific block outputs + const result = await client.executeWorkflow('workflow-id', { + input: { message: 'Count to five' }, + stream: true, + selectedOutputs: ['agent1.content'] // Use blockName.attribute format + }); + + console.log('Workflow result:', result); + } catch (error) { + console.error('Error:', error); + } +} +``` + +流式响应遵循服务器发送事件 (SSE) 格式: + +``` +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"} + +data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"} + +data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}} + +data: [DONE] +``` + +**React 流式示例:** + +```typescript +import { useState, useEffect } from 'react'; + +function StreamingWorkflow() { + const [output, setOutput] = useState(''); + const [loading, setLoading] = useState(false); + + const executeStreaming = async () => { + setLoading(true); + setOutput(''); + + // IMPORTANT: Make this API call from your backend server, not the browser + // Never expose your API key in client-side code + const response = await fetch('https://sim.ai/api/workflows/WORKFLOW_ID/execute', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-API-Key': process.env.SIM_API_KEY! // Server-side environment variable only + }, + body: JSON.stringify({ + message: 'Generate a story', + stream: true, + selectedOutputs: ['agent1.content'] + }) + }); + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + while (reader) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const lines = chunk.split('\n\n'); + + for (const line of lines) { + if (line.startsWith('data: ')) { + const data = line.slice(6); + if (data === '[DONE]') { + setLoading(false); + break; + } + + try { + const parsed = JSON.parse(data); + if (parsed.chunk) { + setOutput(prev => prev + parsed.chunk); + } else if (parsed.event === 'done') { + console.log('Execution complete:', parsed.metadata); + } + } catch (e) { + // Skip invalid JSON + } + } + } + } + }; + + return ( +
+ +
{output}
+
+ ); +} +``` + +## 获取您的 API 密钥 + + + + 访问 [Sim](https://sim.ai) 并登录您的账户。 + + + 导航到您想要以编程方式执行的工作流。 + + + 如果尚未部署,请点击“部署”以部署您的工作流。 + + + 在部署过程中,选择或创建一个 API 密钥。 + + + 复制 API 密钥以在您的 TypeScript/JavaScript 应用程序中使用。 + + + + + 请确保您的 API 密钥安全,切勿将其提交到版本控制中。请使用环境变量或安全的配置管理工具。 + + +## 要求 + +- Node.js 16+ +- TypeScript 5.0+(适用于 TypeScript 项目) + +## TypeScript 支持 + +该 SDK 使用 TypeScript 编写,并提供完整的类型安全: + +```typescript +import { + SimStudioClient, + WorkflowExecutionResult, + WorkflowStatus, + SimStudioError +} from 'simstudio-ts-sdk'; + +// Type-safe client initialization +const client: SimStudioClient = new SimStudioClient({ + apiKey: process.env.SIM_API_KEY! +}); + +// Type-safe workflow execution +const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', { + input: { + message: 'Hello, TypeScript!' + } +}); + +// Type-safe status checking +const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id'); +``` + ## 许可证 Apache-2.0 diff --git a/apps/docs/i18n.lock b/apps/docs/i18n.lock index 4ef71f624c..33479d0856 100644 --- a/apps/docs/i18n.lock +++ b/apps/docs/i18n.lock @@ -2479,16 +2479,16 @@ checksums: content/76: 33b9b1e9744318597da4b925b0995be2 content/77: 6afe3b62e6d53c3dcd07149abcab4c05 content/78: b6363faee219321c16d41a9c3f8d3bdd - content/79: 08410ce9f0ec358b3c7230a56bc66399 + content/79: 3c5b351d25fb0639559eacdad545a0ed content/80: b8b23ab79a7eb32c6f8d5f49f43c51f6 content/81: be358297e2bbb9ab4689d11d072611d1 - content/82: 09fea7c0d742a0eefa77e982e848de6c + content/82: 414b9bf7d35039c6a17f4fb03d6b7431 content/83: 7d098f0349c782f389431377ee512e92 content/84: 22b39537f6a104803389469d211154e4 content/85: d9ec74ab28b264d76f797fdae7c8f3d3 content/86: f29d6bfd74ba3fee0b90180f620b4f47 content/87: 2a59466500b62e57481fe27692a3ed0f - content/88: cbbb123fc3a12bf2ab72dc1bbe373a6e + content/88: 94965695a02aea6c753448c21fd66b18 content/89: 7873aa7487bc3e8a4826d65c1760a4a0 content/90: 98182d9aabe14d5bad43a5ee76a75eab content/91: 67bfa8ae3e22d9a949f08c79a40b8df5 @@ -2500,11 +2500,11 @@ checksums: content/97: dae96b41f0c029b464f02ac65d3c5796 content/98: 41c2bb95317d7c0421817a2b1a68cc09 content/99: 4c95f9fa55f698f220577380dff95011 - content/100: 6695bd47a05f9963134d8a71abb3d298 + content/100: e674c5e6ecaf4dae9fc93e328b8a57c4 content/101: 100e12673551d4ceb5b906b1b9c65059 content/102: ce253674cd7c49320203cda2bdd3685b content/103: 94d4346a735149c2a83f6d2a21b8ab4c - content/104: 3ee4b16b8204ef3b5b7c0322ff636fab + content/104: 869fd72c8911057ee0696f068fa22e35 content/105: 450265802cb0ba5b435b74b9cac1bf23 content/106: b735ede8764e4b2dfb25967e33ab5143 content/107: 0f881e586a03c4b916456c73fad48358 @@ -2834,10 +2834,20 @@ checksums: content/30: dbbf313837f13ddfa4a8843d71cb9cc4 content/31: cf10560ae6defb8ee5da344fc6509f6e content/32: c5dc6e5de6e45b17ee1f5eb567a18e2f - content/33: aa47ff01b631252f024eaaae0c773e42 - content/34: 1266d1c7582bb617cdef56857be34f30 - content/35: c2cef2688104adaf6641092f43d4969a - content/36: 089fc64b4589b2eaa371de7e04c4aed9 + content/33: 332dab0588fb35dabb64b674ba6120eb + content/34: 714b3f99b0a8686bbb3434deb1f682b3 + content/35: ba18ac99184b17d7e49bd1abdc814437 + content/36: bed2b629274d55c38bd637e6a28dbc4a + content/37: 71487ae6f6fb1034d1787456de442e6d + content/38: 137d9874cf5ec8d09bd447f224cc7a7c + content/39: 6b5b4c3b2f98b8fc7dd908fef2605ce8 + content/40: 3af6812662546ce647a55939241fd88e + content/41: 6a4d7f0ccb8c28303251d1ef7b3dcca7 + content/42: 5dce779f77cc2b0abf12802a833df499 + content/43: aa47ff01b631252f024eaaae0c773e42 + content/44: 1266d1c7582bb617cdef56857be34f30 + content/45: c2cef2688104adaf6641092f43d4969a + content/46: 089fc64b4589b2eaa371de7e04c4aed9 722959335ba76c9d0097860e2ad5a952: meta/title: 9842d3af9cf52b7f5ab4a6ed4f2b23d2 content/0: 112d20eb578be8c0f59a13c819bf7716 diff --git a/apps/sim/app/api/billing/update-cost/route.ts b/apps/sim/app/api/billing/update-cost/route.ts index fd897c59bd..418691a97b 100644 --- a/apps/sim/app/api/billing/update-cost/route.ts +++ b/apps/sim/app/api/billing/update-cost/route.ts @@ -3,6 +3,7 @@ import { userStats } from '@sim/db/schema' import { eq, sql } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' +import { checkAndBillOverageThreshold } from '@/lib/billing/threshold-billing' import { checkInternalApiKey } from '@/lib/copilot/utils' import { isBillingEnabled } from '@/lib/environment' import { createLogger } from '@/lib/logs/console/logger' @@ -148,6 +149,9 @@ export async function POST(req: NextRequest) { addedTokens: totalTokens, }) + // Check if user has hit overage threshold and bill incrementally + await checkAndBillOverageThreshold(userId) + const duration = Date.now() - startTime logger.info(`[${requestId}] Cost update completed successfully`, { diff --git a/apps/sim/app/api/wand-generate/route.ts b/apps/sim/app/api/wand-generate/route.ts index 099bc3ea55..88cb8442c4 100644 --- a/apps/sim/app/api/wand-generate/route.ts +++ b/apps/sim/app/api/wand-generate/route.ts @@ -3,6 +3,7 @@ import { userStats, workflow } from '@sim/db/schema' import { eq, sql } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import OpenAI, { AzureOpenAI } from 'openai' +import { checkAndBillOverageThreshold } from '@/lib/billing/threshold-billing' import { env } from '@/lib/env' import { getCostMultiplier, isBillingEnabled } from '@/lib/environment' import { createLogger } from '@/lib/logs/console/logger' @@ -133,6 +134,9 @@ async function updateUserStatsForWand( tokensUsed: totalTokens, costAdded: costToStore, }) + + // Check if user has hit overage threshold and bill incrementally + await checkAndBillOverageThreshold(userId) } catch (error) { logger.error(`[${requestId}] Failed to update user stats for wand usage`, error) } diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/document-tag-entry/document-tag-entry.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/document-tag-entry/document-tag-entry.tsx index 0f25671850..fccca2b5e4 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/document-tag-entry/document-tag-entry.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/document-tag-entry/document-tag-entry.tsx @@ -9,6 +9,7 @@ import { checkTagTrigger, TagDropdown } from '@/components/ui/tag-dropdown' import { MAX_TAG_SLOTS } from '@/lib/knowledge/consts' import { cn } from '@/lib/utils' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/hooks/use-sub-block-value' +import { useAccessibleReferencePrefixes } from '@/app/workspace/[workspaceId]/w/[workflowId]/hooks/use-accessible-reference-prefixes' import type { SubBlockConfig } from '@/blocks/types' import { useKnowledgeBaseTagDefinitions } from '@/hooks/use-knowledge-base-tag-definitions' import { useTagSelection } from '@/hooks/use-tag-selection' @@ -40,6 +41,7 @@ export function DocumentTagEntry({ isConnecting = false, }: DocumentTagEntryProps) { const [storeValue, setStoreValue] = useSubBlockValue(blockId, subBlock.id) + const accessiblePrefixes = useAccessibleReferencePrefixes(blockId) // Get the knowledge base ID from other sub-blocks const [knowledgeBaseIdValue] = useSubBlockValue(blockId, 'knowledgeBaseId') @@ -301,7 +303,12 @@ export function DocumentTagEntry({ )} />
-
{formatDisplayText(cellValue)}
+
+ {formatDisplayText(cellValue, { + accessiblePrefixes, + highlightAll: !accessiblePrefixes, + })} +
{showDropdown && availableTagDefinitions.length > 0 && (
@@ -389,7 +396,10 @@ export function DocumentTagEntry({ />
- {formatDisplayText(cellValue)} + {formatDisplayText(cellValue, { + accessiblePrefixes, + highlightAll: !accessiblePrefixes, + })}
{showTypeDropdown && !isReadOnly && ( @@ -469,7 +479,12 @@ export function DocumentTagEntry({ className='w-full border-0 text-transparent caret-foreground placeholder:text-muted-foreground/50 focus-visible:ring-0 focus-visible:ring-offset-0' />
-
{formatDisplayText(cellValue)}
+
+ {formatDisplayText(cellValue, { + accessiblePrefixes, + highlightAll: !accessiblePrefixes, + })} +
diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/knowledge-tag-filters/knowledge-tag-filters.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/knowledge-tag-filters/knowledge-tag-filters.tsx index 6df8d6582c..9b06b8649c 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/knowledge-tag-filters/knowledge-tag-filters.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/knowledge-tag-filters/knowledge-tag-filters.tsx @@ -239,7 +239,12 @@ export function KnowledgeTagFilters({ onBlur={handleBlur} />
-
{formatDisplayText(cellValue || 'Select tag')}
+
+ {formatDisplayText(cellValue || 'Select tag', { + accessiblePrefixes, + highlightAll: !accessiblePrefixes, + })} +
{showDropdown && tagDefinitions.length > 0 && (
diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/mcp-dynamic-args/mcp-dynamic-args.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/mcp-dynamic-args/mcp-dynamic-args.tsx index 1eb5b15cd9..d40f8d0302 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/mcp-dynamic-args/mcp-dynamic-args.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/components/mcp-dynamic-args/mcp-dynamic-args.tsx @@ -1,5 +1,6 @@ import { useCallback } from 'react' import { useParams } from 'next/navigation' +import { formatDisplayText } from '@/components/ui/formatted-text' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { @@ -14,6 +15,7 @@ import { Switch } from '@/components/ui/switch' import { Textarea } from '@/components/ui/textarea' import { cn } from '@/lib/utils' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/components/sub-block/hooks/use-sub-block-value' +import { useAccessibleReferencePrefixes } from '@/app/workspace/[workspaceId]/w/[workflowId]/hooks/use-accessible-reference-prefixes' import { useMcpTools } from '@/hooks/use-mcp-tools' import { formatParameterLabel } from '@/tools/params' @@ -37,6 +39,7 @@ export function McpDynamicArgs({ const { mcpTools } = useMcpTools(workspaceId) const [selectedTool] = useSubBlockValue(blockId, 'tool') const [toolArgs, setToolArgs] = useSubBlockValue(blockId, subBlockId) + const accessiblePrefixes = useAccessibleReferencePrefixes(blockId) const selectedToolConfig = mcpTools.find((tool) => tool.id === selectedTool) const toolSchema = selectedToolConfig?.inputSchema @@ -180,7 +183,7 @@ export function McpDynamicArgs({ case 'long-input': return ( -
+