Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 15 additions & 18 deletions core/src/main/java/ai/z/openapi/api/chat/ChatApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,20 @@
import java.util.Map;

/**
* Chat Completions API for advanced GLM-4 series models Provides synchronous,
* asynchronous, and streaming chat completion capabilities Supports complex reasoning,
* long context processing (up to 128K tokens), and ultra-fast inference Features
* GLM-4-Plus, GLM-4-Air, GLM-4-Flash, and GLM-4-AllTools with specialized capabilities
* Optimized for Chinese and multilingual conversations with superior performance
* Chat Completions API for advanced GLM series models Provides synchronous, asynchronous,
* and streaming chat completion capabilities Supports complex reasoning, long context
* processing and ultra-fast inference Features
*/
public interface ChatApi {

/**
* Create a streaming chat completion with real-time response Returns response content
* incrementally through Server-Sent Events (SSE) for immediate user feedback
* Optimized for interactive applications requiring low latency and progressive
* content delivery Supports all GLM-4 models with configurable streaming parameters
* and token-by-token generation
* @param request Chat completion parameters including model selection (glm-4-plus,
* glm-4-air, glm-4-flash), messages, temperature, top_p, max_tokens, and streaming
* settings
* content delivery Supports all GLM models with configurable streaming parameters and
* token-by-token generation
* @param request Chat completion parameters including model selection messages,
* temperature, top_p, max_tokens, and streaming settings
* @return Streaming response body with incremental content, usage statistics, and
* completion indicators
*/
Expand All @@ -43,8 +40,8 @@ public interface ChatApi {
* Create a streaming chat completion with custom headers support Returns response
* content incrementally through Server-Sent Events (SSE) for immediate user feedback
* Optimized for interactive applications requiring low latency and progressive
* content delivery Supports all GLM-4 models with configurable streaming parameters
* and custom HTTP headers
* content delivery Supports all GLM models with configurable streaming parameters and
* custom HTTP headers
* @param request Chat completion parameters including model selection, messages, and
* streaming settings
* @param headers Custom HTTP headers to be added to the request
Expand All @@ -70,7 +67,7 @@ Call<ResponseBody> createChatCompletionStream(@Body ChatCompletionCreateParams r
Single<ModelData> createChatCompletionAsync(@Body ChatCompletionCreateParams request);

/**
* Create a synchronous chat completion with immediate response Waits for the GLM-4
* Create a synchronous chat completion with immediate response Waits for the GLM
* model to complete execution and returns the final result Supports complex
* reasoning, tool calling, function execution, and multi-modal understanding Features
* advanced capabilities like web search integration, code interpretation, and image
Expand All @@ -85,11 +82,11 @@ Call<ResponseBody> createChatCompletionStream(@Body ChatCompletionCreateParams r
Single<ModelData> createChatCompletion(@Body ChatCompletionCreateParams request);

/**
* Create a synchronous chat completion with custom headers support Waits for the
* GLM-4 model to complete execution and returns the final result with custom HTTP
* headers Supports complex reasoning, tool calling, function execution, and
* multi-modal understanding Features advanced capabilities like web search
* integration, code interpretation, and image analysis
* Create a synchronous chat completion with custom headers support Waits for the GLM
* models to complete execution and returns the final result with custom HTTP headers
* Supports complex reasoning, tool calling, function execution, and multi-modal
* understanding Features advanced capabilities like web search integration, code
* interpretation, and image analysis
* @param request Chat completion parameters including model selection, conversation
* messages, generation settings, tools configuration, and response format
* @param headers Custom HTTP headers to be added to the request
Expand Down
32 changes: 27 additions & 5 deletions core/src/main/java/ai/z/openapi/api/images/ImagesApi.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
package ai.z.openapi.api.images;

import ai.z.openapi.service.image.AsyncImageResult;
import ai.z.openapi.service.image.CreateImageRequest;
import ai.z.openapi.service.image.ImageResult;
import io.reactivex.rxjava3.core.Single;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;

/**
* Images API for AI-powered image generation Powered by CogView-3-Plus models using
* advanced Transformer architecture Delivers high-quality text-to-image generation with
* performance comparable to industry leaders Features optimized diffusion model with
* enhanced noise planning for superior image quality Supports various image styles,
* sizes, and generation parameters with Chinese text rendering capabilities
* Images API for AI-powered image generation models using advanced Transformer
* architecture Delivers high-quality text-to-image generation with performance comparable
* to industry leaders Features optimized diffusion model with enhanced noise planning for
* superior image quality Supports various image styles, sizes, and generation parameters
* with Chinese text rendering capabilities
*/
public interface ImagesApi {

Expand All @@ -28,4 +31,23 @@ public interface ImagesApi {
@POST("images/generations")
Single<ImageResult> createImage(@Body CreateImageRequest request);

/**
* Asynchronously generate images from text prompts. Submits an image generation task
* and returns immediately with a task ID. Use queryAsyncResult to poll for completion
* status and retrieve results.
* @param request Image generation parameters including prompt, size, style, quality,
* and model selection
* @return Async task information including task ID and initial status
*/
@POST("async/images/generations")
Single<AsyncImageResult> createImageAsync(@Body CreateImageRequest request);

/**
* Query the status and result of an async image generation task.
* @param id The async task ID returned by createImageAsync
* @return Task status and generated image URLs when completed
*/
@GET("async-result/{id}")
Single<AsyncImageResult> queryAsyncResult(@Path("id") String id);

}
2 changes: 1 addition & 1 deletion core/src/main/java/ai/z/openapi/api/videos/VideosApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import retrofit2.http.Path;

/**
* Videos API for AI-powered video generation Powered by CogVideoX models using advanced
* Videos API for AI-powered video generation Powered by CogVideo models using advanced
* Transformer and 3D Causal VAE architecture Supports both text-to-video and
* image-to-video generation with exceptional quality Features natural camera movements,
* semantic coherence, and photorealistic visual output Configurable parameters include
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package ai.z.openapi.service.image;

import ai.z.openapi.core.model.ClientResponse;
import ai.z.openapi.service.model.ChatError;
import lombok.Data;

/**
* Response wrapper for async image generation API calls. Contains the result of async
* image generation operations along with status information.
*/
@Data
public class AsyncImageResponse implements ClientResponse<AsyncImageResult> {

/**
* Response status code.
*/
private int code;

/**
* Response message.
*/
private String msg;

/**
* Indicates whether the request was successful.
*/
private boolean success;

/**
* The async image generation result data.
*/
private AsyncImageResult data;

/**
* Error information if the request failed.
*/
private ChatError error;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package ai.z.openapi.service.image;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
* Result object for async image generation API. Contains task status and image results
* when completed.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AsyncImageResult {

/**
* The unique identifier for the async task.
*/
@JsonProperty("id")
private String id;

/**
* The model used for image generation.
*/
@JsonProperty("model")
private String model;

/**
* The request ID for tracking.
*/
@JsonProperty("request_id")
private String requestId;

/**
* The status of the async task. Possible values: PROCESSING, SUCCESS, FAIL
*/
@JsonProperty("task_status")
private String taskStatus;

/**
* List of generated images. Available when task_status is SUCCESS.
*/
@JsonProperty("image_result")
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private List<Image> imageResult;

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
import lombok.experimental.SuperBuilder;

/**
* A request for ZAi to create an image based on a prompt All fields except prompt are
* optional
* A request to create an image based on a prompt All fields except prompt are optional
*/
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
Expand All @@ -29,15 +28,23 @@ public class CreateImageRequest extends CommonRequest implements ClientRequest<C
private String prompt;

/**
* The model to use for image generation. Defaults to "dall-e-2".
* The model to use for image generation.
*/
private String model;

/**
* The size of the image to generate. Defaults to "256x256".
* The size of the image to generate.
*/
private String size;

/**
* Optional. The quality of the generated image. hd: Generates more refined images
* with richer details and higher overall consistency, but takes longer. standard:
* Quickly generates images, suitable for scenarios with high speed requirements,
* takes less time.
*/
private String quality;

/**
* Sensitive word detection control
*/
Expand Down
15 changes: 15 additions & 0 deletions core/src/main/java/ai/z/openapi/service/image/ImageService.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,19 @@ public interface ImageService {
*/
ImageResponse createImage(CreateImageRequest createImageRequest);

/**
* Asynchronously creates an image based on the provided generation request. Returns
* immediately with a task ID that can be used to query the status.
* @param createImageRequest the image generation request
* @return AsyncImageResponse containing the task ID and initial status
*/
AsyncImageResponse createImageAsync(CreateImageRequest createImageRequest);

/**
* Queries the status and result of an async image generation task.
* @param taskId the async task ID returned by createImageAsync
* @return AsyncImageResponse containing task status and results when completed
*/
AsyncImageResponse queryAsyncResult(String taskId);

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import ai.z.openapi.AbstractAiClient;
import ai.z.openapi.api.images.ImagesApi;
import ai.z.openapi.service.model.AsyncResultRetrieveParams;
import ai.z.openapi.utils.RequestSupplier;

/**
Expand All @@ -24,4 +25,18 @@ public ImageResponse createImage(CreateImageRequest createImageRequest) {
return this.zAiClient.executeRequest(createImageRequest, supplier, ImageResponse.class);
}

@Override
public AsyncImageResponse createImageAsync(CreateImageRequest createImageRequest) {
RequestSupplier<CreateImageRequest, AsyncImageResult> supplier = imagesApi::createImageAsync;
return this.zAiClient.executeRequest(createImageRequest, supplier, AsyncImageResponse.class);
}

@Override
public AsyncImageResponse queryAsyncResult(String taskId) {
AsyncResultRetrieveParams request = new AsyncResultRetrieveParams(taskId);
RequestSupplier<AsyncResultRetrieveParams, AsyncImageResult> supplier = (params) -> imagesApi
.queryAsyncResult(params.getTaskId());
return zAiClient.executeRequest(request, supplier, AsyncImageResponse.class);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ public class ChatFunction {

private String description;

private ChatFunctionParameters parameters;
/**
* The JSON schema defining the function's input arguments, you can use the
* ChatFunctionParameters or others
*/
private Object parameters;

}
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
</scm>

<properties>
<revision>0.3.0</revision>
<revision>0.3.1</revision>
<java.version>8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
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().baseUrl("https://dev.bigmodel.cn/api/paas/v4/").apiKey("08d9c717e10a4dbc8bd3963cb70aafe0.ZAMAdBKwQsrlAbcZ").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();
}
}
}