feat: add sample code (#14)
This commit is contained in:
parent
5e4721cf80
commit
069e1d3a62
8 changed files with 274 additions and 2 deletions
|
|
@ -30,7 +30,7 @@ Add the following dependency to your `pom.xml`:
|
|||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>ai.z</groupId>
|
||||
<groupId>ai.z.openapi</groupId>
|
||||
<artifactId>zai-sdk</artifactId>
|
||||
<version>0.0.1</version>
|
||||
</dependency>
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ Z.ai AI 平台官方 Java SDK,提供统一接口访问强大的AI能力,包
|
|||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>ai.z</groupId>
|
||||
<groupId>ai.z.openapi</groupId>
|
||||
<artifactId>zai-sdk</artifactId>
|
||||
<version>0.0.1</version>
|
||||
</dependency>
|
||||
|
|
|
|||
|
|
@ -9,4 +9,12 @@
|
|||
</parent>
|
||||
<artifactId>samples</artifactId>
|
||||
<name>Java sdk examples</name>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>ai.z.openapi</groupId>
|
||||
<artifactId>zai-sdk</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,53 @@
|
|||
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.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
|
||||
ZaiClient client = ZaiClient.builder().ofZHIPU().build();
|
||||
|
||||
// Or set API Key via code
|
||||
// ZaiClient client = ZaiClient.builder()
|
||||
// .apiKey("your.api.key.your.api.secret")
|
||||
// .build();
|
||||
|
||||
// Create chat request
|
||||
ChatCompletionCreateParams request = ChatCompletionCreateParams.builder()
|
||||
.model(Constants.ModelChatGLM4)
|
||||
.messages(Arrays.asList(
|
||||
ChatMessage.builder()
|
||||
.role(ChatMessageRole.USER.value())
|
||||
.content("Hello, how are you?")
|
||||
.build()
|
||||
))
|
||||
.stream(false)
|
||||
.temperature(0.7f)
|
||||
.maxTokens(1024)
|
||||
.build();
|
||||
|
||||
try {
|
||||
// Execute request
|
||||
ChatCompletionResponse response = client.chat().createChatCompletion(request);
|
||||
|
||||
if (response.isSuccess()) {
|
||||
Object content = response.getData().getChoices().get(0).getMessage().getContent();
|
||||
System.out.println("Response: " + content);
|
||||
} else {
|
||||
System.err.println("Error: " + response.getMsg());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Exception occurred: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
package ai.z.openapi.samples;
|
||||
|
||||
import ai.z.openapi.ZaiClient;
|
||||
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().build();
|
||||
System.out.println("✓ Basic client created successfully");
|
||||
|
||||
// Complete configuration example
|
||||
System.out.println("\n=== Complete Configuration Example ===");
|
||||
ZaiClient advancedClient = ZaiClient.builder()
|
||||
.apiKey("your.api.key.your.api.secret")
|
||||
.baseUrl("https://api.z.ai/api/paas/v4/")
|
||||
.enableTokenCache()
|
||||
.tokenExpire(3600000) // 1小时
|
||||
.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.your.api.secret").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.your.api.secret")
|
||||
.baseUrl("https://custom.api.endpoint/")
|
||||
.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");
|
||||
}
|
||||
}
|
||||
47
samples/src/main/ai.z.openapi.samples/EmbeddingsExample.java
Normal file
47
samples/src/main/ai.z.openapi.samples/EmbeddingsExample.java
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
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
|
||||
ZaiClient client = ZaiClient.builder().build();
|
||||
|
||||
// Create embedding request
|
||||
EmbeddingCreateParams request = EmbeddingCreateParams.builder()
|
||||
.model(Constants.ModelEmbedding3)
|
||||
.input(Arrays.asList("Hello world", "How are you?", "今天天气怎么样?"))
|
||||
.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
package ai.z.openapi.samples;
|
||||
|
||||
import ai.z.openapi.ZaiClient;
|
||||
import ai.z.openapi.service.image.*;
|
||||
import ai.z.openapi.core.Constants;
|
||||
|
||||
/**
|
||||
* Image Generation Example
|
||||
* Demonstrates how to use ZaiClient to generate images
|
||||
*/
|
||||
public class ImageGenerationExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Create client
|
||||
ZaiClient client = ZaiClient.builder().build();
|
||||
|
||||
// Create image generation request
|
||||
CreateImageRequest request = CreateImageRequest.builder()
|
||||
.model(Constants.ModelCogView3Plus)
|
||||
.prompt("A beautiful sunset over mountains, digital art style")
|
||||
.size("1024x1024")
|
||||
.build();
|
||||
|
||||
try {
|
||||
// Execute request
|
||||
ImageResponse response = client.images().createImage(request);
|
||||
|
||||
if (response.isSuccess()) {
|
||||
System.out.println("Successfully generated image:");
|
||||
System.out.println("Creation time: " + response.getData().getCreated());
|
||||
|
||||
response.getData().getData().forEach(image -> {
|
||||
System.out.println("\nImage URL: " + image.getUrl());
|
||||
if (image.getRevisedPrompt() != null) {
|
||||
System.out.println("Revised prompt: " + image.getRevisedPrompt());
|
||||
}
|
||||
});
|
||||
|
||||
System.out.println("\nTip: Please copy the URL above to your browser to view the generated image");
|
||||
} else {
|
||||
System.err.println("Error: " + response.getMsg());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Exception occurred: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
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.Arrays;
|
||||
|
||||
/**
|
||||
* Streaming Chat Example
|
||||
* Demonstrates how to use ZaiClient for streaming chat conversations
|
||||
*/
|
||||
public class StreamingChatExample {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Create client
|
||||
ZaiClient client = ZaiClient.builder().build();
|
||||
|
||||
// Create chat request
|
||||
ChatCompletionCreateParams streamRequest = ChatCompletionCreateParams.builder()
|
||||
.model(Constants.ModelChatGLM4)
|
||||
.messages(Arrays.asList(
|
||||
ChatMessage.builder()
|
||||
.role(ChatMessageRole.USER.value())
|
||||
.content("Tell me a story")
|
||||
.build()
|
||||
))
|
||||
.stream(true) // 启用流式响应
|
||||
.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
|
||||
String content = data.getChoices().get(0).getDelta().getContent();
|
||||
if (content != null) {
|
||||
// Print current chunk content
|
||||
System.out.print(content);
|
||||
}
|
||||
}
|
||||
},
|
||||
error -> System.err.println("\nStream error: " + error.getMessage()),
|
||||
// Process streaming response completion event
|
||||
() -> System.out.println("\nStreaming response completed")
|
||||
);
|
||||
|
||||
// Wait for streaming response to complete
|
||||
Thread.sleep(10000); // Wait for 10 seconds
|
||||
} else {
|
||||
System.err.println("Error: " + response.getMsg());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Exception occurred: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue