Skip to content

Commit 8f5f986

Browse files
authored
chore: remove the client params apiId and apiSecret, fix cache token bug (#58)
1 parent a3cfd23 commit 8f5f986

File tree

8 files changed

+204
-57
lines changed

8 files changed

+204
-57
lines changed

core/src/main/java/ai/z/openapi/core/config/ZaiConfig.java

Lines changed: 4 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -54,16 +54,6 @@ public class ZaiConfig {
5454
*/
5555
private String apiKey;
5656

57-
/**
58-
* API id component.
59-
*/
60-
private String apiId;
61-
62-
/**
63-
* API secret component.
64-
*/
65-
private String apiSecret;
66-
6757
/**
6858
* Custom Http Request Headers
6959
*/
@@ -84,7 +74,8 @@ public class ZaiConfig {
8474
/**
8575
* Flag to disable token caching.
8676
*/
87-
private boolean disableTokenCache;
77+
@Builder.Default
78+
private boolean disableTokenCache = true;
8879

8980
/**
9081
* Maximum number of idle connections in the connection pool.
@@ -96,7 +87,7 @@ public class ZaiConfig {
9687
* Keep alive duration for connections in the pool (in seconds).
9788
*/
9889
@Builder.Default
99-
private long connectionPoolKeepAliveDuration = 1;
90+
private long connectionPoolKeepAliveDuration = 10;
10091

10192
/**
10293
* Time unit for connection pool keep alive duration.
@@ -149,10 +140,8 @@ public ZaiConfig(String apiKey) {
149140
this.apiKey = apiKey;
150141
String[] arrStr = apiKey.split("\\.");
151142
if (arrStr.length != 2) {
152-
throw new RuntimeException("invalid apiSecretKey");
143+
throw new RuntimeException("invalid api Key");
153144
}
154-
this.apiId = arrStr[0];
155-
this.apiSecret = arrStr[1];
156145
}
157146

158147
/**
@@ -166,8 +155,6 @@ public void setApiKey(String apiKey) {
166155
if (arrStr.length != 2) {
167156
throw new RuntimeException("invalid api Key");
168157
}
169-
this.apiId = arrStr[0];
170-
this.apiSecret = arrStr[1];
171158
}
172159

173160
/**
@@ -194,38 +181,10 @@ public String getApiKey() {
194181
if (value != null && !value.isEmpty()) {
195182
// Parse value and set components
196183
this.apiKey = value;
197-
String[] arrStr = value.split("\\.");
198-
if (arrStr.length == 2) {
199-
this.apiId = arrStr[0];
200-
this.apiSecret = arrStr[1];
201-
}
202-
return value;
203184
}
204185
return apiKey;
205186
}
206187

207-
/**
208-
* Gets API key with system property and environment variable fallback.
209-
*/
210-
public String getApiId() {
211-
if (apiId != null && !apiId.isEmpty()) {
212-
return apiId;
213-
}
214-
getApiKey();
215-
return apiId;
216-
}
217-
218-
/**
219-
* Gets API secret with system property and environment variable fallback.
220-
*/
221-
public String getApiSecret() {
222-
if (apiSecret != null && !apiSecret.isEmpty()) {
223-
return apiSecret;
224-
}
225-
getApiKey();
226-
return apiSecret;
227-
}
228-
229188
/**
230189
* Gets expire millis with system property and environment variable fallback.
231190
*/

core/src/main/java/ai/z/openapi/core/token/TokenManager.java

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,12 @@ public TokenManager(ICache cache) {
4444
* @return valid JWT token
4545
*/
4646
public String getToken(ZaiConfig config) {
47-
String tokenCacheKey = genTokenCacheKey(config.getApiId());
47+
String[] arrStr = config.getApiKey().split("\\.");
48+
if (arrStr.length != 2) {
49+
throw new RuntimeException("invalid api Key");
50+
}
51+
String appId = arrStr[0];
52+
String tokenCacheKey = genTokenCacheKey(appId);
4853
String cacheToken = cache.get(tokenCacheKey);
4954
if (StringUtils.isNotEmpty(cacheToken)) {
5055
return cacheToken;
@@ -62,9 +67,15 @@ public String getToken(ZaiConfig config) {
6267
private static String createJwt(ZaiConfig config) {
6368
Algorithm alg;
6469
String algId = config.getAlg();
70+
String[] arrStr = config.getApiKey().split("\\.");
71+
if (arrStr.length != 2) {
72+
throw new RuntimeException("invalid api Key");
73+
}
74+
String appId = arrStr[0];
75+
String apiSecret = arrStr[1];
6576
if ("HS256".equals(algId)) {
6677
try {
67-
alg = Algorithm.HMAC256(config.getApiSecret().getBytes(StandardCharsets.UTF_8));
78+
alg = Algorithm.HMAC256(apiSecret.getBytes(StandardCharsets.UTF_8));
6879
}
6980
catch (Exception e) {
7081
logger.error("Failed to create HMAC256 algorithm", e);
@@ -79,7 +90,7 @@ private static String createJwt(ZaiConfig config) {
7990

8091
Map<String, Object> payload = new HashMap<>();
8192
// here the api_key is the apiId
82-
payload.put("api_key", config.getApiId());
93+
payload.put("api_key", appId);
8394
payload.put("exp", System.currentTimeMillis() + config.getExpireMillis() + DELAY_EXPIRE_TIME);
8495
payload.put("timestamp", Calendar.getInstance().getTimeInMillis());
8596
Map<String, Object> headerClaims = new HashMap<>();

samples/src/main/ai.z.openapi.samples/ChatAsyncCompletionExample.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,7 @@ public static void main(String[] args) {
3838
.build()
3939
))
4040
.stream(false)
41-
.temperature(0.7f)
42-
.maxTokens(1024)
41+
.temperature(1.0f)
4342
.build();
4443

4544
try {

samples/src/main/ai.z.openapi.samples/ChatCompletionExample.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,7 @@ public static void main(String[] args) {
3535
.stream(false)
3636
.thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build())
3737
.responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build())
38-
.temperature(0.7f)
39-
.maxTokens(1024)
38+
.temperature(1.0f)
4039
.build();
4140

4241
try {

samples/src/main/ai.z.openapi.samples/ChatCompletionWithCustomHeadersExample.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,6 @@ public static void main(String[] args) {
3030
.build()
3131
))
3232
.stream(true) // Enable streaming for custom headers support
33-
.temperature(0.7f)
34-
.maxTokens(1024)
3533
.build();
3634

3735
// Create custom headers
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package ai.z.openapi.samples;
2+
3+
import ai.z.openapi.ZhipuAiClient;
4+
import ai.z.openapi.service.model.ChatCompletionCreateParams;
5+
import ai.z.openapi.service.model.ChatCompletionResponse;
6+
import ai.z.openapi.service.model.ChatMessage;
7+
import ai.z.openapi.service.model.ChatMessageRole;
8+
import ai.z.openapi.service.model.ChatThinking;
9+
import ai.z.openapi.service.model.ChatThinkingType;
10+
import ai.z.openapi.service.model.ChatTool;
11+
import ai.z.openapi.service.model.ChatToolType;
12+
import ai.z.openapi.service.model.MCPTool;
13+
import ai.z.openapi.service.model.ResponseFormat;
14+
import ai.z.openapi.service.model.ResponseFormatType;
15+
16+
import java.util.Collections;
17+
18+
/**
19+
* Chat Completion Example
20+
* Demonstrates how to use ZaiClient for basic chat conversations
21+
*/
22+
public class ChatCompletionWithMcpServerUrlExample {
23+
24+
public static void main(String[] args) {
25+
// Create client, recommended to set API Key via environment variable
26+
// export ZAI_API_KEY=your.api_key
27+
// for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient
28+
ZhipuAiClient client = ZhipuAiClient.builder().build();
29+
30+
// Or set API Key via code
31+
// ZaiClient client = ZaiClient.builder()
32+
// .apiKey("your.api_key")
33+
// .build();
34+
35+
// Create chat request
36+
ChatCompletionCreateParams request = ChatCompletionCreateParams.builder()
37+
.model("glm-4.6")
38+
.messages(Collections.singletonList(
39+
ChatMessage.builder()
40+
.role(ChatMessageRole.USER.value())
41+
.content("Hello, how to learn english?")
42+
.build()
43+
))
44+
.stream(false)
45+
.thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build())
46+
.responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build())
47+
.temperature(1.0f)
48+
.maxTokens(1024)
49+
.tools(Collections.singletonList(ChatTool.builder()
50+
.type(ChatToolType.MCP.value())
51+
.mcp(MCPTool.builder()
52+
.server_url("https://open.bigmodel.cn/api/mcp-broker/proxy/sogou-baike/sse")
53+
.server_label("sogou-baike")
54+
.transport_type("sse")
55+
.headers(Collections.singletonMap("Authorization", "Bearer " + System.getProperty("ZAI_API_KEY")))
56+
.build())
57+
.build()))
58+
.build();
59+
60+
try {
61+
// Execute request
62+
ChatCompletionResponse response = client.chat().createChatCompletion(request);
63+
64+
if (response.isSuccess()) {
65+
Object content = response.getData().getChoices().get(0).getMessage();
66+
System.out.println("Response: " + content);
67+
} else {
68+
System.err.println("Error: " + response.getMsg());
69+
}
70+
} catch (Exception e) {
71+
System.err.println("Exception occurred: " + e.getMessage());
72+
e.printStackTrace();
73+
}
74+
}
75+
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
package ai.z.openapi.samples;
2+
3+
import ai.z.openapi.ZhipuAiClient;
4+
import ai.z.openapi.core.Constants;
5+
import ai.z.openapi.core.config.ZaiConfig;
6+
import ai.z.openapi.service.model.ChatCompletionCreateParams;
7+
import ai.z.openapi.service.model.ChatCompletionResponse;
8+
import ai.z.openapi.service.model.ChatMessage;
9+
import ai.z.openapi.service.model.ChatMessageRole;
10+
import ai.z.openapi.service.model.ChatThinking;
11+
import ai.z.openapi.service.model.ChatThinkingType;
12+
import ai.z.openapi.service.model.Choice;
13+
import ai.z.openapi.service.model.Delta;
14+
import ai.z.openapi.service.model.ResponseFormat;
15+
import ai.z.openapi.service.model.ResponseFormatType;
16+
17+
import java.util.Arrays;
18+
import java.util.Collections;
19+
import java.util.concurrent.CountDownLatch;
20+
import java.util.concurrent.TimeUnit;
21+
22+
/**
23+
* Chat Completion Example
24+
* Demonstrates how to use ZaiClient for basic chat conversations
25+
*/
26+
public class CustomClientExample {
27+
28+
public static void main(String[] args) throws Exception {
29+
// Create client, recommended to set API Key via environment variable
30+
// export ZAI_API_KEY=your.api_key
31+
// for Z.ai use the `ZaiClient`, for Zhipu AI use the ZhipuAiClient
32+
ZaiConfig zaiConfig = ZaiConfig.builder()
33+
.apiKey(System.getenv("ZAI_API_KEY"))
34+
.baseUrl(Constants.ZHIPU_AI_BASE_URL)
35+
.customHeaders(Collections.emptyMap())
36+
.disableTokenCache(true)
37+
.requestTimeOut(600)
38+
.timeOutTimeUnit(TimeUnit.SECONDS)
39+
.connectTimeout(60)
40+
.connectionPoolKeepAliveDuration(10)
41+
.connectionPoolTimeUnit(TimeUnit.SECONDS)
42+
.connectionPoolMaxIdleConnections(20)
43+
.build();
44+
45+
ZhipuAiClient client = new ZhipuAiClient(zaiConfig);
46+
47+
// Or set API Key via code
48+
// ZaiClient client = ZaiClient.builder()
49+
// .apiKey("your.api_key")
50+
// .build();
51+
52+
// Create chat request
53+
ChatCompletionCreateParams request = ChatCompletionCreateParams.builder()
54+
.model("glm-4.6")
55+
.messages(Arrays.asList(
56+
ChatMessage.builder()
57+
.role(ChatMessageRole.USER.value())
58+
.content("Hello, are you there")
59+
.build()
60+
))
61+
.stream(true)
62+
.thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build())
63+
.responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build())
64+
.temperature(1.0f)
65+
.build();
66+
67+
// Create latch to wait for streaming completion
68+
CountDownLatch latch = new CountDownLatch(1);
69+
70+
try {
71+
// Execute request
72+
ChatCompletionResponse response = client.chat().createChatCompletion(request);
73+
74+
if (response.isSuccess() && response.getFlowable() != null) {
75+
System.out.println("Starting streaming response...");
76+
response.getFlowable().subscribe(
77+
data -> {
78+
// Process each streaming response chunk
79+
if (data.getChoices() != null && !data.getChoices().isEmpty()) {
80+
// Get content of current chunk
81+
Choice choice = data.getChoices().get(0);
82+
System.out.print(choice + "\n");
83+
}
84+
},
85+
error -> {
86+
System.err.println("\nStream error: " + error.getMessage());
87+
latch.countDown(); // Release latch on error
88+
},
89+
// Process streaming response completion event
90+
() -> {
91+
System.out.println("\nStreaming response completed");
92+
latch.countDown(); // Release latch on completion
93+
}
94+
);
95+
96+
// Wait for streaming to complete (max 60 seconds)
97+
latch.await(60, TimeUnit.SECONDS);
98+
} else {
99+
System.err.println("Error: " + response.getMsg());
100+
}
101+
} catch (Exception e) {
102+
System.err.println("Exception occurred: " + e.getMessage());
103+
e.printStackTrace();
104+
} finally {
105+
client.close();
106+
}
107+
}
108+
}

samples/src/main/ai.z.openapi.samples/CustomTimeoutExample.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public static void main(String[] args) {
3030

3131
// Create chat request
3232
ChatCompletionCreateParams request = ChatCompletionCreateParams.builder()
33-
.model(Constants.ModelChatGLM4_5)
33+
.model("glm-4.6")
3434
.messages(Arrays.asList(
3535
ChatMessage.builder()
3636
.role(ChatMessageRole.USER.value())
@@ -40,8 +40,6 @@ public static void main(String[] args) {
4040
.stream(false)
4141
.thinking(ChatThinking.builder().type(ChatThinkingType.ENABLED.value()).build())
4242
.responseFormat(ResponseFormat.builder().type(ResponseFormatType.TEXT.value()).build())
43-
.temperature(0.7f)
44-
.maxTokens(1024)
4543
.build();
4644

4745
try {

0 commit comments

Comments
 (0)