Skip to content

SDK Reference

The Raikoo SDK provides a TypeScript/JavaScript client library for interacting with the Raikoo API. Use it to execute workflows, chat with AI agents, manage workspaces, and integrate Raikoo capabilities into your applications.

Installation

Install the SDK using npm:

npm install @raikoo-ai/sdk

Or with yarn:

yarn add @raikoo-ai/sdk

Quick Start

import { RaikooClient } from '@raikoo-ai/sdk';

// Create a client with your Personal Access Token
const client = new RaikooClient({
  pat: 'your-personal-access-token',
});

// Execute a workflow
const result = await client.executeWorkflow('projectId', 'workflowId');
console.log(result.status);
console.log(result.messages);

Authentication

Personal Access Token (PAT)

The simplest way to authenticate is with a Personal Access Token:

import { RaikooClient } from '@raikoo-ai/sdk';

const client = new RaikooClient({
  pat: 'your-personal-access-token',
});

You can generate a Personal Access Token from your Raikoo account settings.

Custom Token Provider

For advanced authentication scenarios, provide a custom token provider:

import { RaikooClient, type TokenProvider } from '@raikoo-ai/sdk';

const customProvider: TokenProvider = {
  getToken: async () => {
    // Your custom authentication logic
    const token = await getTokenFromYourAuthSystem();
    return token;
  },
  clearToken: () => {
    // Optional: Clear cached tokens on auth failure
  },
};

const client = new RaikooClient({
  tokenProvider: customProvider,
});

Environment Configuration

Target different API environments by setting the baseUrl:

const client = new RaikooClient({
  pat: 'your-pat',
  baseUrl: 'https://demo-api.raikoo.com',
});

// Or change it later
client.setBaseUrl('https://api.raikoo.com');

The default base URL is https://api.raikoo.com.

Workflows

Listing Workflows

Get all workflows in a project:

const workflows = await client.listWorkflows('projectId');

workflows.forEach(workflow => {
  console.log(`${workflow.name}: ${workflow.description}`);
});

Getting a Workflow

Retrieve a single workflow by ID:

const workflow = await client.getWorkflow('projectId', 'workflowId');
console.log(workflow.name);
console.log(workflow.data);

Listing Workflow Versions

Get all versions of a workflow:

const versions = await client.listWorkflowVersions('projectId', 'workflowId');

versions.forEach(version => {
  console.log(`${version.name} (active: ${version.active})`);
});

Execute Workflow (Response)

Execute a workflow and wait for the final result:

const result = await client.executeWorkflow('projectId', 'workflowId');

console.log(result.status.state); // 'completed', 'failed', etc.
console.log(result.status.usage); // Token usage statistics

// Access all messages from execution
result.messages.forEach(message => {
  console.log(message.type, message);
});

Execute Workflow (Streaming)

Stream workflow execution messages as they arrive:

for await (const message of client.executeWorkflowStream('projectId', 'workflowId')) {
  console.log(message.type, message);

  if (message.type === 'thread-status-update') {
    console.log('Progress:', message.statusText);
  }
}

Execute with Parameters

Pass parameters to a workflow:

const result = await client.executeWorkflow('projectId', 'workflowId', {
  parameters: {
    prompt: 'Analyze this data',
    format: 'json',
    maxTokens: 1000,
  },
});

Execute with Specific Version

Execute a specific workflow version:

const result = await client.executeWorkflow('projectId', 'workflowId', {
  threadPlanVersionId: 'versionId',
});

Execute with Model Override

Override the workflow's default model:

const models = await client.listModels('organizationId');
const gpt4Model = models.find(m => m.model === 'gpt-4');

const result = await client.executeWorkflow('projectId', 'workflowId', {
  modelSelector: gpt4Model,
});

Execute with Workspace (Input Files)

Provide input files to a workflow using a workspace:

// Create a workspace and add input files
const workspace = await client.createWorkspace();
await workspace.writeFile('/input.txt', 'Hello, world!');
await workspace.writeFile('/data.json', JSON.stringify({ key: 'value' }));

// Execute with the workspace
const result = await client.executeWorkflow('projectId', 'workflowId', {
  workspace,
});

// Access output files from the workspace
const files = await workspace.get();
console.log('Output files:', files);

// Read a specific file
const outputContent = await workspace.readFile('/output.txt');
console.log(outputContent);

Extract Output Files

Extract workflow output files as browser-native File objects:

import { extractWorkflowOutputFiles } from '@raikoo-ai/sdk';

const result = await client.executeWorkflow('projectId', 'workflowId');
const output = extractWorkflowOutputFiles(result.messages);

// Access the primary result file (if workflow configured finalResultFilePath)
if (output.resultFile) {
  const text = await output.resultFile.text();
  console.log('Result:', text);
}

// Access additional output files (matched by outputFileGlobPatterns)
for (const file of output.outputFiles) {
  console.log(`${file.name} (${file.size} bytes, ${file.type})`);
  const content = await file.text();
  console.log(content);
}

You can also extract files during streaming execution:

for await (const message of client.executeWorkflowStream('projectId', 'workflowId')) {
  const output = extractWorkflowOutputFiles(message);
  if (output.resultFile) {
    console.log('Got result file:', output.resultFile.name);
  }
}

Execution Options

Advanced execution options:

const result = await client.executeWorkflow('projectId', 'workflowId', {
  // Enable parallel execution of operations
  parallel: true,

  // Maximum number of parallel operations
  parallelBatch: 5,

  // Enable concurrent execution within operations
  concurrent: true,

  // Enable verbose status messages
  verbose: true,

  // Resume from a previous execution
  threadStatusHistoryId: 'historyId',
});

Chat

Chat (Response)

Send a chat message and get the full response:

const response = await client.chat({
  projectId: 'your-project-id',
  messages: [
    { role: 'user', content: 'What can you help me with?' },
  ],
});

console.log(response.content);

Chat (Streaming)

Stream chat responses as they're generated:

for await (const chunk of client.chatStream({
  projectId: 'your-project-id',
  messages: [
    { role: 'user', content: 'Write a poem about TypeScript' },
  ],
})) {
  process.stdout.write(chunk);
}

Multi-turn Conversation

Build a conversation with message history:

const messages = [
  { role: 'user', content: 'What is 2 + 2?' },
  { role: 'assistant', content: '2 + 2 equals 4.' },
  { role: 'user', content: 'What about 3 + 3?' },
];

const response = await client.chat({
  projectId: 'your-project-id',
  messages,
});

console.log(response.content);

Chat with Agent

Use a specific chat agent:

const agents = await client.listChatAgents('organizationId');
const agent = agents.find(a => a.name === 'Code Assistant');

const response = await client.chat({
  projectId: 'your-project-id',
  agentId: agent.id,
  messages: [
    { role: 'user', content: 'Help me debug this code' },
  ],
});

Chat with Model Override

Override the agent's default model:

const models = await client.listModels('organizationId');
const claudeModel = models.find(m => m.model?.includes('claude'));

const response = await client.chat({
  projectId: 'your-project-id',
  modelSelector: claudeModel,
  messages: [
    { role: 'user', content: 'Explain quantum computing' },
  ],
});

Chat with System Prompt

Provide a custom system prompt:

const response = await client.chat({
  projectId: 'your-project-id',
  systemPrompt: 'You are a helpful coding assistant specialized in TypeScript.',
  messages: [
    { role: 'user', content: 'How do I use generics?' },
  ],
});

Chat with Tools

Enable specific tools for the chat session:

const response = await client.chat({
  projectId: 'your-project-id',
  tools: ['web-search', 'code-interpreter'],
  maxToolRoundtrips: 5,
  messages: [
    { role: 'user', content: 'Search for the latest TypeScript features' },
  ],
});

Chat with Workspace Context

Provide files as context using a workspace:

const workspace = await client.createWorkspace();
await workspace.writeFile('/context.txt', 'Important context information');

const workspaceDiff = await workspace.getOverlay();

const response = await client.chat({
  projectId: 'your-project-id',
  workspaceDifference: workspaceDiff,
  messages: [
    { role: 'user', content: 'Analyze the context file' },
  ],
});

Agents

Get Chat Agent

Retrieve a chat agent by ID:

const agent = await client.getChatAgent('chatAgentId');

console.log(agent.name);
console.log(agent.description);
console.log(agent.systemPrompt);
console.log(agent.tools);

List Chat Agents

Get all chat agents in an organization:

const agents = await client.listChatAgents('organizationId');

agents.forEach(agent => {
  console.log(`${agent.id}: ${agent.name}`);
});

Models

List Models

Get available model selectors for an organization:

const models = await client.listModels('organizationId');

models.forEach(selector => {
  if (selector.type === 'model') {
    console.log(`${selector.provider}/${selector.model}`);
    console.log(`  Context: ${selector.linkedModel?.contextWindow}`);
    console.log(`  Modalities: ${selector.linkedModel?.modalities?.join(', ')}`);
  } else if (selector.type === 'model-family') {
    console.log(`Family: ${selector.modelFamily}`);
  }
});

List Provider Models

Get models for a specific provider:

const models = await client.listProviderModels('organizationId', 'openai');

models.forEach(selector => {
  console.log(`${selector.model}`);
  console.log(`  Context: ${selector.linkedModel?.contextWindow}`);
  console.log(`  Capabilities: ${selector.linkedModel?.capabilities?.join(', ')}`);
});

Workspaces

Create Workspace

Create a client-side workspace for managing files:

const workspace = await client.createWorkspace();

// Write files
await workspace.writeFile('/file.txt', 'content');
await workspace.writeFile('/data/file.json', JSON.stringify({ key: 'value' }));

// Read files
const content = await workspace.readFile('/file.txt');

// List files
const files = await workspace.get();
console.log(files);

// Get workspace overlay (changes)
const overlay = await workspace.getOverlay();

Get Remote Workspace

Access a workspace stored on the server:

const workspaceInfo = await client.getWorkspace('workspaceId');

console.log(workspaceInfo.name);
console.log(workspaceInfo.description);
console.log(`Total files: ${workspaceInfo.totalFiles}`);

workspaceInfo.files.forEach(entry => {
  console.log(`${entry.type}: ${entry.path} (${entry.size} bytes)`);
});

Download Workspace File

Download a single file from a remote workspace:

const response = await client.getWorkspaceFile('workspaceId', '/path/to/file.txt');
const content = await response.text();
console.log(content);

// For binary files
const blob = await response.blob();

Download Workspace Directory

Download a directory as a ZIP archive:

const response = await client.getWorkspaceDirectory('workspaceId', '/path/to/dir');
const blob = await response.blob();

// Save or process the ZIP file
const arrayBuffer = await blob.arrayBuffer();

Error Handling

All API errors are thrown as RaikooApiError instances:

import { RaikooApiError } from '@raikoo-ai/sdk';

try {
  const result = await client.executeWorkflow('projectId', 'workflowId');
} catch (error) {
  if (error instanceof RaikooApiError) {
    console.error(`API Error: ${error.status} ${error.statusText}`);
    console.error(`Message: ${error.message}`);
    console.error(`Body: ${error.body}`);
  } else {
    console.error('Unexpected error:', error);
  }
}

The RaikooApiError class provides:

  • status - HTTP status code (e.g., 404, 500)
  • statusText - HTTP status text (e.g., "Not Found")
  • message - Error message
  • body - Raw response body (if available)

Advanced Usage

Streaming with Status Builder

For advanced streaming scenarios, use ThreadStatusBuilder directly:

import { ThreadStatusBuilder } from '@raikoo-ai/sdk';

const workspace = await client.createWorkspace();
const builder = new ThreadStatusBuilder(workspace);

for await (const message of client.executeWorkflowStream('projectId', 'workflowId', { workspace })) {
  await builder.processMessage(message);

  // Access incremental status
  const currentStatus = await builder.get();
  console.log('Current state:', currentStatus.state);
}

// Final status
const finalStatus = await builder.get();
console.log('Final usage:', finalStatus.usage);

Using Serialized File Systems

Initialize a workspace from a serialized file system:

const serializedFs = {
  // Serialized file system structure
  '/file.txt': { content: 'data', type: 'file' },
};

const workspace = await client.createWorkspace({
  serializedFileSystem: serializedFs,
});

// Or pass it directly to workflow execution
const result = await client.executeWorkflow('projectId', 'workflowId', {
  serializedFileSystem: serializedFs,
});

Custom Workspace Configuration

Create a workspace with custom volume configuration:

const workspace = await client.createWorkspace({
  configuration: {
    type: 'memory',
    // Additional volume configuration
  },
  mountConfigurations: {
    '/mnt/data': {
      type: 'memory',
    },
  },
});

API Reference

RaikooClient

The main client class for interacting with the Raikoo API.

Constructor

new RaikooClient(options: RaikooClientOptions)

Methods

Method Description Returns
setBaseUrl(baseUrl: string) Change the API base URL void
getBaseUrl() Get the current API base URL string
createWorkspace(options?) Create a client-side workspace Promise<ClientWorkspace>
listWorkflows(projectId) List all workflows in a project Promise<WorkflowListItem[]>
getWorkflow(projectId, workflowId) Get a single workflow by ID Promise<Workflow>
listWorkflowVersions(projectId, workflowId) List all versions of a workflow Promise<WorkflowVersion[]>
executeWorkflow(projectId, workflowId, options?) Execute a workflow and return the final result Promise<WorkflowResult>
executeWorkflowStream(projectId, workflowId, options?) Execute a workflow with streaming updates AsyncGenerator<ThreadStatusMessage>
chat(options) Send a chat message (non-streaming) Promise<ChatResponse>
chatStream(options) Send a chat message with streaming AsyncGenerator<string>
getChatAgent(chatAgentId) Get a chat agent by ID Promise<ChatAgent>
listChatAgents(organizationId) List chat agents for an organization Promise<ChatAgentSummary[]>
listModels(organizationId) List available model selectors Promise<ModelSelector[]>
listProviderModels(organizationId, providerId) List models for a specific provider Promise<ModelProviderSelector[]>
getWorkspace(workspaceId, path?) Get workspace info and file listing Promise<WorkspaceInfo>
getWorkspaceFile(workspaceId, path) Download a single file from a workspace Promise<Response>
getWorkspaceDirectory(workspaceId, path?) Download a directory as ZIP Promise<Response>

Types

RaikooClientOptions

interface RaikooClientOptions {
  baseUrl?: string;
  pat?: string;
  tokenProvider?: TokenProvider;
}

ExecuteWorkflowOptions

interface ExecuteWorkflowOptions {
  workspace?: ClientWorkspace;
  threadPlanVersionId?: string;
  modelSelector?: ModelProviderSelector;
  serializedFileSystem?: SerializedFileSystem;
  workspaceDifference?: WorkspaceDifference;
  parameters?: Record<string, unknown>;
  threadStatusHistoryId?: string;
  threadStatus?: ThreadStatus;
  parallel?: boolean;
  concurrent?: boolean;
  parallelBatch?: number;
  verbose?: boolean;
}

WorkflowResult

interface WorkflowResult {
  status: ThreadStatus;
  messages: ThreadStatusMessage[];
  workspace: ClientWorkspace;
}

ChatOptions

interface ChatOptions {
  projectId: string;
  messages: ChatMessage[];
  agentId?: string;
  modelSelector?: ModelProviderSelector;
  systemPrompt?: string;
  tools?: string[];
  maxToolRoundtrips?: number;
  workspaceDifference?: WorkspaceDifference;
}

ChatMessage

interface ChatMessage {
  role: 'user' | 'assistant' | 'system';
  content: string;
}

ChatResponse

interface ChatResponse {
  content: string;
}

WorkflowListItem

interface WorkflowListItem {
  id: string;
  name: string;
  description: string;
}

Workflow

interface Workflow extends WorkflowListItem {
  data: unknown;
  createDate?: string;
  updateDate?: string;
  tagListJson?: string;
  layout?: string;
  projectId?: string;
  deleted?: boolean;
  createdBy?: string;
  updatedBy?: string;
}

WorkflowVersion

interface WorkflowVersion {
  id: string;
  name: string;
  description?: string;
  active?: boolean;
  threadPlanId?: string;
  createdBy?: string;
  updatedBy?: string;
  createDate?: string;
  updateDate?: string;
}

ChatAgent

interface ChatAgent {
  id: string;
  name: string;
  description?: string;
  organizationId: string;
  systemPrompt?: string;
  tools?: string;
  defaultModelSelector?: string;
  createdBy?: string;
  createDate?: string;
  updatedBy?: string;
  updateDate?: string;
  deleted?: boolean;
  maxToolRoundtrips?: number;
  projectId?: string;
}

ChatAgentSummary

interface ChatAgentSummary {
  id: string;
  name: string;
}

WorkspaceInfo

interface WorkspaceInfo {
  id: string;
  organizationId: string;
  name: string;
  description?: string;
  files: WorkspaceFileEntry[];
  totalFiles: number;
}

WorkspaceFileEntry

interface WorkspaceFileEntry {
  path: string;
  type: 'file' | 'directory';
  size?: number;
  children?: WorkspaceFileEntry[];
}

WorkflowOutputFiles

interface WorkflowOutputFiles {
  resultFile?: File;
  outputFiles: File[];
}

Utility Functions

extractWorkflowOutputFiles

function extractWorkflowOutputFiles(
  messages: ThreadStatusMessage | ThreadStatusMessage[]
): WorkflowOutputFiles

Extracts output files from workflow execution messages and converts them to browser-native File objects.

parseStatusStream

async function* parseStatusStream(
  response: Response
): AsyncGenerator<ThreadStatusMessage>

Parses a streaming response from the execute-workflow endpoint. This is used internally by executeWorkflowStream but can be used directly for advanced scenarios.

TypeScript Support

The SDK is written in TypeScript and provides full type definitions. All types are exported from the main package:

import type {
  RaikooClientOptions,
  ExecuteWorkflowOptions,
  WorkflowResult,
  ChatOptions,
  ChatMessage,
  ChatResponse,
  Workflow,
  WorkflowListItem,
  WorkflowVersion,
  ChatAgent,
  ChatAgentSummary,
  WorkspaceInfo,
  WorkflowOutputFiles,
  TokenProvider,
  ThreadStatus,
  ThreadStatusMessage,
  ModelSelector,
  ModelProviderSelector,
} from '@raikoo-ai/sdk';

Learn More

Support

For questions or issues with the SDK: