@sthg-sdk/dify.api
v1.2.7
Published
Dify API client with streaming support for STHG Tiangong SDK
Readme
@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
pnpm add @sthg-sdk/dify-apiUsage
Basic Setup
import { DifyClient } from '@sthg-sdk/dify-api';
const client = new DifyClient({
baseUrl: 'https://api.dify.ai/v1',
apiKey: 'your-api-key',
});Chat Messages (Blocking)
const response = await client.chatMessages({
inputs: {},
query: 'Hello, how are you?',
response_mode: 'blocking',
user: 'user-123',
});
console.log(response.answer);Chat Messages (Streaming)
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
// 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
// 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
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
const audioBuffer = await client.textToAudio({
message_id: 'msg-123',
text: 'Hello world',
user: 'user-123',
});
// Convert to audio file or play directlyConversation Management
// 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
// Stop any active streaming connection
client.stopStreaming();Configuration Options
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:
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:
import type {
ChatRequest,
ChatResponse,
CompletionRequest,
CompletionResponse,
WorkflowRunRequest,
WorkflowRunResponse,
StreamingCallbacks,
DifyError,
} from '@sthg-sdk/dify-api';License
Apache-2.0
