### Streaming Workflow Execution with Progress Monitoring Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyWorkflowClient.md This example demonstrates how to execute a workflow and receive updates in real-time using a streaming callback. Implement the WorkflowStreamCallback interface to handle events like workflow start, node completion, and errors. ```java client.runWorkflowStream(request, new WorkflowStreamCallback() { private String workflowRunId; @Override public void onWorkflowStarted(WorkflowStartedEvent event) { workflowRunId = event.getWorkflowId(); System.out.println("Executing workflow..."); } @Override public void onNodeFinished(NodeFinishedEvent event) { System.out.println("✓ " + event.getNodeId()); } @Override public void onWorkflowFinished(WorkflowFinishedEvent event) { System.out.println("Complete: " + event.getOutputs()); } @Override public void onError(ErrorEvent event) { System.err.println("Error: " + event.getMessage()); } }); ``` -------------------------------- ### Typical Workflow: Complete Knowledge Base Setup Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyDatasetsClient.md Demonstrates a typical workflow for setting up a knowledge base, adding documents, and performing retrieval. ```APIDOC ## Typical Workflow: Complete Knowledge Base Setup ### Description This workflow outlines the steps to create a knowledge base, add documents, and then retrieve information from it using the Dify Datasets Client. ### Steps 1. **Create Knowledge Base**: Initialize a new dataset. 2. **Add Documents**: Upload text content to the dataset. 3. **Wait for Indexing**: Allow time for the documents to be processed and indexed. 4. **Retrieve from Knowledge Base**: Perform a semantic search query. 5. **Process Results**: Handle the retrieved segments. ### Example ```java DifyDatasetsClient client = DifyClientFactory.createDatasetsClient( "https://api.dify.ai/v1", "your-api-key" ); // 1. Create knowledge base CreateDatasetRequest createRequest = CreateDatasetRequest.builder() .name("My Knowledge Base") .description("Knowledge base for product documentation") .indexingTechnique("high_quality") .permission("only_me") .provider("vendor") .build(); DatasetResponse dataset = client.createDataset(createRequest); String datasetId = dataset.getId(); // 2. Add documents (text) CreateDocumentByTextRequest docRequest = CreateDocumentByTextRequest.builder() .name("Product Guide") .text("This is our product documentation...") .indexingTechnique("high_quality") .docForm("text_model") .processRule(ProcessRule.builder().mode("automatic").build()) .build(); DocumentResponse docResponse = client.createDocumentByText(datasetId, docRequest); // 3. Wait for indexing Thread.sleep(3000); // 4. Retrieve from knowledge base RetrievalModel retrievalModel = new RetrievalModel(); retrievalModel.setTopK(5); RetrieveRequest retrieveRequest = RetrieveRequest.builder() .query("How do I use this product?") .retrievalModel(retrievalModel) .build(); RetrieveResponse results = client.retrieveDataset(datasetId, retrieveRequest); // 5. Process results results.getRecords().forEach(record -> System.out.println("Found: " + record.getSegment().getContent()) ); ``` ``` -------------------------------- ### Complete Knowledge Base Setup Workflow Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyDatasetsClient.md Demonstrates a typical workflow for setting up a knowledge base with Dify, including creating a dataset, adding documents, and retrieving information. A delay is included to allow for indexing. ```java DifyDatasetsClient client = DifyClientFactory.createDatasetsClient( "https://api.dify.ai/v1", "your-api-key" ); // 1. Create knowledge base CreateDatasetRequest createRequest = CreateDatasetRequest.builder() .name("My Knowledge Base") .description("Knowledge base for product documentation") .indexingTechnique("high_quality") .permission("only_me") .provider("vendor") .build(); DatasetResponse dataset = client.createDataset(createRequest); String datasetId = dataset.getId(); // 2. Add documents (text) CreateDocumentByTextRequest docRequest = CreateDocumentByTextRequest.builder() .name("Product Guide") .text("This is our product documentation...") .indexingTechnique("high_quality") .docForm("text_model") .processRule(ProcessRule.builder().mode("automatic").build()) .build(); DocumentResponse docResponse = client.createDocumentByText(datasetId, docRequest); // 3. Wait for indexing Thread.sleep(3000); // 4. Retrieve from knowledge base RetrievalModel retrievalModel = new RetrievalModel(); retrievalModel.setTopK(5); RetrieveRequest retrieveRequest = RetrieveRequest.builder() .query("How do I use this product?") .retrievalModel(retrievalModel) .build(); RetrieveResponse results = client.retrieveDataset(datasetId, retrieveRequest); // 5. Process results results.getRecords().forEach(record -> System.out.println("Found: " + record.getSegment().getContent()) ); ``` -------------------------------- ### Configure Completion Application Inputs Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/configuration.md Set up input parameters for a Completion application using a Map. This example includes 'topic', 'tone', and 'length' for the input, which are then used to construct a CompletionRequest. ```java Map inputs = new HashMap<>(); inputs.put("topic", "renewable energy"); inputs.put("tone", "formal"); inputs.put("length", "medium"); CompletionRequest request = CompletionRequest.builder() .inputs(inputs) .responseMode(ResponseMode.BLOCKING) .user("user-123") .build(); ``` -------------------------------- ### Guice Dependency Injection Configuration Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyBaseClient.md Configure the Dify client using Guice for dependency injection. This example binds the universal DifyClient to an instance created from environment variables. ```java public class DifyModule extends AbstractModule { @Override protected void configure() { String baseUrl = System.getenv("DIFY_BASE_URL"); String apiKey = System.getenv("DIFY_API_KEY"); bind(DifyClient.class).toInstance( DifyClientFactory.createClient(baseUrl, apiKey) ); } } // Usage public class MyService { private final DifyClient client; @Inject public MyService(DifyClient client) { this.client = client; } } ``` -------------------------------- ### Basic Dify Client Configuration Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/configuration.md Configure the Dify client with base URL, API key, and default timeouts. This is the fundamental setup for interacting with the Dify API. ```java DifyConfig config = DifyConfig.builder() .baseUrl("https://api.dify.ai/v1") .apiKey("your-api-key") .connectTimeout(5000) .readTimeout(60000) .writeTimeout(30000) .build(); DifyClient client = DifyClientFactory.createClient(config); ``` -------------------------------- ### Complete Chat Message Streaming Example Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/Callbacks.md This example demonstrates how to send a chat message with streaming enabled and process the response using `ChatStreamCallback`. It includes handling message chunks, completion events, file messages, errors, and exceptions. ```java public class FullStreamExample { public static void main(String[] args) throws IOException, DifyApiException { DifyChatClient chatClient = DifyClientFactory.createChatClient( "https://api.dify.ai/v1", "your-api-key" ); ChatMessage message = ChatMessage.builder() .query("Explain machine learning in detail") .responseMode(ResponseMode.STREAMING) .user("user-123") .build(); chatClient.sendChatMessageStream(message, new ChatStreamCallback() { private StringBuilder fullText = new StringBuilder(); private int chunkCount = 0; @Override public void onMessage(MessageEvent event) { String chunk = event.getAnswer(); System.out.print(chunk); fullText.append(chunk); chunkCount++; } @Override public void onMessageEnd(MessageEndEvent event) { System.out.println("\n--- Stream Complete ---"); System.out.println("Total chunks: " + chunkCount); System.out.println("Total characters: " + fullText.length()); System.out.println("Message ID: " + event.getMessageId()); System.out.println("Conversation ID: " + event.getConversationId()); if (event.getMetadata() != null) { System.out.println("Prompt tokens: " + event.getMetadata().getPromptTokens()); System.out.println("Completion tokens: " + event.getMetadata().getCompletionTokens()); } } @Override public void onMessageFile(MessageFileEvent event) { System.out.println("\nFile: " + event.getFilename()); } @Override public void onError(ErrorEvent event) { System.err.println("Stream error: " + event.getMessage()); } @Override public void onException(Throwable throwable) { System.err.println("Exception: " + throwable.getMessage()); throwable.printStackTrace(); } }); } } ``` -------------------------------- ### Configure Logback for Dify and OkHttp Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/configuration.md Configure Logback to set logging levels for the Dify client (io.github.imfangs.dify) and OkHttp (okhttp3). This example sets both to DEBUG level. ```xml %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n ``` -------------------------------- ### Basic Dify Client Configuration Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/README.md Configure the Dify client with a base URL and API key using the builder pattern. This is suitable for simple setups and testing. ```java DifyConfig config = DifyConfig.builder() .baseUrl("https://api.dify.ai/v1") .apiKey("your-api-key") .build(); DifyClient client = DifyClientFactory.createClient(config); ``` -------------------------------- ### Configure Custom HTTP Client Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/configuration.md Pass a custom OkHttpClient to the DifyClient for proxy support, authentication middleware, or custom interceptors. This example sets connection, read, and write timeouts, configures an HTTP proxy, and adds a logging interceptor. ```java OkHttpClient customHttpClient = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.company.com", 8080))) .addInterceptor(new HttpLoggingInterceptor()) // Debug logging .build(); DifyClient client = DifyClientFactory.createClient( "https://api.dify.ai/v1", "your-api-key", customHttpClient ); ``` -------------------------------- ### Get Workflow Logs (Basic) Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyWorkflowClient.md Retrieves workflow execution logs with basic filtering by keyword and status. Requires specifying page number and limit. ```java WorkflowLogsResponse logs = workflowClient.getWorkflowLogs( null, // No keyword filter "succeeded", // Only successful executions 1, // First page 20 // 20 items per page ); logs.getData().forEach(log -> System.out.println("Run: " + log.getWorkflowRunId() + " Status: " + log.getStatus()) ); ``` -------------------------------- ### Configure Client Timeouts Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/errors.md Set custom timeout values for client connections and read operations to manage long-running requests. This example demonstrates how to configure connect, read, and write timeouts using DifyConfig. ```java DifyConfig config = DifyConfig.builder() .baseUrl(baseUrl) .apiKey(apiKey) .connectTimeout(10000) // 10 seconds .readTimeout(180000) // 3 minutes for workflows .writeTimeout(60000) // 1 minute for uploads .build(); DifyClient client = DifyClientFactory.createClient(config); ``` -------------------------------- ### Spring Framework Dependency Injection Configuration Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyBaseClient.md Configure Dify clients as Spring beans for easy injection into your services. This example shows how to create both a universal client and type-specific beans. ```java @Configuration public class DifyConfig { @Bean public DifyClient difyClient( @Value("${dify.base-url}") String baseUrl, @Value("${dify.api-key}") String apiKey ) { return DifyClientFactory.createClient(baseUrl, apiKey); } // Type-specific beans @Bean public DifyChatClient chatClient(DifyClient client) { return client; // Implements DifyChatClient } @Bean public DifyWorkflowClient workflowClient(DifyClient client) { return client; // Implements DifyWorkflowClient } } // Usage in service @Service public class DifyService { private final DifyChatClient chatClient; private final DifyWorkflowClient workflowClient; public DifyService(DifyChatClient chatClient, DifyWorkflowClient workflowClient) { this.chatClient = chatClient; this.workflowClient = workflowClient; } public void chat(String query) throws Exception { ChatMessage message = ChatMessage.builder() .query(query) .responseMode(ResponseMode.BLOCKING) .user("user-123") .build(); chatClient.sendChatMessage(message); } } ``` -------------------------------- ### Run Workflow Request (Streaming) Source: https://github.com/imfangs/dify-java-client/blob/main/README_EN.md Executes a workflow in streaming mode, processing events like start, node completion, and finish via a callback. Implement the WorkflowStreamCallback interface to handle these events, as well as errors and exceptions. ```java // Create workflow request Map inputs = new HashMap<>(); inputs.put("content", "Please explain the basic principles of machine learning in detail"); WorkflowRunRequest request = WorkflowRunRequest.builder() .inputs(inputs) .responseMode(ResponseMode.STREAMING) .user("user-123") .build(); // Run workflow streaming request workflowClient.runWorkflowStream(request, new WorkflowStreamCallback() { @Override public void onWorkflowStarted(WorkflowStartedEvent event) { System.out.println("Workflow started: " + event); } @Override public void onNodeStarted(NodeStartedEvent event) { System.out.println("Node started: " + event); } @Override public void onNodeFinished(NodeFinishedEvent event) { System.out.println("Node finished: " + event); } @Override public void onWorkflowFinished(WorkflowFinishedEvent event) { System.out.println("Workflow finished: " + event); } @Override public void onError(ErrorEvent event) { System.err.println("Error: " + event.getMessage()); } @Override public void onException(Throwable throwable) { System.err.println("Exception: " + throwable.getMessage()); } }); ``` -------------------------------- ### Get Application Metadata with DifyChatClient Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyChatClient.md Retrieves application metadata, including parameters and configuration. Use this to get general information about your Dify application. ```java AppMetaResponse meta = chatClient.getAppMeta(); System.out.println("App Name: " + meta.getAppName()); ``` -------------------------------- ### Get Specific Dataset Details with Dify Java Client Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyDatasetsClient.md Retrieves the details of a single knowledge base by its ID. Use this to get information such as the dataset name and total document count. ```java DatasetResponse details = datasetsClient.getDataset("dataset-id-123"); System.out.println("Name: " + details.getName()); System.out.println("Total docs: " + details.getTotalDocuments()); ``` -------------------------------- ### Create and List Knowledge Bases Source: https://github.com/imfangs/dify-java-client/blob/main/README_EN.md Initializes the datasets client and demonstrates creating a new knowledge base with specified parameters. It also shows how to retrieve a list of existing knowledge bases. ```java import com.dify.client.DifyClientFactory; import com.dify.client.datasets.DifyDatasetsClient; import com.dify.client.datasets.model.CreateDatasetRequest; import com.dify.client.datasets.model.DatasetListResponse; import com.dify.client.datasets.model.DatasetResponse; // Create datasets client DifyDatasetsClient datasetsClient = DifyClientFactory.createDatasetsClient("https://api.dify.ai/v1", "your-api-key"); // Create knowledge base CreateDatasetRequest createRequest = CreateDatasetRequest.builder() .name("Test Knowledge Base-" + System.currentTimeMillis()) .description("This is a test knowledge base") .indexingTechnique("high_quality") .permission("only_me") .provider("vendor") .build(); DatasetResponse dataset = datasetsClient.createDataset(createRequest); System.out.println("Created knowledge base ID: " + dataset.getId()); // Get knowledge base list DatasetListResponse datasetList = datasetsClient.getDatasets(1, 10); System.out.println("Total knowledge bases: " + datasetList.getTotal()); ``` -------------------------------- ### Create and Manage Knowledge Bases Source: https://github.com/imfangs/dify-java-client/blob/main/README_EN.md Demonstrates how to initialize the datasets client, create a new knowledge base with specified parameters, and retrieve a list of existing knowledge bases. ```APIDOC ## Create and Manage Knowledge Bases ### Description This section covers the creation and management of knowledge bases. It includes initializing the client, creating a new knowledge base, and listing existing ones. ### Client Initialization ```java DifyDatasetsClient datasetsClient = DifyClientFactory.createDatasetsClient("https://api.dify.ai/v1", "your-api-key"); ``` ### Create Knowledge Base #### Request Body ```json { "name": "string", "description": "string", "indexing_technique": "string", "permission": "string", "provider": "string" } ``` #### Response (200 OK) ```json { "id": "string", "name": "string", "description": "string", "indexing_technique": "string", "permission": "string", "provider": "string", "created_at": "integer", "updated_at": "integer" } ``` ### Get Knowledge Base List #### Parameters - **page** (integer) - Optional - The page number for the list. - **limit** (integer) - Optional - The number of items per page. #### Response (200 OK) ```json { "total": "integer", "data": [ { "id": "string", "name": "string", "description": "string", "indexing_technique": "string", "permission": "string", "provider": "string", "created_at": "integer", "updated_at": "integer" } ] } ``` ``` -------------------------------- ### onNodeStarted Method Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/Callbacks.md Called when a workflow node starts execution. Provides the node's ID, type, and inputs. ```java default void onNodeStarted(NodeStartedEvent event) ``` -------------------------------- ### Get Suggested Questions with DifyChatClient Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyChatClient.md Retrieves AI-generated follow-up questions for a specific message. Requires the message ID and user identifier. ```java SuggestedQuestionsResponse getSuggestedQuestions(String messageId, String user) throws IOException, DifyApiException ``` ```java SuggestedQuestionsResponse suggestions = chatClient.getSuggestedQuestions("msg-123", "user-123"); suggestions.getItems().forEach(q -> System.out.println("Suggested: " + q)); ``` -------------------------------- ### Create Dify Client using Environment Variables Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/configuration.md Instantiate the Dify client by reading base URL and API key from environment variables. Connection and timeout settings can also be configured. ```java public class DifyClientProvider { public static DifyClient createClient() { String baseUrl = System.getenv("DIFY_BASE_URL"); String apiKey = System.getenv("DIFY_API_KEY"); if (baseUrl == null || apiKey == null) { throw new IllegalStateException( "DIFY_BASE_URL and DIFY_API_KEY environment variables must be set" ); } DifyConfig config = DifyConfig.builder() .baseUrl(baseUrl) .apiKey(apiKey) .connectTimeout(5000) .readTimeout(60000) .writeTimeout(30000) .build(); return DifyClientFactory.createClient(config); } } ``` -------------------------------- ### Create a Complete DifyClient Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyClientFactory.md Initializes a DifyClient that implements all available interfaces. Use this for general-purpose interaction with Dify. Supports simple URL/key initialization or a detailed DifyConfig object. ```java DifyClient client = DifyClientFactory.createClient( "https://api.dify.ai/v1", "your-api-key" ); ``` ```java DifyConfig config = DifyConfig.builder() .baseUrl("https://api.dify.ai/v1") .apiKey("your-api-key") .connectTimeout(5000) .readTimeout(60000) .writeTimeout(30000) .build(); DifyClient client = DifyClientFactory.createClient(config); ``` -------------------------------- ### Get Indexing Status Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyDatasetsClient.md Retrieves the indexing and embedding status of documents within a specific dataset. Use this method to monitor the progress of document processing. ```java IndexingStatusResponse status = datasetsClient.getIndexingStatus("dataset-id-123", null); System.out.println("Indexed: " + status.getIndexedCount()); System.out.println("Remaining: " + status.getPendingCount()); ``` -------------------------------- ### Create and Use Completion Client (Blocking) Source: https://github.com/imfangs/dify-java-client/blob/main/README_EN.md Initializes a completion client and sends a request in blocking mode. Ensure you have your API key and the correct API endpoint. ```java // Create completion client DifyCompletionClient completionClient = DifyClientFactory.createCompletionClient("https://api.dify.ai/v1", "your-api-key"); // Create request Map inputs = new HashMap<>(); inputs.put("content", "eggplant"); CompletionRequest request = CompletionRequest.builder() .inputs(inputs) .responseMode(ResponseMode.BLOCKING) .user("user-123") .build(); // Send request and get response CompletionResponse response = completionClient.sendCompletionMessage(request); System.out.println("Generated text: " + response.getAnswer()); ``` -------------------------------- ### Create Dataset with Dify Java Client Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyDatasetsClient.md Use this method to create a new knowledge base. Provide dataset name, description, indexing technique, and permission settings. Ensure the provider is set to 'vendor' for file uploads. ```java CreateDatasetRequest createRequest = CreateDatasetRequest.builder() .name("Test Knowledge Base-" + System.currentTimeMillis()) .description("This is a test knowledge base") .indexingTechnique("high_quality") // "high_quality" or "economy" .permission("only_me") // "only_me" or "all_team_members" .provider("vendor") // "vendor" for file upload .build(); DatasetResponse dataset = datasetsClient.createDataset(createRequest); System.out.println("Created dataset ID: " + dataset.getId()); ``` -------------------------------- ### Configure Proxy with Authentication Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/configuration.md Set up an OkHttpClient to use an HTTP proxy with basic authentication. This snippet configures the proxy address and provides a proxy authenticator to handle credentials. ```java OkHttpClient proxyClient = new OkHttpClient.Builder() .proxy(new Proxy( Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080) )) .proxyAuthenticator((route, response) -> { String credential = Credentials.basic("username", "password"); return response.request().newBuilder() .header("Proxy-Authorization", credential) .build(); }) .build(); DifyClient client = DifyClientFactory.createClient( baseUrl, apiKey, proxyClient ); ``` -------------------------------- ### Configure Dify Client Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/types.md Use DifyConfig to set up the API base URL, authentication key, and timeouts. Then, create a DifyClient instance using the factory. ```java DifyConfig config = DifyConfig.builder() .baseUrl("https://api.dify.ai/v1") .apiKey("your-api-key") .connectTimeout(10000) .readTimeout(120000) .writeTimeout(60000) .build(); DifyClient client = DifyClientFactory.createClient(config); ``` -------------------------------- ### Retrieve Specific Segment Details Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyDatasetsClient.md Gets the details of a single segment using its ID, along with the dataset and document IDs. Useful for inspecting a specific piece of content. ```java SegmentResponse segment = datasetsClient.getSegment( "dataset-id-123", "doc-id-456", "seg-id-789" ); System.out.println("Content: " + segment.getContent()); ``` -------------------------------- ### Get Detailed Document Information Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyDatasetsClient.md Retrieves detailed information for a specific document, including its name and segment count. Allows filtering of metadata to be 'all', 'only', or 'without'. ```java DetailedDocumentResponse detail = datasetsClient.getDocumentDetail( "dataset-id-123", "doc-id-456", "all" ); System.out.println("Document: " + detail.getName()); System.out.println("Segments: " + detail.getSegmentCount()); ``` -------------------------------- ### Retrieve Segments from Dify Document Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyDatasetsClient.md Fetches segments from a document, with optional filtering by keyword and status, and pagination. Use this to get a list of segments or specific ones based on criteria. ```java SegmentListResponse segments = datasetsClient.getSegments( "dataset-id-123", "doc-id-456", null, null, 1, 20 ); segments.getSegments().forEach(seg -> System.out.println("Segment: " + seg.getContent()) ); ``` -------------------------------- ### Create and Run Workflow (Blocking) Source: https://github.com/imfangs/dify-java-client/blob/main/README_EN.md Initializes a workflow client and executes a workflow in blocking mode. The response contains the task ID and output data from the workflow execution. ```java // Create workflow client DifyWorkflowClient workflowClient = DifyClientFactory.createWorkflowClient("https://api.dify.ai/v1", "your-api-key"); // Create workflow request Map inputs = new HashMap<>(); inputs.put("content", "Please introduce AI application scenarios"); WorkflowRunRequest request = WorkflowRunRequest.builder() .inputs(inputs) .responseMode(ResponseMode.BLOCKING) .user("user-123") .build(); // Run workflow and get response WorkflowRunResponse response = workflowClient.runWorkflow(request); System.out.println("Workflow execution ID: " + response.getTaskId()); // Output results if (response.getData() != null) { for (Map.Entry entry : response.getData().getOutputs().entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } ``` -------------------------------- ### Get Workflow Run Status Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyWorkflowClient.md Retrieves the status and details of a specific workflow execution using its run ID. This method can throw IOExceptions for network issues or DifyApiExceptions for API-related errors. ```java WorkflowRunStatusResponse status = workflowClient.getWorkflowRun("workflow-run-id-123"); System.out.println("Status: " + status.getStatus()); // "succeeded", "failed", "running" System.out.println("Outputs: " + status.getOutputs()); System.out.println("Error: " + status.getError()); ``` -------------------------------- ### Create Dify Client with Properties Configuration Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/configuration.md Programmatically create a Dify client using values injected from a properties file. This Java configuration class maps properties to client parameters. ```java @Configuration public class DifyConfig { @Value("${dify.base-url}") private String baseUrl; @Value("${dify.api-key}") private String apiKey; @Bean public DifyClient difyClient() { return DifyClientFactory.createClient(baseUrl, apiKey); } } ``` -------------------------------- ### Configure Chat Application Inputs Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/configuration.md Prepare input parameters for a Chat application by creating a Map and populating it with 'user_question' and 'context'. This map is then used to build a ChatMessage object. ```java Map inputs = new HashMap<>(); inputs.put("user_question", "What is machine learning?"); inputs.put("context", "General knowledge"); ChatMessage message = ChatMessage.builder() .query("Ask about AI") .inputs(inputs) .responseMode(ResponseMode.BLOCKING) .user("user-123") .build(); ``` -------------------------------- ### Get Workflow Logs (Advanced) Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyWorkflowClient.md Retrieves workflow logs with advanced filtering options including date ranges, session IDs, and account names. Requires specifying page number and limit. ```java WorkflowLogsResponse logs = workflowClient.getWorkflowLogs( "error", // Search for "error" in logs "failed", // Show failed executions "2024-12-31T23:59:59Z", // Before this date "2024-01-01T00:00:00Z", // After this date null, // Any session "admin-user", // Created by this account 1, // Page 1 50 // 50 results ); ``` -------------------------------- ### Universal Dify Client Usage Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyBaseClient.md Demonstrates how to create and use the universal DifyClient, which can then be used to call methods from any of the underlying specific client interfaces. ```java // Create universal client DifyClient client = DifyClientFactory.createClient(baseUrl, apiKey); // Use as any interface client.sendChatMessage(chatMessage); // DifyChatClient method client.sendCompletionMessage(completionRequest); // DifyCompletionClient method client.runWorkflow(workflowRequest); // DifyWorkflowClient method ``` -------------------------------- ### createCompletionClient Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyClientFactory.md Initializes a client for text completion and generation tasks. Supports initialization with a base URL and API key, or a DifyConfig object. ```APIDOC ## createCompletionClient ### Description Provides a client specifically designed for text completion and generation functionalities. Initialization can be performed using a base URL and API key, or through a `DifyConfig` object for more detailed setup. ### Method Signatures ```java public static DifyCompletionClient createCompletionClient(String baseUrl, String apiKey) public static DifyCompletionClient createCompletionClient(String baseUrl, String apiKey, OkHttpClient httpClient) public static DifyCompletionClient createCompletionClient(DifyConfig config) ``` ### Parameters #### createCompletionClient(String baseUrl, String apiKey) - **baseUrl** (String) - Required - API base URL - **apiKey** (String) - Required - API authentication key #### createCompletionClient(String baseUrl, String apiKey, OkHttpClient httpClient) - **baseUrl** (String) - Required - API base URL - **apiKey** (String) - Required - API authentication key - **httpClient** (OkHttpClient) - Optional - Custom HTTP client #### createCompletionClient(DifyConfig config) - **config** (DifyConfig) - Required - Configuration object ### Returns - `DifyCompletionClient` - Client instance for text generation operations ### Example ```java DifyCompletionClient completionClient = DifyClientFactory.createCompletionClient( "https://api.dify.ai/v1", "your-api-key" ); ``` ``` -------------------------------- ### Get Conversation Variables - Java Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyChatClient.md Retrieves variables captured during a conversation. Use this to fetch historical variable data. Parameters include conversation ID, user ID, and optional pagination or filtering by variable name. ```java VariableResponse vars = chatClient.getConversationVariables( "conv-123", "user-123", null, 20, null ); ``` -------------------------------- ### onPing Method Implementation Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/Callbacks.md Implement this method to respond to server-sent ping messages, which are used to keep the connection alive during long delays. ```java @Override public void onPing(PingEvent event) { System.out.println("Server ping received"); } ``` -------------------------------- ### Handle HTTP 404 Not Found for Non-existent Resources Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/errors.md Handle DifyApiException with status 404 and error code 'not_found' when a requested resource, like a conversation ID, does not exist. The example shows how to create a new conversation as an alternative. ```java try { MessageListResponse messages = chatClient.getMessages( "non-existent-conversation-id", "user-123", null, 10 ); } catch (DifyApiException e) { // Status: 404, Code: "not_found" System.err.println("Conversation not found: " + e.getErrorMessage()); // Create a new conversation instead ChatMessage newMessage = ChatMessage.builder() .query("Hello") .responseMode(ResponseMode.BLOCKING) .user("user-123") .build(); ChatMessageResponse response = chatClient.sendChatMessage(newMessage); } ``` -------------------------------- ### Configure Dify Client using Properties File Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/configuration.md Define Dify client settings, including base URL, API key, and timeouts, in an application.properties file. The API key can be sourced from environment variables. ```properties # application.properties dify.base-url=https://api.dify.ai/v1 dify.api-key=${DIFY_API_KEY} dify.connect-timeout=5000 dify.read-timeout=60000 dify.write-timeout=30000 ``` -------------------------------- ### Create Dataset Request Model Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/types.md Use this model to define parameters for creating a new knowledge base dataset. Specify name, description, indexing technique, permissions, and provider details. ```java import com.fasterxml.jackson.annotation.JsonProperty; import io.github.imfangs.dify.client.model.datasets.UpdateDatasetRequest; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class CreateDatasetRequest { private String name; // Dataset name (required) private String description; // Optional description private String indexingTechnique; // "high_quality" or "economy" private String permission; // "only_me", "all_team_members", "partial_members" private String provider; // "vendor" or "external" private String externalKnowledgeApiId; // For external sources private String externalKnowledgeId; // For external sources @JsonProperty("embedding_model") private String embeddingModel; // Optional embedding model @JsonProperty("embedding_model_provider") private String embeddingModelProvider; // Optional embedding provider @JsonProperty("retrieval_model") private UpdateDatasetRequest.RetrievalModel retrievalModel; } ``` -------------------------------- ### Status Polling for Asynchronous Workflow Execution Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyWorkflowClient.md Use this pattern when you need to start a workflow asynchronously and then periodically check its status. The code polls the workflow run status until it's completed or failed, with a 2-second delay between polls. ```java // Start execution WorkflowRunResponse initial = client.runWorkflow(request); String runId = initial.getWorkflowRunId(); // Poll for status boolean completed = false; while (!completed) { WorkflowRunStatusResponse status = client.getWorkflowRun(runId); System.out.println("Status: " + status.getStatus()); if ("succeeded".equals(status.getStatus())) { System.out.println("Results: " + status.getOutputs()); completed = true; } else if ("failed".equals(status.getStatus())) { System.err.println("Error: " + status.getError()); completed = true; } Thread.sleep(2000); // Wait 2 seconds before checking again } ``` -------------------------------- ### Interface Composition for DifyClient Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyBaseClient.md Demonstrates how to access specific functionalities or the universal client interface. Each interface is independently useful for its respective features. ```java DifyChatClient chat = client; // Can use chat features DifyCompletionClient completion = client; // Can use completion features DifyWorkflowClient workflow = client; // Can use workflow features // Or use universal interface DifyClient all = client; // Can use everything ``` -------------------------------- ### Create Dify Clients Source: https://github.com/imfangs/dify-java-client/blob/main/README_EN.md Instantiate various Dify clients using the DifyClientFactory. Supports creating a general client, or specific clients for chat, completion, chatflows, workflows, and datasets. Custom configurations for timeouts can also be applied. ```java // Create a complete Dify client DifyClient client = DifyClientFactory.createClient("https://api.dify.ai/v1", "your-api-key"); // Create specific types of clients DifyChatClient chatClient = DifyClientFactory.createChatClient("https://api.dify.ai/v1", "your-api-key"); DifyCompletionClient completionClient = DifyClientFactory.createCompletionClient("https://api.dify.ai/v1", "your-api-key"); DifyChatflowClient chatflowClient = DifyClientFactory.createChatWorkflowClient("https://api.dify.ai/v1", "your-api-key"); DifyWorkflowClient workflowClient = DifyClientFactory.createWorkflowClient("https://api.dify.ai/v1", "your-api-key"); DifyDatasetsClient datasetsClient = DifyClientFactory.createDatasetsClient("https://api.dify.ai/v1", "your-api-key"); // Create client with custom configuration DifyConfig config = DifyConfig.builder() .baseUrl("https://api.dify.ai/v1") .apiKey("your-api-key") .connectTimeout(5000) .readTimeout(60000) .writeTimeout(30000) .build(); DifyClient clientWithConfig = DifyClientFactory.createClient(config); ``` -------------------------------- ### Run Workflow in Streaming Mode Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyWorkflowClient.md Executes a workflow and receives events in real-time using a callback. Ensure the request is configured with ResponseMode.STREAMING. The callback handles various workflow events like start, node execution, completion, and errors. ```java Map inputs = new HashMap<>(); inputs.put("content", "Explain the basic principles of machine learning"); WorkflowRunRequest request = WorkflowRunRequest.builder() .inputs(inputs) .responseMode(ResponseMode.STREAMING) .user("user-123") .build(); workflowClient.runWorkflowStream(request, new WorkflowStreamCallback() { @Override public void onWorkflowStarted(WorkflowStartedEvent event) { System.out.println("Workflow started: " + event.getWorkflowId()); } @Override public void onNodeStarted(NodeStartedEvent event) { System.out.println("Node started: " + event.getNodeId()); } @Override public void onNodeFinished(NodeFinishedEvent event) { System.out.println("Node finished: " + event.getNodeId()); System.out.println("Outputs: " + event.getOutputs()); } @Override public void onWorkflowFinished(WorkflowFinishedEvent event) { System.out.println("Workflow completed!"); System.out.println("Final outputs: " + event.getOutputs()); } @Override public void onError(ErrorEvent event) { System.err.println("Workflow error: " + event.getMessage()); } @Override public void onException(Throwable e) { e.printStackTrace(); } }); ``` -------------------------------- ### Handle HTTP 500 Server Errors with Retry Strategy Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/errors.md Implement a retry mechanism for HTTP 500 errors, which indicate server-side issues. This example shows how to catch DifyApiException, check for status codes >= 500, and retry the operation a specified number of times with a delay. ```java try { WorkflowRunResponse response = workflowClient.runWorkflow(request); } catch (DifyApiException e) { if (e.getStatusCode() >= 500) { System.err.println("Server error: " + e.getErrorMessage()); // Implement retry strategy int maxRetries = 3; int retryDelay = 2000; for (int i = 0; i < maxRetries; i++) { try { Thread.sleep(retryDelay); response = workflowClient.runWorkflow(request); break; } catch (DifyApiException retry) { if (i == maxRetries - 1) { throw retry; } } } } } ``` -------------------------------- ### Create a DifyChatClient Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyClientFactory.md Creates a client specifically for chat and conversation functionalities. Initialize with base URL and API key, or a DifyConfig object. ```java DifyChatClient chatClient = DifyClientFactory.createChatClient( "https://api.dify.ai/v1", "your-api-key" ); ``` -------------------------------- ### Create DifyDatasetsClient Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyClientFactory.md Creates a client for knowledge base (datasets) management. Use this to manage your Dify knowledge bases. Requires API base URL and API key. ```java DifyDatasetsClient datasetsClient = DifyClientFactory.createDatasetsClient( "https://api.dify.ai/v1", "your-api-key" ); ``` -------------------------------- ### Create Document by Text Request Model Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/types.md Use this model to create a document from plain text. Provide the document name, content, and optional parameters like document type, metadata, indexing technique, form, and language. ```java import java.util.Map; import io.github.imfangs.dify.client.model.datasets.ProcessRule; import io.github.imfangs.dify.client.model.datasets.RetrievalModel; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class CreateDocumentByTextRequest { private String name; // Document name private String text; // Document content private String docType; // Optional document type private Map docMetadata; // Optional metadata private String indexingTechnique; // "high_quality" or "economy" private String docForm; // "text_model", "hierarchical_model", "qa_model" private String docLanguage; // "English", "Chinese", etc. private ProcessRule processRule; // Processing configuration private RetrievalModel retrievalModel; // Retrieval settings private String embeddingModel; private String embeddingModelProvider; } ``` -------------------------------- ### Production Dify Client Configuration with Timeouts Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/README.md Configure the Dify client for production using environment variables for base URL and API key, and set custom connect, read, and write timeouts for robust network handling. ```java DifyConfig config = DifyConfig.builder() .baseUrl(System.getenv("DIFY_BASE_URL")) .apiKey(System.getenv("DIFY_API_KEY")) .connectTimeout(10000) // 10 seconds .readTimeout(180000) // 3 minutes .writeTimeout(60000) // 1 minute .build(); ``` -------------------------------- ### Create Dify Client with Custom Configuration Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyClientFactory.md Configure timeouts (connect, read, write) for production environments by building a DifyConfig object. This allows for fine-tuning network behavior for different operation types. ```java DifyConfig config = DifyConfig.builder() .baseUrl("https://api.dify.ai/v1") .apiKey(System.getenv("DIFY_API_KEY")) .connectTimeout(10000) // 10 seconds .readTimeout(120000) // 2 minutes for long-running operations .writeTimeout(60000) // 1 minute for uploads .build(); DifyClient client = DifyClientFactory.createClient(config); ``` -------------------------------- ### Create Dify Client with Custom HTTP Client Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyClientFactory.md Integrate a custom OkHttpClient for advanced networking scenarios, such as setting up proxies or custom interceptors. This provides granular control over the HTTP client. ```java OkHttpClient customHttpClient = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.example.com", 8080))) .build(); DifyClient client = DifyClientFactory.createClient(baseUrl, apiKey, customHttpClient); ``` -------------------------------- ### createClient Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyClientFactory.md Creates a complete Dify client that implements all interfaces: DifyChatClient, DifyCompletionClient, DifyChatflowClient, and DifyWorkflowClient. It can be initialized with a base URL and API key, or with a DifyConfig object for more advanced configurations. ```APIDOC ## createClient ### Description Creates a complete Dify client that implements all interfaces: `DifyChatClient`, `DifyCompletionClient`, `DifyChatflowClient`, and `DifyWorkflowClient`. It supports initialization via a base URL and API key, or through a `DifyConfig` object for more granular control over settings like timeouts. ### Method Signatures ```java public static DifyClient createClient(String baseUrl, String apiKey) public static DifyClient createClient(String baseUrl, String apiKey, OkHttpClient httpClient) public static DifyClient createClient(DifyConfig config) ``` ### Parameters #### createClient(String baseUrl, String apiKey) - **baseUrl** (String) - Required - API base URL (e.g., `https://api.dify.ai/v1`) - **apiKey** (String) - Required - API key/token for authentication #### createClient(String baseUrl, String apiKey, OkHttpClient httpClient) - **baseUrl** (String) - Required - API base URL (e.g., `https://api.dify.ai/v1`) - **apiKey** (String) - Required - API key/token for authentication - **httpClient** (OkHttpClient) - Optional - Custom OkHttp client (uses default if omitted) #### createClient(DifyConfig config) - **config** (DifyConfig) - Required - Configuration object containing URL, API key, and timeouts ### Returns - `DifyClient` - A client implementing all application type interfaces ### Example ```java // Simple initialization DifyClient client = DifyClientFactory.createClient( "https://api.dify.ai/v1", "your-api-key" ); // With custom timeouts DifyConfig config = DifyConfig.builder() .baseUrl("https://api.dify.ai/v1") .apiKey("your-api-key") .connectTimeout(5000) .readTimeout(60000) .writeTimeout(30000) .build(); DifyClient client = DifyClientFactory.createClient(config); ``` ``` -------------------------------- ### Create a DifyCompletionClient Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyClientFactory.md Generates a client tailored for text completion and generation tasks. Initialization can be done using base URL and API key, or a DifyConfig object. ```java DifyCompletionClient completionClient = DifyClientFactory.createCompletionClient( "https://api.dify.ai/v1", "your-api-key" ); ``` -------------------------------- ### Metadata for Usage and Execution Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/types.md Provides details on token usage for prompts, completions, and total tokens consumed during an operation. ```java @Data public class Metadata { private Integer promptTokens; // Tokens used in prompt private Integer completionTokens; // Tokens in response private Integer totalTokens; // Total tokens used // ... other metadata fields } ``` -------------------------------- ### Create and Use Universal Dify Client Source: https://github.com/imfangs/dify-java-client/blob/main/_autodocs/api-reference/DifyBaseClient.md Use the universal client when your application needs to interact with multiple Dify application types. This allows for a single client instance for all operations. ```java DifyClient client = DifyClientFactory.createClient(baseUrl, apiKey); // Can call any method client.sendChatMessage(chatMessage); client.sendCompletionMessage(completionRequest); client.runWorkflow(workflowRequest); ```