TypeScript/JavaScript SDK
Sim 的官方 TypeScript/JavaScript SDK 提供完整的类型安全,支持 Node.js 和浏览器环境,允许您从 Node.js 应用程序、Web 应用程序和其他 JavaScript 环境中以编程方式执行工作流。目前,所有工作流执行均为同步。
TypeScript SDK 提供完整的类型安全,支持 Node.js 和浏览器环境。目前,所有工作流执行均为同步。
安装
使用您喜欢的包管理器安装 SDK:
npm install simstudio-ts-sdk
yarn add simstudio-ts-sdk
bun add simstudio-ts-sdk
快速开始
以下是一个简单的示例,帮助您快速入门:
import { SimStudioClient } from 'simstudio-ts-sdk';
// Initialize the client
const client = new SimStudioClient({
apiKey: 'your-api-key-here',
baseUrl: 'https://sim.ai' // optional, defaults to https://sim.ai
});
// Execute a workflow
try {
const result = await client.executeWorkflow('workflow-id');
console.log('Workflow executed successfully:', result);
} catch (error) {
console.error('Workflow execution failed:', error);
}
API 参考
SimStudioClient
构造函数
new SimStudioClient(config: SimStudioConfig)
配置:
config.apiKey
(字符串): 您的 Sim API 密钥config.baseUrl
(字符串,可选): Sim API 的基础 URL(默认为https://sim.ai
)
方法
executeWorkflow()
执行带有可选输入数据的工作流。
const result = await client.executeWorkflow('workflow-id', {
input: { message: 'Hello, world!' },
timeout: 30000 // 30 seconds
});
参数:
workflowId
(字符串):要执行的工作流的 IDoptions
(ExecutionOptions,可选):input
(任意类型):传递给工作流的输入数据timeout
(数字):超时时间(以毫秒为单位,默认值:30000)
返回值: Promise<WorkflowExecutionResult>
getWorkflowStatus()
获取工作流的状态(部署状态等)。
const status = await client.getWorkflowStatus('workflow-id');
console.log('Is deployed:', status.isDeployed);
参数:
workflowId
(字符串):工作流的 ID
返回值: Promise<WorkflowStatus>
validateWorkflow()
验证工作流是否已准备好执行。
const isReady = await client.validateWorkflow('workflow-id');
if (isReady) {
// Workflow is deployed and ready
}
参数:
workflowId
(字符串):工作流的 ID
返回值: Promise<boolean>
executeWorkflowSync()
当前,此方法与 executeWorkflow()
相同,因为所有执行都是同步的。提供此方法是为了在将来添加异步执行时保持兼容性。
执行工作流(当前为同步,与 executeWorkflow()
相同)。
const result = await client.executeWorkflowSync('workflow-id', {
input: { data: 'some input' },
timeout: 60000
});
参数:
workflowId
(字符串):要执行的工作流的 IDoptions
(ExecutionOptions,可选):input
(任意类型):传递给工作流的输入数据timeout
(数字):初始请求的超时时间(以毫秒为单位)
返回值: Promise<WorkflowExecutionResult>
setApiKey()
更新 API 密钥。
client.setApiKey('new-api-key');
setBaseUrl()
更新基础 URL。
client.setBaseUrl('https://my-custom-domain.com');
类型
WorkflowExecutionResult
interface WorkflowExecutionResult {
success: boolean;
output?: any;
error?: string;
logs?: any[];
metadata?: {
duration?: number;
executionId?: string;
[key: string]: any;
};
traceSpans?: any[];
totalDuration?: number;
}
WorkflowStatus
interface WorkflowStatus {
isDeployed: boolean;
deployedAt?: string;
isPublished: boolean;
needsRedeployment: boolean;
}
SimStudioError
class SimStudioError extends Error {
code?: string;
status?: number;
}
示例
基本工作流执行
使用您的 API 密钥设置 SimStudioClient。
检查工作流是否已部署并准备好执行。
使用您的输入数据运行工作流。
处理执行结果并处理任何错误。
import { SimStudioClient } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
apiKey: process.env.SIMSTUDIO_API_KEY!
});
async function runWorkflow() {
try {
// Check if workflow is ready
const isReady = await client.validateWorkflow('my-workflow-id');
if (!isReady) {
throw new Error('Workflow is not deployed or ready');
}
// Execute the workflow
const result = await client.executeWorkflow('my-workflow-id', {
input: {
message: 'Process this data',
userId: '12345'
}
});
if (result.success) {
console.log('Output:', result.output);
console.log('Duration:', result.metadata?.duration);
} else {
console.error('Workflow failed:', result.error);
}
} catch (error) {
console.error('Error:', error);
}
}
runWorkflow();
错误处理
处理工作流执行过程中可能发生的不同类型的错误:
import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
apiKey: process.env.SIMSTUDIO_API_KEY!
});
async function executeWithErrorHandling() {
try {
const result = await client.executeWorkflow('workflow-id');
return result;
} catch (error) {
if (error instanceof SimStudioError) {
switch (error.code) {
case 'UNAUTHORIZED':
console.error('Invalid API key');
break;
case 'TIMEOUT':
console.error('Workflow execution timed out');
break;
case 'USAGE_LIMIT_EXCEEDED':
console.error('Usage limit exceeded');
break;
case 'INVALID_JSON':
console.error('Invalid JSON in request body');
break;
default:
console.error('Workflow error:', error.message);
}
} else {
console.error('Unexpected error:', error);
}
throw error;
}
}
环境配置
使用环境变量配置客户端:
import { SimStudioClient } from 'simstudio-ts-sdk';
// Development configuration
const apiKey = process.env.SIMSTUDIO_API_KEY;
if (!apiKey) {
throw new Error('SIMSTUDIO_API_KEY environment variable is required');
}
const client = new SimStudioClient({
apiKey,
baseUrl: process.env.SIMSTUDIO_BASE_URL // optional
});
import { SimStudioClient } from 'simstudio-ts-sdk';
// Production configuration with validation
const apiKey = process.env.SIMSTUDIO_API_KEY;
if (!apiKey) {
throw new Error('SIMSTUDIO_API_KEY environment variable is required');
}
const client = new SimStudioClient({
apiKey,
baseUrl: process.env.SIMSTUDIO_BASE_URL || 'https://sim.ai'
});
Node.js Express 集成
与 Express.js 服务器集成:
import express from 'express';
import { SimStudioClient } from 'simstudio-ts-sdk';
const app = express();
const client = new SimStudioClient({
apiKey: process.env.SIMSTUDIO_API_KEY!
});
app.use(express.json());
app.post('/execute-workflow', async (req, res) => {
try {
const { workflowId, input } = req.body;
const result = await client.executeWorkflow(workflowId, {
input,
timeout: 60000
});
res.json({
success: true,
data: result
});
} catch (error) {
console.error('Workflow execution error:', error);
res.status(500).json({
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
});
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Next.js API 路由
与 Next.js API 路由一起使用:
// pages/api/workflow.ts or app/api/workflow/route.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { SimStudioClient } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
apiKey: process.env.SIMSTUDIO_API_KEY!
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const { workflowId, input } = req.body;
const result = await client.executeWorkflow(workflowId, {
input,
timeout: 30000
});
res.status(200).json(result);
} catch (error) {
console.error('Error executing workflow:', error);
res.status(500).json({
error: 'Failed to execute workflow'
});
}
}
浏览器使用
在浏览器中使用(需正确配置 CORS):
import { SimStudioClient } from 'simstudio-ts-sdk';
// Note: In production, use a proxy server to avoid exposing API keys
const client = new SimStudioClient({
apiKey: 'your-public-api-key', // Use with caution in browser
baseUrl: 'https://sim.ai'
});
async function executeClientSideWorkflow() {
try {
const result = await client.executeWorkflow('workflow-id', {
input: {
userInput: 'Hello from browser'
}
});
console.log('Workflow result:', result);
// Update UI with result
document.getElementById('result')!.textContent =
JSON.stringify(result.output, null, 2);
} catch (error) {
console.error('Error:', error);
}
}
// Attach to button click
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
在浏览器中使用 SDK 时,请注意不要暴露敏感的 API 密钥。建议使用后端代理或具有有限权限的公共 API 密钥。
React Hook 示例
为工作流执行创建一个自定义 React Hook:
import { useState, useCallback } from 'react';
import { SimStudioClient, WorkflowExecutionResult } from 'simstudio-ts-sdk';
const client = new SimStudioClient({
apiKey: process.env.NEXT_PUBLIC_SIMSTUDIO_API_KEY!
});
interface UseWorkflowResult {
result: WorkflowExecutionResult | null;
loading: boolean;
error: Error | null;
executeWorkflow: (workflowId: string, input?: any) => Promise<void>;
}
export function useWorkflow(): UseWorkflowResult {
const [result, setResult] = useState<WorkflowExecutionResult | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const executeWorkflow = useCallback(async (workflowId: string, input?: any) => {
setLoading(true);
setError(null);
setResult(null);
try {
const workflowResult = await client.executeWorkflow(workflowId, {
input,
timeout: 30000
});
setResult(workflowResult);
} catch (err) {
setError(err instanceof Error ? err : new Error('Unknown error'));
} finally {
setLoading(false);
}
}, []);
return {
result,
loading,
error,
executeWorkflow
};
}
// Usage in component
function WorkflowComponent() {
const { result, loading, error, executeWorkflow } = useWorkflow();
const handleExecute = () => {
executeWorkflow('my-workflow-id', {
message: 'Hello from React!'
});
};
return (
<div>
<button onClick={handleExecute} disabled={loading}>
{loading ? 'Executing...' : 'Execute Workflow'}
</button>
{error && <div>Error: {error.message}</div>}
{result && (
<div>
<h3>Result:</h3>
<pre>{JSON.stringify(result, null, 2)}</pre>
</div>
)}
</div>
);
}
获取您的 API 密钥
访问 Sim 并登录您的账户。
导航到您想要以编程方式执行的工作流。
如果尚未部署,请点击“部署”以部署您的工作流。
在部署过程中,选择或创建一个 API 密钥。
复制 API 密钥以在您的 TypeScript/JavaScript 应用程序中使用。
请确保您的 API 密钥安全,切勿将其提交到版本控制中。使用环境变量或安全配置管理。
要求
- Node.js 16+
- TypeScript 5.0+(适用于 TypeScript 项目)
TypeScript 支持
SDK 是用 TypeScript 编写的,并提供完整的类型安全:
import {
SimStudioClient,
WorkflowExecutionResult,
WorkflowStatus,
SimStudioError
} from 'simstudio-ts-sdk';
// Type-safe client initialization
const client: SimStudioClient = new SimStudioClient({
apiKey: process.env.SIMSTUDIO_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