-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathChatAsyncCompletionExample.java
More file actions
59 lines (52 loc) · 2.23 KB
/
ChatAsyncCompletionExample.java
File metadata and controls
59 lines (52 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package ai.z.openapi.samples;
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
ZhipuAiClient client = ZhipuAiClient.builder().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-4.6")
.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();
}
}
}