Dify Java Client

repository·main·Indexed 20 days ago

https://github.com/imfangs/dify-java-client

A Java library for integrating Dify's generative AI capabilities into applications. It provides comprehensive support for Chat, Completion, Workflow, and Chatflow application APIs, as well as Knowledge Base (Datasets) APIs. Features include blocking and streaming interaction modes, session management, file processing, and support for Human-in-the-loop and Reasoning flows. Compatible with Java 8+, Maven 3.x, and Gradle 4.x+.

Tokens
13.8K
Snippets
26
Records
38
Agent score
67%

What's inside dify-java-client

  1. Choose a response mode

    main

    When making API calls, you can choose between two response modes:

    • ResponseMode.BLOCKING: Synchronous calls that wait for the complete response.
    • ResponseMode.STREAMING: Streaming mode that receives real-time generated content via callbacks.
  2. Configure ResponseMode for synchronous or streaming responses

    main

    When making API calls, you can specify the ResponseMode to determine how you receive data:

    • ResponseMode.BLOCKING: Synchronous call. The client waits for the complete response before returning.
    • ResponseMode.STREAMING: Streaming mode. Content is received in real-time via callbacks.
  3. Supported Dify application types and clients

    main

    The library provides specialized clients for different Dify application models:

    • Chat Applications: Use DifyChatClient for conversational interactions, including conversation management and message feedback.
    • Completion Applications: Use DifyCompletionClient for text generation tasks.
    • Chatflow Applications: Use DifyChatflowClient for workflow-orchestrated conversational applications.
    • Workflow Applications: Use DifyWorkflowClient for standard workflow applications.
    • Knowledge Base Management: Use DifyDatasetsClient to manage knowledge bases, documents, and semantic retrieval.
  4. Interaction Modes and Features

    main

    The Dify Java Client supports several interaction patterns and multimedia capabilities:

    • Blocking Mode: Synchronous API calls that wait for a complete response.
    • Streaming Mode: Real-time content reception via callbacks, suitable for typewriter effects.
    • File Processing: Support for file uploads, speech-to-text, and text-to-speech functionality.
    • Session Management: Capabilities to create/manage sessions, retrieve history, rename sessions, provide message feedback (like/dislike), and fetch suggested questions.
    • Knowledge Base (Datasets) Lifecycle: Full support for creating/managing knowledge bases, uploading/managing documents, managing document segments, and performing semantic retrieval.
  5. Supported Dify Application Types

    main

    The client provides specialized clients for different Dify application architectures:

    • Chat (DifyChatClient): For conversational applications. Supports session management and message feedback.
    • Completion (DifyCompletionClient): For text generation applications.
    • Chatflow (DifyChatflowClient): For workflow-orchestrated chat applications.
    • Workflow (DifyWorkflowClient): For standard workflow applications.
    • Datasets (DifyDatasetsClient): For managing knowledge bases, documents, and retrieval processes.
  6. Select the appropriate Dify Client Type

    main

    The library provides specialized clients depending on the type of Dify application you are interacting with. Use DifyClient for full access to all features, or choose a specialized client for specific application types:

    • DifyChatClient: For chat applications. Supports conversations, conversation management, and message feedback.
    • DifyCompletionClient: For text generation applications. Supports text generation and stopping generation.
    • DifyChatflowClient: For workflow-orchestrated chat applications.
    • DifyWorkflowClient: For workflow applications. Supports workflow execution and management.
    • DifyDatasetsClient: For knowledge base management. Supports document management, retrieval, RAG pipelines, and batch/signed downloads.
  7. Choose a Response Mode (Blocking vs Streaming)

    main

    When making API calls, you can specify how you want to receive the response using ResponseMode:

    • ResponseMode.BLOCKING: Synchronous mode. The client waits for the complete response before returning.
    • ResponseMode.STREAMING: Asynchronous/Streaming mode. The client receives real-time generated content through callbacks.
  8. Choose the appropriate DifyClient type

    main

    The library provides specialized client types depending on the type of Dify application you are interacting with:

    • DifyClient: The full client supporting all API functionalities.
    • DifyChatClient: For Chat applications. Supports conversations, conversation management, and message feedback.
    • DifyCompletionClient: For Text Generation applications. Supports text generation and stopping generation.
    • DifyChatflowClient: For Workflow-controlled Chat applications. Supports workflow-controlled conversations.
    • DifyWorkflowClient: For Workflow applications. Supports workflow execution and management.
    • DifyDatasetsClient: For Knowledge Base management. Supports document management, search, batch/signed downloads, and RAG pipelines.
  9. Handle Reasoning Chunks (Reasoning Flow)

    main

    When using Chatflow applications where the LLM node has reasoning_format=separated enabled, the model's internal thought process is emitted separately from the final answer.

    Use onReasoningChunk in the ChatflowStreamCallback to capture these chunks. This allows you to render a "Thinking..." UI component separately from the main response text.

    Key Event:

    • onReasoningChunk(ReasoningChunkEvent event): Provides the reasoning text and an isFinal flag indicating if the thought process is complete.
    chatflowClient.sendChatMessageStream(message, new ChatflowStreamCallback() {
        @Override
        public void onReasoningChunk(ReasoningChunkEvent event) {
            // Render thinking process in a separate UI panel
            String reasoning = event.getData().getReasoning();
            boolean isFinal = Boolean.TRUE.equals(event.getData().getIsFinal());
            renderThinking(reasoning, isFinal);
        }
    
        @Override
        public void onMessage(MessageEvent event) {
            // Render the actual answer
            appendAnswer(event.getAnswer());
        }
    });
  10. Use Chat Applications (Chat)

    main

    Interact with Chat applications using either blocking or streaming modes. Use DifyChatClient to send messages, manage conversation history, handle feedback, and perform audio-to-text/text-to-audio conversions.

    Blocking Mode: Wait for the full response before proceeding. Streaming Mode: Use ChatStreamCallback to handle real-time message chunks, end events, and errors.

    Key Capabilities:

    • Conversation Management: Retrieve message history, list conversations, rename, or delete them.
    • Feedback: Send likes/dislikes to messages and retrieve suggested questions.
    • Audio: Convert audio files to text and text to audio data.
    // Blocking Mode
    DifyChatClient chatClient = DifyClientFactory.createChatClient("https://api.dify.ai/v1", "your-api-key");
    ChatMessage message = ChatMessage.builder()
        .query("你好,请介绍一下自己")
        .user("user-123")
        .responseMode(ResponseMode.BLOCKING)
        .build();
    ChatMessageResponse response = chatClient.sendChatMessage(message);
    System.out.println("回复: " + response.getAnswer());
    
    // Streaming Mode
    chatClient.sendChatMessageStream(message, new ChatStreamCallback() {
        @Override
        public void onMessage(MessageEvent event) {
            System.out.println("收到消息片段: " + event.getAnswer());
        }
        @Override
        public void onMessageEnd(MessageEndEvent event) {
            System.out.println("消息结束,完整消息ID: " + event.getMessageId());
        }
        @Override
        public void onError(ErrorEvent event) {
            System.err.println("错误: " + event.getMessage());
        }
        @Override
        public void onException(Throwable throwable) {
            System.err.println("异常: " + throwable.getMessage());
        }
    });
  11. Use Chat Applications in Blocking and Streaming Modes

    main

    The DifyChatClient allows you to interact with chat-based applications. You can use Blocking Mode for simple request-response cycles or Streaming Mode to receive real-time message chunks via a callback.

    Blocking Mode

    Use sendChatMessage(message) to wait for the full response. Set responseMode(ResponseMode.BLOCKING) in the ChatMessage builder.

    Streaming Mode

    Use sendChatMessageStream(message, callback) to handle real-time updates. Implement ChatStreamCallback to handle onMessage (chunks), onMessageEnd (completion), onError, and onException events.

    // Blocking Mode
    DifyChatClient chatClient = DifyClientFactory.createChatClient("https://api.dify.ai/v1", "your-api-key");
    ChatMessage message = ChatMessage.builder()
        .query("Hello, please introduce yourself")
        .user("user-123")
        .responseMode(ResponseMode.BLOCKING)
        .build();
    ChatMessageResponse response = chatClient.sendChatMessage(message);
    
    // Streaming Mode
    chatClient.sendChatMessageStream(message, new ChatStreamCallback() {
        @Override
        public void onMessage(MessageEvent event) {
            System.out.println("Received message chunk: " + event.getAnswer());
        }
        // ... other overrides
    });
  12. Handle Reasoning Chunks in Chatflows

    main

    When using a Chatflow LLM node with reasoning_format=separated, the model's chain-of-thought (reasoning) is streamed separately from the final answer.

    Use ChatflowStreamCallback.onReasoningChunk(ReasoningChunkEvent event) to capture these intermediate thoughts. The event.getData().getIsFinal() boolean indicates if the reasoning process has concluded.

    chatflowClient.sendChatMessageStream(message, new ChatflowStreamCallback() {
        @Override
        public void onReasoningChunk(ReasoningChunkEvent event) {
            // Access reasoning text via event.getData().getReasoning()
            System.out.println("Thinking: " + event.getData().getReasoning());
        }
    });