chore: add agent sample and fix agent (#16)
This commit is contained in:
parent
b22470dd77
commit
363843cf3a
10 changed files with 703 additions and 16 deletions
|
|
@ -0,0 +1,51 @@
|
||||||
|
package ai.z.openapi.service.agents;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||||
|
@Builder
|
||||||
|
public class AgentContent {
|
||||||
|
|
||||||
|
/** 消息类型 text image_url video_url */
|
||||||
|
private String type;
|
||||||
|
|
||||||
|
/** 消息内容 when type is text */
|
||||||
|
private String text;
|
||||||
|
|
||||||
|
/** 消息图片URL when type is image_url */
|
||||||
|
@JsonProperty("image_url")
|
||||||
|
private String imageUrl;
|
||||||
|
|
||||||
|
/** 消息视频URL when type is video_url */
|
||||||
|
@JsonProperty("video_url")
|
||||||
|
private String videoUrl;
|
||||||
|
|
||||||
|
/** 消息对象 when type is object */
|
||||||
|
@JsonProperty("object")
|
||||||
|
private Object object;
|
||||||
|
|
||||||
|
public static AgentContent ofText(String text) {
|
||||||
|
return AgentContent.builder().type("text").text(text).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AgentContent ofImageUrl(String imageUrl) {
|
||||||
|
return AgentContent.builder().type("image_url").imageUrl(imageUrl).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AgentContent ofVideoUrl(String videoUrl) {
|
||||||
|
return AgentContent.builder().type("video_url").videoUrl(videoUrl).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AgentContent ofObject(Object object) {
|
||||||
|
return AgentContent.builder().type("object").object(object).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
package ai.z.openapi.service.agents;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
@NoArgsConstructor
|
||||||
|
@Builder
|
||||||
|
public class AgentMessage {
|
||||||
|
|
||||||
|
private String role;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* list AgentContent or One AgentContent
|
||||||
|
*/
|
||||||
|
private Object content;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -4,7 +4,6 @@ import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
import ai.z.openapi.core.model.ClientRequest;
|
import ai.z.openapi.core.model.ClientRequest;
|
||||||
import ai.z.openapi.service.CommonRequest;
|
import ai.z.openapi.service.CommonRequest;
|
||||||
import ai.z.openapi.service.model.ChatMessage;
|
|
||||||
import ai.z.openapi.service.model.SensitiveWordCheckRequest;
|
import ai.z.openapi.service.model.SensitiveWordCheckRequest;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
|
|
@ -35,7 +34,7 @@ public class AgentsCompletionRequest extends CommonRequest implements ClientRequ
|
||||||
/**
|
/**
|
||||||
* Message body
|
* Message body
|
||||||
*/
|
*/
|
||||||
private List<ChatMessage> messages;
|
private List<AgentMessage> messages;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Synchronous call: false, SSE call: true
|
* Synchronous call: false, SSE call: true
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,14 @@
|
||||||
package ai.z.openapi.service.model;
|
package ai.z.openapi.service.model;
|
||||||
|
|
||||||
|
import ai.z.openapi.service.agents.AgentMessage;
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
import lombok.Builder;
|
import lombok.Builder;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.NoArgsConstructor;
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@NoArgsConstructor
|
@NoArgsConstructor
|
||||||
@AllArgsConstructor
|
@AllArgsConstructor
|
||||||
|
|
@ -21,6 +24,12 @@ public class Choice {
|
||||||
@JsonProperty("message")
|
@JsonProperty("message")
|
||||||
private ChatMessage message;
|
private ChatMessage message;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* for agent message
|
||||||
|
*/
|
||||||
|
@JsonProperty("messages")
|
||||||
|
private List<AgentMessage> messages;
|
||||||
|
|
||||||
@JsonProperty("delta")
|
@JsonProperty("delta")
|
||||||
private Delta delta;
|
private Delta delta;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -68,9 +68,9 @@ public class AgentServiceTest {
|
||||||
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
|
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
|
||||||
void testSyncAgentCompletion() throws JsonProcessingException {
|
void testSyncAgentCompletion() throws JsonProcessingException {
|
||||||
// Prepare test data
|
// Prepare test data
|
||||||
List<ChatMessage> messages = new ArrayList<>();
|
List<AgentMessage> messages = new ArrayList<>();
|
||||||
ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(),
|
AgentMessage userMessage = new AgentMessage(ChatMessageRole.USER.value(),
|
||||||
"Hello, please translate this to Chinese: How are you?");
|
AgentContent.ofText("Hello, please translate this to Chinese: How are you?"));
|
||||||
messages.add(userMessage);
|
messages.add(userMessage);
|
||||||
|
|
||||||
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
|
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
|
||||||
|
|
@ -101,9 +101,9 @@ public class AgentServiceTest {
|
||||||
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
|
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
|
||||||
void testStreamAgentCompletion() throws JsonProcessingException {
|
void testStreamAgentCompletion() throws JsonProcessingException {
|
||||||
// Prepare test data
|
// Prepare test data
|
||||||
List<ChatMessage> messages = new ArrayList<>();
|
List<AgentMessage> messages = new ArrayList<>();
|
||||||
ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(),
|
AgentMessage userMessage = new AgentMessage(ChatMessageRole.USER.value(),
|
||||||
"Please translate this to Chinese: The weather is beautiful today");
|
AgentContent.ofText("Please translate this to Chinese: The weather is beautiful today"));
|
||||||
messages.add(userMessage);
|
messages.add(userMessage);
|
||||||
|
|
||||||
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
|
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
|
||||||
|
|
@ -207,8 +207,8 @@ public class AgentServiceTest {
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Test Parameter Validation - Null Agent ID")
|
@DisplayName("Test Parameter Validation - Null Agent ID")
|
||||||
void testValidation_NullAgentId() {
|
void testValidation_NullAgentId() {
|
||||||
List<ChatMessage> messages = new ArrayList<>();
|
List<AgentMessage> messages = new ArrayList<>();
|
||||||
messages.add(new ChatMessage(ChatMessageRole.USER.value(), "Test message"));
|
messages.add(new AgentMessage(ChatMessageRole.USER.value(), "Test message"));
|
||||||
|
|
||||||
AgentsCompletionRequest request = AgentsCompletionRequest.builder().messages(messages).build();
|
AgentsCompletionRequest request = AgentsCompletionRequest.builder().messages(messages).build();
|
||||||
|
|
||||||
|
|
@ -231,14 +231,16 @@ public class AgentServiceTest {
|
||||||
@DisplayName("Test Multi-turn Conversation with Agent")
|
@DisplayName("Test Multi-turn Conversation with Agent")
|
||||||
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
|
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
|
||||||
void testMultiTurnConversationWithAgent() throws JsonProcessingException {
|
void testMultiTurnConversationWithAgent() throws JsonProcessingException {
|
||||||
List<ChatMessage> messages = new ArrayList<>();
|
List<AgentMessage> messages = new ArrayList<>();
|
||||||
|
|
||||||
// First round of conversation
|
// First round of conversation
|
||||||
messages.add(new ChatMessage(ChatMessageRole.USER.value(), "Please translate 'Hello' to Chinese"));
|
messages.add(new AgentMessage(ChatMessageRole.USER.value(),
|
||||||
messages.add(new ChatMessage(ChatMessageRole.ASSISTANT.value(), "你好"));
|
AgentContent.ofText("Please translate 'Hello' to Chinese")));
|
||||||
|
messages.add(new AgentMessage(ChatMessageRole.ASSISTANT.value(), AgentContent.ofText("你好")));
|
||||||
|
|
||||||
// Second round of conversation
|
// Second round of conversation
|
||||||
messages.add(new ChatMessage(ChatMessageRole.USER.value(), "Now translate 'Thank you' to Chinese"));
|
messages.add(new AgentMessage(ChatMessageRole.USER.value(),
|
||||||
|
AgentContent.ofText("Now translate 'Thank you' to Chinese")));
|
||||||
|
|
||||||
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
|
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
|
||||||
|
|
||||||
|
|
@ -264,8 +266,9 @@ public class AgentServiceTest {
|
||||||
@DisplayName("Test Agent Completion with Custom Variables")
|
@DisplayName("Test Agent Completion with Custom Variables")
|
||||||
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
|
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
|
||||||
void testAgentCompletionWithCustomVariables() throws JsonProcessingException {
|
void testAgentCompletionWithCustomVariables() throws JsonProcessingException {
|
||||||
List<ChatMessage> messages = new ArrayList<>();
|
List<AgentMessage> messages = new ArrayList<>();
|
||||||
ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), "Translate this text");
|
AgentMessage userMessage = new AgentMessage(ChatMessageRole.USER.value(),
|
||||||
|
AgentContent.ofText("Translate this text"));
|
||||||
messages.add(userMessage);
|
messages.add(userMessage);
|
||||||
|
|
||||||
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
|
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
|
||||||
|
|
|
||||||
82
samples/src/main/ai.z.openapi.samples/AgentExample.java
Normal file
82
samples/src/main/ai.z.openapi.samples/AgentExample.java
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
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.agents.AgentAsyncResultRetrieveParams;
|
||||||
|
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.Choice;
|
||||||
|
import ai.z.openapi.service.model.ModelData;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
ZaiClient client = ZaiClient.builder().ofZHIPU().build();
|
||||||
|
|
||||||
|
// Or set API Key via code
|
||||||
|
// ZaiClient client = ZaiClient.builder()
|
||||||
|
// .apiKey("your.api.key.your.api.secret")
|
||||||
|
// .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<AgentMessage> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
89
samples/src/main/ai.z.openapi.samples/CogVideoXExample.java
Normal file
89
samples/src/main/ai.z.openapi.samples/CogVideoXExample.java
Normal file
|
|
@ -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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
ZaiClient client = ZaiClient.builder().build();
|
||||||
|
|
||||||
|
// Or set API Key via code
|
||||||
|
// ZaiClient client = ZaiClient.builder()
|
||||||
|
// .apiKey("your.api.key.your.api.secret")
|
||||||
|
// .build();
|
||||||
|
|
||||||
|
// Basic Video Generation
|
||||||
|
generateBasicVideo(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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);
|
||||||
|
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
System.out.println("Video generation request successful!");
|
||||||
|
System.out.println("Task ID: " + response.getData().getId());
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,129 @@
|
||||||
|
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.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Base64;
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
ZaiClient client = ZaiClient.builder().build();
|
||||||
|
|
||||||
|
// Or set API Key via code
|
||||||
|
// ZaiClient client = ZaiClient.builder()
|
||||||
|
// .apiKey("your.api.key.your.api.secret")
|
||||||
|
// .build();
|
||||||
|
|
||||||
|
// Generate video from image using Vidu
|
||||||
|
generateVideoFromImage(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
String imagePath = "path/to/your/image.jpg";
|
||||||
|
|
||||||
|
try {
|
||||||
|
// For demonstration purposes, we'll skip the actual file reading
|
||||||
|
// In a real application, you would read and encode the image file
|
||||||
|
String imageBase64 = "sample_base64_string";
|
||||||
|
|
||||||
|
// Uncomment the following code to read and encode a real image file
|
||||||
|
/*
|
||||||
|
File imageFile = new File(imagePath);
|
||||||
|
if (imageFile.exists()) {
|
||||||
|
byte[] fileContent = FileUtils.readFileToByteArray(imageFile);
|
||||||
|
imageBase64 = Base64.getEncoder().encodeToString(fileContent);
|
||||||
|
} else {
|
||||||
|
System.err.println("Image file not found: " + imagePath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
// 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(imageBase64) // Base64 encoded image
|
||||||
|
.requestId("vidu-image-example-" + System.currentTimeMillis())
|
||||||
|
.duration(5) // 5 seconds duration
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// Skip the actual API call in this example to avoid errors with a fake image
|
||||||
|
System.out.println("In a real application, the following code would be executed:");
|
||||||
|
System.out.println("VideosResponse response = client.videos().videoGenerations(request);");
|
||||||
|
System.out.println("\nNote: This example is skipping the actual API call since we're using a placeholder image.");
|
||||||
|
System.out.println("To run this example with a real image, uncomment the image reading code and provide a valid image path.");
|
||||||
|
|
||||||
|
// Uncomment the following code to make the actual API call with a real image
|
||||||
|
/*
|
||||||
|
// Execute request
|
||||||
|
VideosResponse response = client.videos().videoGenerations(request);
|
||||||
|
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
System.out.println("Video generation request successful!");
|
||||||
|
System.out.println("Task ID: " + response.getData().getId());
|
||||||
|
System.out.println("Status: " + response.getData().getStatus());
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,127 @@
|
||||||
|
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
|
||||||
|
ZaiClient client = ZaiClient.builder().build();
|
||||||
|
|
||||||
|
// Or set API Key via code
|
||||||
|
// ZaiClient client = ZaiClient.builder()
|
||||||
|
// .apiKey("your.api.key.your.api.secret")
|
||||||
|
// .build();
|
||||||
|
|
||||||
|
// Example: Generate video from text using Vidu
|
||||||
|
generateVideoFromText(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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())
|
||||||
|
.build();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Execute request
|
||||||
|
VideosResponse response = client.videos().videoGenerations(request);
|
||||||
|
|
||||||
|
if (response.isSuccess()) {
|
||||||
|
System.out.println("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 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
|
||||||
|
.size("1280x720") // Custom resolution
|
||||||
|
.duration(8) // 8 seconds duration
|
||||||
|
.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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
177
samples/src/main/ai.z.openapi.samples/WebSearchExample.java
Normal file
177
samples/src/main/ai.z.openapi.samples/WebSearchExample.java
Normal file
|
|
@ -0,0 +1,177 @@
|
||||||
|
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
|
||||||
|
ZaiClient client = ZaiClient.builder().build();
|
||||||
|
|
||||||
|
// Or set API Key via code
|
||||||
|
// ZaiClient client = ZaiClient.builder()
|
||||||
|
// .apiKey("your.api.key.your.api.secret")
|
||||||
|
// .build();
|
||||||
|
|
||||||
|
// Example 1: Basic Web Search
|
||||||
|
basicWebSearch(client);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<SearchChatMessage> 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<SearchChatMessage> 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in a new issue