From 7afede1d7e5aac31e6b83acd2f373f433cd6b352 Mon Sep 17 00:00:00 2001 From: tomsun28 Date: Wed, 3 Jun 2026 18:01:01 +0800 Subject: [PATCH 1/4] feat: update new models glm-5.2 and support reasoning_effort --- README.md | 6 +++--- README_CN.md | 6 +++--- core/src/main/java/ai/z/openapi/core/Constants.java | 5 +++++ .../openapi/service/model/ChatCompletionCreateParams.java | 7 +++++++ 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index e86f539..4d7e1f6 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ ZaiClient client = ZaiClient.builder() // Create chat request ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model("glm-5.1") + .model("glm-5.2") .messages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.USER.value()) @@ -154,7 +154,7 @@ if (response.isSuccess()) { ```java // Create streaming request ChatCompletionCreateParams streamRequest = ChatCompletionCreateParams.builder() - .model("glm-5.1") + .model("glm-5.2") .messages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.USER.value()) @@ -284,7 +284,7 @@ public class AIController { @PostMapping("/chat") public ResponseEntity chat(@RequestBody ChatRequest request) { ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() - .model("glm-5.1") + .model("glm-5.2") .messages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.USER.value()) diff --git a/README_CN.md b/README_CN.md index f5c778c..c0dbf76 100644 --- a/README_CN.md +++ b/README_CN.md @@ -125,7 +125,7 @@ ZaiClient client = ZaiClient.builder() // 创建对话请求 ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model("glm-5.1") + .model("glm-5.2") .messages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.USER.value()) @@ -153,7 +153,7 @@ if (response.isSuccess()) { ```java // 创建流式请求 ChatCompletionCreateParams streamRequest = ChatCompletionCreateParams.builder() - .model("glm-5.1") + .model("glm-5.2") .messages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.USER.value()) @@ -285,7 +285,7 @@ public class AIController { @PostMapping("/chat") public ResponseEntity chat(@RequestBody ChatRequest request) { ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() - .model("glm-5.1") + .model("glm-5.2") .messages(Arrays.asList( ChatMessage.builder() .role(ChatMessageRole.USER.value()) diff --git a/core/src/main/java/ai/z/openapi/core/Constants.java b/core/src/main/java/ai/z/openapi/core/Constants.java index d737a61..f0e29e6 100644 --- a/core/src/main/java/ai/z/openapi/core/Constants.java +++ b/core/src/main/java/ai/z/openapi/core/Constants.java @@ -34,6 +34,11 @@ private Constants() { // Text Generation Models // ============================================================================= + /** + * GLM-5.2 model code + */ + public static final String ModelGLM5_2 = "glm-5.2"; + /** * GLM-5.1 model code */ diff --git a/core/src/main/java/ai/z/openapi/service/model/ChatCompletionCreateParams.java b/core/src/main/java/ai/z/openapi/service/model/ChatCompletionCreateParams.java index 10d343c..cb8387c 100644 --- a/core/src/main/java/ai/z/openapi/service/model/ChatCompletionCreateParams.java +++ b/core/src/main/java/ai/z/openapi/service/model/ChatCompletionCreateParams.java @@ -127,4 +127,11 @@ public class ChatCompletionCreateParams extends CommonRequest implements ClientR @JsonProperty("watermark_enabled") private Boolean watermarkEnabled; + /** + * Reasoning effort level, supported values: none, minimal, low, medium, high, xhigh, max. + * Defaults to max when not specified. Effective for glm-5.2 and above models. + */ + @JsonProperty("reasoning_effort") + private String reasoningEffort; + } From 6c673d815b5238dc7f8c375a937aadd7aea75e8d Mon Sep 17 00:00:00 2001 From: tomsun28 Date: Wed, 3 Jun 2026 18:03:58 +0800 Subject: [PATCH 2/4] feat: update new models glm-5.2 and support reasoning_effort --- README.md | 4 ++-- README_CN.md | 4 ++-- .../java/ai/z/openapi/core/token/HttpRequestInterceptor.java | 2 +- .../z/openapi/service/model/ChatCompletionCreateParams.java | 4 ++-- pom.xml | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 4d7e1f6..c4264c5 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ Add the following dependency to your `pom.xml`: ai.z.openapi zai-sdk - 0.3.3 + 0.3.5 ``` @@ -39,7 +39,7 @@ Add the following dependency to your `build.gradle` (for Groovy DSL): ```groovy dependencies { - implementation 'ai.z.openapi:zai-sdk:0.3.3' + implementation 'ai.z.openapi:zai-sdk:0.3.5' } ``` diff --git a/README_CN.md b/README_CN.md index c0dbf76..b84ec62 100644 --- a/README_CN.md +++ b/README_CN.md @@ -30,7 +30,7 @@ Z.ai AI 平台官方 Java SDK,提供统一接口访问强大的AI能力,包 ai.z.openapi zai-sdk - 0.3.3 + 0.3.5 ``` @@ -39,7 +39,7 @@ Z.ai AI 平台官方 Java SDK,提供统一接口访问强大的AI能力,包 ```groovy dependencies { - implementation 'ai.z.openapi:zai-sdk:0.3.3' + implementation 'ai.z.openapi:zai-sdk:0.3.5' } ``` diff --git a/core/src/main/java/ai/z/openapi/core/token/HttpRequestInterceptor.java b/core/src/main/java/ai/z/openapi/core/token/HttpRequestInterceptor.java index dd9974a..ea077d8 100644 --- a/core/src/main/java/ai/z/openapi/core/token/HttpRequestInterceptor.java +++ b/core/src/main/java/ai/z/openapi/core/token/HttpRequestInterceptor.java @@ -40,7 +40,7 @@ public Response intercept(Chain chain) throws IOException { .newBuilder() .header("Authorization", "Bearer " + accessToken) .header("x-source-channel", source_channel) - .header("Zai-SDK-Ver", "0.3.3"); + .header("Zai-SDK-Ver", "0.3.5"); if (Objects.nonNull(config.getCustomHeaders())) { for (Map.Entry entry : config.getCustomHeaders().entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); diff --git a/core/src/main/java/ai/z/openapi/service/model/ChatCompletionCreateParams.java b/core/src/main/java/ai/z/openapi/service/model/ChatCompletionCreateParams.java index cb8387c..66cb5fc 100644 --- a/core/src/main/java/ai/z/openapi/service/model/ChatCompletionCreateParams.java +++ b/core/src/main/java/ai/z/openapi/service/model/ChatCompletionCreateParams.java @@ -128,8 +128,8 @@ public class ChatCompletionCreateParams extends CommonRequest implements ClientR private Boolean watermarkEnabled; /** - * Reasoning effort level, supported values: none, minimal, low, medium, high, xhigh, max. - * Defaults to max when not specified. Effective for glm-5.2 and above models. + * Reasoning effort level, supported values: none, minimal, low, medium, high, xhigh, + * max. Defaults to max when not specified. Effective for glm-5.2 and above models. */ @JsonProperty("reasoning_effort") private String reasoningEffort; diff --git a/pom.xml b/pom.xml index 88ce6c1..d504399 100644 --- a/pom.xml +++ b/pom.xml @@ -45,7 +45,7 @@ - 0.3.4 + 0.3.5 8 UTF-8 UTF-8 From 46bc6226d66f2cc137170178c115679176b576a2 Mon Sep 17 00:00:00 2001 From: tomsun28 Date: Wed, 3 Jun 2026 20:26:35 +0800 Subject: [PATCH 3/4] bugfix: fix default value initialization and deprecated API usage - Remove @NoArgsConstructor and add explicit no-arg constructor to properly initialize @Builder.Default values - Fix connectionPoolKeepAliveDuration default value check from 1 to 10 - Replace deprecated PropertyNamingStrategy with PropertyNamingStrategies --- .../ai/z/openapi/core/config/ZaiConfig.java | 22 ++++++++++++++++--- .../MessageDeserializeFactory.java | 4 ++-- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/core/src/main/java/ai/z/openapi/core/config/ZaiConfig.java b/core/src/main/java/ai/z/openapi/core/config/ZaiConfig.java index bde6e02..0f297b0 100644 --- a/core/src/main/java/ai/z/openapi/core/config/ZaiConfig.java +++ b/core/src/main/java/ai/z/openapi/core/config/ZaiConfig.java @@ -2,7 +2,6 @@ import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.NoArgsConstructor; import lombok.Setter; import java.util.Map; @@ -17,7 +16,6 @@ */ @Setter @Builder -@NoArgsConstructor @AllArgsConstructor public class ZaiConfig { @@ -128,12 +126,30 @@ public class ZaiConfig { @Builder.Default private String source_channel = "java-sdk"; + /** + * No-arg constructor that mirrors all {@link Builder.Default} field values. Lombok's + * {@code @NoArgsConstructor} does not apply {@code @Builder.Default} values, so we + * write this constructor explicitly to ensure every field starts with the same + * defaults as the builder. + */ + public ZaiConfig() { + this.expireMillis = 30 * 60 * 1000; + this.alg = "HS256"; + this.disableTokenCache = true; + this.connectionPoolMaxIdleConnections = 5; + this.connectionPoolKeepAliveDuration = 10; + this.connectionPoolTimeUnit = TimeUnit.SECONDS; + this.timeOutTimeUnit = TimeUnit.SECONDS; + this.source_channel = "java-sdk"; + } + /** * Constructor with combined API secret key. * @param apiKey combined secret key in format {apiKey}.{apiSecret} * @throws RuntimeException if apiSecretKey format is invalid */ public ZaiConfig(String apiKey) { + this(); this.apiKey = apiKey; String[] arrStr = apiKey.split("\\."); if (arrStr.length != 2) { @@ -251,7 +267,7 @@ public int getConnectionPoolMaxIdleConnections() { * variable fallback. */ public long getConnectionPoolKeepAliveDuration() { - if (connectionPoolKeepAliveDuration != 1) { // If not default value + if (connectionPoolKeepAliveDuration != 10) { // If not default value return connectionPoolKeepAliveDuration; } String propValue = System.getProperty(ENV_CONNECTION_POOL_KEEP_ALIVE); diff --git a/core/src/main/java/ai/z/openapi/service/deserialize/MessageDeserializeFactory.java b/core/src/main/java/ai/z/openapi/service/deserialize/MessageDeserializeFactory.java index afcd86a..f7f8a60 100644 --- a/core/src/main/java/ai/z/openapi/service/deserialize/MessageDeserializeFactory.java +++ b/core/src/main/java/ai/z/openapi/service/deserialize/MessageDeserializeFactory.java @@ -3,7 +3,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.PropertyNamingStrategy; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.databind.module.SimpleModule; import ai.z.openapi.service.assistant.AssistantChoice; import ai.z.openapi.service.deserialize.assistant.AssistantChoiceDeserializer; @@ -14,7 +14,7 @@ public static ObjectMapper defaultObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); + mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); SimpleModule module = new SimpleModule(); module.addDeserializer(AssistantChoice.class, new AssistantChoiceDeserializer()); From 67312c6b2f3c6820210c323309c553607e3412b2 Mon Sep 17 00:00:00 2001 From: tomsun28 Date: Thu, 4 Jun 2026 10:25:47 +0800 Subject: [PATCH 4/4] refactor: reorganize samples structure and add Maven exec plugin - Add exec-maven-plugin configuration to samples/pom.xml for easier example execution - Move example files from ai.z.openapi.samples package to java/ai/z/openapi/samples directory - Relocate all example classes including AgentExample, AudioSpeechExample, ChatCompletionExample, etc. - No functional changes to example code, only directory structure reorganization --- samples/pom.xml | 13 ++ .../ai.z.openapi.samples/AgentExample.java | 75 ------- .../AgentVideoExample.java | 72 ------- .../AudioSpeechExample.java | 51 ----- .../AudioSpeechStreamExample.java | 68 ------- .../AudioTranscriptionsExample.java | 57 ------ .../AudioTranscriptionsStreamExample.java | 69 ------- .../ChatAsyncCompletionExample.java | 60 ------ .../ChatCompletionBase64Example.java | 68 ------- .../ChatCompletionExample.java | 58 ------ .../ChatCompletionMultiFileExample.java | 56 ------ .../ChatCompletionStreamExample.java | 63 ------ ...hatCompletionWithCustomHeadersExample.java | 91 --------- ...ChatCompletionWithMcpServerUrlExample.java | 78 -------- .../ClientConfigurationExample.java | 71 ------- .../CogVideoX3Example.java | 176 ---------------- .../CogVideoXExample.java | 80 -------- .../CustomClientExample.java | 107 ---------- .../CustomTimeoutExample.java | 63 ------ .../EmbeddingsExample.java | 51 ----- .../FileParsingExample.java | 124 ------------ .../FileParsingSyncExample.java | 64 ------ .../FunctionCallingExample.java | 92 --------- .../GLM41VThinkingExample.java | 51 ----- .../GLMVisionExample.java | 59 ------ .../ImageGenerationAsyncExample.java | 49 ----- .../ImageGenerationExample.java | 29 --- .../ModerationExample.java | 163 --------------- .../ViduAspectVideoExample.java | 70 ------- .../ViduImageToVideoExample.java | 83 -------- .../ViduStartEndVideoExample.java | 74 ------- .../ViduTextToVideoExample.java | 122 ----------- .../VoiceCloneExample.java | 180 ----------------- .../WebReaderExample.java | 82 -------- .../WebSearchExample.java | 179 ----------------- .../ai/z/openapi/samples/AgentExample.java | 77 +++++++ .../z/openapi/samples/AgentVideoExample.java | 75 +++++++ .../z/openapi/samples/AudioSpeechExample.java | 55 +++++ .../samples/AudioSpeechStreamExample.java | 70 +++++++ .../samples/AudioTranscriptionsExample.java | 62 ++++++ .../AudioTranscriptionsStreamExample.java | 71 +++++++ .../samples/ChatAsyncCompletionExample.java | 59 ++++++ .../samples/ChatCompletionBase64Example.java | 63 ++++++ .../samples/ChatCompletionExample.java | 60 ++++++ .../ChatCompletionMultiFileExample.java | 47 +++++ .../samples/ChatCompletionStreamExample.java | 61 ++++++ ...hatCompletionWithCustomHeadersExample.java | 87 ++++++++ ...ChatCompletionWithMcpServerUrlExample.java | 80 ++++++++ .../samples/ClientConfigurationExample.java | 72 +++++++ .../z/openapi/samples/CogVideoX3Example.java | 189 ++++++++++++++++++ .../z/openapi/samples/CogVideoXExample.java | 85 ++++++++ .../openapi/samples/CustomClientExample.java | 104 ++++++++++ .../openapi/samples/CustomTimeoutExample.java | 63 ++++++ .../z/openapi/samples/EmbeddingsExample.java | 55 +++++ .../z/openapi/samples/FileParsingExample.java | 135 +++++++++++++ .../samples/FileParsingSyncExample.java | 67 +++++++ .../samples/FunctionCallingExample.java | 95 +++++++++ .../samples/GLM41VThinkingExample.java | 47 +++++ .../z/openapi/samples/GLMVisionExample.java | 55 +++++ .../samples}/HandwritingOcrExample.java | 22 +- .../samples/ImageGenerationAsyncExample.java | 51 +++++ .../samples/ImageGenerationExample.java | 30 +++ .../samples}/LayoutParsingExample.java | 28 +-- .../z/openapi/samples/ModerationExample.java | 158 +++++++++++++++ .../samples/ViduAspectVideoExample.java | 76 +++++++ .../samples/ViduImageToVideoExample.java | 89 +++++++++ .../samples/ViduStartEndVideoExample.java | 81 ++++++++ .../samples/ViduTextToVideoExample.java | 130 ++++++++++++ .../z/openapi/samples/VoiceCloneExample.java | 189 ++++++++++++++++++ .../z/openapi/samples/WebReaderExample.java | 85 ++++++++ .../z/openapi/samples/WebSearchExample.java | 180 +++++++++++++++++ 71 files changed, 2946 insertions(+), 2855 deletions(-) delete mode 100644 samples/src/main/ai.z.openapi.samples/AgentExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/AgentVideoExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/AudioSpeechExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/AudioSpeechStreamExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/AudioTranscriptionsExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/AudioTranscriptionsStreamExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ChatAsyncCompletionExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ChatCompletionBase64Example.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ChatCompletionExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ChatCompletionMultiFileExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ChatCompletionStreamExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ChatCompletionWithCustomHeadersExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ChatCompletionWithMcpServerUrlExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ClientConfigurationExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/CogVideoX3Example.java delete mode 100644 samples/src/main/ai.z.openapi.samples/CogVideoXExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/CustomClientExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/CustomTimeoutExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/EmbeddingsExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/FileParsingExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/FileParsingSyncExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/FunctionCallingExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/GLM41VThinkingExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/GLMVisionExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ImageGenerationAsyncExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ImageGenerationExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ModerationExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ViduAspectVideoExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ViduImageToVideoExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ViduStartEndVideoExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/ViduTextToVideoExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/VoiceCloneExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/WebReaderExample.java delete mode 100644 samples/src/main/ai.z.openapi.samples/WebSearchExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/AgentExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/AgentVideoExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/AudioSpeechExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/AudioSpeechStreamExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/AudioTranscriptionsExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/AudioTranscriptionsStreamExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ChatAsyncCompletionExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ChatCompletionBase64Example.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ChatCompletionExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ChatCompletionMultiFileExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ChatCompletionStreamExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ChatCompletionWithCustomHeadersExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ChatCompletionWithMcpServerUrlExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ClientConfigurationExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/CogVideoX3Example.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/CogVideoXExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/CustomClientExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/CustomTimeoutExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/EmbeddingsExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/FileParsingExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/FileParsingSyncExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/FunctionCallingExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/GLM41VThinkingExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/GLMVisionExample.java rename samples/src/main/{ai.z.openapi.samples => java/ai/z/openapi/samples}/HandwritingOcrExample.java (88%) create mode 100644 samples/src/main/java/ai/z/openapi/samples/ImageGenerationAsyncExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ImageGenerationExample.java rename samples/src/main/{ai.z.openapi.samples => java/ai/z/openapi/samples}/LayoutParsingExample.java (87%) create mode 100644 samples/src/main/java/ai/z/openapi/samples/ModerationExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ViduAspectVideoExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ViduImageToVideoExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ViduStartEndVideoExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/ViduTextToVideoExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/VoiceCloneExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/WebReaderExample.java create mode 100644 samples/src/main/java/ai/z/openapi/samples/WebSearchExample.java diff --git a/samples/pom.xml b/samples/pom.xml index b2f145c..92239bc 100644 --- a/samples/pom.xml +++ b/samples/pom.xml @@ -17,4 +17,17 @@ ${revision} + + + + + org.codehaus.mojo + exec-maven-plugin + 3.1.0 + + compile + + + + diff --git a/samples/src/main/ai.z.openapi.samples/AgentExample.java b/samples/src/main/ai.z.openapi.samples/AgentExample.java deleted file mode 100644 index 5cc1180..0000000 --- a/samples/src/main/ai.z.openapi.samples/AgentExample.java +++ /dev/null @@ -1,75 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.ZhipuAiClient; -import ai.z.openapi.service.agents.AgentContent; -import ai.z.openapi.service.agents.AgentMessage; -import ai.z.openapi.service.agents.AgentsCompletionRequest; -import ai.z.openapi.service.model.ChatCompletionResponse; -import ai.z.openapi.service.model.ChatMessageRole; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Agent Example - * Demonstrates how to use ZaiClient for agent-based completions - */ -public class AgentExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - syncAgentCompletion(client); - } - - /** - * Example of synchronous agent completion - */ - private static void syncAgentCompletion(ZaiClient client) { - System.out.println("\n=== Synchronous Agent Completion Example ==="); - - // Create messages for the agent - List messages = new ArrayList<>(); - AgentMessage userMessage = new AgentMessage( - ChatMessageRole.USER.value(), - Arrays.asList(AgentContent.ofText("Hello, please translate this to French: How are you today?")) - ); - messages.add(userMessage); - - // Create agent completion request - AgentsCompletionRequest request = AgentsCompletionRequest.builder() - .agentId("general_translation") // Using translation agent - .stream(false) // Non-streaming mode - .messages(messages) - .customVariables(JsonNodeFactory.instance.objectNode().put("source_lang", "en").put("target_lang", "cn")) - .requestId("agent-example-" + System.currentTimeMillis()) - .build(); - - try { - // Execute request - ChatCompletionResponse response = client.agents().createAgentCompletion(request); - - if (response.isSuccess()) { - System.out.println("Agent completion successful!"); - - // Display agent response - Object content = response.getData().getChoices().get(0).getMessages(); - System.out.println("\nResponse: " + new ObjectMapper().writeValueAsString(content)); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/AgentVideoExample.java b/samples/src/main/ai.z.openapi.samples/AgentVideoExample.java deleted file mode 100644 index a9e517b..0000000 --- a/samples/src/main/ai.z.openapi.samples/AgentVideoExample.java +++ /dev/null @@ -1,72 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.agents.AgentContent; -import ai.z.openapi.service.agents.AgentMessage; -import ai.z.openapi.service.agents.AgentsCompletionRequest; -import ai.z.openapi.service.model.ChatCompletionResponse; -import ai.z.openapi.service.model.ChatMessageRole; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Agent Example - * Demonstrates how to use ZaiClient for agent-based completions - */ -public class AgentVideoExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - syncAgentCompletion(client); - } - - /** - * Example of synchronous agent completion - */ - private static void syncAgentCompletion(ZaiClient client) { - System.out.println("\n=== Synchronous Agent Completion Example ==="); - - // Create messages for the agent - List messages = new ArrayList<>(); - AgentMessage userMessage = new AgentMessage( - ChatMessageRole.USER.value(), - Arrays.asList(AgentContent.ofText("The two figures in the painting gradually approach each other, then kissing passionately, alternating deep and determined intensity") - , AgentContent.ofImageUrl("https://img-repo-intl.imdr.cn/dr/sample-182141/xoJteuReBtNCdoMoH.jpg!w1080.jpg")) - ); - messages.add(userMessage); - - // Create agent completion request - AgentsCompletionRequest request = AgentsCompletionRequest.builder() - .agentId("vidu_template_agent") // Using translation agent - .stream(false) // Non-streaming mode - .messages(messages) - .customVariables(JsonNodeFactory.instance.objectNode().put("template", "french_kiss")) - .requestId("agent-example-" + System.currentTimeMillis()) - .build(); - - try { - // Execute request - ChatCompletionResponse response = client.agents().createAgentCompletion(request); - - if (response.isSuccess()) { - System.out.println("Agent completion successful!"); - System.out.println("\nResponse: " + new ObjectMapper().writeValueAsString(response.getData())); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/AudioSpeechExample.java b/samples/src/main/ai.z.openapi.samples/AudioSpeechExample.java deleted file mode 100644 index f50ddb5..0000000 --- a/samples/src/main/ai.z.openapi.samples/AudioSpeechExample.java +++ /dev/null @@ -1,51 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.ZhipuAiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.audio.AudioSpeechRequest; -import ai.z.openapi.service.audio.AudioSpeechResponse; - -/** - * Audio Speech Example - * Demonstrates how to use ZaiClient for audio speech - */ -public class AudioSpeechExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Or set API Key via code - // ZaiClient client = ZaiClient.builder() - // .apiKey("your.api_key") - // .build(); - - // Create request - AudioSpeechRequest request = AudioSpeechRequest.builder() - .model(Constants.ModelTTS) - .input("Hello, this is a test for text-to-speech functionality.") - .voice("tongtong") - .stream(false) - .responseFormat("pcm") - .build(); - - try { - // Execute request - AudioSpeechResponse response = client.audio().createSpeech(request); - - if (response.isSuccess()) { - System.out.println("Response: " + response.getData()); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/AudioSpeechStreamExample.java b/samples/src/main/ai.z.openapi.samples/AudioSpeechStreamExample.java deleted file mode 100644 index dc85314..0000000 --- a/samples/src/main/ai.z.openapi.samples/AudioSpeechStreamExample.java +++ /dev/null @@ -1,68 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.audio.AudioSpeechRequest; -import ai.z.openapi.service.audio.AudioSpeechStreamingResponse; -import ai.z.openapi.service.model.Delta; -import ai.z.openapi.service.model.ModelData; - -/** - * Streaming Audio Speech Example - * Demonstrates how to use ZaiClient for streaming text-to-speech conversion - */ -public class AudioSpeechStreamExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Create speech request with streaming enabled - AudioSpeechRequest request = AudioSpeechRequest.builder() - .model(Constants.ModelTTS) - .input("Hello, how's the weather today") - .voice("tongtong") - .responseFormat("pcm") - .stream(true) // Enable streaming response - .build(); - - try { - // Execute streaming request - AudioSpeechStreamingResponse response = client.audio().createStreamingSpeech(request); - - if (response.isSuccess() && response.getFlowable() != null) { - System.out.println("Starting streaming TTS response..."); - - response.getFlowable().subscribe( - data -> { - // Process each streaming response chunk - if (data.getChoices() != null && !data.getChoices().isEmpty()) { - // Get content of current chunk - Delta delta = data.getChoices().get(0).getDelta(); - - // Print current audio content (base64 encoded) - if (delta != null && delta.getContent() != null) { - System.out.println("Received audio chunk: " + delta.getContent()); - } - } - }, - error -> System.err.println("\nStream error: " + error.getMessage()), - // Process streaming response completion event - () -> System.out.println("\nStreaming TTS completed") - ); - - // Wait for streaming to complete - Thread.sleep(10000); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/AudioTranscriptionsExample.java b/samples/src/main/ai.z.openapi.samples/AudioTranscriptionsExample.java deleted file mode 100644 index d9b4519..0000000 --- a/samples/src/main/ai.z.openapi.samples/AudioTranscriptionsExample.java +++ /dev/null @@ -1,57 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.audio.AudioTranscriptionRequest; -import ai.z.openapi.service.audio.AudioTranscriptionResponse; - -import java.io.File; - -/** - * Audio Transcriptions Example - * Demonstrates how to use ZaiClient for audio transcription (speech-to-text) - */ -public class AudioTranscriptionsExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Prepare audio file - // Supported formats: .wav, .mp3 - // Limitations: file size ≤ 25 MB, duration ≤ 30 seconds - // The sample audio file is located at: samples/src/main/resources/asr.wav - File audioFile = new File("samples/src/main/resources/asr.wav"); - - // Create transcription request - AudioTranscriptionRequest request = AudioTranscriptionRequest.builder() - .model(Constants.ModelGLMASR) - .file(audioFile) - .stream(false) - .build(); - - try { - // Execute request - AudioTranscriptionResponse response = client.audio().createTranscription(request); - - if (response.isSuccess()) { - System.out.println("Transcription Result:"); - String text = response.getData().getText(); - // Remove leading newline if present - if (text != null && text.startsWith("\n")) { - text = text.substring(1); - } - System.out.println(text); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/AudioTranscriptionsStreamExample.java b/samples/src/main/ai.z.openapi.samples/AudioTranscriptionsStreamExample.java deleted file mode 100644 index 2bdf118..0000000 --- a/samples/src/main/ai.z.openapi.samples/AudioTranscriptionsStreamExample.java +++ /dev/null @@ -1,69 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.audio.AudioTranscriptionChunk; -import ai.z.openapi.service.audio.AudioTranscriptionRequest; -import ai.z.openapi.service.audio.AudioTranscriptionResponse; - -import java.io.File; - -/** - * Streaming Audio Transcription Example - * Demonstrates how to use ZaiClient for streaming audio transcription (speech-to-text) - */ -public class AudioTranscriptionsStreamExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Prepare audio file - // Supported formats: .wav, .mp3 - // Limitations: file size ≤ 25 MB, duration ≤ 30 seconds - // The sample audio file is located at: samples/src/main/resources/asr.wav - File audioFile = new File("samples/src/main/resources/asr.wav"); - - // Create transcription request with streaming enabled - AudioTranscriptionRequest request = AudioTranscriptionRequest.builder() - .model(Constants.ModelGLMASR) - .file(audioFile) - .stream(true) // Enable streaming response - .build(); - - try { - // Execute streaming request - AudioTranscriptionResponse response = client.audio().createTranscription(request); - - if (response.isSuccess() && response.getFlowable() != null) { - System.out.println("Starting streaming transcription..."); - - response.getFlowable().subscribe( - chunk -> { - // Process each streaming response chunk - // delta is already a String containing the text content - if (chunk.getDelta() != null) { - String delta = chunk.getDelta(); - // Print each chunk on a new line to show streaming effect - System.out.println(delta); - } - }, - error -> System.err.println("Stream error: " + error.getMessage()), - () -> System.out.println("Streaming transcription completed") - ); - - // Wait for streaming to complete - Thread.sleep(10000); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ChatAsyncCompletionExample.java b/samples/src/main/ai.z.openapi.samples/ChatAsyncCompletionExample.java deleted file mode 100644 index 2850be8..0000000 --- a/samples/src/main/ai.z.openapi.samples/ChatAsyncCompletionExample.java +++ /dev/null @@ -1,60 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.ZhipuAiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.model.AsyncResultRetrieveParams; -import ai.z.openapi.service.model.ChatCompletionCreateParams; -import ai.z.openapi.service.model.ChatCompletionResponse; -import ai.z.openapi.service.model.ChatMessage; -import ai.z.openapi.service.model.ChatMessageRole; -import ai.z.openapi.service.model.QueryModelResultResponse; - -import java.util.Arrays; - -/** - * Chat Completion Example - * Demonstrates how to use ZaiClient for basic chat conversations - */ -public class ChatAsyncCompletionExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Or set API Key via code - // ZaiClient client = ZaiClient.builder() - // .apiKey("your.api_key") - // .build(); - - // Create chat request - ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model("glm-5.1") - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content("Hello, how are you?") - .build() - )) - .stream(false) - .temperature(1.0f) - .build(); - - try { - // Execute request - ChatCompletionResponse response = client.chat().asyncChatCompletion(request); - System.out.println("Response Task: " + response.getData()); - Thread.sleep(10000); - QueryModelResultResponse queryModelResultResponse = client.chat().retrieveAsyncResult(AsyncResultRetrieveParams.builder() - .taskId(response.getData().getId()).build()); - System.out.println("Response Data: " + queryModelResultResponse.getData()); - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ChatCompletionBase64Example.java b/samples/src/main/ai.z.openapi.samples/ChatCompletionBase64Example.java deleted file mode 100644 index 9080418..0000000 --- a/samples/src/main/ai.z.openapi.samples/ChatCompletionBase64Example.java +++ /dev/null @@ -1,68 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.ZhipuAiClient; -import ai.z.openapi.service.model.ChatCompletionCreateParams; -import ai.z.openapi.service.model.ChatCompletionResponse; -import ai.z.openapi.service.model.ChatMessage; -import ai.z.openapi.service.model.ChatMessageRole; -import ai.z.openapi.service.model.ChatThinking; -import ai.z.openapi.service.model.ImageUrl; -import ai.z.openapi.service.model.MessageContent; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.Arrays; -import java.util.Base64; - -/** - * Streaming Chat Example - * Demonstrates how to use ZaiClient for streaming chat conversations - */ -public class ChatCompletionBase64Example { - - public static void main(String[] args) throws IOException { - // Create client - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - String file = ClassLoader.getSystemResource("grounding.png").getFile(); - byte[] bytes = Files.readAllBytes(new File(file).toPath()); - Base64.Encoder encoder = Base64.getEncoder(); - String base64 = encoder.encodeToString(bytes); - - // Create chat request - ChatCompletionCreateParams streamRequest = ChatCompletionCreateParams.builder() - .model("glm-5v-turbo") - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content(Arrays.asList( - MessageContent.builder() - .type("image_url") - .imageUrl(ImageUrl.builder() - .url(base64) - .build()) - .build(), - MessageContent.builder() - .type("text") - .text("What are the pic talk about?") - .build() - )) - .build() - )) - .thinking(ChatThinking.builder().type("enabled").build()) - .build(); - - ChatCompletionResponse response = client.chat().createChatCompletion(streamRequest); - - if (response.isSuccess()) { - Object content = response.getData().getChoices().get(0).getMessage(); - System.out.println("Response: " + content); - } else { - System.err.println("Error: " + response.getMsg()); - } - client.close(); - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ChatCompletionExample.java b/samples/src/main/ai.z.openapi.samples/ChatCompletionExample.java deleted file mode 100644 index 5ac5649..0000000 --- a/samples/src/main/ai.z.openapi.samples/ChatCompletionExample.java +++ /dev/null @@ -1,58 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.ZhipuAiClient; -import ai.z.openapi.service.model.*; - -import java.util.Arrays; - -/** - * Chat Completion Example - * Demonstrates how to use ZaiClient for basic chat conversations - */ -public class ChatCompletionExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Or set API Key via code - // ZaiClient client = ZaiClient.builder() - // .apiKey("your.api_key") - // .build(); - - // Create chat request - ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model("glm-5.1") - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content("Hello, how to learn english?") - .build() - )) - .stream(false) - .thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build()) - .responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build()) - .temperature(1.0f) - .build(); - - try { - // Execute request - ChatCompletionResponse response = client.chat().createChatCompletion(request); - - if (response.isSuccess()) { - Object content = response.getData().getChoices().get(0).getMessage(); - System.out.println("Response: " + content); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ChatCompletionMultiFileExample.java b/samples/src/main/ai.z.openapi.samples/ChatCompletionMultiFileExample.java deleted file mode 100644 index bbcbb3f..0000000 --- a/samples/src/main/ai.z.openapi.samples/ChatCompletionMultiFileExample.java +++ /dev/null @@ -1,56 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.ZhipuAiClient; -import ai.z.openapi.service.model.*; -import java.util.Arrays; - -public class ChatCompletionMultiFileExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model("glm-5v-turbo") - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content(Arrays.asList( - MessageContent.builder() - .type("file_url") - .fileUrl(FileUrl.builder() - .url("https://cdn.bigmodel.cn/static/demo/demo2.txt") - .build()) - .build(), - MessageContent.builder() - .type("file_url") - .fileUrl(FileUrl.builder() - .url("https://cdn.bigmodel.cn/static/demo/demo1.pdf") - .build()) - .build(), - MessageContent.builder() - .type("text") - .text("What are the files show about?") - .build() - )) - .build() - )) - .thinking(ChatThinking.builder() - .type("enabled") - .build()) - .build(); - - ChatCompletionResponse response = client.chat().createChatCompletion(request); - - if (response.isSuccess()) { - Object reply = response.getData().getChoices().get(0).getMessage(); - System.out.println(reply); - } else { - System.err.println("Error: " + response.getMsg()); - } - client.close(); - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ChatCompletionStreamExample.java b/samples/src/main/ai.z.openapi.samples/ChatCompletionStreamExample.java deleted file mode 100644 index 283574f..0000000 --- a/samples/src/main/ai.z.openapi.samples/ChatCompletionStreamExample.java +++ /dev/null @@ -1,63 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.model.*; -import java.util.Arrays; - -/** - * Streaming Chat Example - * Demonstrates how to use ZaiClient for streaming chat conversations - */ -public class ChatCompletionStreamExample { - - public static void main(String[] args) { - // Create client - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Create chat request - ChatCompletionCreateParams streamRequest = ChatCompletionCreateParams.builder() - .model("glm-5.1") - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content("Tell me a story") - .build() - )) - .thinking(ChatThinking.builder().type("enabled").build()) - .stream(true) // Enable streaming response - .build(); - - try { - // Execute streaming request - ChatCompletionResponse response = client.chat().createChatCompletion(streamRequest); - - if (response.isSuccess() && response.getFlowable() != null) { - System.out.println("Starting streaming response..."); - response.getFlowable().subscribe( - data -> { - // Process each streaming response chunk - if (data.getChoices() != null && !data.getChoices().isEmpty()) { - // Get content of current chunk - Delta delta = data.getChoices().get(0).getDelta(); - // Print current chunk - System.out.print(delta + "\n"); - } - }, - error -> System.err.println("\nStream error: " + error.getMessage()), - // Process streaming response completion event - () -> System.out.println("\nStreaming response completed") - ); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - if (client != null) { - client.close(); - } - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ChatCompletionWithCustomHeadersExample.java b/samples/src/main/ai.z.openapi.samples/ChatCompletionWithCustomHeadersExample.java deleted file mode 100644 index 2605219..0000000 --- a/samples/src/main/ai.z.openapi.samples/ChatCompletionWithCustomHeadersExample.java +++ /dev/null @@ -1,91 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.ZhipuAiClient; -import ai.z.openapi.service.model.*; -import ai.z.openapi.core.Constants; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -/** - * Chat Completion with Custom Headers Example - * Demonstrates how to use ZaiClient for chat conversations with custom HTTP headers - */ -public class ChatCompletionWithCustomHeadersExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Create chat request - ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model("glm-5.1") - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content("Hello, how are you?") - .build() - )) - .stream(true) // Enable streaming for custom headers support - .build(); - - // Create custom headers - Map customHeaders = new HashMap<>(); - customHeaders.put("X-Custom-User-ID", "user123"); - customHeaders.put("X-Request-Source", "mobile-app"); - customHeaders.put("Session-Id", "session-abc-123"); - - try { - // Execute request with custom headers - // This works for both streaming and non-streaming requests - ChatCompletionResponse response = client.chat().createChatCompletion(request, customHeaders); - - // Example for non-streaming request with custom headers - ChatCompletionCreateParams nonStreamingRequest = ChatCompletionCreateParams.builder() - .model(Constants.ModelChatGLM4_5) - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content("What is artificial intelligence?") - .build() - )) - .stream(false) // Explicitly set to false for non-streaming - .temperature(0.7f) - .maxTokens(1024) - .build(); - - ChatCompletionResponse nonStreamingResponse = client.chat() - .createChatCompletion(nonStreamingRequest, customHeaders); - - System.out.println("Non-streaming response: " + nonStreamingResponse.getData()); - - if (response.isSuccess() && response.getFlowable() != null) { - System.out.println("Streaming response with custom headers:"); - response.getFlowable().subscribe( - data -> { - // Handle streaming chunk - if (data.getChoices() != null && !data.getChoices().isEmpty()) { - String content = data.getChoices().get(0).getDelta().getContent(); - if (content != null) { - System.out.print(content); - } - } - }, - error -> System.err.println("\nStream error: " + error.getMessage()), - () -> System.out.println("\nStream completed") - ); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ChatCompletionWithMcpServerUrlExample.java b/samples/src/main/ai.z.openapi.samples/ChatCompletionWithMcpServerUrlExample.java deleted file mode 100644 index 44c5029..0000000 --- a/samples/src/main/ai.z.openapi.samples/ChatCompletionWithMcpServerUrlExample.java +++ /dev/null @@ -1,78 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.ZhipuAiClient; -import ai.z.openapi.service.model.ChatCompletionCreateParams; -import ai.z.openapi.service.model.ChatCompletionResponse; -import ai.z.openapi.service.model.ChatMessage; -import ai.z.openapi.service.model.ChatMessageRole; -import ai.z.openapi.service.model.ChatThinking; -import ai.z.openapi.service.model.ChatThinkingType; -import ai.z.openapi.service.model.ChatTool; -import ai.z.openapi.service.model.ChatToolType; -import ai.z.openapi.service.model.MCPTool; -import ai.z.openapi.service.model.ResponseFormat; -import ai.z.openapi.service.model.ResponseFormatType; - -import java.util.Collections; - -/** - * Chat Completion Example - * Demonstrates how to use ZaiClient for basic chat conversations - */ -public class ChatCompletionWithMcpServerUrlExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Or set API Key via code - // ZaiClient client = ZaiClient.builder() - // .apiKey("your.api_key") - // .build(); - - // Create chat request - ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model("glm-5") - .messages(Collections.singletonList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content("Hello, how to learn english?") - .build() - )) - .stream(false) - .thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build()) - .responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build()) - .temperature(1.0f) - .maxTokens(1024) - .tools(Collections.singletonList(ChatTool.builder() - .type(ChatToolType.MCP.value()) - .mcp(MCPTool.builder() - .server_url("https://open.bigmodel.cn/api/mcp-broker/proxy/sogou-baike/sse") - .server_label("sogou-baike") - .transport_type("sse") - .headers(Collections.singletonMap("Authorization", "Bearer " + System.getProperty("ZAI_API_KEY"))) - .build()) - .build())) - .build(); - - try { - // Execute request - ChatCompletionResponse response = client.chat().createChatCompletion(request); - - if (response.isSuccess()) { - Object content = response.getData().getChoices().get(0).getMessage(); - System.out.println("Response: " + content); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ClientConfigurationExample.java b/samples/src/main/ai.z.openapi.samples/ClientConfigurationExample.java deleted file mode 100644 index 4abe954..0000000 --- a/samples/src/main/ai.z.openapi.samples/ClientConfigurationExample.java +++ /dev/null @@ -1,71 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.ZhipuAiClient; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -/** - * Client Configuration Example - * Demonstrates different configuration methods for ZaiClient - */ -public class ClientConfigurationExample { - - public static void main(String[] args) { - - System.out.println("=== Basic Configuration Example ==="); - ZaiClient basicClient = ZaiClient.builder().apiKey("xxx.xxx").build(); - System.out.println("✓ Basic client created successfully"); - - // Complete configuration example - System.out.println("\n=== Complete Configuration Example ==="); - Map customHeaders = new HashMap<>(); - customHeaders.put("Session-Id", "custom-session-id-xx"); - ZaiClient advancedClient = ZaiClient.builder() - .apiKey("your.api_key") - .baseUrl("https://api.z.ai/api/paas/v4/") - .customHeaders(customHeaders) - .enableTokenCache() - .tokenExpire(3600000) // 1 hour - .connectionPool(10, 5, TimeUnit.MINUTES) - .build(); - System.out.println("✓ Advanced client created successfully"); - - // ZHIPU platform specific client - System.out.println("\n=== ZHIPU Platform Specific Configuration ==="); - ZaiClient zhipuClient = ZaiClient.ofZHIPU("your.api_key").build(); - System.out.println("✓ ZHIPU platform client created successfully"); - - ZhipuAiClient zhipuAiClient = ZhipuAiClient.builder() - .apiKey("your.api_key") - .baseUrl("https://api.z.ai/api/paas/v4/") - .customHeaders(customHeaders) - .enableTokenCache() - .tokenExpire(3600000) // 1 hour - .connectionPool(10, 5, TimeUnit.MINUTES) - .build(); - System.out.println("✓ ZHIPU platform client created successfully"); - - // Custom configuration example - System.out.println("\n=== Custom Configuration Example ==="); - ZaiClient customClient = ZaiClient.builder() - .apiKey("your.api_key") - .baseUrl("https://custom.api.endpoint/") - .customHeaders(customHeaders) - .enableTokenCache() - .tokenExpire(7200000) - .connectionPool(20, 10, TimeUnit.MINUTES) - .build(); - System.out.println("✓ Custom client created successfully"); - - System.out.println("\n=== Configuration Description ==="); - System.out.println("1. apiKey: API key, format is 'key.secret'"); - System.out.println("2. baseUrl: API base URL"); - System.out.println("3. enableTokenCache: Enable token caching to improve performance"); - System.out.println("4. tokenExpire: Token expiration time (milliseconds)"); - System.out.println("5. connectionPool: Connection pool configuration (max connections, keep-alive time, time unit)"); - System.out.println("\nRecommended to use environment variable ZAI_API_KEY to set API key for better security"); - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/CogVideoX3Example.java b/samples/src/main/ai.z.openapi.samples/CogVideoX3Example.java deleted file mode 100644 index a944006..0000000 --- a/samples/src/main/ai.z.openapi.samples/CogVideoX3Example.java +++ /dev/null @@ -1,176 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.videos.VideoCreateParams; -import ai.z.openapi.service.videos.VideoObject; -import ai.z.openapi.service.videos.VideosResponse; - -import java.util.Arrays; - -/** - * CogVideoX-3 Example - * Demonstrates how to use ZaiClient for advanced video generation with CogVideoX-3 - * Features: Text-to-video, Image-to-video, First-last frame generation - */ -public class CogVideoX3Example { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Or set API Key via code - // ZaiClient client = ZaiClient.builder() - // .apiKey("your.api_key") - // .build(); - - // Video generation examples - textToVideoExample(client); - imageToVideoExample(client); - firstLastFrameVideoExample(client); - client.close(); - } - - /** - * Example of text-to-video generation using CogVideoX-3 - */ - private static void textToVideoExample(ZaiClient client) { - System.out.println("=== CogVideoX-3 Text-to-Video Generation Example ==="); - - try { - VideoCreateParams request = VideoCreateParams.builder() - .model("cogvideox-3") - .prompt("A cute kitten chasing butterflies in a garden, bright sunshine, blooming flowers, clear and stable picture") - .quality("quality") // "quality" for quality priority, "speed" for speed priority - .withAudio(true) - .size("1920x1080") // Video resolution, supports up to 4K - .fps(30) // Frame rate, can be 30 or 60 - .build(); - - VideosResponse response = client.videos().videoGenerations(request); - - if (response.isSuccess()) { - String taskId = response.getData().getId(); - System.out.println("Video generation task submitted, Task ID: " + taskId); - System.out.println("Please wait for video generation to complete..."); - - // Wait and check result - Thread.sleep(60000); // Wait 1 minute - checkVideoResult(client, taskId); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Example of image-to-video generation using CogVideoX-3 - */ - private static void imageToVideoExample(ZaiClient client) { - System.out.println("\n=== CogVideoX-3 Image-to-Video Generation Example ==="); - - try { - VideoCreateParams request = VideoCreateParams.builder() - .model("cogvideox-3") - .imageUrl("https://img.iplaysoft.com/wp-content/uploads/2019/free-images/free_stock_photo.jpg") - .prompt("Make the scene come alive, showing natural dynamic effects") - .quality("quality") - .withAudio(true) - .size("1920x1080") - .fps(30) - .build(); - - VideosResponse response = client.videos().videoGenerations(request); - - if (response.isSuccess()) { - String taskId = response.getData().getId(); - System.out.println("Image-to-video task submitted, Task ID: " + taskId); - System.out.println("Please wait for video generation to complete..."); - - // Wait and check result - Thread.sleep(60000); // Wait 1 minute - checkVideoResult(client, taskId); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Example of first-last frame video generation using CogVideoX-3 - * This is a new feature in CogVideoX-3 - */ - private static void firstLastFrameVideoExample(ZaiClient client) { - System.out.println("\n=== CogVideoX-3 First-Last Frame Video Generation Example ==="); - - try { - // Define first and last frame URLs - String firstFrameUrl = "https://gd-hbimg.huaban.com/ccee58d77afe8f5e17a572246b1994f7e027657fe9e6-qD66In_fw1200webp"; - String lastFrameUrl = "https://gd-hbimg.huaban.com/cc2601d568a72d18d90b2cc7f1065b16b2d693f7fa3f7-hDAwNq_fw1200webp"; - - VideoCreateParams request = VideoCreateParams.builder() - .model("cogvideox-3") - .imageUrl(Arrays.asList(firstFrameUrl, lastFrameUrl)) // Pass first and last frame URLs - .prompt("Dragon King transforms into Ao Bing, ink wash style rendering, main subject slowly transforms with rotating camera movement, smooth and natural transition") - .quality("quality") - .withAudio(true) - .size("1920x1080") - .fps(30) - .build(); - - VideosResponse response = client.videos().videoGenerations(request); - - if (response.isSuccess()) { - String taskId = response.getData().getId(); - System.out.println("First-last frame video generation task submitted, Task ID: " + taskId); - System.out.println("Please wait for video generation to complete..."); - System.out.println("Note: First-last frame generation can create coherent transition videos, naturally connecting static frames into dynamic narratives."); - - // Wait and check result - Thread.sleep(60000); // Wait 1 minute - checkVideoResult(client, taskId); - } else { - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Check video generation result - */ - private static void checkVideoResult(ZaiClient client, String taskId) { - try { - VideosResponse response = client.videos().videoGenerationsResult(taskId); - - if (response.isSuccess()) { - VideoObject result = response.getData(); - String status = result.getTaskStatus(); - - System.out.println("Task status: " + status); - - if ("SUCCESS".equals(status)) { - System.out.println("Video generation successful!"); - if (result.getVideoResult() != null && !result.getVideoResult().isEmpty()) { - System.out.println("Video URL: " + result.getVideoResult().get(0).getUrl()); - } - } else if ("PROCESSING".equals(status)) { - System.out.println("Video is still being generated, please check again later..."); - } - } else { - System.err.println("Query result error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred while querying video result: " + e.getMessage()); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/CogVideoXExample.java b/samples/src/main/ai.z.openapi.samples/CogVideoXExample.java deleted file mode 100644 index b724be6..0000000 --- a/samples/src/main/ai.z.openapi.samples/CogVideoXExample.java +++ /dev/null @@ -1,80 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.videos.VideoCreateParams; -import ai.z.openapi.service.videos.VideosResponse; - -/** - * CogVideoX Example - * Demonstrates how to use ZaiClient to generate videos using CogVideoX models - */ -public class CogVideoXExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Or set API Key via code - // ZaiClient client = ZaiClient.builder() - // .apiKey("your.api_key") - // .build(); - - // Basic Video Generation - generateBasicVideo(client); - client.close(); - } - - /** - * Example of basic video generation using CogVideoX - */ - private static void generateBasicVideo(ZaiClient client) { - System.out.println("\n=== Basic CogVideoX Generation Example ==="); - - // Create video generation request - VideoCreateParams request = VideoCreateParams.builder() - .model(Constants.ModelCogVideoX) // Using CogVideoX model - .prompt("A beautiful sunset over the ocean with waves gently crashing on the shore") - .requestId("cogvideox-example-" + System.currentTimeMillis()) - .build(); - - try { - // Execute request - VideosResponse response = client.videos().videoGenerations(request); - System.out.println("Response: " + response.getData()); - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Example of checking video generation result - * Note: You need to replace the taskId with a real task ID from a previous generation request - */ - private static void checkVideoResult(ZaiClient client) { - System.out.println("\n=== Check Video Generation Result Example ==="); - - // Replace with a real task ID from a previous generation request - String taskId = "your-task-id-here"; - - System.out.println("Checking result for task ID: " + taskId); - System.out.println("Note: In a real application, replace 'your-task-id-here' with an actual task ID."); - - try { - // Execute request to check result - VideosResponse response = client.videos().videoGenerationsResult(taskId); - - if (response.isSuccess()) { - System.out.println("Video generation: " + response.getData()); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/CustomClientExample.java b/samples/src/main/ai.z.openapi.samples/CustomClientExample.java deleted file mode 100644 index 5e0ff75..0000000 --- a/samples/src/main/ai.z.openapi.samples/CustomClientExample.java +++ /dev/null @@ -1,107 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZhipuAiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.core.config.ZaiConfig; -import ai.z.openapi.service.model.ChatCompletionCreateParams; -import ai.z.openapi.service.model.ChatCompletionResponse; -import ai.z.openapi.service.model.ChatMessage; -import ai.z.openapi.service.model.ChatMessageRole; -import ai.z.openapi.service.model.ChatThinking; -import ai.z.openapi.service.model.ChatThinkingType; -import ai.z.openapi.service.model.Choice; -import ai.z.openapi.service.model.Delta; -import ai.z.openapi.service.model.ResponseFormat; -import ai.z.openapi.service.model.ResponseFormatType; - -import java.util.Arrays; -import java.util.Collections; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Chat Completion Example - * Demonstrates how to use ZaiClient for basic chat conversations - */ -public class CustomClientExample { - - public static void main(String[] args) throws Exception { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiConfig zaiConfig = ZaiConfig.builder() - .apiKey(System.getenv("ZAI_API_KEY")) - .baseUrl(Constants.ZHIPU_AI_BASE_URL) - .customHeaders(Collections.emptyMap()) - .disableTokenCache(true) - .readTimeout(600) - .timeOutTimeUnit(TimeUnit.SECONDS) - .connectionPoolKeepAliveDuration(10) - .connectionPoolTimeUnit(TimeUnit.SECONDS) - .connectionPoolMaxIdleConnections(20) - .build(); - - ZhipuAiClient client = new ZhipuAiClient(zaiConfig); - - // Or set API Key via code - // ZaiClient client = ZaiClient.builder() - // .apiKey("your.api_key") - // .build(); - - // Create chat request - ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model("glm-5") - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content("Hello, are you there") - .build() - )) - .stream(true) - .thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build()) - .responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build()) - .temperature(1.0f) - .build(); - - // Create latch to wait for streaming completion - CountDownLatch latch = new CountDownLatch(1); - - try { - // Execute request - ChatCompletionResponse response = client.chat().createChatCompletion(request); - - if (response.isSuccess() && response.getFlowable() != null) { - System.out.println("Starting streaming response..."); - response.getFlowable().subscribe( - data -> { - // Process each streaming response chunk - if (data.getChoices() != null && !data.getChoices().isEmpty()) { - // Get content of current chunk - Choice choice = data.getChoices().get(0); - System.out.print(choice + "\n"); - } - }, - error -> { - System.err.println("\nStream error: " + error.getMessage()); - latch.countDown(); // Release latch on error - }, - // Process streaming response completion event - () -> { - System.out.println("\nStreaming response completed"); - latch.countDown(); // Release latch on completion - } - ); - - // Wait for streaming to complete (max 60 seconds) - latch.await(60, TimeUnit.SECONDS); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/CustomTimeoutExample.java b/samples/src/main/ai.z.openapi.samples/CustomTimeoutExample.java deleted file mode 100644 index 32ac356..0000000 --- a/samples/src/main/ai.z.openapi.samples/CustomTimeoutExample.java +++ /dev/null @@ -1,63 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.ZhipuAiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.model.ChatCompletionCreateParams; -import ai.z.openapi.service.model.ChatCompletionResponse; -import ai.z.openapi.service.model.ChatMessage; -import ai.z.openapi.service.model.ChatMessageRole; -import ai.z.openapi.service.model.ChatThinking; -import ai.z.openapi.service.model.ChatThinkingType; -import ai.z.openapi.service.model.ResponseFormat; -import ai.z.openapi.service.model.ResponseFormatType; - -import java.util.Arrays; -import java.util.concurrent.TimeUnit; - -/** - * Chat Completion Example - * Demonstrates how to use ZaiClient for basic chat conversations - */ -public class CustomTimeoutExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI() - .networkConfig(0, 10, 30, 30, TimeUnit.SECONDS) - .build(); - - // Create chat request - ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model("glm-5") - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content("Hello, how to learn english?") - .build() - )) - .stream(false) - .thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build()) - .responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build()) - .build(); - - try { - // Execute request - ChatCompletionResponse response = client.chat().createChatCompletion(request); - - if (response.isSuccess()) { - Object content = response.getData().getChoices().get(0).getMessage(); - System.out.println("Response: " + content); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/EmbeddingsExample.java b/samples/src/main/ai.z.openapi.samples/EmbeddingsExample.java deleted file mode 100644 index b85a29f..0000000 --- a/samples/src/main/ai.z.openapi.samples/EmbeddingsExample.java +++ /dev/null @@ -1,51 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.embedding.*; -import ai.z.openapi.core.Constants; -import java.util.Arrays; - -/** - * Embeddings Example - * Demonstrates how to use ZaiClient to generate text embeddings - */ -public class EmbeddingsExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Create embedding request - EmbeddingCreateParams request = EmbeddingCreateParams.builder() - .model(Constants.ModelEmbedding3) - .input(Arrays.asList("Hello world", "How are you?", "How is the weather today?")) - .build(); - - try { - // Execute request - EmbeddingResponse response = client.embeddings().createEmbeddings(request); - - if (response.isSuccess()) { - System.out.println("Successfully generated embeddings:"); - System.out.println("Model: " + response.getData().getModel()); - System.out.println("Usage statistics: " + response.getData().getUsage().getTotalTokens() + " tokens"); - - response.getData().getData().forEach(embedding -> { - System.out.println("\nIndex: " + embedding.getIndex()); - System.out.println("Vector dimensions: " + embedding.getEmbedding().size()); - System.out.println("Vector first 5 values: " + - embedding.getEmbedding().subList(0, Math.min(5, embedding.getEmbedding().size()))); - }); - } else { - System.err.println("Error: Embedding generation failed: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Embedding exception: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/FileParsingExample.java b/samples/src/main/ai.z.openapi.samples/FileParsingExample.java deleted file mode 100644 index ca232e2..0000000 --- a/samples/src/main/ai.z.openapi.samples/FileParsingExample.java +++ /dev/null @@ -1,124 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.fileparsing.FileParsingDownloadReq; -import ai.z.openapi.service.fileparsing.FileParsingDownloadResponse; -import ai.z.openapi.service.fileparsing.FileParsingResponse; -import ai.z.openapi.service.fileparsing.FileParsingUploadReq; -import ai.z.openapi.utils.StringUtils; - -public class FileParsingExample { - - public static void main(String[] args) { - - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - try { - // Example 1: Create a file parsing task - System.out.println("=== Example: Create file parsing task ==="); - String filePath = "your file path"; - String taskId = createFileParsingTaskExample(client, filePath, "pdf", "lite"); - - // Example 2: Get parsing result - System.out.println("\n=== Example: Get parsing result ==="); - getFileParsingResultExample(client, taskId); - - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } - - /** - * Example: Create parsing task (upload file and parse) - * - * @param client ZaiClient instance - * @return TaskId of the parsing task - */ - private static String createFileParsingTaskExample(ZaiClient client, String filePath, String fileType, String toolType) { - if (StringUtils.isEmpty(filePath)) { - System.err.println("Invalid file path."); - return null; - } - try { - FileParsingUploadReq uploadReq = FileParsingUploadReq.builder() - .filePath(filePath) - .fileType(fileType) // support: pdf, docx etc. - .toolType(toolType) // tool type: lite, prime, expert - .build(); - - System.out.println("Uploading file and creating parsing task..."); - FileParsingResponse response = client.fileParsing().createParseTask(uploadReq); - if (response.isSuccess()) { - if (null != response.getData().getTaskId()) { - String taskId = response.getData().getTaskId(); - System.out.println("Parsing task created successfully, TaskId: " + taskId); - return taskId; - } else { - System.err.println("Failed to create parsing task: " + response.getData().getMessage()); - } - } else { - System.err.println("Failed to create parsing task: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("File parsing task error: " + e.getMessage()); - } - // Return null indicates task creation failed - return null; - } - - /** - * Example: Get parsing result - * - * @param client ZaiClient instance - * @param taskId ID of the parsing task - */ - private static void getFileParsingResultExample(ZaiClient client, String taskId) { - if (taskId == null || taskId.isEmpty()) { - System.err.println("Invalid task ID. Cannot get parsing result."); - return; - } - - try { - int maxRetry = 100; // Maximum 100 polling attempts - int intervalMs = 3000; // 3 seconds interval between each polling - for (int i = 0; i < maxRetry; i++) { - FileParsingDownloadReq downloadReq = FileParsingDownloadReq.builder() - .taskId(taskId) - .formatType("text") - .build(); - - FileParsingDownloadResponse response = client.fileParsing().getParseResult(downloadReq); - - if (response.isSuccess()) { - String status = response.getData().getStatus(); - System.out.println("Current task status: " + status); - - if ("succeeded".equalsIgnoreCase(status)) { - System.out.println("Parsing result obtained successfully!"); - System.out.println("Parsed content: " + response.getData().getContent()); - System.out.println("Download link: " + response.getData().getParsingResultUrl()); - return; - } else if ("processing".equalsIgnoreCase(status)) { - System.out.println("Parsing in progress, please wait..."); - Thread.sleep(intervalMs); - } else { - System.out.println("Parsing task exception, status: " + status + ", message: " + response.getData().getMessage()); - return; - } - } else { - System.err.println("Failed to get parsing result: " + response.getMsg()); - return; - } - } - System.out.println("Wait timeout, please check the parsing result later."); - } catch (Exception e) { - System.err.println("Exception occurred while getting parsing result: " + e.getMessage()); - } - } -} diff --git a/samples/src/main/ai.z.openapi.samples/FileParsingSyncExample.java b/samples/src/main/ai.z.openapi.samples/FileParsingSyncExample.java deleted file mode 100644 index 7f12d77..0000000 --- a/samples/src/main/ai.z.openapi.samples/FileParsingSyncExample.java +++ /dev/null @@ -1,64 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.fileparsing.FileParsingDownloadResponse; -import ai.z.openapi.service.fileparsing.FileParsingUploadReq; -import ai.z.openapi.utils.StringUtils; - -public class FileParsingSyncExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - - // Alternatively, the API Key can be specified directly in the code - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - try { - System.out.println("=== Example: Creating file parsing task ==="); - - String filePath = "your file path"; - FileParsingDownloadResponse result = syncFileParsingTaskExample(client, filePath, "pdf", "prime-sync"); - - System.out.println("Parsing task created successfully, TaskId: " + result.getData().getTaskId()); - System.out.println("File content: " + result.getData().getContent()); - System.out.println("Download link: " + result.getData().getParsingResultUrl()); - - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } - - /** - * Example: Create parsing task (upload file and parse) - * - * @param client ZaiClient instance - * @return Parsing task's taskId - */ - private static FileParsingDownloadResponse syncFileParsingTaskExample(ZaiClient client, String filePath, String fileType, String toolType) { - if (StringUtils.isEmpty(filePath)) { - System.err.println("Invalid file path."); - return null; - } - try { - FileParsingUploadReq uploadReq = FileParsingUploadReq.builder() - .filePath(filePath) - .fileType(fileType) // Supported types: pdf, docx, etc. - .toolType(toolType) // Parsing tool type: lite, prime, expert - .build(); - - System.out.println("Uploading file and creating parsing task..."); - return client.fileParsing().syncParse(uploadReq); - } catch (Exception e) { - System.err.println("File parsing task error: " + e.getMessage()); - } - // Returning null means task creation failed - return null; - } - - -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/FunctionCallingExample.java b/samples/src/main/ai.z.openapi.samples/FunctionCallingExample.java deleted file mode 100644 index 3d44c45..0000000 --- a/samples/src/main/ai.z.openapi.samples/FunctionCallingExample.java +++ /dev/null @@ -1,92 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.model.*; -import ai.z.openapi.core.Constants; -import java.util.*; - -public class FunctionCallingExample { - - // Simulate weather API - public static Map getWeather(String location, String date) { - Map weather = new HashMap<>(); - weather.put("location", location); - weather.put("date", date != null ? date : "today"); - weather.put("weather", "sunny"); - weather.put("temperature", "25°C"); - weather.put("humidity", "60%"); - return weather; - } - - // Simulate stock API - public static Map getStockPrice(String symbol) { - Map stock = new HashMap<>(); - stock.put("symbol", symbol); - stock.put("price", 150.25); - stock.put("change", "+2.5%"); - return stock; - } - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Define function tools - Map properties = new HashMap<>(); - ChatFunctionParameterProperty locationProperty = ChatFunctionParameterProperty - .builder().type("string").description("City name, for example: Beijing").build(); - properties.put("location", locationProperty); - ChatFunctionParameterProperty unitProperty = ChatFunctionParameterProperty - .builder().type("string").enums(Arrays.asList("celsius", "fahrenheit")).build(); - properties.put("unit", unitProperty); - ChatTool weatherTool = ChatTool.builder() - .type(ChatToolType.FUNCTION.value()) - .function(ChatFunction.builder() - .name("get_weather") - .description("Get weather information for a specified location") - .parameters(ChatFunctionParameters.builder() - .type("object") - .properties(properties) - .build()) - .build()) - .build(); - - // Create request - ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model(Constants.ModelChatGLM4_5) - .messages(Collections.singletonList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content("How's the weather in Beijing today?") - .build() - )) - .tools(Collections.singletonList(weatherTool)) - .toolChoice("auto") - .build(); - - // Send request - ChatCompletionResponse response = client.chat().createChatCompletion(request); - - if (response.isSuccess()) { - // Handle function calling - ChatMessage assistantMessage = response.getData().getChoices().get(0).getMessage(); - if (assistantMessage.getToolCalls() != null && !assistantMessage.getToolCalls().isEmpty()) { - for (ToolCalls toolCall : assistantMessage.getToolCalls()) { - String functionName = toolCall.getFunction().getName(); - - if ("get_weather".equals(functionName)) { - Map result = getWeather("Beijing", null); - System.out.println("Weather info: " + result); - } - } - } else { - System.out.println(assistantMessage.getContent()); - } - } else { - System.err.println("Error: " + response.getMsg()); - } - client.close(); - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/GLM41VThinkingExample.java b/samples/src/main/ai.z.openapi.samples/GLM41VThinkingExample.java deleted file mode 100644 index d07d44a..0000000 --- a/samples/src/main/ai.z.openapi.samples/GLM41VThinkingExample.java +++ /dev/null @@ -1,51 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.model.ChatCompletionCreateParams; -import ai.z.openapi.service.model.ChatCompletionResponse; -import ai.z.openapi.service.model.ChatMessage; -import ai.z.openapi.service.model.ChatMessageRole; -import ai.z.openapi.service.model.ImageUrl; -import ai.z.openapi.service.model.MessageContent; - -import java.util.Arrays; - -public class GLM41VThinkingExample { - - public static void main(String[] args) { - - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() - .model("glm-4.1v-thinking-flashx") - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content(Arrays.asList( - MessageContent.builder() - .type("text") - .text("Describe this image") - .build(), - MessageContent.builder() - .type("image_url") - .imageUrl(ImageUrl.builder() - .url("https://aigc-files.bigmodel.cn/api/cogview/20250723213827da171a419b9b4906_0.png") - .build()) - .build())) - .build() - )) - .build(); - - ChatCompletionResponse response = client.chat().createChatCompletion(request); - - if (response.isSuccess()) { - Object reply = response.getData().getChoices().get(0).getMessage().getContent(); - System.out.println(reply); - } else { - System.err.println("Error: " + response.getMsg()); - } - client.close(); - } - -} diff --git a/samples/src/main/ai.z.openapi.samples/GLMVisionExample.java b/samples/src/main/ai.z.openapi.samples/GLMVisionExample.java deleted file mode 100644 index 3559b47..0000000 --- a/samples/src/main/ai.z.openapi.samples/GLMVisionExample.java +++ /dev/null @@ -1,59 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.model.ChatCompletionCreateParams; -import ai.z.openapi.service.model.ChatCompletionResponse; -import ai.z.openapi.service.model.ChatMessage; -import ai.z.openapi.service.model.ChatMessageRole; -import ai.z.openapi.service.model.ChatThinking; -import ai.z.openapi.service.model.ImageUrl; -import ai.z.openapi.service.model.MessageContent; - -import java.io.IOException; -import java.util.Arrays; - -/** - * Streaming Chat Example - * Demonstrates how to use ZaiClient for streaming chat conversations - */ -public class GLMVisionExample { - - public static void main(String[] args) throws IOException { - // Create client - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Create chat request - ChatCompletionCreateParams streamRequest = ChatCompletionCreateParams.builder() - .model("glm-5v-turbo") - .messages(Arrays.asList( - ChatMessage.builder() - .role(ChatMessageRole.USER.value()) - .content(Arrays.asList( - MessageContent.builder() - .type("image_url") - .imageUrl(ImageUrl.builder() - .url("https://cdn.bigmodel.cn/static/logo/register.png") - .build()) - .build(), - MessageContent.builder() - .type("text") - .text("What are the pic talk about?") - .build() - )) - .build() - )) - .thinking(ChatThinking.builder().type("enabled").build()) - .build(); - - ChatCompletionResponse response = client.chat().createChatCompletion(streamRequest); - - if (response.isSuccess()) { - Object content = response.getData().getChoices().get(0).getMessage(); - System.out.println("Response: " + content); - } else { - System.err.println("Error: " + response.getMsg()); - } - client.chat(); - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ImageGenerationAsyncExample.java b/samples/src/main/ai.z.openapi.samples/ImageGenerationAsyncExample.java deleted file mode 100644 index 70f15ac..0000000 --- a/samples/src/main/ai.z.openapi.samples/ImageGenerationAsyncExample.java +++ /dev/null @@ -1,49 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.image.AsyncImageResponse; -import ai.z.openapi.service.image.CreateImageRequest; - -/** - * Images Example - * Demonstrates how to use ZaiClient to generate async image - */ -public class ImageGenerationAsyncExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - generateAsyncImage(client); - client.close(); - } - - private static void generateAsyncImage(ZaiClient client) { - System.out.println("\n=== Basic Images Generation Example ==="); - - // Create image generation request - CreateImageRequest request = CreateImageRequest.builder() - .model("glm-image") - .prompt("A beautiful sunset over mountains, digital art style") - .size("1024x1024") - .quality("hd") - .build(); - - try { - // Execute request - AsyncImageResponse response = client.images().createImageAsync(request); - System.out.println("Response 1: " + response.getData()); - String taskId = response.getData().getId(); - response = client.images().queryAsyncResult(taskId); - System.out.println("Response 2: " + response.getData()); - Thread.sleep(40000); - response = client.images().queryAsyncResult(taskId); - System.out.println("Response 3: " + response.getData()); - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ImageGenerationExample.java b/samples/src/main/ai.z.openapi.samples/ImageGenerationExample.java deleted file mode 100644 index f580ebb..0000000 --- a/samples/src/main/ai.z.openapi.samples/ImageGenerationExample.java +++ /dev/null @@ -1,29 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.image.CreateImageRequest; -import ai.z.openapi.service.image.ImageResponse; - -/** - * Image Generation Example - * Demonstrates how to use ZaiClient to generate images - */ -public class ImageGenerationExample { - - public static void main(String[] args) { - // Create client - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Create image generation request - CreateImageRequest request = CreateImageRequest.builder() - .model(Constants.ModelCogView4250304) - .prompt("A beautiful sunset over mountains, digital art style") - .size("1024x1024") - .build(); - ImageResponse response = client.images().createImage(request); - System.out.println(response.getData()); - client.close(); - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ModerationExample.java b/samples/src/main/ai.z.openapi.samples/ModerationExample.java deleted file mode 100644 index 95b5a7e..0000000 --- a/samples/src/main/ai.z.openapi.samples/ModerationExample.java +++ /dev/null @@ -1,163 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.moderations.*; - -import java.util.Arrays; -import java.util.List; - -/** - * Moderation Example - * Demonstrates how to use ZaiClient to moderate content for safety - */ -public class ModerationExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Example 1: Text moderation - System.out.println("=== Text Moderation Example ==="); - moderateText(client); - - // Example 2: Image moderation - System.out.println("\n=== Image Moderation Example ==="); - moderateImage(client); - client.close(); - } - - private static void moderateText(ZaiClient client) { - // Create text moderation inputs - List inputs = Arrays.asList( - ModerationInput.text("This is a normal message about technology.") - ); - - // Create moderation request - ModerationCreateParams request = ModerationCreateParams.builder() - .model("moderation") - .input(inputs) - .build(); - - try { - // Execute request - ModerationResponse response = client.moderations().createModeration(request); - - if (response.isSuccess()) { - System.out.println("Text moderation completed successfully:"); - System.out.println("Request ID: " + response.getData().getRequestId()); - - response.getData().getResultList().forEach(item -> { - System.out.println("\nContent Type: " + item.getContentType()); - System.out.println("Risk Level: " + item.getRiskLevel()); - System.out.println("Risk Type: " + item.getRiskType()); - System.out.println("Is Safe: " + item.isSafe()); - System.out.println("Is Flagged: " + item.isFlagged()); - }); - } else { - System.err.println("Error: Text moderation failed: " + response.getMsg()); - if (response.getError() != null) { - System.err.println("Error details: " + response.getError().getMessage()); - } - } - } catch (Exception e) { - System.err.println("Text moderation exception: " + e.getMessage()); - e.printStackTrace(); - } - } - - private static void moderateImage(ZaiClient client) { - // Create image moderation input - List inputs = Arrays.asList( - ModerationInput.image("https://example.com/sample-image.jpg"), - ModerationInput.image("https://example.com/another-image.png") - ); - - // Create moderation request - ModerationCreateParams request = ModerationCreateParams.builder() - .model("moderation") - .input(inputs) - .build(); - - try { - // Execute request - ModerationResponse response = client.moderations().createModeration(request); - - if (response.isSuccess()) { - System.out.println("Image moderation completed successfully:"); - System.out.println("Request ID: " + response.getData().getRequestId()); - - response.getData().getResultList().forEach(item -> { - System.out.println("\nContent Type: " + item.getContentType()); - System.out.println("Risk Level: " + item.getRiskLevel()); - System.out.println("Status: " + (item.isSafe() ? "SAFE" : "FLAGGED")); - if (item.getRiskType() != null) { - System.out.println("Risk Type: " + item.getRiskType()); - } - }); - } else { - System.err.println("Error: Image moderation failed: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Image moderation exception: " + e.getMessage()); - e.printStackTrace(); - } - } - - private static void moderateMixedContent(ZaiClient client) { - // Create mixed content moderation inputs - List inputs = Arrays.asList( - ModerationInput.text("This is a text message to be moderated."), - ModerationInput.image("https://example.com/image-to-check.jpg"), - ModerationInput.video("https://example.com/video-sample.mp4"), - ModerationInput.audio("https://example.com/audio-sample.mp3") - ); - - // Create moderation request - ModerationCreateParams request = ModerationCreateParams.builder() - .model("moderation") - .input(inputs) - .build(); - - try { - // Execute request - ModerationResponse response = client.moderations().createModeration(request); - - if (response.isSuccess()) { - System.out.println("Mixed content moderation completed successfully:"); - System.out.println("Total items processed: " + response.getData().getResultList().size()); - - response.getData().getResultList().forEach(item -> { - System.out.println("\n--- Moderation Result ---"); - System.out.println("Content Type: " + item.getContentType()); - System.out.println("Risk Assessment: " + item.getRiskLevel()); - System.out.println("Safety Status: " + (item.isSafe() ? "✓ SAFE" : "⚠ FLAGGED")); - - if (item.isFlagged()) { - System.out.println("Risk Category: " + item.getRiskType()); - } - }); - - // Summary statistics - long safeCount = response.getData().getResultList().stream() - .mapToLong(item -> item.isSafe() ? 1 : 0) - .sum(); - long flaggedCount = response.getData().getResultList().size() - safeCount; - - System.out.println("\n--- Summary ---"); - System.out.println("Safe items: " + safeCount); - System.out.println("Flagged items: " + flaggedCount); - - if (response.getData().getUsage() != null) { - System.out.println("Total tokens used: " + response.getData().getUsage().getModerationText()); - } - } else { - System.err.println("Error: Mixed content moderation failed: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Mixed content moderation exception: " + e.getMessage()); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ViduAspectVideoExample.java b/samples/src/main/ai.z.openapi.samples/ViduAspectVideoExample.java deleted file mode 100644 index e6fa03e..0000000 --- a/samples/src/main/ai.z.openapi.samples/ViduAspectVideoExample.java +++ /dev/null @@ -1,70 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.videos.VideoCreateParams; -import ai.z.openapi.service.videos.VideosResponse; - -import java.util.Arrays; - -/** - * Vidu Image-to-Video Example - * Demonstrates how to use ZaiClient to generate videos from images using Vidu models - */ -public class ViduAspectVideoExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - generateVideoStartEnd(client); - client.close(); - } - - private static void generateVideoStartEnd(ZaiClient client) { - - try { - // Create video generation request - VideoCreateParams request = VideoCreateParams.builder() - .model(Constants.ModelVidu2Reference) // Using Vidu 2 Image model - .prompt("An astronaut floating in space with Earth visible in the background, anime style") - .imageUrl(Arrays.asList("https://aigc-files.bigmodel.cn/api/cogview/20250723213827da171a419b9b4906_0.png")) - .duration(4) - .size("1280x720") - .withAudio(true) - .movementAmplitude("auto") - .aspectRatio("16:9") - .build(); - - VideosResponse response = client.videos().videoGenerations(request); - System.out.println("Task " + response.getData()); - - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Example of checking video generation result - * Note: You need to replace the taskId with a real task ID from a previous generation request - */ - private static void checkVideoResult(ZaiClient client, String taskId) { - System.out.println("\n=== Check Video Generation Result Example ==="); - try { - VideosResponse response = client.videos().videoGenerationsResult(taskId); - - if (response.isSuccess()) { - System.out.println("Video generation: " + response.getData()); - - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ViduImageToVideoExample.java b/samples/src/main/ai.z.openapi.samples/ViduImageToVideoExample.java deleted file mode 100644 index fde78b0..0000000 --- a/samples/src/main/ai.z.openapi.samples/ViduImageToVideoExample.java +++ /dev/null @@ -1,83 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.videos.VideoCreateParams; -import ai.z.openapi.service.videos.VideosResponse; - -/** - * Vidu Image-to-Video Example - * Demonstrates how to use ZaiClient to generate videos from images using Vidu models - */ -public class ViduImageToVideoExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - generateVideoFromImage(client); - client.close(); - } - - /** - * Example of generating video from an image using Vidu - * Note: You need to provide a valid image file path - */ - private static void generateVideoFromImage(ZaiClient client) { - System.out.println("\n=== Vidu Image-to-Video Generation Example ==="); - - // Path to your image file - // In a real application, replace with an actual image path - - - try { - // Create video generation request - VideoCreateParams request = VideoCreateParams.builder() - .model(Constants.ModelVidu2Image) // Using Vidu 2 Image model - .prompt("Transform this image into a dynamic scene with gentle movement") - .imageUrl("https://aigc-files.bigmodel.cn/api/cogview/20250723213827da171a419b9b4906_0.png") // Base64 encoded image - .duration(4) // 5 seconds duration - .size("1280x720") - .withAudio(true) - .movementAmplitude("auto") - .build(); - - VideosResponse response = client.videos().videoGenerations(request); - System.out.println("Task " + response.getData()); - - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Example of checking video generation result - * Note: You need to replace the taskId with a real task ID from a previous generation request - */ - private static void checkVideoResult(ZaiClient client) { - System.out.println("\n=== Check Video Generation Result Example ==="); - - // Replace with a real task ID from a previous generation request - String taskId = "your-task-id-here"; - - System.out.println("Checking result for task ID: " + taskId); - System.out.println("Note: In a real application, replace 'your-task-id-here' with an actual task ID."); - - try { - VideosResponse response = client.videos().videoGenerationsResult(taskId); - - if (response.isSuccess()) { - System.out.println("Video generation: " + response.getData()); - - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ViduStartEndVideoExample.java b/samples/src/main/ai.z.openapi.samples/ViduStartEndVideoExample.java deleted file mode 100644 index b6e5b0d..0000000 --- a/samples/src/main/ai.z.openapi.samples/ViduStartEndVideoExample.java +++ /dev/null @@ -1,74 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.videos.VideoCreateParams; -import ai.z.openapi.service.videos.VideosResponse; - -import java.util.Arrays; - -/** - * Vidu Image-to-Video Example - * Demonstrates how to use ZaiClient to generate videos from images using Vidu models - */ -public class ViduStartEndVideoExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - generateVideoStartEnd(client); - client.close(); - } - - /** - * Example of generating video from an image using Vidu - * Note: You need to provide a valid image file path - */ - private static void generateVideoStartEnd(ZaiClient client) { - System.out.println("\n=== Vidu Image-to-Video Generation Example ==="); - - try { - // Create video generation request - VideoCreateParams request = VideoCreateParams.builder() - .model(Constants.ModelViduQ1StartEnd) // Using Vidu 2 Image model - .prompt("An astronaut floating in space with Earth visible in the background, anime style") - .imageUrl(Arrays.asList("https://aigc-files.bigmodel.cn/api/cogview/20250723213827da171a419b9b4906_0.png", "https://aigc-files.bigmodel.cn/api/cogview/20250723213827da171a419b9b4906_0.png")) - .duration(5) // 5 seconds duration - .size("1920x1080") - .withAudio(true) - .movementAmplitude("auto") - .build(); - - VideosResponse response = client.videos().videoGenerations(request); - System.out.println("Task " + response.getData()); - - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Example of checking video generation result - * Note: You need to replace the taskId with a real task ID from a previous generation request - */ - private static void checkVideoResult(ZaiClient client, String taskId) { - System.out.println("\n=== Check Video Generation Result Example ==="); - try { - VideosResponse response = client.videos().videoGenerationsResult(taskId); - - if (response.isSuccess()) { - System.out.println("Video generation: " + response.getData()); - - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/ViduTextToVideoExample.java b/samples/src/main/ai.z.openapi.samples/ViduTextToVideoExample.java deleted file mode 100644 index 2f5c597..0000000 --- a/samples/src/main/ai.z.openapi.samples/ViduTextToVideoExample.java +++ /dev/null @@ -1,122 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.core.Constants; -import ai.z.openapi.service.videos.VideoCreateParams; -import ai.z.openapi.service.videos.VideosResponse; - -/** - * Vidu Text-to-Video Example - * Demonstrates how to use ZaiClient to generate videos from text using Vidu models - */ -public class ViduTextToVideoExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Or set API Key via code - // ZaiClient client = ZaiClient.builder() - // .apiKey("your.api_key") - // .build(); - - // Example: Generate video from text using Vidu - generateVideoFromText(client); - client.close(); - } - - /** - * Example of generating video from text using Vidu - */ - private static void generateVideoFromText(ZaiClient client) { - System.out.println("\n=== Vidu Text-to-Video Generation Example ==="); - - // Create video generation request - VideoCreateParams request = VideoCreateParams.builder() - .model(Constants.ModelViduQ1Text) // Using Vidu Q1 Text model - .prompt("A person walking through a beautiful forest with sunlight filtering through the trees") - .requestId("vidu-text-example-" + System.currentTimeMillis()) - .duration(5) - .size("1920x1080") - .build(); - - try { - // Execute request - VideosResponse response = client.videos().videoGenerations(request); - System.out.println("Data: " + response.getData()); - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Example of generating video from text with custom settings - */ - private static void generateVideoFromTextWithCustomSettings(ZaiClient client) { - System.out.println("\n=== Vidu Text-to-Video with Custom Settings Example ==="); - - // Create video generation request with custom settings - VideoCreateParams request = VideoCreateParams.builder() - .model(Constants.ModelViduQ1Text) // Using Vidu Q1 Text model - .prompt("An astronaut floating in space with Earth visible in the background, anime style") - .requestId("vidu-text-custom-example-" + System.currentTimeMillis()) - .quality("high") // High quality setting - .withAudio(true) // Generate with audio - .duration(5) - .size("1920x1080") - .fps(30) // 30 frames per second - .build(); - - try { - // Execute request - VideosResponse response = client.videos().videoGenerations(request); - - if (response.isSuccess()) { - System.out.println("Custom video generation request successful!"); - System.out.println("Task ID: " + response.getData().getId()); - System.out.println("Data: " + response.getData()); - System.out.println("\nNote: Video generation is an asynchronous process."); - System.out.println("Use the Task ID to check the status and retrieve the result later."); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Example of checking video generation result - * Note: You need to replace the taskId with a real task ID from a previous generation request - */ - private static void checkVideoResult(ZaiClient client) { - System.out.println("\n=== Check Video Generation Result Example ==="); - - // Replace with a real task ID from a previous generation request - String taskId = "your-task-id-here"; - - System.out.println("Checking result for task ID: " + taskId); - System.out.println("Note: In a real application, replace 'your-task-id-here' with an actual task ID."); - - try { - // Skip the actual API call in this example to avoid errors with a fake task ID - if (!taskId.equals("your-task-id-here")) { - // Execute request to check result - VideosResponse response = client.videos().videoGenerationsResult(taskId); - - if (response.isSuccess()) { - System.out.println("Video generation: " + response.getData()); - } else { - System.err.println("Error: " + response.getMsg()); - } - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/VoiceCloneExample.java b/samples/src/main/ai.z.openapi.samples/VoiceCloneExample.java deleted file mode 100644 index 138e4aa..0000000 --- a/samples/src/main/ai.z.openapi.samples/VoiceCloneExample.java +++ /dev/null @@ -1,180 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.file.FileApiResponse; -import ai.z.openapi.service.file.FileService; -import ai.z.openapi.service.file.FileUploadParams; -import ai.z.openapi.service.file.UploadFilePurpose; -import ai.z.openapi.service.voiceclone.*; - -import java.nio.file.Paths; - -/** - * Voice Clone Example - * Demonstrates how to use ZaiClient for voice cloning operations including: - * - Uploading voice samples - * - Creating voice clones - * - Listing existing voices - * - Deleting voice clones - */ -public class VoiceCloneExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Or set API Key via code - // ZaiClient client = ZaiClient.builder() - // .apiKey("your.api_key") - // .build(); - - VoiceCloneService voiceCloneService = client.voiceClone(); - FileService fileService = client.files(); - - try { - // Example 1: Create a voice clone - System.out.println("=== Voice Clone Creation Example ==="); - createVoiceCloneExample(voiceCloneService, fileService); - - // Example 2: List existing voices - System.out.println("\n=== Voice List Example ==="); - listVoicesExample(voiceCloneService); - - // Example 3: Delete a voice clone - System.out.println("\n=== Voice Deletion Example ==="); - deleteVoiceExample(voiceCloneService); - - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } - - /** - * Example of creating a voice clone with file upload - */ - private static void createVoiceCloneExample(VoiceCloneService voiceCloneService, FileService fileService) { - try { - // Step 1: Upload the voice input audio file - String voiceInputFilePath = Paths.get("samples", "resources", "voice_clone_input.mp3").toString(); - - FileUploadParams uploadRequest = FileUploadParams.builder() - .filePath(voiceInputFilePath) - .purpose(UploadFilePurpose.VOICE_CLONE_INPUT.value()) - .requestId("voice-clone-example-" + System.currentTimeMillis()) - .build(); - - System.out.println("Uploading voice input file..."); - FileApiResponse uploadResponse = fileService.uploadFile(uploadRequest); - - if (uploadResponse.isSuccess()) { - String fileId = uploadResponse.getData().getId(); - System.out.println("Voice input file uploaded successfully with ID: " + fileId); - - // Step 2: Create voice clone using the uploaded file - VoiceCloneRequest request = new VoiceCloneRequest(); - request.setVoiceName("My Custom Voice"); - request.setText("Hello, this is a sample text for voice cloning training"); - request.setInput("Welcome to our voice synthesis system"); - request.setFileId(fileId); - request.setRequestId("clone-request-" + System.currentTimeMillis()); - request.setModel("CogTTS-clone"); - - System.out.println("Creating voice clone..."); - VoiceCloneResponse response = voiceCloneService.cloneVoice(request); - - if (response.isSuccess()) { - System.out.println("Voice clone created successfully!"); - System.out.println("Voice: " + response.getData().getVoice()); - } else { - System.err.println("Voice clone creation failed: " + response.getMsg()); - if (response.getError() != null) { - System.err.println("Error details: " + response.getError().getMessage()); - } - } - } else { - System.err.println("File upload failed: " + uploadResponse.getMsg()); - } - } catch (Exception e) { - System.err.println("Error in voice clone creation: " + e.getMessage()); - } - } - - /** - * Example of listing existing voice clones - */ - private static void listVoicesExample(VoiceCloneService voiceCloneService) { - try { - // List all private voices - VoiceListRequest request = new VoiceListRequest(); - request.setVoiceType("PRIVATE"); // Filter for custom voice clones - request.setRequestId("list-request-" + System.currentTimeMillis()); - - System.out.println("Retrieving voice list..."); - VoiceListResponse response = voiceCloneService.listVoice(request); - - if (response.isSuccess()) { - System.out.println("Voice list retrieved successfully!"); - if (response.getData().getVoiceList() != null && !response.getData().getVoiceList().isEmpty()) { - System.out.println("Found " + response.getData().getVoiceList().size() + " voices:"); - for (VoiceData voice : response.getData().getVoiceList()) { - System.out.println("- Voice: " + voice.getVoice()); - System.out.println(" Name: " + voice.getVoiceName()); - System.out.println(" Type: " + voice.getVoiceType()); - if (voice.getDownloadUrl() != null) { - System.out.println(" Download URL: " + voice.getDownloadUrl()); - } - if (voice.getCreateTime() != null) { - System.out.println(" Created: " + voice.getCreateTime()); - } - System.out.println(); - } - } else { - System.out.println("No voices found."); - } - } else { - System.err.println("Voice list retrieval failed: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Error in voice list retrieval: " + e.getMessage()); - } - } - - /** - * Example of deleting a voice clone - * Note: Replace "your-voice" with an actual voice from your account - */ - private static void deleteVoiceExample(VoiceCloneService voiceCloneService) { - try { - // Note: This is just an example - replace with actual voice - String voiceToDelete = "your-voice-here"; - - VoiceDeleteRequest request = new VoiceDeleteRequest(); - request.setVoice(voiceToDelete); - request.setRequestId("delete-request-" + System.currentTimeMillis()); - - System.out.println("Deleting voice: " + voiceToDelete); - VoiceDeleteResponse response = voiceCloneService.deleteVoice(request); - - if (response.isSuccess()) { - System.out.println("Voice clone deleted successfully!"); - if (response.getData().getUpdateTime() != null) { - System.out.println("Deletion time: " + response.getData().getUpdateTime()); - } - } else { - System.err.println("Voice deletion failed: " + response.getMsg()); - if (response.getError() != null) { - System.err.println("Error details: " + response.getError().getMessage()); - } - } - } catch (Exception e) { - // Expected to fail with example voice - System.out.println("Note: This example uses a placeholder voice and is expected to fail."); - System.out.println("Replace 'your-voice-here' with an actual voice to test deletion."); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/WebReaderExample.java b/samples/src/main/ai.z.openapi.samples/WebReaderExample.java deleted file mode 100644 index 61271e0..0000000 --- a/samples/src/main/ai.z.openapi.samples/WebReaderExample.java +++ /dev/null @@ -1,82 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.web_reader.WebReaderRequest; -import ai.z.openapi.service.web_reader.WebReaderResponse; -import ai.z.openapi.service.web_reader.WebReaderResult; - -/** - * Web Reader Example - * Demonstrates how to use ZaiClient for web page reading and parsing capabilities - */ -public class WebReaderExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - basicWebReader(client); - } - - /** - * Example of basic web reader functionality - */ - private static void basicWebReader(ZaiClient client) { - System.out.println("\n=== Web Reader Example ==="); - - // Create web reader request - WebReaderRequest request = WebReaderRequest.builder() - .url("https://example.com/") - .returnFormat("markdown") - .withImagesSummary(Boolean.TRUE) - .withLinksSummary(Boolean.TRUE) - .build(); - - try { - // Execute request - WebReaderResponse response = client.webReader().createWebReader(request); - - if (response.isSuccess()) { - System.out.println("Read successful!"); - - WebReaderResult result = response.getData(); - if (result != null && result.getReaderResult() != null) { - WebReaderResult.ReaderData data = result.getReaderResult(); - System.out.println("Title: " + data.getTitle()); - System.out.println("URL: " + data.getUrl()); - System.out.println("Description: " + data.getDescription()); - - String content = data.getContent(); - if (content != null) { - String preview = content.length() > 300 ? content.substring(0, 300) + "..." : content; - System.out.println("\nContent preview:\n" + preview); - } - - if (data.getImages() != null) { - System.out.println("\nImages count: " + data.getImages().size()); - } - if (data.getLinks() != null) { - System.out.println("Links count: " + data.getLinks().size()); - } - } - else { - System.out.println("No reader result returned."); - } - } - else { - System.err.println("Error: " + response.getMsg()); - if (response.getError() != null) { - System.err.println("Error detail: " + response.getError()); - } - } - } - catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } finally { - client.close(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/WebSearchExample.java b/samples/src/main/ai.z.openapi.samples/WebSearchExample.java deleted file mode 100644 index 47db2d6..0000000 --- a/samples/src/main/ai.z.openapi.samples/WebSearchExample.java +++ /dev/null @@ -1,179 +0,0 @@ -package ai.z.openapi.samples; - -import ai.z.openapi.ZaiClient; -import ai.z.openapi.service.model.ChatMessageRole; -import ai.z.openapi.service.tools.ChoiceDelta; -import ai.z.openapi.service.tools.SearchChatMessage; -import ai.z.openapi.service.tools.WebSearchApiResponse; -import ai.z.openapi.service.tools.WebSearchMessage; -import ai.z.openapi.service.tools.WebSearchParamsRequest; -import ai.z.openapi.service.web_search.WebSearchRequest; -import ai.z.openapi.service.web_search.WebSearchResponse; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Web Search Example - * Demonstrates how to use ZaiClient for web search capabilities - */ -public class WebSearchExample { - - public static void main(String[] args) { - // Create client, recommended to set API Key via environment variable - // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() - ZaiClient client = ZaiClient.builder().ofZAI().build(); - - // Or set API Key via code - // ZaiClient client = ZaiClient.builder() - // .apiKey("your.api_key") - // .build(); - - // Example 1: Basic Web Search - basicWebSearch(client); - client.close(); - } - - /** - * Example of basic web search functionality - */ - private static void basicWebSearch(ZaiClient client) { - System.out.println("\n=== Basic Web Search Example ==="); - - // Create web search request - WebSearchRequest request = WebSearchRequest.builder() - .searchEngine("search_std") - .searchQuery("latest AI technology trends") - .count(3) // Number of results to return - .searchRecencyFilter("oneYear") // Filter for results within the last year - .contentSize("high") // Request detailed content - .requestId("web-search-example-" + System.currentTimeMillis()) - .build(); - - try { - // Execute request - WebSearchResponse response = client.webSearch().createWebSearch(request); - - if (response.isSuccess()) { - System.out.println("Search successful!"); - System.out.println("Number of results: " + response.getData().getWebSearchResp().size()); - - // Display search results - response.getData().getWebSearchResp().forEach(result -> { - System.out.println("\nTitle: " + result.getTitle()); - System.out.println("Result: " + result); - }); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Example of web search pro functionality (non-streaming) - */ - private static void webSearchPro(ZaiClient client) { - System.out.println("\n=== Web Search Pro Example ==="); - - // Create messages for the search - List messages = new ArrayList<>(); - SearchChatMessage userMessage = new SearchChatMessage( - ChatMessageRole.USER.value(), - "What are the latest developments in quantum computing?" - ); - messages.add(userMessage); - - // Create web search pro request - WebSearchParamsRequest request = WebSearchParamsRequest.builder() - .model("web-search-pro") - .stream(false) // Non-streaming mode - .messages(messages) - .requestId("web-search-pro-example-" + System.currentTimeMillis()) - .build(); - - try { - // Execute request - WebSearchApiResponse response = client.webSearch().createWebSearchPro(request); - - if (response.isSuccess()) { - System.out.println("Search successful!"); - - // Display search result - WebSearchMessage content = response.getData().getChoices().get(0).getMessage(); - System.out.println("\nResponse: " + content); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } - - /** - * Example of web search pro with streaming functionality - */ - private static void webSearchProStream(ZaiClient client) { - System.out.println("\n=== Web Search Pro Streaming Example ==="); - - // Create messages for the search - List messages = new ArrayList<>(); - SearchChatMessage userMessage = new SearchChatMessage( - ChatMessageRole.USER.value(), - "What are the recent advancements in renewable energy?" - ); - messages.add(userMessage); - - // Create web search pro streaming request - WebSearchParamsRequest request = WebSearchParamsRequest.builder() - .model("web-search-pro") - .stream(true) // Enable streaming - .messages(messages) - .requestId("web-search-pro-stream-example-" + System.currentTimeMillis()) - .build(); - - try { - // Execute streaming request - WebSearchApiResponse response = client.webSearch().createWebSearchProStream(request); - - if (response.isSuccess() && response.getFlowable() != null) { - System.out.println("Streaming search started..."); - - // Track streaming progress - AtomicInteger messageCount = new AtomicInteger(0); - AtomicBoolean isFirst = new AtomicBoolean(true); - StringBuilder fullContent = new StringBuilder(); - - // Subscribe to the stream - response.getFlowable().doOnNext(webSearchPro -> { - if (isFirst.getAndSet(false)) { - System.out.println("Receiving stream response:"); - } - - if (webSearchPro.getChoices() != null && !webSearchPro.getChoices().isEmpty()) { - ChoiceDelta content = webSearchPro.getChoices().get(0).getDelta(); - System.out.print(content); - fullContent.append(content); - messageCount.incrementAndGet(); - } - }) - .doOnComplete(() -> { - System.out.println("\n\nStream completed. Received " + messageCount.get() + " chunks."); - System.out.println("Full response length: " + fullContent.length() + " characters"); - }) - .blockingSubscribe(); - } else { - System.err.println("Error: " + response.getMsg()); - } - } catch (Exception e) { - System.err.println("Exception occurred: " + e.getMessage()); - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/AgentExample.java b/samples/src/main/java/ai/z/openapi/samples/AgentExample.java new file mode 100644 index 0000000..717a899 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/AgentExample.java @@ -0,0 +1,77 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.ZhipuAiClient; +import ai.z.openapi.service.agents.AgentContent; +import ai.z.openapi.service.agents.AgentMessage; +import ai.z.openapi.service.agents.AgentsCompletionRequest; +import ai.z.openapi.service.model.ChatCompletionResponse; +import ai.z.openapi.service.model.ChatMessageRole; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Agent Example Demonstrates how to use ZaiClient for agent-based completions + */ +public class AgentExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + syncAgentCompletion(client); + } + + /** + * Example of synchronous agent completion + */ + private static void syncAgentCompletion(ZaiClient client) { + System.out.println("\n=== Synchronous Agent Completion Example ==="); + + // Create messages for the agent + List messages = new ArrayList<>(); + AgentMessage userMessage = new AgentMessage(ChatMessageRole.USER.value(), + Arrays.asList(AgentContent.ofText("Hello, please translate this to French: How are you today?"))); + messages.add(userMessage); + + // Create agent completion request + AgentsCompletionRequest request = AgentsCompletionRequest.builder() + .agentId("general_translation") // Using translation agent + .stream(false) // Non-streaming mode + .messages(messages) + .customVariables(JsonNodeFactory.instance.objectNode().put("source_lang", "en").put("target_lang", "cn")) + .requestId("agent-example-" + System.currentTimeMillis()) + .build(); + + try { + // Execute request + ChatCompletionResponse response = client.agents().createAgentCompletion(request); + + if (response.isSuccess()) { + System.out.println("Agent completion successful!"); + + // Display agent response + Object content = response.getData().getChoices().get(0).getMessages(); + System.out.println("\nResponse: " + new ObjectMapper().writeValueAsString(content)); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/AgentVideoExample.java b/samples/src/main/java/ai/z/openapi/samples/AgentVideoExample.java new file mode 100644 index 0000000..03d5e81 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/AgentVideoExample.java @@ -0,0 +1,75 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.agents.AgentContent; +import ai.z.openapi.service.agents.AgentMessage; +import ai.z.openapi.service.agents.AgentsCompletionRequest; +import ai.z.openapi.service.model.ChatCompletionResponse; +import ai.z.openapi.service.model.ChatMessageRole; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Agent Example Demonstrates how to use ZaiClient for agent-based completions + */ +public class AgentVideoExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + syncAgentCompletion(client); + } + + /** + * Example of synchronous agent completion + */ + private static void syncAgentCompletion(ZaiClient client) { + System.out.println("\n=== Synchronous Agent Completion Example ==="); + + // Create messages for the agent + List messages = new ArrayList<>(); + AgentMessage userMessage = new AgentMessage(ChatMessageRole.USER.value(), Arrays.asList(AgentContent.ofText( + "The two figures in the painting gradually approach each other, then kissing passionately, alternating deep and determined intensity"), + AgentContent + .ofImageUrl("https://img-repo-intl.imdr.cn/dr/sample-182141/xoJteuReBtNCdoMoH.jpg!w1080.jpg"))); + messages.add(userMessage); + + // Create agent completion request + AgentsCompletionRequest request = AgentsCompletionRequest.builder() + .agentId("vidu_template_agent") // Using translation agent + .stream(false) // Non-streaming mode + .messages(messages) + .customVariables(JsonNodeFactory.instance.objectNode().put("template", "french_kiss")) + .requestId("agent-example-" + System.currentTimeMillis()) + .build(); + + try { + // Execute request + ChatCompletionResponse response = client.agents().createAgentCompletion(request); + + if (response.isSuccess()) { + System.out.println("Agent completion successful!"); + System.out.println("\nResponse: " + new ObjectMapper().writeValueAsString(response.getData())); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/AudioSpeechExample.java b/samples/src/main/java/ai/z/openapi/samples/AudioSpeechExample.java new file mode 100644 index 0000000..831aef2 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/AudioSpeechExample.java @@ -0,0 +1,55 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.ZhipuAiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.audio.AudioSpeechRequest; +import ai.z.openapi.service.audio.AudioSpeechResponse; + +/** + * Audio Speech Example Demonstrates how to use ZaiClient for audio speech + */ +public class AudioSpeechExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Or set API Key via code + // ZaiClient client = ZaiClient.builder() + // .apiKey("your.api_key") + // .build(); + + // Create request + AudioSpeechRequest request = AudioSpeechRequest.builder() + .model(Constants.ModelTTS) + .input("Hello, this is a test for text-to-speech functionality.") + .voice("tongtong") + .stream(false) + .responseFormat("pcm") + .build(); + + try { + // Execute request + AudioSpeechResponse response = client.audio().createSpeech(request); + + if (response.isSuccess()) { + System.out.println("Response: " + response.getData()); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/AudioSpeechStreamExample.java b/samples/src/main/java/ai/z/openapi/samples/AudioSpeechStreamExample.java new file mode 100644 index 0000000..13d3a21 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/AudioSpeechStreamExample.java @@ -0,0 +1,70 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.audio.AudioSpeechRequest; +import ai.z.openapi.service.audio.AudioSpeechStreamingResponse; +import ai.z.openapi.service.model.Delta; +import ai.z.openapi.service.model.ModelData; + +/** + * Streaming Audio Speech Example Demonstrates how to use ZaiClient for streaming + * text-to-speech conversion + */ +public class AudioSpeechStreamExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Create speech request with streaming enabled + AudioSpeechRequest request = AudioSpeechRequest.builder() + .model(Constants.ModelTTS) + .input("Hello, how's the weather today") + .voice("tongtong") + .responseFormat("pcm") + .stream(true) // Enable streaming response + .build(); + + try { + // Execute streaming request + AudioSpeechStreamingResponse response = client.audio().createStreamingSpeech(request); + + if (response.isSuccess() && response.getFlowable() != null) { + System.out.println("Starting streaming TTS response..."); + + response.getFlowable().subscribe(data -> { + // Process each streaming response chunk + if (data.getChoices() != null && !data.getChoices().isEmpty()) { + // Get content of current chunk + Delta delta = data.getChoices().get(0).getDelta(); + + // Print current audio content (base64 encoded) + if (delta != null && delta.getContent() != null) { + System.out.println("Received audio chunk: " + delta.getContent()); + } + } + }, error -> System.err.println("\nStream error: " + error.getMessage()), + // Process streaming response completion event + () -> System.out.println("\nStreaming TTS completed")); + + // Wait for streaming to complete + Thread.sleep(10000); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/AudioTranscriptionsExample.java b/samples/src/main/java/ai/z/openapi/samples/AudioTranscriptionsExample.java new file mode 100644 index 0000000..b251632 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/AudioTranscriptionsExample.java @@ -0,0 +1,62 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.audio.AudioTranscriptionRequest; +import ai.z.openapi.service.audio.AudioTranscriptionResponse; + +import java.io.File; + +/** + * Audio Transcriptions Example Demonstrates how to use ZaiClient for audio transcription + * (speech-to-text) + */ +public class AudioTranscriptionsExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Prepare audio file + // Supported formats: .wav, .mp3 + // Limitations: file size ≤ 25 MB, duration ≤ 30 seconds + // The sample audio file is located at: samples/src/main/resources/asr.wav + File audioFile = new File("samples/src/main/resources/asr.wav"); + + // Create transcription request + AudioTranscriptionRequest request = AudioTranscriptionRequest.builder() + .model(Constants.ModelGLMASR) + .file(audioFile) + .stream(false) + .build(); + + try { + // Execute request + AudioTranscriptionResponse response = client.audio().createTranscription(request); + + if (response.isSuccess()) { + System.out.println("Transcription Result:"); + String text = response.getData().getText(); + // Remove leading newline if present + if (text != null && text.startsWith("\n")) { + text = text.substring(1); + } + System.out.println(text); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/AudioTranscriptionsStreamExample.java b/samples/src/main/java/ai/z/openapi/samples/AudioTranscriptionsStreamExample.java new file mode 100644 index 0000000..e56f58a --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/AudioTranscriptionsStreamExample.java @@ -0,0 +1,71 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.audio.AudioTranscriptionChunk; +import ai.z.openapi.service.audio.AudioTranscriptionRequest; +import ai.z.openapi.service.audio.AudioTranscriptionResponse; + +import java.io.File; + +/** + * Streaming Audio Transcription Example Demonstrates how to use ZaiClient for streaming + * audio transcription (speech-to-text) + */ +public class AudioTranscriptionsStreamExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Prepare audio file + // Supported formats: .wav, .mp3 + // Limitations: file size ≤ 25 MB, duration ≤ 30 seconds + // The sample audio file is located at: samples/src/main/resources/asr.wav + File audioFile = new File("samples/src/main/resources/asr.wav"); + + // Create transcription request with streaming enabled + AudioTranscriptionRequest request = AudioTranscriptionRequest.builder() + .model(Constants.ModelGLMASR) + .file(audioFile) + .stream(true) // Enable streaming response + .build(); + + try { + // Execute streaming request + AudioTranscriptionResponse response = client.audio().createTranscription(request); + + if (response.isSuccess() && response.getFlowable() != null) { + System.out.println("Starting streaming transcription..."); + + response.getFlowable().subscribe(chunk -> { + // Process each streaming response chunk + // delta is already a String containing the text content + if (chunk.getDelta() != null) { + String delta = chunk.getDelta(); + // Print each chunk on a new line to show streaming effect + System.out.println(delta); + } + }, error -> System.err.println("Stream error: " + error.getMessage()), + () -> System.out.println("Streaming transcription completed")); + + // Wait for streaming to complete + Thread.sleep(10000); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ChatAsyncCompletionExample.java b/samples/src/main/java/ai/z/openapi/samples/ChatAsyncCompletionExample.java new file mode 100644 index 0000000..1dad862 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ChatAsyncCompletionExample.java @@ -0,0 +1,59 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.ZhipuAiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.model.AsyncResultRetrieveParams; +import ai.z.openapi.service.model.ChatCompletionCreateParams; +import ai.z.openapi.service.model.ChatCompletionResponse; +import ai.z.openapi.service.model.ChatMessage; +import ai.z.openapi.service.model.ChatMessageRole; +import ai.z.openapi.service.model.QueryModelResultResponse; + +import java.util.Arrays; + +/** + * Chat Completion Example Demonstrates how to use ZaiClient for basic chat conversations + */ +public class ChatAsyncCompletionExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Or set API Key via code + // ZaiClient client = ZaiClient.builder() + // .apiKey("your.api_key") + // .build(); + + // Create chat request + ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() + .model("glm-5.1") + .messages(Arrays.asList( + ChatMessage.builder().role(ChatMessageRole.USER.value()).content("Hello, how are you?").build())) + .stream(false) + .temperature(1.0f) + .build(); + + try { + // Execute request + ChatCompletionResponse response = client.chat().asyncChatCompletion(request); + System.out.println("Response Task: " + response.getData()); + Thread.sleep(10000); + QueryModelResultResponse queryModelResultResponse = client.chat() + .retrieveAsyncResult(AsyncResultRetrieveParams.builder().taskId(response.getData().getId()).build()); + System.out.println("Response Data: " + queryModelResultResponse.getData()); + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ChatCompletionBase64Example.java b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionBase64Example.java new file mode 100644 index 0000000..f430c2e --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionBase64Example.java @@ -0,0 +1,63 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.ZhipuAiClient; +import ai.z.openapi.service.model.ChatCompletionCreateParams; +import ai.z.openapi.service.model.ChatCompletionResponse; +import ai.z.openapi.service.model.ChatMessage; +import ai.z.openapi.service.model.ChatMessageRole; +import ai.z.openapi.service.model.ChatThinking; +import ai.z.openapi.service.model.ImageUrl; +import ai.z.openapi.service.model.MessageContent; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.Base64; + +/** + * Streaming Chat Example Demonstrates how to use ZaiClient for streaming chat + * conversations + */ +public class ChatCompletionBase64Example { + + public static void main(String[] args) throws IOException { + // Create client + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + String file = ClassLoader.getSystemResource("grounding.png").getFile(); + byte[] bytes = Files.readAllBytes(new File(file).toPath()); + Base64.Encoder encoder = Base64.getEncoder(); + String base64 = encoder.encodeToString(bytes); + + // Create chat request + ChatCompletionCreateParams streamRequest = ChatCompletionCreateParams.builder() + .model("glm-5v-turbo") + .messages(Arrays.asList(ChatMessage.builder() + .role(ChatMessageRole.USER.value()) + .content(Arrays.asList( + MessageContent.builder() + .type("image_url") + .imageUrl(ImageUrl.builder().url(base64).build()) + .build(), + MessageContent.builder().type("text").text("What are the pic talk about?").build())) + .build())) + .thinking(ChatThinking.builder().type("enabled").build()) + .build(); + + ChatCompletionResponse response = client.chat().createChatCompletion(streamRequest); + + if (response.isSuccess()) { + Object content = response.getData().getChoices().get(0).getMessage(); + System.out.println("Response: " + content); + } + else { + System.err.println("Error: " + response.getMsg()); + } + client.close(); + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ChatCompletionExample.java b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionExample.java new file mode 100644 index 0000000..df1b489 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionExample.java @@ -0,0 +1,60 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.ZhipuAiClient; +import ai.z.openapi.service.model.*; + +import java.util.Arrays; + +/** + * Chat Completion Example Demonstrates how to use ZaiClient for basic chat conversations + */ +public class ChatCompletionExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Or set API Key via code + // ZaiClient client = ZaiClient.builder() + // .apiKey("your.api_key") + // .build(); + + // Create chat request + ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() + .model("glm-5.1") + .messages(Arrays.asList(ChatMessage.builder() + .role(ChatMessageRole.USER.value()) + .content("Hello, how to learn english?") + .build())) + .stream(false) + .thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build()) + .responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build()) + .temperature(1.0f) + .build(); + + try { + // Execute request + ChatCompletionResponse response = client.chat().createChatCompletion(request); + + if (response.isSuccess()) { + Object content = response.getData().getChoices().get(0).getMessage(); + System.out.println("Response: " + content); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ChatCompletionMultiFileExample.java b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionMultiFileExample.java new file mode 100644 index 0000000..45f66e8 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionMultiFileExample.java @@ -0,0 +1,47 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.ZhipuAiClient; +import ai.z.openapi.service.model.*; +import java.util.Arrays; + +public class ChatCompletionMultiFileExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() + .model("glm-5v-turbo") + .messages(Arrays.asList(ChatMessage.builder() + .role(ChatMessageRole.USER.value()) + .content(Arrays.asList( + MessageContent.builder() + .type("file_url") + .fileUrl(FileUrl.builder().url("https://cdn.bigmodel.cn/static/demo/demo2.txt").build()) + .build(), + MessageContent.builder() + .type("file_url") + .fileUrl(FileUrl.builder().url("https://cdn.bigmodel.cn/static/demo/demo1.pdf").build()) + .build(), + MessageContent.builder().type("text").text("What are the files show about?").build())) + .build())) + .thinking(ChatThinking.builder().type("enabled").build()) + .build(); + + ChatCompletionResponse response = client.chat().createChatCompletion(request); + + if (response.isSuccess()) { + Object reply = response.getData().getChoices().get(0).getMessage(); + System.out.println(reply); + } + else { + System.err.println("Error: " + response.getMsg()); + } + client.close(); + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ChatCompletionStreamExample.java b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionStreamExample.java new file mode 100644 index 0000000..b758ba7 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionStreamExample.java @@ -0,0 +1,61 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.model.*; +import java.util.Arrays; + +/** + * Streaming Chat Example Demonstrates how to use ZaiClient for streaming chat + * conversations + */ +public class ChatCompletionStreamExample { + + public static void main(String[] args) { + // Create client + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Create chat request + ChatCompletionCreateParams streamRequest = ChatCompletionCreateParams.builder() + .model("glm-5.1") + .messages(Arrays + .asList(ChatMessage.builder().role(ChatMessageRole.USER.value()).content("Tell me a story").build())) + .thinking(ChatThinking.builder().type("enabled").build()) + .stream(true) // Enable streaming response + .build(); + + try { + // Execute streaming request + ChatCompletionResponse response = client.chat().createChatCompletion(streamRequest); + + if (response.isSuccess() && response.getFlowable() != null) { + System.out.println("Starting streaming response..."); + response.getFlowable().subscribe(data -> { + // Process each streaming response chunk + if (data.getChoices() != null && !data.getChoices().isEmpty()) { + // Get content of current chunk + Delta delta = data.getChoices().get(0).getDelta(); + // Print current chunk + System.out.print(delta + "\n"); + } + }, error -> System.err.println("\nStream error: " + error.getMessage()), + // Process streaming response completion event + () -> System.out.println("\nStreaming response completed")); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + if (client != null) { + client.close(); + } + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ChatCompletionWithCustomHeadersExample.java b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionWithCustomHeadersExample.java new file mode 100644 index 0000000..5cffefb --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionWithCustomHeadersExample.java @@ -0,0 +1,87 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.ZhipuAiClient; +import ai.z.openapi.service.model.*; +import ai.z.openapi.core.Constants; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +/** + * Chat Completion with Custom Headers Example Demonstrates how to use ZaiClient for chat + * conversations with custom HTTP headers + */ +public class ChatCompletionWithCustomHeadersExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Create chat request + ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() + .model("glm-5.1") + .messages(Arrays.asList( + ChatMessage.builder().role(ChatMessageRole.USER.value()).content("Hello, how are you?").build())) + .stream(true) // Enable streaming for custom headers support + .build(); + + // Create custom headers + Map customHeaders = new HashMap<>(); + customHeaders.put("X-Custom-User-ID", "user123"); + customHeaders.put("X-Request-Source", "mobile-app"); + customHeaders.put("Session-Id", "session-abc-123"); + + try { + // Execute request with custom headers + // This works for both streaming and non-streaming requests + ChatCompletionResponse response = client.chat().createChatCompletion(request, customHeaders); + + // Example for non-streaming request with custom headers + ChatCompletionCreateParams nonStreamingRequest = ChatCompletionCreateParams.builder() + .model(Constants.ModelChatGLM4_5) + .messages(Arrays.asList(ChatMessage.builder() + .role(ChatMessageRole.USER.value()) + .content("What is artificial intelligence?") + .build())) + .stream(false) // Explicitly set to false for non-streaming + .temperature(0.7f) + .maxTokens(1024) + .build(); + + ChatCompletionResponse nonStreamingResponse = client.chat() + .createChatCompletion(nonStreamingRequest, customHeaders); + + System.out.println("Non-streaming response: " + nonStreamingResponse.getData()); + + if (response.isSuccess() && response.getFlowable() != null) { + System.out.println("Streaming response with custom headers:"); + response.getFlowable().subscribe(data -> { + // Handle streaming chunk + if (data.getChoices() != null && !data.getChoices().isEmpty()) { + String content = data.getChoices().get(0).getDelta().getContent(); + if (content != null) { + System.out.print(content); + } + } + }, error -> System.err.println("\nStream error: " + error.getMessage()), + () -> System.out.println("\nStream completed")); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ChatCompletionWithMcpServerUrlExample.java b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionWithMcpServerUrlExample.java new file mode 100644 index 0000000..c543a6b --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ChatCompletionWithMcpServerUrlExample.java @@ -0,0 +1,80 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.ZhipuAiClient; +import ai.z.openapi.service.model.ChatCompletionCreateParams; +import ai.z.openapi.service.model.ChatCompletionResponse; +import ai.z.openapi.service.model.ChatMessage; +import ai.z.openapi.service.model.ChatMessageRole; +import ai.z.openapi.service.model.ChatThinking; +import ai.z.openapi.service.model.ChatThinkingType; +import ai.z.openapi.service.model.ChatTool; +import ai.z.openapi.service.model.ChatToolType; +import ai.z.openapi.service.model.MCPTool; +import ai.z.openapi.service.model.ResponseFormat; +import ai.z.openapi.service.model.ResponseFormatType; + +import java.util.Collections; + +/** + * Chat Completion Example Demonstrates how to use ZaiClient for basic chat conversations + */ +public class ChatCompletionWithMcpServerUrlExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Or set API Key via code + // ZaiClient client = ZaiClient.builder() + // .apiKey("your.api_key") + // .build(); + + // Create chat request + ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() + .model("glm-5") + .messages(Collections.singletonList(ChatMessage.builder() + .role(ChatMessageRole.USER.value()) + .content("Hello, how to learn english?") + .build())) + .stream(false) + .thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build()) + .responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build()) + .temperature(1.0f) + .maxTokens(1024) + .tools(Collections.singletonList(ChatTool.builder() + .type(ChatToolType.MCP.value()) + .mcp(MCPTool.builder() + .server_url("https://open.bigmodel.cn/api/mcp-broker/proxy/sogou-baike/sse") + .server_label("sogou-baike") + .transport_type("sse") + .headers(Collections.singletonMap("Authorization", "Bearer " + System.getProperty("ZAI_API_KEY"))) + .build()) + .build())) + .build(); + + try { + // Execute request + ChatCompletionResponse response = client.chat().createChatCompletion(request); + + if (response.isSuccess()) { + Object content = response.getData().getChoices().get(0).getMessage(); + System.out.println("Response: " + content); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ClientConfigurationExample.java b/samples/src/main/java/ai/z/openapi/samples/ClientConfigurationExample.java new file mode 100644 index 0000000..bd38166 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ClientConfigurationExample.java @@ -0,0 +1,72 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.ZhipuAiClient; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * Client Configuration Example Demonstrates different configuration methods for ZaiClient + */ +public class ClientConfigurationExample { + + public static void main(String[] args) { + + System.out.println("=== Basic Configuration Example ==="); + ZaiClient basicClient = ZaiClient.builder().apiKey("xxx.xxx").build(); + System.out.println("✓ Basic client created successfully"); + + // Complete configuration example + System.out.println("\n=== Complete Configuration Example ==="); + Map customHeaders = new HashMap<>(); + customHeaders.put("Session-Id", "custom-session-id-xx"); + ZaiClient advancedClient = ZaiClient.builder() + .apiKey("your.api_key") + .baseUrl("https://api.z.ai/api/paas/v4/") + .customHeaders(customHeaders) + .enableTokenCache() + .tokenExpire(3600000) // 1 hour + .connectionPool(10, 5, TimeUnit.MINUTES) + .build(); + System.out.println("✓ Advanced client created successfully"); + + // ZHIPU platform specific client + System.out.println("\n=== ZHIPU Platform Specific Configuration ==="); + ZaiClient zhipuClient = ZaiClient.ofZHIPU("your.api_key").build(); + System.out.println("✓ ZHIPU platform client created successfully"); + + ZhipuAiClient zhipuAiClient = ZhipuAiClient.builder() + .apiKey("your.api_key") + .baseUrl("https://api.z.ai/api/paas/v4/") + .customHeaders(customHeaders) + .enableTokenCache() + .tokenExpire(3600000) // 1 hour + .connectionPool(10, 5, TimeUnit.MINUTES) + .build(); + System.out.println("✓ ZHIPU platform client created successfully"); + + // Custom configuration example + System.out.println("\n=== Custom Configuration Example ==="); + ZaiClient customClient = ZaiClient.builder() + .apiKey("your.api_key") + .baseUrl("https://custom.api.endpoint/") + .customHeaders(customHeaders) + .enableTokenCache() + .tokenExpire(7200000) + .connectionPool(20, 10, TimeUnit.MINUTES) + .build(); + System.out.println("✓ Custom client created successfully"); + + System.out.println("\n=== Configuration Description ==="); + System.out.println("1. apiKey: API key, format is 'key.secret'"); + System.out.println("2. baseUrl: API base URL"); + System.out.println("3. enableTokenCache: Enable token caching to improve performance"); + System.out.println("4. tokenExpire: Token expiration time (milliseconds)"); + System.out + .println("5. connectionPool: Connection pool configuration (max connections, keep-alive time, time unit)"); + System.out.println("\nRecommended to use environment variable ZAI_API_KEY to set API key for better security"); + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/CogVideoX3Example.java b/samples/src/main/java/ai/z/openapi/samples/CogVideoX3Example.java new file mode 100644 index 0000000..a30d981 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/CogVideoX3Example.java @@ -0,0 +1,189 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.videos.VideoCreateParams; +import ai.z.openapi.service.videos.VideoObject; +import ai.z.openapi.service.videos.VideosResponse; + +import java.util.Arrays; + +/** + * CogVideoX-3 Example Demonstrates how to use ZaiClient for advanced video generation + * with CogVideoX-3 Features: Text-to-video, Image-to-video, First-last frame generation + */ +public class CogVideoX3Example { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Or set API Key via code + // ZaiClient client = ZaiClient.builder() + // .apiKey("your.api_key") + // .build(); + + // Video generation examples + textToVideoExample(client); + imageToVideoExample(client); + firstLastFrameVideoExample(client); + client.close(); + } + + /** + * Example of text-to-video generation using CogVideoX-3 + */ + private static void textToVideoExample(ZaiClient client) { + System.out.println("=== CogVideoX-3 Text-to-Video Generation Example ==="); + + try { + VideoCreateParams request = VideoCreateParams.builder() + .model("cogvideox-3") + .prompt("A cute kitten chasing butterflies in a garden, bright sunshine, blooming flowers, clear and stable picture") + .quality("quality") // "quality" for quality priority, "speed" for speed + // priority + .withAudio(true) + .size("1920x1080") // Video resolution, supports up to 4K + .fps(30) // Frame rate, can be 30 or 60 + .build(); + + VideosResponse response = client.videos().videoGenerations(request); + + if (response.isSuccess()) { + String taskId = response.getData().getId(); + System.out.println("Video generation task submitted, Task ID: " + taskId); + System.out.println("Please wait for video generation to complete..."); + + // Wait and check result + Thread.sleep(60000); // Wait 1 minute + checkVideoResult(client, taskId); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example of image-to-video generation using CogVideoX-3 + */ + private static void imageToVideoExample(ZaiClient client) { + System.out.println("\n=== CogVideoX-3 Image-to-Video Generation Example ==="); + + try { + VideoCreateParams request = VideoCreateParams.builder() + .model("cogvideox-3") + .imageUrl("https://img.iplaysoft.com/wp-content/uploads/2019/free-images/free_stock_photo.jpg") + .prompt("Make the scene come alive, showing natural dynamic effects") + .quality("quality") + .withAudio(true) + .size("1920x1080") + .fps(30) + .build(); + + VideosResponse response = client.videos().videoGenerations(request); + + if (response.isSuccess()) { + String taskId = response.getData().getId(); + System.out.println("Image-to-video task submitted, Task ID: " + taskId); + System.out.println("Please wait for video generation to complete..."); + + // Wait and check result + Thread.sleep(60000); // Wait 1 minute + checkVideoResult(client, taskId); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example of first-last frame video generation using CogVideoX-3 This is a new + * feature in CogVideoX-3 + */ + private static void firstLastFrameVideoExample(ZaiClient client) { + System.out.println("\n=== CogVideoX-3 First-Last Frame Video Generation Example ==="); + + try { + // Define first and last frame URLs + String firstFrameUrl = "https://gd-hbimg.huaban.com/ccee58d77afe8f5e17a572246b1994f7e027657fe9e6-qD66In_fw1200webp"; + String lastFrameUrl = "https://gd-hbimg.huaban.com/cc2601d568a72d18d90b2cc7f1065b16b2d693f7fa3f7-hDAwNq_fw1200webp"; + + VideoCreateParams request = VideoCreateParams.builder() + .model("cogvideox-3") + .imageUrl(Arrays.asList(firstFrameUrl, lastFrameUrl)) // Pass first and + // last frame URLs + .prompt("Dragon King transforms into Ao Bing, ink wash style rendering, main subject slowly transforms with rotating camera movement, smooth and natural transition") + .quality("quality") + .withAudio(true) + .size("1920x1080") + .fps(30) + .build(); + + VideosResponse response = client.videos().videoGenerations(request); + + if (response.isSuccess()) { + String taskId = response.getData().getId(); + System.out.println("First-last frame video generation task submitted, Task ID: " + taskId); + System.out.println("Please wait for video generation to complete..."); + System.out.println( + "Note: First-last frame generation can create coherent transition videos, naturally connecting static frames into dynamic narratives."); + + // Wait and check result + Thread.sleep(60000); // Wait 1 minute + checkVideoResult(client, taskId); + } + else { + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Check video generation result + */ + private static void checkVideoResult(ZaiClient client, String taskId) { + try { + VideosResponse response = client.videos().videoGenerationsResult(taskId); + + if (response.isSuccess()) { + VideoObject result = response.getData(); + String status = result.getTaskStatus(); + + System.out.println("Task status: " + status); + + if ("SUCCESS".equals(status)) { + System.out.println("Video generation successful!"); + if (result.getVideoResult() != null && !result.getVideoResult().isEmpty()) { + System.out.println("Video URL: " + result.getVideoResult().get(0).getUrl()); + } + } + else if ("PROCESSING".equals(status)) { + System.out.println("Video is still being generated, please check again later..."); + } + } + else { + System.err.println("Query result error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred while querying video result: " + e.getMessage()); + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/CogVideoXExample.java b/samples/src/main/java/ai/z/openapi/samples/CogVideoXExample.java new file mode 100644 index 0000000..3270b1d --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/CogVideoXExample.java @@ -0,0 +1,85 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.videos.VideoCreateParams; +import ai.z.openapi.service.videos.VideosResponse; + +/** + * CogVideoX Example Demonstrates how to use ZaiClient to generate videos using CogVideoX + * models + */ +public class CogVideoXExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Or set API Key via code + // ZaiClient client = ZaiClient.builder() + // .apiKey("your.api_key") + // .build(); + + // Basic Video Generation + generateBasicVideo(client); + client.close(); + } + + /** + * Example of basic video generation using CogVideoX + */ + private static void generateBasicVideo(ZaiClient client) { + System.out.println("\n=== Basic CogVideoX Generation Example ==="); + + // Create video generation request + VideoCreateParams request = VideoCreateParams.builder() + .model(Constants.ModelCogVideoX) // Using CogVideoX model + .prompt("A beautiful sunset over the ocean with waves gently crashing on the shore") + .requestId("cogvideox-example-" + System.currentTimeMillis()) + .build(); + + try { + // Execute request + VideosResponse response = client.videos().videoGenerations(request); + System.out.println("Response: " + response.getData()); + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example of checking video generation result Note: You need to replace the taskId + * with a real task ID from a previous generation request + */ + private static void checkVideoResult(ZaiClient client) { + System.out.println("\n=== Check Video Generation Result Example ==="); + + // Replace with a real task ID from a previous generation request + String taskId = "your-task-id-here"; + + System.out.println("Checking result for task ID: " + taskId); + System.out.println("Note: In a real application, replace 'your-task-id-here' with an actual task ID."); + + try { + // Execute request to check result + VideosResponse response = client.videos().videoGenerationsResult(taskId); + + if (response.isSuccess()) { + System.out.println("Video generation: " + response.getData()); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/CustomClientExample.java b/samples/src/main/java/ai/z/openapi/samples/CustomClientExample.java new file mode 100644 index 0000000..8547152 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/CustomClientExample.java @@ -0,0 +1,104 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZhipuAiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.core.config.ZaiConfig; +import ai.z.openapi.service.model.ChatCompletionCreateParams; +import ai.z.openapi.service.model.ChatCompletionResponse; +import ai.z.openapi.service.model.ChatMessage; +import ai.z.openapi.service.model.ChatMessageRole; +import ai.z.openapi.service.model.ChatThinking; +import ai.z.openapi.service.model.ChatThinkingType; +import ai.z.openapi.service.model.Choice; +import ai.z.openapi.service.model.Delta; +import ai.z.openapi.service.model.ResponseFormat; +import ai.z.openapi.service.model.ResponseFormatType; + +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Chat Completion Example Demonstrates how to use ZaiClient for basic chat conversations + */ +public class CustomClientExample { + + public static void main(String[] args) throws Exception { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiConfig zaiConfig = ZaiConfig.builder() + .apiKey(System.getenv("ZAI_API_KEY")) + .baseUrl(Constants.ZHIPU_AI_BASE_URL) + .customHeaders(Collections.emptyMap()) + .disableTokenCache(true) + .readTimeout(600) + .timeOutTimeUnit(TimeUnit.SECONDS) + .connectionPoolKeepAliveDuration(10) + .connectionPoolTimeUnit(TimeUnit.SECONDS) + .connectionPoolMaxIdleConnections(20) + .build(); + + ZhipuAiClient client = new ZhipuAiClient(zaiConfig); + + // Or set API Key via code + // ZaiClient client = ZaiClient.builder() + // .apiKey("your.api_key") + // .build(); + + // Create chat request + ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() + .model("glm-5") + .messages(Arrays.asList( + ChatMessage.builder().role(ChatMessageRole.USER.value()).content("Hello, are you there").build())) + .stream(true) + .thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build()) + .responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build()) + .temperature(1.0f) + .build(); + + // Create latch to wait for streaming completion + CountDownLatch latch = new CountDownLatch(1); + + try { + // Execute request + ChatCompletionResponse response = client.chat().createChatCompletion(request); + + if (response.isSuccess() && response.getFlowable() != null) { + System.out.println("Starting streaming response..."); + response.getFlowable().subscribe(data -> { + // Process each streaming response chunk + if (data.getChoices() != null && !data.getChoices().isEmpty()) { + // Get content of current chunk + Choice choice = data.getChoices().get(0); + System.out.print(choice + "\n"); + } + }, error -> { + System.err.println("\nStream error: " + error.getMessage()); + latch.countDown(); // Release latch on error + }, + // Process streaming response completion event + () -> { + System.out.println("\nStreaming response completed"); + latch.countDown(); // Release latch on completion + }); + + // Wait for streaming to complete (max 60 seconds) + latch.await(60, TimeUnit.SECONDS); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/CustomTimeoutExample.java b/samples/src/main/java/ai/z/openapi/samples/CustomTimeoutExample.java new file mode 100644 index 0000000..d8d9e29 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/CustomTimeoutExample.java @@ -0,0 +1,63 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.ZhipuAiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.model.ChatCompletionCreateParams; +import ai.z.openapi.service.model.ChatCompletionResponse; +import ai.z.openapi.service.model.ChatMessage; +import ai.z.openapi.service.model.ChatMessageRole; +import ai.z.openapi.service.model.ChatThinking; +import ai.z.openapi.service.model.ChatThinkingType; +import ai.z.openapi.service.model.ResponseFormat; +import ai.z.openapi.service.model.ResponseFormatType; + +import java.util.Arrays; +import java.util.concurrent.TimeUnit; + +/** + * Chat Completion Example Demonstrates how to use ZaiClient for basic chat conversations + */ +public class CustomTimeoutExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().networkConfig(0, 10, 30, 30, TimeUnit.SECONDS).build(); + + // Create chat request + ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() + .model("glm-5") + .messages(Arrays.asList(ChatMessage.builder() + .role(ChatMessageRole.USER.value()) + .content("Hello, how to learn english?") + .build())) + .stream(false) + .thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build()) + .responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build()) + .build(); + + try { + // Execute request + ChatCompletionResponse response = client.chat().createChatCompletion(request); + + if (response.isSuccess()) { + Object content = response.getData().getChoices().get(0).getMessage(); + System.out.println("Response: " + content); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/EmbeddingsExample.java b/samples/src/main/java/ai/z/openapi/samples/EmbeddingsExample.java new file mode 100644 index 0000000..b0090e7 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/EmbeddingsExample.java @@ -0,0 +1,55 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.embedding.*; +import ai.z.openapi.core.Constants; +import java.util.Arrays; + +/** + * Embeddings Example Demonstrates how to use ZaiClient to generate text embeddings + */ +public class EmbeddingsExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Create embedding request + EmbeddingCreateParams request = EmbeddingCreateParams.builder() + .model(Constants.ModelEmbedding3) + .input(Arrays.asList("Hello world", "How are you?", "How is the weather today?")) + .build(); + + try { + // Execute request + EmbeddingResponse response = client.embeddings().createEmbeddings(request); + + if (response.isSuccess()) { + System.out.println("Successfully generated embeddings:"); + System.out.println("Model: " + response.getData().getModel()); + System.out.println("Usage statistics: " + response.getData().getUsage().getTotalTokens() + " tokens"); + + response.getData().getData().forEach(embedding -> { + System.out.println("\nIndex: " + embedding.getIndex()); + System.out.println("Vector dimensions: " + embedding.getEmbedding().size()); + System.out.println("Vector first 5 values: " + + embedding.getEmbedding().subList(0, Math.min(5, embedding.getEmbedding().size()))); + }); + } + else { + System.err.println("Error: Embedding generation failed: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Embedding exception: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/FileParsingExample.java b/samples/src/main/java/ai/z/openapi/samples/FileParsingExample.java new file mode 100644 index 0000000..11d1684 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/FileParsingExample.java @@ -0,0 +1,135 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.fileparsing.FileParsingDownloadReq; +import ai.z.openapi.service.fileparsing.FileParsingDownloadResponse; +import ai.z.openapi.service.fileparsing.FileParsingResponse; +import ai.z.openapi.service.fileparsing.FileParsingUploadReq; +import ai.z.openapi.utils.StringUtils; + +public class FileParsingExample { + + public static void main(String[] args) { + + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + try { + // Example 1: Create a file parsing task + System.out.println("=== Example: Create file parsing task ==="); + String filePath = "your file path"; + String taskId = createFileParsingTaskExample(client, filePath, "pdf", "lite"); + + // Example 2: Get parsing result + System.out.println("\n=== Example: Get parsing result ==="); + getFileParsingResultExample(client, taskId); + + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + + /** + * Example: Create parsing task (upload file and parse) + * @param client ZaiClient instance + * @return TaskId of the parsing task + */ + private static String createFileParsingTaskExample(ZaiClient client, String filePath, String fileType, + String toolType) { + if (StringUtils.isEmpty(filePath)) { + System.err.println("Invalid file path."); + return null; + } + try { + FileParsingUploadReq uploadReq = FileParsingUploadReq.builder() + .filePath(filePath) + .fileType(fileType) // support: pdf, docx etc. + .toolType(toolType) // tool type: lite, prime, expert + .build(); + + System.out.println("Uploading file and creating parsing task..."); + FileParsingResponse response = client.fileParsing().createParseTask(uploadReq); + if (response.isSuccess()) { + if (null != response.getData().getTaskId()) { + String taskId = response.getData().getTaskId(); + System.out.println("Parsing task created successfully, TaskId: " + taskId); + return taskId; + } + else { + System.err.println("Failed to create parsing task: " + response.getData().getMessage()); + } + } + else { + System.err.println("Failed to create parsing task: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("File parsing task error: " + e.getMessage()); + } + // Return null indicates task creation failed + return null; + } + + /** + * Example: Get parsing result + * @param client ZaiClient instance + * @param taskId ID of the parsing task + */ + private static void getFileParsingResultExample(ZaiClient client, String taskId) { + if (taskId == null || taskId.isEmpty()) { + System.err.println("Invalid task ID. Cannot get parsing result."); + return; + } + + try { + int maxRetry = 100; // Maximum 100 polling attempts + int intervalMs = 3000; // 3 seconds interval between each polling + for (int i = 0; i < maxRetry; i++) { + FileParsingDownloadReq downloadReq = FileParsingDownloadReq.builder() + .taskId(taskId) + .formatType("text") + .build(); + + FileParsingDownloadResponse response = client.fileParsing().getParseResult(downloadReq); + + if (response.isSuccess()) { + String status = response.getData().getStatus(); + System.out.println("Current task status: " + status); + + if ("succeeded".equalsIgnoreCase(status)) { + System.out.println("Parsing result obtained successfully!"); + System.out.println("Parsed content: " + response.getData().getContent()); + System.out.println("Download link: " + response.getData().getParsingResultUrl()); + return; + } + else if ("processing".equalsIgnoreCase(status)) { + System.out.println("Parsing in progress, please wait..."); + Thread.sleep(intervalMs); + } + else { + System.out.println("Parsing task exception, status: " + status + ", message: " + + response.getData().getMessage()); + return; + } + } + else { + System.err.println("Failed to get parsing result: " + response.getMsg()); + return; + } + } + System.out.println("Wait timeout, please check the parsing result later."); + } + catch (Exception e) { + System.err.println("Exception occurred while getting parsing result: " + e.getMessage()); + } + } + +} diff --git a/samples/src/main/java/ai/z/openapi/samples/FileParsingSyncExample.java b/samples/src/main/java/ai/z/openapi/samples/FileParsingSyncExample.java new file mode 100644 index 0000000..6de014f --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/FileParsingSyncExample.java @@ -0,0 +1,67 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.fileparsing.FileParsingDownloadResponse; +import ai.z.openapi.service.fileparsing.FileParsingUploadReq; +import ai.z.openapi.utils.StringUtils; + +public class FileParsingSyncExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + + // Alternatively, the API Key can be specified directly in the code + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + try { + System.out.println("=== Example: Creating file parsing task ==="); + + String filePath = "your file path"; + FileParsingDownloadResponse result = syncFileParsingTaskExample(client, filePath, "pdf", "prime-sync"); + + System.out.println("Parsing task created successfully, TaskId: " + result.getData().getTaskId()); + System.out.println("File content: " + result.getData().getContent()); + System.out.println("Download link: " + result.getData().getParsingResultUrl()); + + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + + /** + * Example: Create parsing task (upload file and parse) + * @param client ZaiClient instance + * @return Parsing task's taskId + */ + private static FileParsingDownloadResponse syncFileParsingTaskExample(ZaiClient client, String filePath, + String fileType, String toolType) { + if (StringUtils.isEmpty(filePath)) { + System.err.println("Invalid file path."); + return null; + } + try { + FileParsingUploadReq uploadReq = FileParsingUploadReq.builder() + .filePath(filePath) + .fileType(fileType) // Supported types: pdf, docx, etc. + .toolType(toolType) // Parsing tool type: lite, prime, expert + .build(); + + System.out.println("Uploading file and creating parsing task..."); + return client.fileParsing().syncParse(uploadReq); + } + catch (Exception e) { + System.err.println("File parsing task error: " + e.getMessage()); + } + // Returning null means task creation failed + return null; + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/FunctionCallingExample.java b/samples/src/main/java/ai/z/openapi/samples/FunctionCallingExample.java new file mode 100644 index 0000000..108421c --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/FunctionCallingExample.java @@ -0,0 +1,95 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.model.*; +import ai.z.openapi.core.Constants; +import java.util.*; + +public class FunctionCallingExample { + + // Simulate weather API + public static Map getWeather(String location, String date) { + Map weather = new HashMap<>(); + weather.put("location", location); + weather.put("date", date != null ? date : "today"); + weather.put("weather", "sunny"); + weather.put("temperature", "25°C"); + weather.put("humidity", "60%"); + return weather; + } + + // Simulate stock API + public static Map getStockPrice(String symbol) { + Map stock = new HashMap<>(); + stock.put("symbol", symbol); + stock.put("price", 150.25); + stock.put("change", "+2.5%"); + return stock; + } + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Define function tools + Map properties = new HashMap<>(); + ChatFunctionParameterProperty locationProperty = ChatFunctionParameterProperty.builder() + .type("string") + .description("City name, for example: Beijing") + .build(); + properties.put("location", locationProperty); + ChatFunctionParameterProperty unitProperty = ChatFunctionParameterProperty.builder() + .type("string") + .enums(Arrays.asList("celsius", "fahrenheit")) + .build(); + properties.put("unit", unitProperty); + ChatTool weatherTool = ChatTool.builder() + .type(ChatToolType.FUNCTION.value()) + .function(ChatFunction.builder() + .name("get_weather") + .description("Get weather information for a specified location") + .parameters(ChatFunctionParameters.builder().type("object").properties(properties).build()) + .build()) + .build(); + + // Create request + ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() + .model(Constants.ModelChatGLM4_5) + .messages(Collections.singletonList(ChatMessage.builder() + .role(ChatMessageRole.USER.value()) + .content("How's the weather in Beijing today?") + .build())) + .tools(Collections.singletonList(weatherTool)) + .toolChoice("auto") + .build(); + + // Send request + ChatCompletionResponse response = client.chat().createChatCompletion(request); + + if (response.isSuccess()) { + // Handle function calling + ChatMessage assistantMessage = response.getData().getChoices().get(0).getMessage(); + if (assistantMessage.getToolCalls() != null && !assistantMessage.getToolCalls().isEmpty()) { + for (ToolCalls toolCall : assistantMessage.getToolCalls()) { + String functionName = toolCall.getFunction().getName(); + + if ("get_weather".equals(functionName)) { + Map result = getWeather("Beijing", null); + System.out.println("Weather info: " + result); + } + } + } + else { + System.out.println(assistantMessage.getContent()); + } + } + else { + System.err.println("Error: " + response.getMsg()); + } + client.close(); + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/GLM41VThinkingExample.java b/samples/src/main/java/ai/z/openapi/samples/GLM41VThinkingExample.java new file mode 100644 index 0000000..91c6ee5 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/GLM41VThinkingExample.java @@ -0,0 +1,47 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.model.ChatCompletionCreateParams; +import ai.z.openapi.service.model.ChatCompletionResponse; +import ai.z.openapi.service.model.ChatMessage; +import ai.z.openapi.service.model.ChatMessageRole; +import ai.z.openapi.service.model.ImageUrl; +import ai.z.openapi.service.model.MessageContent; + +import java.util.Arrays; + +public class GLM41VThinkingExample { + + public static void main(String[] args) { + + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + ChatCompletionCreateParams request = ChatCompletionCreateParams.builder() + .model("glm-4.1v-thinking-flashx") + .messages(Arrays.asList(ChatMessage.builder() + .role(ChatMessageRole.USER.value()) + .content(Arrays.asList(MessageContent.builder().type("text").text("Describe this image").build(), + MessageContent.builder() + .type("image_url") + .imageUrl(ImageUrl.builder() + .url("https://aigc-files.bigmodel.cn/api/cogview/20250723213827da171a419b9b4906_0.png") + .build()) + .build())) + .build())) + .build(); + + ChatCompletionResponse response = client.chat().createChatCompletion(request); + + if (response.isSuccess()) { + Object reply = response.getData().getChoices().get(0).getMessage().getContent(); + System.out.println(reply); + } + else { + System.err.println("Error: " + response.getMsg()); + } + client.close(); + } + +} diff --git a/samples/src/main/java/ai/z/openapi/samples/GLMVisionExample.java b/samples/src/main/java/ai/z/openapi/samples/GLMVisionExample.java new file mode 100644 index 0000000..47c2c25 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/GLMVisionExample.java @@ -0,0 +1,55 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.model.ChatCompletionCreateParams; +import ai.z.openapi.service.model.ChatCompletionResponse; +import ai.z.openapi.service.model.ChatMessage; +import ai.z.openapi.service.model.ChatMessageRole; +import ai.z.openapi.service.model.ChatThinking; +import ai.z.openapi.service.model.ImageUrl; +import ai.z.openapi.service.model.MessageContent; + +import java.io.IOException; +import java.util.Arrays; + +/** + * Streaming Chat Example Demonstrates how to use ZaiClient for streaming chat + * conversations + */ +public class GLMVisionExample { + + public static void main(String[] args) throws IOException { + // Create client + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Create chat request + ChatCompletionCreateParams streamRequest = ChatCompletionCreateParams.builder() + .model("glm-5v-turbo") + .messages(Arrays.asList(ChatMessage.builder() + .role(ChatMessageRole.USER.value()) + .content(Arrays.asList( + MessageContent.builder() + .type("image_url") + .imageUrl( + ImageUrl.builder().url("https://cdn.bigmodel.cn/static/logo/register.png").build()) + .build(), + MessageContent.builder().type("text").text("What are the pic talk about?").build())) + .build())) + .thinking(ChatThinking.builder().type("enabled").build()) + .build(); + + ChatCompletionResponse response = client.chat().createChatCompletion(streamRequest); + + if (response.isSuccess()) { + Object content = response.getData().getChoices().get(0).getMessage(); + System.out.println("Response: " + content); + } + else { + System.err.println("Error: " + response.getMsg()); + } + client.chat(); + } + +} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/HandwritingOcrExample.java b/samples/src/main/java/ai/z/openapi/samples/HandwritingOcrExample.java similarity index 88% rename from samples/src/main/ai.z.openapi.samples/HandwritingOcrExample.java rename to samples/src/main/java/ai/z/openapi/samples/HandwritingOcrExample.java index 06cb6e7..21a84af 100644 --- a/samples/src/main/ai.z.openapi.samples/HandwritingOcrExample.java +++ b/samples/src/main/java/ai/z/openapi/samples/HandwritingOcrExample.java @@ -11,7 +11,8 @@ public class HandwritingOcrExample { public static void main(String[] args) { // Create client, recommended to set API Key via environment variable // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() // You can also set the API Key directly in the code for testing ZaiClient client = ZaiClient.builder().ofZAI().build(); @@ -20,18 +21,22 @@ public static void main(String[] args) { System.out.println("=== Handwriting OCR Example ==="); String filePath = ""; // Change to your own image path - HandwritingOcrResponse response = syncHandwritingOcrExample(client, filePath, "hand_write", "CHN_ENG", true); + HandwritingOcrResponse response = syncHandwritingOcrExample(client, filePath, "hand_write", "CHN_ENG", + true); if (response != null && response.getData() != null) { System.out.println(response.getData()); - } else { + } + else { System.out.println("Recognition failed."); } - } catch (Exception e) { + } + catch (Exception e) { System.err.println("Exception occurred: " + e.getMessage()); e.printStackTrace(); - } finally { - client.close(); - } + } + finally { + client.close(); + } } /** @@ -43,7 +48,7 @@ public static void main(String[] args) { * @return OCR response object */ private static HandwritingOcrResponse syncHandwritingOcrExample(ZaiClient client, String filePath, String toolType, - String languageType, Boolean probability) { + String languageType, Boolean probability) { if (filePath == null || filePath.trim().isEmpty()) { System.err.println("Invalid file path."); return null; @@ -64,4 +69,5 @@ private static HandwritingOcrResponse syncHandwritingOcrExample(ZaiClient client // Return null indicates failure return null; } + } \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ImageGenerationAsyncExample.java b/samples/src/main/java/ai/z/openapi/samples/ImageGenerationAsyncExample.java new file mode 100644 index 0000000..91695ab --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ImageGenerationAsyncExample.java @@ -0,0 +1,51 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.image.AsyncImageResponse; +import ai.z.openapi.service.image.CreateImageRequest; + +/** + * Images Example Demonstrates how to use ZaiClient to generate async image + */ +public class ImageGenerationAsyncExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + generateAsyncImage(client); + client.close(); + } + + private static void generateAsyncImage(ZaiClient client) { + System.out.println("\n=== Basic Images Generation Example ==="); + + // Create image generation request + CreateImageRequest request = CreateImageRequest.builder() + .model("glm-image") + .prompt("A beautiful sunset over mountains, digital art style") + .size("1024x1024") + .quality("hd") + .build(); + + try { + // Execute request + AsyncImageResponse response = client.images().createImageAsync(request); + System.out.println("Response 1: " + response.getData()); + String taskId = response.getData().getId(); + response = client.images().queryAsyncResult(taskId); + System.out.println("Response 2: " + response.getData()); + Thread.sleep(40000); + response = client.images().queryAsyncResult(taskId); + System.out.println("Response 3: " + response.getData()); + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ImageGenerationExample.java b/samples/src/main/java/ai/z/openapi/samples/ImageGenerationExample.java new file mode 100644 index 0000000..c2ff54f --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ImageGenerationExample.java @@ -0,0 +1,30 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.image.CreateImageRequest; +import ai.z.openapi.service.image.ImageResponse; + +/** + * Image Generation Example Demonstrates how to use ZaiClient to generate images + */ +public class ImageGenerationExample { + + public static void main(String[] args) { + // Create client + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Create image generation request + CreateImageRequest request = CreateImageRequest.builder() + .model(Constants.ModelCogView4250304) + .prompt("A beautiful sunset over mountains, digital art style") + .size("1024x1024") + .build(); + ImageResponse response = client.images().createImage(request); + System.out.println(response.getData()); + client.close(); + } + +} \ No newline at end of file diff --git a/samples/src/main/ai.z.openapi.samples/LayoutParsingExample.java b/samples/src/main/java/ai/z/openapi/samples/LayoutParsingExample.java similarity index 87% rename from samples/src/main/ai.z.openapi.samples/LayoutParsingExample.java rename to samples/src/main/java/ai/z/openapi/samples/LayoutParsingExample.java index 9b45d64..885b73d 100644 --- a/samples/src/main/ai.z.openapi.samples/LayoutParsingExample.java +++ b/samples/src/main/java/ai/z/openapi/samples/LayoutParsingExample.java @@ -10,7 +10,8 @@ public class LayoutParsingExample { public static void main(String[] args) { // Create client, recommended to set API Key via environment variable // export ZAI_API_KEY=your.api_key - // for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient.builder().ofZHIPU().build() + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() // You can also set the API Key directly in the code for testing ZaiClient client = ZaiClient.builder().ofZAI().build(); @@ -23,10 +24,12 @@ public static void main(String[] args) { LayoutParsingResponse response = layoutParsingExample(client, "glm-ocr", imageUrl); printResult(response); - } catch (Exception e) { + } + catch (Exception e) { System.err.println("Exception occurred: " + e.getMessage()); e.printStackTrace(); - } finally { + } + finally { client.close(); } } @@ -50,10 +53,7 @@ private static LayoutParsingResponse layoutParsingExample(ZaiClient client, Stri return null; } try { - LayoutParsingCreateParams params = LayoutParsingCreateParams.builder() - .model(model) - .file(file) - .build(); + LayoutParsingCreateParams params = LayoutParsingCreateParams.builder().model(model).file(file).build(); System.out.println("Request parameters:"); System.out.println(" model: " + model); @@ -87,15 +87,16 @@ private static void printResult(LayoutParsingResponse response) { System.out.println("Created: " + data.getCreated()); System.out.println("Model: " + data.getModel()); System.out.println("Request ID: " + data.getRequestId()); - System.out.println("Markdown results length: " + (data.getMdResults() != null ? data.getMdResults().length() : 0)); + System.out.println( + "Markdown results length: " + (data.getMdResults() != null ? data.getMdResults().length() : 0)); if (data.getLayoutDetails() != null) { System.out.println("Layout pages count: " + data.getLayoutDetails().size()); data.getLayoutDetails().stream().limit(1).forEach(page -> { System.out.println("First page blocks count: " + (page != null ? page.size() : 0)); if (page != null) { page.stream().limit(3).forEach(detail -> { - System.out.println( - " - index: " + detail.getIndex() + ", label: " + detail.getLabel() + ", bbox: " + detail.getBbox2d()); + System.out.println(" - index: " + detail.getIndex() + ", label: " + detail.getLabel() + + ", bbox: " + detail.getBbox2d()); }); } }); @@ -104,7 +105,8 @@ private static void printResult(LayoutParsingResponse response) { System.out.println("Data info:"); System.out.println(" num_pages: " + data.getDataInfo().getNumPages()); if (data.getDataInfo().getPages() != null && !data.getDataInfo().getPages().isEmpty()) { - System.out.println(" first page size: " + data.getDataInfo().getPages().get(0).getWidth() + "x" + data.getDataInfo().getPages().get(0).getHeight()); + System.out.println(" first page size: " + data.getDataInfo().getPages().get(0).getWidth() + "x" + + data.getDataInfo().getPages().get(0).getHeight()); } } if (data.getUsage() != null) { @@ -113,9 +115,11 @@ private static void printResult(LayoutParsingResponse response) { System.out.println(" completion_tokens: " + data.getUsage().getCompletionTokens()); System.out.println(" total_tokens: " + data.getUsage().getTotalTokens()); if (data.getUsage().getPromptTokensDetails() != null) { - System.out.println(" prompt_tokens_details.cached_tokens: " + data.getUsage().getPromptTokensDetails().getCachedTokens()); + System.out.println(" prompt_tokens_details.cached_tokens: " + + data.getUsage().getPromptTokensDetails().getCachedTokens()); } } } } + } diff --git a/samples/src/main/java/ai/z/openapi/samples/ModerationExample.java b/samples/src/main/java/ai/z/openapi/samples/ModerationExample.java new file mode 100644 index 0000000..ef681d7 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ModerationExample.java @@ -0,0 +1,158 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.moderations.*; + +import java.util.Arrays; +import java.util.List; + +/** + * Moderation Example Demonstrates how to use ZaiClient to moderate content for safety + */ +public class ModerationExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Example 1: Text moderation + System.out.println("=== Text Moderation Example ==="); + moderateText(client); + + // Example 2: Image moderation + System.out.println("\n=== Image Moderation Example ==="); + moderateImage(client); + client.close(); + } + + private static void moderateText(ZaiClient client) { + // Create text moderation inputs + List inputs = Arrays + .asList(ModerationInput.text("This is a normal message about technology.")); + + // Create moderation request + ModerationCreateParams request = ModerationCreateParams.builder().model("moderation").input(inputs).build(); + + try { + // Execute request + ModerationResponse response = client.moderations().createModeration(request); + + if (response.isSuccess()) { + System.out.println("Text moderation completed successfully:"); + System.out.println("Request ID: " + response.getData().getRequestId()); + + response.getData().getResultList().forEach(item -> { + System.out.println("\nContent Type: " + item.getContentType()); + System.out.println("Risk Level: " + item.getRiskLevel()); + System.out.println("Risk Type: " + item.getRiskType()); + System.out.println("Is Safe: " + item.isSafe()); + System.out.println("Is Flagged: " + item.isFlagged()); + }); + } + else { + System.err.println("Error: Text moderation failed: " + response.getMsg()); + if (response.getError() != null) { + System.err.println("Error details: " + response.getError().getMessage()); + } + } + } + catch (Exception e) { + System.err.println("Text moderation exception: " + e.getMessage()); + e.printStackTrace(); + } + } + + private static void moderateImage(ZaiClient client) { + // Create image moderation input + List inputs = Arrays.asList(ModerationInput.image("https://example.com/sample-image.jpg"), + ModerationInput.image("https://example.com/another-image.png")); + + // Create moderation request + ModerationCreateParams request = ModerationCreateParams.builder().model("moderation").input(inputs).build(); + + try { + // Execute request + ModerationResponse response = client.moderations().createModeration(request); + + if (response.isSuccess()) { + System.out.println("Image moderation completed successfully:"); + System.out.println("Request ID: " + response.getData().getRequestId()); + + response.getData().getResultList().forEach(item -> { + System.out.println("\nContent Type: " + item.getContentType()); + System.out.println("Risk Level: " + item.getRiskLevel()); + System.out.println("Status: " + (item.isSafe() ? "SAFE" : "FLAGGED")); + if (item.getRiskType() != null) { + System.out.println("Risk Type: " + item.getRiskType()); + } + }); + } + else { + System.err.println("Error: Image moderation failed: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Image moderation exception: " + e.getMessage()); + e.printStackTrace(); + } + } + + private static void moderateMixedContent(ZaiClient client) { + // Create mixed content moderation inputs + List inputs = Arrays.asList(ModerationInput.text("This is a text message to be moderated."), + ModerationInput.image("https://example.com/image-to-check.jpg"), + ModerationInput.video("https://example.com/video-sample.mp4"), + ModerationInput.audio("https://example.com/audio-sample.mp3")); + + // Create moderation request + ModerationCreateParams request = ModerationCreateParams.builder().model("moderation").input(inputs).build(); + + try { + // Execute request + ModerationResponse response = client.moderations().createModeration(request); + + if (response.isSuccess()) { + System.out.println("Mixed content moderation completed successfully:"); + System.out.println("Total items processed: " + response.getData().getResultList().size()); + + response.getData().getResultList().forEach(item -> { + System.out.println("\n--- Moderation Result ---"); + System.out.println("Content Type: " + item.getContentType()); + System.out.println("Risk Assessment: " + item.getRiskLevel()); + System.out.println("Safety Status: " + (item.isSafe() ? "✓ SAFE" : "⚠ FLAGGED")); + + if (item.isFlagged()) { + System.out.println("Risk Category: " + item.getRiskType()); + } + }); + + // Summary statistics + long safeCount = response.getData() + .getResultList() + .stream() + .mapToLong(item -> item.isSafe() ? 1 : 0) + .sum(); + long flaggedCount = response.getData().getResultList().size() - safeCount; + + System.out.println("\n--- Summary ---"); + System.out.println("Safe items: " + safeCount); + System.out.println("Flagged items: " + flaggedCount); + + if (response.getData().getUsage() != null) { + System.out.println("Total tokens used: " + response.getData().getUsage().getModerationText()); + } + } + else { + System.err.println("Error: Mixed content moderation failed: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Mixed content moderation exception: " + e.getMessage()); + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ViduAspectVideoExample.java b/samples/src/main/java/ai/z/openapi/samples/ViduAspectVideoExample.java new file mode 100644 index 0000000..2cd63f1 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ViduAspectVideoExample.java @@ -0,0 +1,76 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.videos.VideoCreateParams; +import ai.z.openapi.service.videos.VideosResponse; + +import java.util.Arrays; + +/** + * Vidu Image-to-Video Example Demonstrates how to use ZaiClient to generate videos from + * images using Vidu models + */ +public class ViduAspectVideoExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + generateVideoStartEnd(client); + client.close(); + } + + private static void generateVideoStartEnd(ZaiClient client) { + + try { + // Create video generation request + VideoCreateParams request = VideoCreateParams.builder() + .model(Constants.ModelVidu2Reference) // Using Vidu 2 Image model + .prompt("An astronaut floating in space with Earth visible in the background, anime style") + .imageUrl(Arrays + .asList("https://aigc-files.bigmodel.cn/api/cogview/20250723213827da171a419b9b4906_0.png")) + .duration(4) + .size("1280x720") + .withAudio(true) + .movementAmplitude("auto") + .aspectRatio("16:9") + .build(); + + VideosResponse response = client.videos().videoGenerations(request); + System.out.println("Task " + response.getData()); + + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example of checking video generation result Note: You need to replace the taskId + * with a real task ID from a previous generation request + */ + private static void checkVideoResult(ZaiClient client, String taskId) { + System.out.println("\n=== Check Video Generation Result Example ==="); + try { + VideosResponse response = client.videos().videoGenerationsResult(taskId); + + if (response.isSuccess()) { + System.out.println("Video generation: " + response.getData()); + + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ViduImageToVideoExample.java b/samples/src/main/java/ai/z/openapi/samples/ViduImageToVideoExample.java new file mode 100644 index 0000000..62976c0 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ViduImageToVideoExample.java @@ -0,0 +1,89 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.videos.VideoCreateParams; +import ai.z.openapi.service.videos.VideosResponse; + +/** + * Vidu Image-to-Video Example Demonstrates how to use ZaiClient to generate videos from + * images using Vidu models + */ +public class ViduImageToVideoExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + generateVideoFromImage(client); + client.close(); + } + + /** + * Example of generating video from an image using Vidu Note: You need to provide a + * valid image file path + */ + private static void generateVideoFromImage(ZaiClient client) { + System.out.println("\n=== Vidu Image-to-Video Generation Example ==="); + + // Path to your image file + // In a real application, replace with an actual image path + + try { + // Create video generation request + VideoCreateParams request = VideoCreateParams.builder() + .model(Constants.ModelVidu2Image) // Using Vidu 2 Image model + .prompt("Transform this image into a dynamic scene with gentle movement") + .imageUrl("https://aigc-files.bigmodel.cn/api/cogview/20250723213827da171a419b9b4906_0.png") // Base64 + // encoded + // image + .duration(4) // 5 seconds duration + .size("1280x720") + .withAudio(true) + .movementAmplitude("auto") + .build(); + + VideosResponse response = client.videos().videoGenerations(request); + System.out.println("Task " + response.getData()); + + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example of checking video generation result Note: You need to replace the taskId + * with a real task ID from a previous generation request + */ + private static void checkVideoResult(ZaiClient client) { + System.out.println("\n=== Check Video Generation Result Example ==="); + + // Replace with a real task ID from a previous generation request + String taskId = "your-task-id-here"; + + System.out.println("Checking result for task ID: " + taskId); + System.out.println("Note: In a real application, replace 'your-task-id-here' with an actual task ID."); + + try { + VideosResponse response = client.videos().videoGenerationsResult(taskId); + + if (response.isSuccess()) { + System.out.println("Video generation: " + response.getData()); + + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ViduStartEndVideoExample.java b/samples/src/main/java/ai/z/openapi/samples/ViduStartEndVideoExample.java new file mode 100644 index 0000000..c396a45 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ViduStartEndVideoExample.java @@ -0,0 +1,81 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.videos.VideoCreateParams; +import ai.z.openapi.service.videos.VideosResponse; + +import java.util.Arrays; + +/** + * Vidu Image-to-Video Example Demonstrates how to use ZaiClient to generate videos from + * images using Vidu models + */ +public class ViduStartEndVideoExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + generateVideoStartEnd(client); + client.close(); + } + + /** + * Example of generating video from an image using Vidu Note: You need to provide a + * valid image file path + */ + private static void generateVideoStartEnd(ZaiClient client) { + System.out.println("\n=== Vidu Image-to-Video Generation Example ==="); + + try { + // Create video generation request + VideoCreateParams request = VideoCreateParams.builder() + .model(Constants.ModelViduQ1StartEnd) // Using Vidu 2 Image model + .prompt("An astronaut floating in space with Earth visible in the background, anime style") + .imageUrl( + Arrays.asList("https://aigc-files.bigmodel.cn/api/cogview/20250723213827da171a419b9b4906_0.png", + "https://aigc-files.bigmodel.cn/api/cogview/20250723213827da171a419b9b4906_0.png")) + .duration(5) // 5 seconds duration + .size("1920x1080") + .withAudio(true) + .movementAmplitude("auto") + .build(); + + VideosResponse response = client.videos().videoGenerations(request); + System.out.println("Task " + response.getData()); + + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example of checking video generation result Note: You need to replace the taskId + * with a real task ID from a previous generation request + */ + private static void checkVideoResult(ZaiClient client, String taskId) { + System.out.println("\n=== Check Video Generation Result Example ==="); + try { + VideosResponse response = client.videos().videoGenerationsResult(taskId); + + if (response.isSuccess()) { + System.out.println("Video generation: " + response.getData()); + + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/ViduTextToVideoExample.java b/samples/src/main/java/ai/z/openapi/samples/ViduTextToVideoExample.java new file mode 100644 index 0000000..bfde6c2 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/ViduTextToVideoExample.java @@ -0,0 +1,130 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.core.Constants; +import ai.z.openapi.service.videos.VideoCreateParams; +import ai.z.openapi.service.videos.VideosResponse; + +/** + * Vidu Text-to-Video Example Demonstrates how to use ZaiClient to generate videos from + * text using Vidu models + */ +public class ViduTextToVideoExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Or set API Key via code + // ZaiClient client = ZaiClient.builder() + // .apiKey("your.api_key") + // .build(); + + // Example: Generate video from text using Vidu + generateVideoFromText(client); + client.close(); + } + + /** + * Example of generating video from text using Vidu + */ + private static void generateVideoFromText(ZaiClient client) { + System.out.println("\n=== Vidu Text-to-Video Generation Example ==="); + + // Create video generation request + VideoCreateParams request = VideoCreateParams.builder() + .model(Constants.ModelViduQ1Text) // Using Vidu Q1 Text model + .prompt("A person walking through a beautiful forest with sunlight filtering through the trees") + .requestId("vidu-text-example-" + System.currentTimeMillis()) + .duration(5) + .size("1920x1080") + .build(); + + try { + // Execute request + VideosResponse response = client.videos().videoGenerations(request); + System.out.println("Data: " + response.getData()); + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example of generating video from text with custom settings + */ + private static void generateVideoFromTextWithCustomSettings(ZaiClient client) { + System.out.println("\n=== Vidu Text-to-Video with Custom Settings Example ==="); + + // Create video generation request with custom settings + VideoCreateParams request = VideoCreateParams.builder() + .model(Constants.ModelViduQ1Text) // Using Vidu Q1 Text model + .prompt("An astronaut floating in space with Earth visible in the background, anime style") + .requestId("vidu-text-custom-example-" + System.currentTimeMillis()) + .quality("high") // High quality setting + .withAudio(true) // Generate with audio + .duration(5) + .size("1920x1080") + .fps(30) // 30 frames per second + .build(); + + try { + // Execute request + VideosResponse response = client.videos().videoGenerations(request); + + if (response.isSuccess()) { + System.out.println("Custom video generation request successful!"); + System.out.println("Task ID: " + response.getData().getId()); + System.out.println("Data: " + response.getData()); + System.out.println("\nNote: Video generation is an asynchronous process."); + System.out.println("Use the Task ID to check the status and retrieve the result later."); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example of checking video generation result Note: You need to replace the taskId + * with a real task ID from a previous generation request + */ + private static void checkVideoResult(ZaiClient client) { + System.out.println("\n=== Check Video Generation Result Example ==="); + + // Replace with a real task ID from a previous generation request + String taskId = "your-task-id-here"; + + System.out.println("Checking result for task ID: " + taskId); + System.out.println("Note: In a real application, replace 'your-task-id-here' with an actual task ID."); + + try { + // Skip the actual API call in this example to avoid errors with a fake task + // ID + if (!taskId.equals("your-task-id-here")) { + // Execute request to check result + VideosResponse response = client.videos().videoGenerationsResult(taskId); + + if (response.isSuccess()) { + System.out.println("Video generation: " + response.getData()); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/VoiceCloneExample.java b/samples/src/main/java/ai/z/openapi/samples/VoiceCloneExample.java new file mode 100644 index 0000000..059d52b --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/VoiceCloneExample.java @@ -0,0 +1,189 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.file.FileApiResponse; +import ai.z.openapi.service.file.FileService; +import ai.z.openapi.service.file.FileUploadParams; +import ai.z.openapi.service.file.UploadFilePurpose; +import ai.z.openapi.service.voiceclone.*; + +import java.nio.file.Paths; + +/** + * Voice Clone Example Demonstrates how to use ZaiClient for voice cloning operations + * including: - Uploading voice samples - Creating voice clones - Listing existing voices + * - Deleting voice clones + */ +public class VoiceCloneExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Or set API Key via code + // ZaiClient client = ZaiClient.builder() + // .apiKey("your.api_key") + // .build(); + + VoiceCloneService voiceCloneService = client.voiceClone(); + FileService fileService = client.files(); + + try { + // Example 1: Create a voice clone + System.out.println("=== Voice Clone Creation Example ==="); + createVoiceCloneExample(voiceCloneService, fileService); + + // Example 2: List existing voices + System.out.println("\n=== Voice List Example ==="); + listVoicesExample(voiceCloneService); + + // Example 3: Delete a voice clone + System.out.println("\n=== Voice Deletion Example ==="); + deleteVoiceExample(voiceCloneService); + + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + + /** + * Example of creating a voice clone with file upload + */ + private static void createVoiceCloneExample(VoiceCloneService voiceCloneService, FileService fileService) { + try { + // Step 1: Upload the voice input audio file + String voiceInputFilePath = Paths.get("samples", "resources", "voice_clone_input.mp3").toString(); + + FileUploadParams uploadRequest = FileUploadParams.builder() + .filePath(voiceInputFilePath) + .purpose(UploadFilePurpose.VOICE_CLONE_INPUT.value()) + .requestId("voice-clone-example-" + System.currentTimeMillis()) + .build(); + + System.out.println("Uploading voice input file..."); + FileApiResponse uploadResponse = fileService.uploadFile(uploadRequest); + + if (uploadResponse.isSuccess()) { + String fileId = uploadResponse.getData().getId(); + System.out.println("Voice input file uploaded successfully with ID: " + fileId); + + // Step 2: Create voice clone using the uploaded file + VoiceCloneRequest request = new VoiceCloneRequest(); + request.setVoiceName("My Custom Voice"); + request.setText("Hello, this is a sample text for voice cloning training"); + request.setInput("Welcome to our voice synthesis system"); + request.setFileId(fileId); + request.setRequestId("clone-request-" + System.currentTimeMillis()); + request.setModel("CogTTS-clone"); + + System.out.println("Creating voice clone..."); + VoiceCloneResponse response = voiceCloneService.cloneVoice(request); + + if (response.isSuccess()) { + System.out.println("Voice clone created successfully!"); + System.out.println("Voice: " + response.getData().getVoice()); + } + else { + System.err.println("Voice clone creation failed: " + response.getMsg()); + if (response.getError() != null) { + System.err.println("Error details: " + response.getError().getMessage()); + } + } + } + else { + System.err.println("File upload failed: " + uploadResponse.getMsg()); + } + } + catch (Exception e) { + System.err.println("Error in voice clone creation: " + e.getMessage()); + } + } + + /** + * Example of listing existing voice clones + */ + private static void listVoicesExample(VoiceCloneService voiceCloneService) { + try { + // List all private voices + VoiceListRequest request = new VoiceListRequest(); + request.setVoiceType("PRIVATE"); // Filter for custom voice clones + request.setRequestId("list-request-" + System.currentTimeMillis()); + + System.out.println("Retrieving voice list..."); + VoiceListResponse response = voiceCloneService.listVoice(request); + + if (response.isSuccess()) { + System.out.println("Voice list retrieved successfully!"); + if (response.getData().getVoiceList() != null && !response.getData().getVoiceList().isEmpty()) { + System.out.println("Found " + response.getData().getVoiceList().size() + " voices:"); + for (VoiceData voice : response.getData().getVoiceList()) { + System.out.println("- Voice: " + voice.getVoice()); + System.out.println(" Name: " + voice.getVoiceName()); + System.out.println(" Type: " + voice.getVoiceType()); + if (voice.getDownloadUrl() != null) { + System.out.println(" Download URL: " + voice.getDownloadUrl()); + } + if (voice.getCreateTime() != null) { + System.out.println(" Created: " + voice.getCreateTime()); + } + System.out.println(); + } + } + else { + System.out.println("No voices found."); + } + } + else { + System.err.println("Voice list retrieval failed: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Error in voice list retrieval: " + e.getMessage()); + } + } + + /** + * Example of deleting a voice clone Note: Replace "your-voice" with an actual voice + * from your account + */ + private static void deleteVoiceExample(VoiceCloneService voiceCloneService) { + try { + // Note: This is just an example - replace with actual voice + String voiceToDelete = "your-voice-here"; + + VoiceDeleteRequest request = new VoiceDeleteRequest(); + request.setVoice(voiceToDelete); + request.setRequestId("delete-request-" + System.currentTimeMillis()); + + System.out.println("Deleting voice: " + voiceToDelete); + VoiceDeleteResponse response = voiceCloneService.deleteVoice(request); + + if (response.isSuccess()) { + System.out.println("Voice clone deleted successfully!"); + if (response.getData().getUpdateTime() != null) { + System.out.println("Deletion time: " + response.getData().getUpdateTime()); + } + } + else { + System.err.println("Voice deletion failed: " + response.getMsg()); + if (response.getError() != null) { + System.err.println("Error details: " + response.getError().getMessage()); + } + } + } + catch (Exception e) { + // Expected to fail with example voice + System.out.println("Note: This example uses a placeholder voice and is expected to fail."); + System.out.println("Replace 'your-voice-here' with an actual voice to test deletion."); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/WebReaderExample.java b/samples/src/main/java/ai/z/openapi/samples/WebReaderExample.java new file mode 100644 index 0000000..9e335d6 --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/WebReaderExample.java @@ -0,0 +1,85 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.web_reader.WebReaderRequest; +import ai.z.openapi.service.web_reader.WebReaderResponse; +import ai.z.openapi.service.web_reader.WebReaderResult; + +/** + * Web Reader Example Demonstrates how to use ZaiClient for web page reading and parsing + * capabilities + */ +public class WebReaderExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + basicWebReader(client); + } + + /** + * Example of basic web reader functionality + */ + private static void basicWebReader(ZaiClient client) { + System.out.println("\n=== Web Reader Example ==="); + + // Create web reader request + WebReaderRequest request = WebReaderRequest.builder() + .url("https://example.com/") + .returnFormat("markdown") + .withImagesSummary(Boolean.TRUE) + .withLinksSummary(Boolean.TRUE) + .build(); + + try { + // Execute request + WebReaderResponse response = client.webReader().createWebReader(request); + + if (response.isSuccess()) { + System.out.println("Read successful!"); + + WebReaderResult result = response.getData(); + if (result != null && result.getReaderResult() != null) { + WebReaderResult.ReaderData data = result.getReaderResult(); + System.out.println("Title: " + data.getTitle()); + System.out.println("URL: " + data.getUrl()); + System.out.println("Description: " + data.getDescription()); + + String content = data.getContent(); + if (content != null) { + String preview = content.length() > 300 ? content.substring(0, 300) + "..." : content; + System.out.println("\nContent preview:\n" + preview); + } + + if (data.getImages() != null) { + System.out.println("\nImages count: " + data.getImages().size()); + } + if (data.getLinks() != null) { + System.out.println("Links count: " + data.getLinks().size()); + } + } + else { + System.out.println("No reader result returned."); + } + } + else { + System.err.println("Error: " + response.getMsg()); + if (response.getError() != null) { + System.err.println("Error detail: " + response.getError()); + } + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + finally { + client.close(); + } + } + +} \ No newline at end of file diff --git a/samples/src/main/java/ai/z/openapi/samples/WebSearchExample.java b/samples/src/main/java/ai/z/openapi/samples/WebSearchExample.java new file mode 100644 index 0000000..262470d --- /dev/null +++ b/samples/src/main/java/ai/z/openapi/samples/WebSearchExample.java @@ -0,0 +1,180 @@ +package ai.z.openapi.samples; + +import ai.z.openapi.ZaiClient; +import ai.z.openapi.service.model.ChatMessageRole; +import ai.z.openapi.service.tools.ChoiceDelta; +import ai.z.openapi.service.tools.SearchChatMessage; +import ai.z.openapi.service.tools.WebSearchApiResponse; +import ai.z.openapi.service.tools.WebSearchMessage; +import ai.z.openapi.service.tools.WebSearchParamsRequest; +import ai.z.openapi.service.web_search.WebSearchRequest; +import ai.z.openapi.service.web_search.WebSearchResponse; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Web Search Example Demonstrates how to use ZaiClient for web search capabilities + */ +public class WebSearchExample { + + public static void main(String[] args) { + // Create client, recommended to set API Key via environment variable + // export ZAI_API_KEY=your.api_key + // for Z.ai use the `ZaiClient`, for Zhipu AI use the + // ZhipuAiClient.builder().ofZHIPU().build() + ZaiClient client = ZaiClient.builder().ofZAI().build(); + + // Or set API Key via code + // ZaiClient client = ZaiClient.builder() + // .apiKey("your.api_key") + // .build(); + + // Example 1: Basic Web Search + basicWebSearch(client); + client.close(); + } + + /** + * Example of basic web search functionality + */ + private static void basicWebSearch(ZaiClient client) { + System.out.println("\n=== Basic Web Search Example ==="); + + // Create web search request + WebSearchRequest request = WebSearchRequest.builder() + .searchEngine("search_std") + .searchQuery("latest AI technology trends") + .count(3) // Number of results to return + .searchRecencyFilter("oneYear") // Filter for results within the last year + .contentSize("high") // Request detailed content + .requestId("web-search-example-" + System.currentTimeMillis()) + .build(); + + try { + // Execute request + WebSearchResponse response = client.webSearch().createWebSearch(request); + + if (response.isSuccess()) { + System.out.println("Search successful!"); + System.out.println("Number of results: " + response.getData().getWebSearchResp().size()); + + // Display search results + response.getData().getWebSearchResp().forEach(result -> { + System.out.println("\nTitle: " + result.getTitle()); + System.out.println("Result: " + result); + }); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example of web search pro functionality (non-streaming) + */ + private static void webSearchPro(ZaiClient client) { + System.out.println("\n=== Web Search Pro Example ==="); + + // Create messages for the search + List messages = new ArrayList<>(); + SearchChatMessage userMessage = new SearchChatMessage(ChatMessageRole.USER.value(), + "What are the latest developments in quantum computing?"); + messages.add(userMessage); + + // Create web search pro request + WebSearchParamsRequest request = WebSearchParamsRequest.builder() + .model("web-search-pro") + .stream(false) // Non-streaming mode + .messages(messages) + .requestId("web-search-pro-example-" + System.currentTimeMillis()) + .build(); + + try { + // Execute request + WebSearchApiResponse response = client.webSearch().createWebSearchPro(request); + + if (response.isSuccess()) { + System.out.println("Search successful!"); + + // Display search result + WebSearchMessage content = response.getData().getChoices().get(0).getMessage(); + System.out.println("\nResponse: " + content); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + + /** + * Example of web search pro with streaming functionality + */ + private static void webSearchProStream(ZaiClient client) { + System.out.println("\n=== Web Search Pro Streaming Example ==="); + + // Create messages for the search + List messages = new ArrayList<>(); + SearchChatMessage userMessage = new SearchChatMessage(ChatMessageRole.USER.value(), + "What are the recent advancements in renewable energy?"); + messages.add(userMessage); + + // Create web search pro streaming request + WebSearchParamsRequest request = WebSearchParamsRequest.builder() + .model("web-search-pro") + .stream(true) // Enable streaming + .messages(messages) + .requestId("web-search-pro-stream-example-" + System.currentTimeMillis()) + .build(); + + try { + // Execute streaming request + WebSearchApiResponse response = client.webSearch().createWebSearchProStream(request); + + if (response.isSuccess() && response.getFlowable() != null) { + System.out.println("Streaming search started..."); + + // Track streaming progress + AtomicInteger messageCount = new AtomicInteger(0); + AtomicBoolean isFirst = new AtomicBoolean(true); + StringBuilder fullContent = new StringBuilder(); + + // Subscribe to the stream + response.getFlowable().doOnNext(webSearchPro -> { + if (isFirst.getAndSet(false)) { + System.out.println("Receiving stream response:"); + } + + if (webSearchPro.getChoices() != null && !webSearchPro.getChoices().isEmpty()) { + ChoiceDelta content = webSearchPro.getChoices().get(0).getDelta(); + System.out.print(content); + fullContent.append(content); + messageCount.incrementAndGet(); + } + }).doOnComplete(() -> { + System.out.println("\n\nStream completed. Received " + messageCount.get() + " chunks."); + System.out.println("Full response length: " + fullContent.length() + " characters"); + }).blockingSubscribe(); + } + else { + System.err.println("Error: " + response.getMsg()); + } + } + catch (Exception e) { + System.err.println("Exception occurred: " + e.getMessage()); + e.printStackTrace(); + } + } + +} \ No newline at end of file