@ragwalla/assistants-sdk-ts
v0.1.0
Published
OpenAI Assistants API types, schemas, error classes, and streaming helpers for Cloudflare Workers
Downloads
8
Maintainers
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-tsRequirements
- 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 detailsNotFoundError- Generic 404 errorThreadNotFoundError- Specific thread not found errorBadRequestError- 400 validation errorsTokenLimitExceededError- Token limit errorsOpenAIError- OpenAI-specific errorsUnexpectedError- Catch-all for unexpected errors
Streaming
sendSSE()- Send individual SSE eventssendInitialEvents()- Send thread.created and run status eventssendFinalEvent()- Send final run status and done eventsendRequiresActionEvent()- Send requires_action statushandleCompletionStream()- Process OpenAI streaming responseshandleStreamError()- Handle and send streaming errorsprocessAnnotations()- Process file citation annotations
Utilities
generateId()- Generate OpenAI-compatible IDstransformResponse()- Transform API responses
Constants
OPENAI_MODELS- All available OpenAI modelsEMBEDDING_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 testContributing
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.
