OpenAgentAGI
Sdks

TypeScript/JavaScript SDK

OpenAgentAGI-ийн албан ёсны TypeScript/JavaScript SDK нь бүрэн type safety-тай бөгөөд Node.js болон browser орчныг хоёуланг нь дэмждэг. Ингэснээр та Node.js аппликейшн, веб аппликейшн болон бусад JavaScript орчноос workflow-уудыг програмчлалын аргаар гүйцэтгэх боломжтой. Одоогоор бүх workflow execution нь synchronous (дараалсан) хэлбэртэй байна.

TypeScript SDK нь бүрэн type safety-тай бөгөөд Node.js болон browser орчныг хоёуланг нь дэмждэг. Одоогоор бүх workflow execution нь synchronous байна.

Суулгах (Installation)

Өөрийн хүссэн package manager-ийг ашиглан SDK-г суулгана:

npm install openagentagi-ts-sdk
yarn add openagentagi-ts-sdk
bun add openagentagi-ts-sdk

Эхлэх (Quick Start)

Хэрхэн хэрэглэж эхлэхийг доорх жишээнээс харна уу:

import { OpenAgentAGIClient } from 'openagentagi-ts-sdk';

// Initialize the client
const client = new OpenAgentAGIClient({
  apiKey: 'your-api-key-here',
  baseUrl: 'https://www.openagentagi.com' // optional, defaults to https://www.openagentagi.com
});

// 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 Reference

OpenAgentAGIClient

Constructor

new OpenAgentAGIClient(config: SimStudioConfig)

Configuration:

  • config.apiKey (string): Your OpenAgentAGI API key
  • config.baseUrl (string, optional): Base URL for the OpenAgentAGI API (defaults to https://www.openagentagi.com)

Methods

executeWorkflow()

Execute a workflow with optional input data.

const result = await client.executeWorkflow('workflow-id', {
  input: { message: 'Hello, world!' },
  timeout: 30000 // 30 seconds
});

Parameters:

  • workflowId (string): The ID of the workflow to execute
  • options (ExecutionOptions, optional):
    • input (any): Input data to pass to the workflow
    • timeout (number): Timeout in milliseconds (default: 30000)

Returns: Promise<WorkflowExecutionResult>

getWorkflowStatus()

Get the status of a workflow (deployment status, etc.).

const status = await client.getWorkflowStatus('workflow-id');
console.log('Is deployed:', status.isDeployed);

Parameters:

  • workflowId (string): The ID of the workflow

Returns: Promise<WorkflowStatus>

validateWorkflow()

Validate that a workflow is ready for execution.

const isReady = await client.validateWorkflow('workflow-id');
if (isReady) {
  // Workflow is deployed and ready
}

Parameters:

  • workflowId (string): The ID of the workflow

Returns: Promise<boolean>

executeWorkflowSync()

Currently, this method is identical to executeWorkflow() since all executions are synchronous. This method is provided for future compatibility when asynchronous execution is added.

Execute a workflow (currently synchronous, same as executeWorkflow()).

const result = await client.executeWorkflowSync('workflow-id', {
  input: { data: 'some input' },
  timeout: 60000
});

Parameters:

  • workflowId (string): The ID of the workflow to execute
  • options (ExecutionOptions, optional):
    • input (any): Input data to pass to the workflow
    • timeout (number): Timeout for the initial request in milliseconds

Returns: Promise<WorkflowExecutionResult>

setApiKey()

Update the API key.

client.setApiKey('new-api-key');
setBaseUrl()

Update the base URL.

client.setBaseUrl('https://my-custom-domain.com');

Types

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;
}

OpenAgentAGIError

class OpenAgentAGIError extends Error {
  code?: string;
  status?: number;
}

Examples

Basic Workflow Execution

Set up the OpenAgentAGIClient with your API key.

Check if the workflow is deployed and ready for execution.

Run the workflow with your input data.

Process the execution result and handle any errors.

import { OpenAgentAGIClient } from 'openagentagi-ts-sdk';

const client = new OpenAgentAGIClient({
  apiKey: process.env.OPENAGENTAGI_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();

Error Handling

Handle different types of errors that may occur during workflow execution:

import { OpenAgentAGIClient, OpenAgentAGIError } from 'openagentagi-ts-sdk';

const client = new OpenAgentAGIClient({
  apiKey: process.env.OPENAGENTAGI_API_KEY!
});

async function executeWithErrorHandling() {
  try {
    const result = await client.executeWorkflow('workflow-id');
    return result;
  } catch (error) {
    if (error instanceof OpenAgentAGIError) {
      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;
  }
}

Environment Configuration

Configure the client using environment variables:

import { OpenAgentAGIClient } from 'openagentagi-ts-sdk';

// Development configuration
const apiKey = process.env.OPENAGENTAGI_API_KEY;
if (!apiKey) {
  throw new Error('OPENAGENTAGI_API_KEY environment variable is required');
}

const client = new OpenAgentAGIClient({
  apiKey,
  baseUrl: process.env.OPENAGENTAGI_BASE_URL // optional
});
import { OpenAgentAGIClient } from 'openagentagi-ts-sdk';

// Production configuration with validation
const apiKey = process.env.OPENAGENTAGI_API_KEY;
if (!apiKey) {
  throw new Error('OPENAGENTAGI_API_KEY environment variable is required');
}

const client = new OpenAgentAGIClient({
  apiKey,
  baseUrl: process.env.OPENAGENTAGI_BASE_URL || 'https://www.openagentagi.com'
});

Node.js Express Integration

Integrate with an Express.js server:

import express from 'express';
import { OpenAgentAGIClient } from 'openagentagi-ts-sdk';

const app = express();
const client = new OpenAgentAGIClient({
  apiKey: process.env.OPENAGENTAGI_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 Route

Use with Next.js API routes:

// pages/api/workflow.ts or app/api/workflow/route.ts
import { NextApiRequest, NextApiResponse } from 'next';
import { OpenAgentAGIClient } from 'openagentagi-ts-sdk';

const client = new OpenAgentAGIClient({
  apiKey: process.env.OPENAGENTAGI_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'
    });
  }
}

Browser Usage

Use in the browser (with proper CORS configuration):

import { OpenAgentAGIClient } from 'openagentagi-ts-sdk';

// Note: In production, use a proxy server to avoid exposing API keys
const client = new OpenAgentAGIClient({
  apiKey: 'your-public-api-key', // Use with caution in browser
  baseUrl: 'https://www.openagentagi.com'
});

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);

When using the SDK in the browser, be careful not to expose sensitive API keys. Consider using a backend proxy or public API keys with limited permissions.

React Hook Example

Create a custom React hook for workflow execution:

import { useState, useCallback } from 'react';
import { OpenAgentAGIClient, WorkflowExecutionResult } from 'openagentagi-ts-sdk';

const client = new OpenAgentAGIClient({
  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>
  );
}

Getting Your API Key

Navigate to OpenAgentAGI 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:

import { 
  OpenAgentAGIClient, 
  WorkflowExecutionResult, 
  WorkflowStatus,
  OpenAgentAGIError 
} from 'openagentagi-ts-sdk';

// Type-safe client initialization
const client: OpenAgentAGIClient = new OpenAgentAGIClient({
  apiKey: process.env.OPENAGENTAGI_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');

License

Apache-2.0

TypeScript/JavaScript SDK