npm package: @ragwalla/assistants-sdk-ts
Description: OpenAI Assistants API types, schemas, error classes, and streaming helpers for Cloudflare Workers
Author: Ragwalla
Latest version: 0.1.0

# @ragwalla/assistants-sdk-ts

OpenAI Assistants API types, schemas, error classes, and streaming helpers optimized for Cloudflare Workers.

## Features

- **TypeScript Types**: Comprehensive type definitions for the entire OpenAI Assistants API
- **Zod Schemas**: Runtime validation schemas for assistants, threads, messages, runs, and more
- **Error Handling**: Framework-agnostic error classes with specialized adapters (Hono)
- **Streaming Support**: Server-Sent Events (SSE) helpers for streaming assistant responses
- **Utilities**: ID generation, data transformation helpers, and OpenAI model constants
- **Tree-shakeable**: Modular exports allow bundlers to eliminate unused code
- **Dual Format**: Ships with both ESM and CommonJS builds

## Installation

```bash
npm install @ragwalla/assistants-sdk-ts
```

## Requirements

- Node.js >= 18.0.0
- TypeScript 5.0+ (for type definitions)

## Quick Start

### Using Types

```typescript
import type { Assistant, Thread, Message, Run } from '@ragwalla/assistants-sdk-ts';

const assistant: Assistant = {
  id: 'asst_abc123',
  object: 'assistant',
  created_at: Date.now(),
  name: 'My Assistant',
  model: 'gpt-4-turbo-preview',
  // ...
};
```

### Validating with Schemas

```typescript
import { AssistantCreateParamsSchema } from '@ragwalla/assistants-sdk-ts/schemas';

const result = AssistantCreateParamsSchema.safeParse({
  model: 'gpt-4-turbo-preview',
  name: 'Math Tutor',
  instructions: 'You are a helpful math tutor.',
});

if (result.success) {
  console.log('Valid assistant params:', result.data);
} else {
  console.error('Validation errors:', result.error);
}
```

### Error Handling

```typescript
import { ApiError, ThreadNotFoundError, TokenLimitExceededError } from '@ragwalla/assistants-sdk-ts';

try {
  // Your API call
} catch (error) {
  if (error instanceof ThreadNotFoundError) {
    console.error('Thread not found:', error.threadId);
  } else if (error instanceof TokenLimitExceededError) {
    console.error('Token limit exceeded');
  } else if (error instanceof ApiError) {
    console.error('API error:', error.message, error.statusCode);
  }
}
```

### Streaming with Cloudflare Workers

```typescript
import { sendSSE, handleCompletionStream, sendInitialEvents, sendFinalEvent } from '@ragwalla/assistants-sdk-ts/streaming';
import type { StreamContext } from '@ragwalla/assistants-sdk-ts';

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const { readable, writable } = new TransformStream();
    const writer = writable.getWriter();
    const encoder = new TextEncoder();

    const context: StreamContext = {
      writer,
      encoder,
      threadId: 'thread_abc123',
      runId: 'run_xyz789',
    };

    // Start streaming
    (async () => {
      try {
        await sendInitialEvents(context);

        // Process OpenAI streaming response
        const openaiResponse = await fetch('https://api.openai.com/v1/threads/runs', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${env.OPENAI_API_KEY}`,
            'Content-Type': 'application/json',
            'OpenAI-Beta': 'assistants=v2',
          },
          body: JSON.stringify({ stream: true }),
        });

        await handleCompletionStream(openaiResponse, context);
        await sendFinalEvent(context, 'completed');
      } catch (error) {
        await handleStreamError(error, context);
      } finally {
        await writer.close();
      }
    })();

    return new Response(readable, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
      },
    });
  },
};
```

### Using with Hono

```typescript
import { Hono } from 'hono';
import { honoErrorHandler } from '@ragwalla/assistants-sdk-ts/errors/adapters/hono';

const app = new Hono();

app.onError(honoErrorHandler);

app.get('/assistants/:id', async (c) => {
  const id = c.req.param('id');
  // Your logic here
});

export default app;
```

## Available Subpath Exports

The package provides modular exports to keep your bundle size small:

```typescript
// Main entry - includes types, constants, errors, utilities, and streaming
import { ... } from '@ragwalla/assistants-sdk-ts';

// Type definitions only
import type { Assistant, Thread, Message } from '@ragwalla/assistants-sdk-ts/types';

// Zod schemas for validation
import { AssistantSchema, ThreadSchema } from '@ragwalla/assistants-sdk-ts/schemas';

// Error handling
import { ApiError, ThreadNotFoundError } from '@ragwalla/assistants-sdk-ts/errors';

// Hono error adapter
import { honoErrorHandler } from '@ragwalla/assistants-sdk-ts/errors/adapters/hono';

// Streaming utilities
import { sendSSE, handleCompletionStream } from '@ragwalla/assistants-sdk-ts/streaming';

// Utility functions
import { generateId, transformResponse } from '@ragwalla/assistants-sdk-ts/utilities';

// OpenAI model constants
import { OPENAI_MODELS, EMBEDDING_MODELS } from '@ragwalla/assistants-sdk-ts/constants';
```

## API Overview

### Types
Comprehensive TypeScript types for:
- Assistants
- Threads
- Messages
- Runs
- Vector Stores
- Tools (Function, File Search, Code Interpreter)
- Completions
- Embeddings

### Schemas
Zod validation schemas for all API resources, including:
- Create/Update parameter schemas
- Response schemas
- Nested object schemas (metadata, tool resources, etc.)

### Error Classes
- `ApiError` - Base error class with status code and error details
- `NotFoundError` - Generic 404 error
- `ThreadNotFoundError` - Specific thread not found error
- `BadRequestError` - 400 validation errors
- `TokenLimitExceededError` - Token limit errors
- `OpenAIError` - OpenAI-specific errors
- `UnexpectedError` - Catch-all for unexpected errors

### Streaming
- `sendSSE()` - Send individual SSE events
- `sendInitialEvents()` - Send thread.created and run status events
- `sendFinalEvent()` - Send final run status and done event
- `sendRequiresActionEvent()` - Send requires_action status
- `handleCompletionStream()` - Process OpenAI streaming responses
- `handleStreamError()` - Handle and send streaming errors
- `processAnnotations()` - Process file citation annotations

### Utilities
- `generateId()` - Generate OpenAI-compatible IDs
- `transformResponse()` - Transform API responses

### Constants
- `OPENAI_MODELS` - All available OpenAI models
- `EMBEDDING_MODELS` - All available embedding models

## Development

```bash
# Install dependencies
npm install

# Build the package
npm run build

# Run type checking
npm run build:check

# Run tests
npm test

# Run tests in watch mode
npm run test
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

MIT License - see the [LICENSE](LICENSE) file for details.

## Links

- [GitHub Repository](https://github.com/ragwalla/ragwalla-assistants-sdk-ts)
- [npm Package](https://www.npmjs.com/package/@ragwalla/assistants-sdk-ts)
- [OpenAI Assistants API Documentation](https://platform.openai.com/docs/assistants)

## Support

For issues and questions, please [open an issue](https://github.com/ragwalla/ragwalla-assistants-sdk-ts/issues) on GitHub.