Dify Chat API Client Package: Complete Functionalities and TypeScript Implementation Guide

The Dify Chat API client package provides a fully-typed TypeScript SDK that handles authentication, HTTP request management, and exposes comprehensive methods for conversations, messages, files, workflows, audio processing, and annotations.

The @dify-chat/api package is a comprehensive TypeScript client designed for the Dify Chat platform. This Dify Chat API client abstracts the complexity of direct HTTP calls while providing complete type safety through interfaces defined in the src/types/ directory, making it ideal for building robust chat applications with full IntelliSense support.

Configuration and Request Handling

The foundation of the Dify Chat API client rests on the XRequest class implemented in src/base-request.ts. This class manages all HTTP interactions with the Dify platform.

Core Request Architecture

The XRequest class provides several utility methods for HTTP operations:

  • baseRequest() – Core fetch wrapper that attaches the Authorization: Bearer <apiKey> header
  • jsonRequest() – Handles JSON payload serialization and content-type headers
  • get(), post(), delete() – Convenience methods for specific HTTP verbs

The request layer automatically checks the X-Version response header to keep DIFY_INFO.version updated and throws a custom UnauthorizedError when encountering 401 responses.

Client Factory

For quick instantiation, the package exports createDifyApiInstance from src/api/index.ts. This factory function returns a fully configured DifyApi client ready for immediate use.

Application Information Methods

The Dify Chat API client provides several methods to retrieve metadata about your Dify application:

  • getAppInfo() – Retrieves basic application information
  • getAppMeta() – Fetches application metadata and configuration
  • getAppParameters() – Gets configurable parameters for the application
  • getAppSiteSetting() – Retrieves web application site settings

All methods return Promise-wrapped TypeScript interfaces such as IGetAppInfoResponse, providing compile-time type safety.

Conversation Management

Managing conversation lifecycles is a core functionality of the Dify Chat API client, implemented through methods that interact with conversation resources.

Conversation Operations

  • listConversations({ limit, page }) – Paginates through conversation history, returning IConversationItem arrays
  • renameConversation(conversationId, name) – Updates conversation display names
  • deleteConversation(conversationId) – Permanently removes conversation threads

Message Retrieval

  • listMessages(conversationId, { limit, page }) – Fetches message history within a specific conversation, returning typed message objects

Message Handling and Streaming

The Dify Chat API client excels at real-time message processing with full support for streaming responses.

Core Messaging Methods

  • sendMessage(params) – Sends chat messages with support for text, files, and custom inputs. Accepts response_mode: 'streaming' for real-time responses
  • stopTask(taskId) – Terminates active streaming tasks
  • createMessageFeedback(messageId, rating, content) – Submits user feedback on specific messages
  • getNextSuggestions(conversationId) – Retrieves AI-generated follow-up suggestions

Streaming Implementation

Methods like sendMessage, text2Audio, runWorkflow, and completion use response_mode: 'streaming' and forward the raw fetch response, allowing callers to pipe data via SSE or ReadableStream interfaces.

File Operations

The Dify Chat API client provides comprehensive file handling capabilities:

  • uploadFile(file) – Uploads files to Dify storage, returning IUploadFileResponse with file IDs
  • filePreview(fileId) – Generates preview URLs for uploaded files

Uploaded files can be referenced in subsequent sendMessage calls using the files parameter with transfer_method: 'local_file'.

Audio and Speech Processing

The client supports bidirectional audio conversion:

  • text2Audio(params) – Converts text to speech with streaming audio output
  • audio2Text(audioFile) – Transcribes audio files to text

Both methods handle binary audio data and support streaming responses for real-time audio generation.

Workflow Execution

For Dify workflow applications, the client provides:

  • runWorkflow(inputs) – Initiates workflow execution with file and parameter inputs
  • getWorkflowResult(workflowRunId) – Polls for workflow completion and retrieves results

Workflow methods support both blocking and streaming execution modes.

Completion and Annotation Management

LLM Completion

  • completion(params) – Performs generic completion requests with streaming support, useful for non-chat LLM interactions

Annotation Resources

The client manages annotation (knowledge base) operations:

  • createAnnotation(content, question, answer) – Creates new annotation entries
  • getAnnotationList() – Lists existing annotations
  • updateAnnotation(annotationId, updates) – Modifies annotation content
  • deleteAnnotation(annotationId) – Removes annotations

Architectural Highlights

The Dify Chat API client demonstrates excellent separation of concerns:

  • Typed request layer – The XRequest class in src/base-request.ts centralizes fetch logic, authentication header injection, and error handling
  • Modular type system – All request/response shapes are declared in src/types/*.ts, enabling strict compile-time validation
  • Factory pattern – The createDifyApiInstance function provides immediate access to a configured DifyApi client without manual instantiation
  • Streaming support – Raw fetch responses are preserved for streaming methods, allowing integration with SSE or ReadableStream consumers

Summary

The Dify Chat API client package delivers a production-ready TypeScript SDK for the Dify platform with the following key capabilities:

  • Complete HTTP abstraction via the XRequest class with automatic authentication and error handling
  • Conversation lifecycle management including creation, renaming, deletion, and message history retrieval
  • Real-time messaging with streaming response support for chat, audio, and workflow execution
  • File handling with upload, preview, and attachment capabilities in messages
  • Audio processing for text-to-speech and speech-to-text conversion
  • Workflow automation with execution and result polling methods
  • Annotation management for knowledge base operations
  • Full type safety through comprehensive TypeScript interfaces in src/types/

Frequently Asked Questions

How do I initialize the Dify Chat API client in my TypeScript project?

Import the createDifyApiInstance function from @dify-chat/api and call it with your API credentials. You must provide the apiBase (e.g., https://api.dify.ai/v1), your apiKey, and a user identifier. This factory function returns a fully configured DifyApi instance ready for immediate use.

What is the difference between streaming and blocking response modes in the Dify Chat API client?

The client supports response_mode: 'streaming' for real-time data delivery in methods like sendMessage, completion, and runWorkflow. In streaming mode, the method returns the raw fetch Response object, allowing you to consume data via SSE or ReadableStream interfaces. Blocking mode (when available) would return the complete response after processing finishes, though the client primarily emphasizes streaming capabilities for interactive applications.

How does the Dify Chat API client handle authentication errors?

The XRequest class in src/base-request.ts automatically injects the Authorization: Bearer <apiKey> header into every request. When the API returns a 401 status code, the request layer throws a custom UnauthorizedError exception. Additionally, the client monitors the X-Version response header to automatically update the cached DIFY_INFO.version, ensuring compatibility tracking without manual intervention.

Can I use the Dify Chat API client for workflow execution as well as chat applications?

Yes, the client provides dedicated workflow methods including runWorkflow for initiating executions and getWorkflowResult for polling completion status. These methods support file inputs, custom parameters, and streaming responses, making them suitable for automating complex business processes beyond simple conversational interfaces. The workflow functionality shares the same authentication and type-safe patterns as the chat methods.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →