npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ragwalla/assistants-sdk-ts

v0.1.0

Published

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

Downloads

8

Readme

@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

npm install @ragwalla/assistants-sdk-ts

Requirements

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

Quick Start

Using Types

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

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

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

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

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:

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

# 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 file for details.

Links

Support

For issues and questions, please open an issue on GitHub.