dify-client-typescript
v1.0.0
Published
TypeScript SDK for Dify API - Chat, Completion, Workflow, and Knowledge Base management
Downloads
6
Maintainers
Readme
# Dify TypeScript SDK
A comprehensive TypeScript SDK for interacting with the Dify API, supporting Chat applications, Completion applications, Workflows, and Knowledge Base management.
Features
- 🤖 Chat Applications: Full conversation management with streaming support
- 📝 Completion Applications: Text generation and completion
- 🔄 Workflow Applications: Execute and monitor workflows
- 📚 Knowledge Base: Dataset and document management
- 📁 File Management: Upload and manage files
- 🎙️ Text-to-Speech & Speech-to-Text: Audio processing capabilities
- 📊 Feedback & Analytics: Message feedback and application insights
- 🔧 TypeScript Support: Full type safety and IntelliSense
Installation
npm install dify-client-typescript
# or
yarn add dify-client-typescript
# or
bun add dify-client-typescriptQuick Start
Initialize the Client
import { DifyClient } from 'dify-client-typescript';
const client = new DifyClient({
apiKey: 'your-api-key',
apiBaseUrl: 'https://api.dify.ai/v1' // Optional, defaults to this
});Chat Application Example
// Send a chat message
const response = await client.chat.sendMessage({
query: "Hello, how can I help you today?",
user: "user-123",
response_mode: "blocking", // or "streaming"
conversation_id: "conv-abc123" // Optional, for continuing conversation
});
console.log(response.answer);
// Get conversation history
const conversations = await client.chat.getConversations({
user: "user-123",
limit: 20
});
// Upload and use files
const uploadedFile = await client.chat.uploadFile(file, "user-123");
const messageWithFile = await client.chat.sendMessage({
query: "What's in this image?",
user: "user-123",
files: [{
type: "image",
transfer_method: "local_file",
upload_file_id: uploadedFile.id
}]
});Completion Application Example
// Generate text completion
const completion = await client.completion.createMessage({
inputs: {
query: "Translate 'Hello World' to Spanish"
},
user: "user-123",
response_mode: "blocking"
});
console.log(completion.answer);Workflow Application Example
// Execute a workflow
const workflowResult = await client.workflow.run({
inputs: {
input_text: "Process this data",
language: "English"
},
user: "user-123",
response_mode: "blocking"
});
console.log(workflowResult.data.outputs);
// Get workflow run details
const runDetails = await client.workflow.getRunDetail(workflowResult.workflow_run_id);Knowledge Base Management
// List datasets
const datasets = await client.datasets.list({
page: 1,
limit: 20
});
// Create a new dataset
const newDataset = await client.datasets.create({
name: "My Knowledge Base",
description: "A comprehensive knowledge base"
});
// Update dataset
const updatedDataset = await client.datasets.update(newDataset.id, {
description: "Updated description"
});File Management
// Upload a file
const uploadedFile = await client.files.upload(file, "user-123");
// Preview/download a file
const fileContent = await client.files.preview(uploadedFile.id);Text-to-Speech & Speech-to-Text
// Convert text to audio
const audioResponse = await client.tts.textToAudio({
text: "Hello, this is a test message",
user: "user-123"
});
// Convert audio to text
const transcription = await client.tts.audioToText(audioFile, "user-123");
console.log(transcription.text);Feedback and Analytics
// Submit message feedback
await client.feedback.submitMessageFeedback("message-id", {
rating: "like",
user: "user-123",
content: "Great response!"
});
// Get application feedbacks
const feedbacks = await client.feedback.getAppFeedbacks({
page: 1,
limit: 20
});Application Information
// Get app basic information
const appInfo = await client.application.getInfo();
// Get app parameters and configuration
const appParams = await client.application.getParameters("user-123");
// Get WebApp settings
const webAppSettings = await client.application.getWebAppSettings();Streaming Support
For real-time responses, you can use streaming mode:
// Note: Streaming responses require Server-Sent Events handling
// This example shows the request setup - you'll need to implement SSE parsing
const streamResponse = await client.chat.sendMessage({
query: "Tell me a long story",
user: "user-123",
response_mode: "streaming"
});
// The response will be a stream of Server-Sent Events
// You'll need to parse these events to get incremental responsesError Handling
The SDK throws descriptive errors that you can catch and handle:
try {
const response = await client.chat.sendMessage({
query: "Hello",
user: "user-123"
});
} catch (error) {
console.error('API Error:', error.message);
// Handle specific error cases
if (error.message.includes('unauthorized')) {
// Handle authentication error
}
}API Reference
DifyClient
The main client class that provides access to all Dify APIs:
client.chat- Chat application APIsclient.completion- Completion application APIsclient.workflow- Workflow application APIsclient.datasets- Knowledge base managementclient.files- File managementclient.feedback- Feedback and analyticsclient.application- Application informationclient.tts- Text-to-Speech and Speech-to-Text
Configuration Options
interface DifyClientOptions {
apiKey: string; // Your Dify API key
apiBaseUrl?: string; // API base URL (optional)
}TypeScript Support
This SDK is built with TypeScript and provides full type definitions for all API responses and request parameters. This enables:
- IntelliSense and auto-completion in your IDE
- Compile-time type checking
- Better development experience with clear API contracts
Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- Documentation: Dify Documentation
- Issues: GitHub Issues
- Community: Dify Community
To install dependencies:
bun installTo run:
bun run index.tsThis project was created using bun init in bun v1.2.21. Bun is a fast all-in-one JavaScript runtime.
