npm package: @sthg-sdk/dify-api
Description: Dify API client with streaming support for STHG Tiangong SDK
Latest version: 1.1.0

# @sthg-sdk/dify-api

Dify API client with streaming support for STHG Tiangong SDK.

## Features

- ✨ Complete Dify API coverage
- 🚀 Streaming support using Microsoft's fetch-event-source
- 📝 Full TypeScript support
- 🔄 Both blocking and streaming modes
- 🛡️ Built-in error handling
- 🎯 Easy to use API

## Installation

```bash
pnpm add @sthg-sdk/dify-api
```

## Usage

### Basic Setup

```typescript
import { DifyClient } from '@sthg-sdk/dify-api';

const client = new DifyClient({
  baseUrl: 'https://api.dify.ai/v1',
  apiKey: 'your-api-key',
});
```

### Chat Messages (Blocking)

```typescript
const response = await client.chatMessages({
  inputs: {},
  query: 'Hello, how are you?',
  response_mode: 'blocking',
  user: 'user-123',
});

console.log(response.answer);
```

### Chat Messages (Streaming)

```typescript
await client.chatMessagesStream(
  {
    inputs: {},
    query: 'Tell me a long story',
    response_mode: 'streaming',
    user: 'user-123',
  },
  {
    onMessage: (data) => {
      console.log('Received:', data);
    },
    onEnd: () => {
      console.log('Stream ended');
    },
    onError: (error) => {
      console.error('Stream error:', error);
    },
    onClose: () => {
      console.log('Connection closed');
    },
  }
);
```

### Completion

```typescript
// Blocking mode
const completion = await client.completion({
  inputs: { name: 'John' },
  response_mode: 'blocking',
  user: 'user-123',
});

// Streaming mode
await client.completionStream(
  {
    inputs: { name: 'John' },
    response_mode: 'streaming',
    user: 'user-123',
  },
  {
    onMessage: (data) => console.log(data),
    onEnd: () => console.log('Done'),
  }
);
```

### Workflow Run

```typescript
// Blocking mode
const workflowResult = await client.workflowRun({
  inputs: { query: 'What is the weather today?' },
  response_mode: 'blocking',
  user: 'user-123',
});

// Streaming mode
await client.workflowRunStream(
  {
    inputs: { query: 'Process this data' },
    response_mode: 'streaming',
    user: 'user-123',
  },
  {
    onMessage: (data) => console.log('Workflow update:', data),
    onError: (error) => console.error('Workflow error:', error),
  }
);
```

### Audio to Text

```typescript
const audioFile = new File([audioBuffer], 'audio.wav', { type: 'audio/wav' });

const transcription = await client.audioToText({
  file: audioFile,
  user: 'user-123',
});

console.log(transcription.text);
```

### Text to Audio

```typescript
const audioBuffer = await client.textToAudio({
  message_id: 'msg-123',
  text: 'Hello world',
  user: 'user-123',
});

// Convert to audio file or play directly
```

### Conversation Management

```typescript
// Get conversations
const conversations = await client.getConversations('user-123');

// Get conversation messages
const messages = await client.getConversationMessages(
  'conversation-id',
  'user-123'
);

// Rename conversation
await client.renameConversation(
  'conversation-id',
  'New Name',
  'user-123'
);

// Delete conversation
await client.deleteConversation('conversation-id', 'user-123');
```

### Stop Streaming

```typescript
// Stop any active streaming connection
client.stopStreaming();
```

## Configuration Options

```typescript
interface DifyConfig {
  baseUrl: string;           // Required: Dify API base URL
  apiKey: string;            // Required: Your API key
  headers?: Record<string, string>; // Optional: Custom headers
  timeout?: number;          // Optional: Request timeout (default: 30000ms)
}
```

## Error Handling

The client provides comprehensive error handling:

```typescript
try {
  const response = await client.chatMessages({
    inputs: {},
    query: 'Hello',
    response_mode: 'blocking',
    user: 'user-123',
  });
} catch (error) {
  if (error.status === 401) {
    console.error('Authentication failed');
  } else if (error.status === 429) {
    console.error('Rate limit exceeded');
  } else {
    console.error('API error:', error.message);
  }
}
```

## TypeScript Support

The package includes comprehensive TypeScript definitions for all request and response types:

```typescript
import type {
  ChatRequest,
  ChatResponse,
  CompletionRequest,
  CompletionResponse,
  WorkflowRunRequest,
  WorkflowRunResponse,
  StreamingCallbacks,
  DifyError,
} from '@sthg-sdk/dify-api';
```

## License

Apache-2.0