chore: remove knowledge and document relate (#12)

This commit is contained in:
tomsun28 2025-07-18 13:23:55 +08:00 committed by GitHub
parent ac50baa8f4
commit 226d8018ff
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
34 changed files with 0 additions and 2092 deletions

View file

@ -21,10 +21,6 @@ import ai.z.openapi.service.web_search.WebSearchService;
import ai.z.openapi.service.web_search.WebSearchServiceImpl; import ai.z.openapi.service.web_search.WebSearchServiceImpl;
import ai.z.openapi.service.videos.VideosService; import ai.z.openapi.service.videos.VideosService;
import ai.z.openapi.service.videos.VideosServiceImpl; import ai.z.openapi.service.videos.VideosServiceImpl;
import ai.z.openapi.service.knowledge.KnowledgeService;
import ai.z.openapi.service.knowledge.KnowledgeServiceImpl;
import ai.z.openapi.service.document.DocumentService;
import ai.z.openapi.service.document.DocumentServiceImpl;
import ai.z.openapi.service.assistant.AssistantService; import ai.z.openapi.service.assistant.AssistantService;
import ai.z.openapi.service.assistant.AssistantServiceImpl; import ai.z.openapi.service.assistant.AssistantServiceImpl;
import ai.z.openapi.core.config.ZaiConfig; import ai.z.openapi.core.config.ZaiConfig;
@ -116,12 +112,6 @@ public class ZaiClient extends AbstractClientBaseService {
/** Videos service for video processing */ /** Videos service for video processing */
private VideosService videosService; private VideosService videosService;
/** Knowledge service for knowledge base operations */
private KnowledgeService knowledgeService;
/** Document service for document processing */
private DocumentService documentService;
/** Assistant service for AI assistant functionality */ /** Assistant service for AI assistant functionality */
private AssistantService assistantService; private AssistantService assistantService;
@ -253,30 +243,6 @@ public class ZaiClient extends AbstractClientBaseService {
return videosService; return videosService;
} }
/**
* Returns the knowledge service for knowledge base operations. This service manages
* knowledge bases and retrieval operations.
* @return the KnowledgeService instance (lazily initialized)
*/
public synchronized KnowledgeService knowledge() {
if (knowledgeService == null) {
this.knowledgeService = new KnowledgeServiceImpl(this);
}
return knowledgeService;
}
/**
* Returns the document service for document processing. This service handles document
* parsing, analysis, and manipulation.
* @return the DocumentService instance (lazily initialized)
*/
public synchronized DocumentService documents() {
if (documentService == null) {
this.documentService = new DocumentServiceImpl(this);
}
return documentService;
}
/** /**
* Returns the assistant service for AI assistant functionality. This service provides * Returns the assistant service for AI assistant functionality. This service provides
* advanced AI assistant capabilities. * advanced AI assistant capabilities.

View file

@ -1,72 +0,0 @@
package ai.z.openapi.api.knowledge;
import ai.z.openapi.service.knowledge.KnowledgeBaseParams;
import ai.z.openapi.service.knowledge.KnowledgeId;
import ai.z.openapi.service.knowledge.KnowledgePage;
import ai.z.openapi.service.knowledge.KnowledgeUsed;
import io.reactivex.Single;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Knowledge Base Management API for document storage and retrieval Provides comprehensive
* knowledge base operations including creation, modification, and querying Enables AI
* models to access and utilize structured knowledge for enhanced responses
*/
public interface KnowledgeApi {
/**
* Create a new knowledge base Establishes a new knowledge repository for storing and
* organizing documents
* @param knowledgeBaseParams Configuration parameters including name, description,
* and settings
* @return Knowledge base information with ID, status, and metadata
*/
@POST("knowledge")
Single<KnowledgeId> knowledgeCreate(@Body KnowledgeBaseParams knowledgeBaseParams);
/**
* Modify an existing knowledge base Updates knowledge base configuration and settings
* @param knowledge_id Unique identifier of the knowledge base to modify
* @param knowledgeBaseParams Updated configuration parameters
* @return HTTP response indicating modification success or failure
*/
@PUT("knowledge/{knowledge_id}")
Single<Response<Void>> knowledgeModify(@Path("knowledge_id") String knowledge_id,
@Body KnowledgeBaseParams knowledgeBaseParams);
/**
* Query and list knowledge bases with pagination Retrieves a paginated list of
* available knowledge bases
* @param page Page number for pagination (starting from 1)
* @param size Number of knowledge bases to return per page
* @return Paginated list of knowledge bases with metadata
*/
@GET("knowledge")
Single<KnowledgePage> knowledgeQuery(@Query("page") Integer page, @Query("size") Integer size);
/**
* Delete a knowledge base Permanently removes the knowledge base and all associated
* documents
* @param knowledge_id Unique identifier of the knowledge base to delete
* @return HTTP response indicating deletion success or failure
*/
@DELETE("knowledge/{knowledge_id}")
Single<Response<Void>> knowledgeDelete(@Path("knowledge_id") String knowledge_id);
/**
* Get knowledge base usage statistics Retrieves information about storage capacity
* and usage metrics
* @return Knowledge base usage details including capacity and consumption
*/
@GET("knowledge/capacity")
Single<KnowledgeUsed> knowledgeUsed();
}

View file

@ -1,101 +0,0 @@
package ai.z.openapi.api.knowledge.document;
import ai.z.openapi.service.knowledge.document.DocumentData;
import ai.z.openapi.service.knowledge.document.DocumentEditParams;
import ai.z.openapi.service.knowledge.document.DocumentObject;
import ai.z.openapi.service.knowledge.document.DocumentPage;
import io.reactivex.Single;
import okhttp3.MultipartBody;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
/**
* Document Management API for intelligent knowledge base content Provides comprehensive
* document operations within knowledge bases for RAG (Retrieval-Augmented Generation)
* Supports document upload, automatic processing, vectorization, modification, deletion,
* and retrieval Enables efficient knowledge management for AI systems with advanced
* indexing and search capabilities Features automatic content extraction, chunking,
* embedding generation, and semantic organization
*/
public interface DocumentApi {
/**
* Create and upload a new document to knowledge base with automatic processing
* Uploads document content for intelligent processing, content extraction, and
* vectorization Supports multiple file formats (PDF, DOC, TXT, MD) with automatic
* format detection Features automatic text chunking, embedding generation, and
* semantic indexing for optimal retrieval
* @param document Multipart document data including file content, metadata, and
* processing preferences
* @return Document object with unique ID, processing status, extraction results, and
* indexing information
*/
@POST("files")
Single<DocumentObject> createDocument(@Body MultipartBody document);
/**
* Modify an existing document with intelligent reprocessing Updates document
* metadata, content, or processing settings with automatic re-indexing Supports
* content updates, metadata changes, and processing parameter adjustments Triggers
* automatic re-vectorization and re-indexing when content is modified
* @param documentId Unique identifier of the document to modify
* @param documentEditParams Updated document parameters including content, metadata,
* and processing settings
* @return HTTP response indicating modification success, processing status, and any
* validation errors
*/
@PUT("document/{document_id}")
Single<Response<Void>> modifyDocument(@Path("document_id") String documentId,
@Body DocumentEditParams documentEditParams);
/**
* Delete a document from knowledge base with complete cleanup Permanently removes the
* document, its indexed content, generated embeddings, and all associated metadata
* Ensures complete removal from vector database and search indices for data
* consistency Irreversible operation that affects knowledge base search and retrieval
* capabilities
* @param documentId Unique identifier of the document to delete
* @return HTTP response indicating deletion success, cleanup status, and any
* dependency warnings
*/
@DELETE("document/{document_id}")
Single<Response<Void>> deleteDocument(@Path("document_id") String documentId);
/**
* Query and list documents with advanced filtering and pagination Retrieves documents
* from knowledge base with comprehensive filter options and sorting Supports
* filtering by knowledge base, purpose, processing status, and content type Provides
* efficient pagination for large document collections with optimized performance
* @param knowledgeId Filter documents by specific knowledge base ID (optional)
* @param purpose Filter documents by their intended purpose or category (optional)
* @param page Page number for pagination (starts from 1)
* @param limit Maximum number of documents to return per page (recommended: 10-50)
* @param order Sort order for the document list (e.g., 'created_at', 'updated_at',
* 'name')
* @return Paginated list of documents with metadata, processing status, and summary
* information
*/
@GET("files")
Single<DocumentPage> queryDocumentList(@Query("knowledge_id") String knowledgeId, @Query("purpose") String purpose,
@Query("page") Integer page, @Query("limit") Integer limit, @Query("order") String order);
/**
* Retrieve comprehensive information about a specific document Gets detailed document
* data including content, processing status, embedding information, and usage
* statistics Provides insights into document processing results, chunk distribution,
* and retrieval performance Essential for monitoring document quality and
* troubleshooting knowledge base issues
* @param documentId Unique identifier of the document to retrieve
* @return Complete document data with content, metadata, processing details,
* embedding statistics, and access history
*/
@GET("document/{document_id}")
Single<DocumentData> retrieveDocument(@Path("document_id") String documentId);
}

View file

@ -1,51 +0,0 @@
package ai.z.openapi.service.document;
import ai.z.openapi.service.knowledge.document.DocumentCreateParams;
import ai.z.openapi.service.knowledge.document.DocumentEditParams;
import ai.z.openapi.service.knowledge.document.QueryDocumentRequest;
import ai.z.openapi.service.knowledge.document.DocumentDataResponse;
import ai.z.openapi.service.knowledge.document.DocumentEditResponse;
import ai.z.openapi.service.knowledge.document.DocumentObjectResponse;
import ai.z.openapi.service.knowledge.document.QueryDocumentApiResponse;
/**
* Document service interface
*/
public interface DocumentService {
/**
* Creates a new document.
* @param request the document creation request
* @return DocumentDataResponse containing the creation result
*/
DocumentObjectResponse createDocument(DocumentCreateParams request);
/**
* Modifies an existing document.
* @param request the document modification request
* @return DocumentEditResponse containing the modification result
*/
DocumentEditResponse modifyDocument(DocumentEditParams request);
/**
* Deletes a document.
* @param documentId the document ID to delete
* @return DocumentObjectResponse containing the deletion result
*/
DocumentEditResponse deleteDocument(String documentId);
/**
* Lists documents.
* @param request the query request
* @return QueryDocumentApiResponse containing the document list
*/
QueryDocumentApiResponse listDocuments(QueryDocumentRequest request);
/**
* Retrieves a specific document.
* @param documentId the document ID to retrieve
* @return DocumentDataResponse containing the document details
*/
DocumentDataResponse retrieveDocument(String documentId);
}

View file

@ -1,144 +0,0 @@
package ai.z.openapi.service.document;
import ai.z.openapi.ZaiClient;
import ai.z.openapi.api.knowledge.document.DocumentApi;
import ai.z.openapi.service.deserialize.MessageDeserializeFactory;
import ai.z.openapi.service.knowledge.document.DocumentCreateParams;
import ai.z.openapi.service.knowledge.document.DocumentData;
import ai.z.openapi.service.knowledge.document.DocumentDataResponse;
import ai.z.openapi.service.knowledge.document.DocumentEditParams;
import ai.z.openapi.service.knowledge.document.DocumentEditResponse;
import ai.z.openapi.service.knowledge.document.DocumentObject;
import ai.z.openapi.service.knowledge.document.DocumentObjectResponse;
import ai.z.openapi.service.knowledge.document.DocumentPage;
import ai.z.openapi.service.knowledge.document.QueryDocumentRequest;
import ai.z.openapi.service.knowledge.document.QueryDocumentApiResponse;
import ai.z.openapi.utils.RequestSupplier;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Response;
import java.util.Date;
/**
* Implementation of DocumentService
*/
@Slf4j
public class DocumentServiceImpl implements DocumentService {
private final ZaiClient zAiClient;
private final DocumentApi documentApi;
private final ObjectMapper mapper = MessageDeserializeFactory.defaultObjectMapper();
public DocumentServiceImpl(ZaiClient zAiClient) {
this.zAiClient = zAiClient;
this.documentApi = zAiClient.retrofit().create(DocumentApi.class);
}
@Override
public DocumentObjectResponse createDocument(DocumentCreateParams request) {
// Only one of getUploadDetail and getFilePath can exist
if (request.getUploadDetail() != null && request.getFilePath() != null) {
throw new RuntimeException("Only one of upload detail and file path can exist");
}
RequestSupplier<DocumentCreateParams, DocumentObject> supplier = (params) -> {
// Convert DocumentCreateParams to MultipartBody
MultipartBody.Builder formBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
try {
if (params.getFilePath() != null) {
java.io.File file = new java.io.File(params.getFilePath());
if (!file.exists()) {
throw new RuntimeException("file not found");
}
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(),
RequestBody.create(MediaType.parse("application/octet-stream"), file));
formBodyBuilder.addPart(filePart);
}
if (params.getUploadDetail() != null) {
formBodyBuilder.addFormDataPart("upload_detail", null, RequestBody.create(
MediaType.parse("application/json"), mapper.writeValueAsString(params.getUploadDetail())));
}
formBodyBuilder.addFormDataPart("knowledge_id", params.getKnowledgeId());
if (params.getSentenceSize() != null) {
formBodyBuilder.addFormDataPart("sentence_size", String.valueOf(params.getSentenceSize()));
}
formBodyBuilder.addFormDataPart("purpose", params.getPurpose());
if (params.getCustomSeparator() != null) {
formBodyBuilder.addFormDataPart("custom_separator", null,
RequestBody.create(MediaType.parse("application/json"),
mapper.writeValueAsString(params.getCustomSeparator())));
}
if (params.getExtraJson() != null) {
for (String s : params.getExtraJson().keySet()) {
if (params.getExtraJson().get(s) instanceof String
|| params.getExtraJson().get(s) instanceof Number
|| params.getExtraJson().get(s) instanceof Boolean
|| params.getExtraJson().get(s) instanceof Character) {
formBodyBuilder.addFormDataPart(s, params.getExtraJson().get(s).toString());
}
else if (params.getExtraJson().get(s) instanceof Date) {
Date date = (Date) params.getExtraJson().get(s);
formBodyBuilder.addFormDataPart(s, String.valueOf(date.getTime()));
}
else {
formBodyBuilder.addFormDataPart(s, null,
RequestBody.create(MediaType.parse("application/json"),
mapper.writeValueAsString(params.getExtraJson().get(s))));
}
}
}
}
catch (Exception e) {
log.error(e.getMessage(), e);
}
MultipartBody multipartBody = formBodyBuilder.build();
return documentApi.createDocument(multipartBody);
};
return zAiClient.executeRequest(request, supplier, DocumentObjectResponse.class);
}
@Override
public DocumentEditResponse modifyDocument(DocumentEditParams request) {
RequestSupplier<DocumentEditParams, Response<Void>> supplier = (params) -> documentApi
.modifyDocument(params.getId(), params);
return zAiClient.executeRequest(request, supplier, DocumentEditResponse.class);
}
@Override
public DocumentEditResponse deleteDocument(String documentId) {
DocumentEditParams params = new DocumentEditParams();
params.setId(documentId);
RequestSupplier<DocumentEditParams, Response<Void>> supplier = (params1) -> documentApi
.deleteDocument(params1.getId());
return zAiClient.executeRequest(params, supplier, DocumentEditResponse.class);
}
@Override
public QueryDocumentApiResponse listDocuments(QueryDocumentRequest request) {
RequestSupplier<QueryDocumentRequest, DocumentPage> supplier = (params) -> documentApi.queryDocumentList(
params.getKnowledgeId(), params.getPurpose(), params.getPage(), params.getLimit(), params.getOrder());
return zAiClient.executeRequest(request, supplier, QueryDocumentApiResponse.class);
}
@Override
public DocumentDataResponse retrieveDocument(String documentId) {
DocumentEditParams params = new DocumentEditParams();
params.setId(documentId);
RequestSupplier<DocumentEditParams, DocumentData> supplier = (id) -> documentApi.retrieveDocument(id.getId());
return zAiClient.executeRequest(params, supplier, DocumentDataResponse.class);
}
}

View file

@ -1,20 +0,0 @@
package ai.z.openapi.service.knowledge;
import ai.z.openapi.core.model.ClientResponse;
import ai.z.openapi.service.model.ChatError;
import lombok.Data;
@Data
public class CreateKnowledgeResponse implements ClientResponse<KnowledgeId> {
private int code;
private String msg;
private boolean success;
private KnowledgeId data;
private ChatError error;
}

View file

@ -1,50 +0,0 @@
package ai.z.openapi.service.knowledge;
import com.fasterxml.jackson.annotation.JsonProperty;
import ai.z.openapi.core.model.ClientRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
@EqualsAndHashCode(callSuper = false)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class KnowledgeBaseParams implements ClientRequest<KnowledgeBaseParams> {
/**
* Knowledge base parameter type definition
* <p>
* Attributes: embedding_id (int): Vector model ID bound to the knowledge base name
* (String): Knowledge base name, limited to 100 characters customer_identifier
* (String): User identifier, within 32 characters description (String): Knowledge
* base description, limited to 500 characters background (String): Background color
* icon (String): Knowledge base icon bucket_id (String): Bucket ID, limited to 32
* characters
*/
@JsonProperty("embedding_id")
private int embeddingId;
@JsonProperty("name")
private String name;
@JsonProperty("knowledge_id")
private String knowledgeId;
@JsonProperty("customer_identifier")
private String customerIdentifier;
@JsonProperty("description")
private String description;
@JsonProperty("background")
private String background;
@JsonProperty("icon")
private String icon;
}

View file

@ -1,40 +0,0 @@
package ai.z.openapi.service.knowledge;
import ai.z.openapi.core.model.ClientResponse;
import ai.z.openapi.service.model.ChatError;
import lombok.Data;
import retrofit2.Response;
/**
* Response for knowledge base edit operations. This class contains the response data for
* knowledge base modification requests.
*/
@Data
public class KnowledgeEditResponse implements ClientResponse<Response<Void>> {
/**
* Response status code.
*/
private int code;
/**
* Response message.
*/
private String msg;
/**
* Indicates if the edit operation was successful.
*/
private boolean success;
/**
* The response data (typically void for edit operations).
*/
private Response<Void> data;
/**
* Error information if the edit operation failed.
*/
private ChatError error;
}

View file

@ -1,25 +0,0 @@
package ai.z.openapi.service.knowledge;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents the usage information of the knowledge base.
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class KnowledgeId {
/**
* Unique identifier for the knowledge base
*/
@JsonProperty("id")
private String id;
}

View file

@ -1,67 +0,0 @@
package ai.z.openapi.service.knowledge;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents the knowledge base information.
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class KnowledgeInfo {
/**
* Knowledge base unique ID
*/
@JsonProperty("id")
private String id;
/**
* Vector model bound to the knowledge base
*/
@JsonProperty("embedding_id")
private String embeddingId;
/**
* Knowledge base name, limited to 100 characters
*/
@JsonProperty("name")
private String name;
/**
* User identifier, within 32 characters
*/
@JsonProperty("customer_identifier")
private String customerIdentifier;
/**
* Knowledge base description, limited to 500 characters
*/
@JsonProperty("description")
private String description;
/**
* Background color: 'blue', 'red', 'orange', 'purple', 'sky'
*/
@JsonProperty("background")
private String background;
/**
* Knowledge base icon: question: question mark, book: book, seal: seal, wrench:
* wrench, tag: tag, horn: horn, house: house
*/
@JsonProperty("icon")
private String icon;
/**
* Bucket ID, limited to 32 characters
*/
@JsonProperty("bucket_id")
private String bucketId;
}

View file

@ -1,32 +0,0 @@
package ai.z.openapi.service.knowledge;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents a page of knowledge base information.
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class KnowledgePage {
/**
* Knowledge base information list
*/
@JsonProperty("list")
private List<KnowledgeInfo> list;
/**
* Total count
*/
@JsonProperty("total")
private Integer total;
}

View file

@ -1,42 +0,0 @@
package ai.z.openapi.service.knowledge;
/**
* Knowledge service interface
*/
public interface KnowledgeService {
/**
* Creates a new knowledge base.
* @param request the knowledge creation request
* @return CreateKnowledgeResponse containing the creation result
*/
CreateKnowledgeResponse createKnowledge(KnowledgeBaseParams request);
/**
* Modifies an existing knowledge base.
* @param request the knowledge modification request
* @return KnowledgeEditResponse containing the modification result
*/
KnowledgeEditResponse modifyKnowledge(KnowledgeBaseParams request);
/**
* Queries knowledge.
* @param request the knowledge query request
* @return QueryKnowledgeApiResponse containing the query result
*/
QueryKnowledgeApiResponse queryKnowledge(QueryKnowledgeRequest request);
/**
* Deletes a knowledge base.
* @param knowledgeId the knowledge ID to delete
* @return KnowledgeResponse containing the deletion result
*/
KnowledgeEditResponse deleteKnowledge(String knowledgeId);
/**
* Checks if knowledge is used.
* @return KnowledgeUsedResponse containing the usage status
*/
KnowledgeUsedResponse checkKnowledgeUsed();
}

View file

@ -1,89 +0,0 @@
package ai.z.openapi.service.knowledge;
import ai.z.openapi.ZaiClient;
import ai.z.openapi.api.knowledge.KnowledgeApi;
import ai.z.openapi.service.model.AsyncResultRetrieveParams;
import ai.z.openapi.utils.RequestSupplier;
import ai.z.openapi.utils.StringUtils;
import retrofit2.Response;
/**
* Knowledge service implementation
*/
public class KnowledgeServiceImpl implements KnowledgeService {
private final ZaiClient zAiClient;
private final KnowledgeApi knowledgeApi;
public KnowledgeServiceImpl(ZaiClient zAiClient) {
this.zAiClient = zAiClient;
this.knowledgeApi = this.zAiClient.retrofit().create(KnowledgeApi.class);
}
@Override
public CreateKnowledgeResponse createKnowledge(KnowledgeBaseParams request) {
validateCreateKnowledgeParams(request);
RequestSupplier<KnowledgeBaseParams, KnowledgeId> supplier = knowledgeApi::knowledgeCreate;
return this.zAiClient.executeRequest(request, supplier, CreateKnowledgeResponse.class);
}
@Override
public KnowledgeEditResponse modifyKnowledge(KnowledgeBaseParams request) {
validateModifyKnowledgeParams(request);
RequestSupplier<KnowledgeBaseParams, Response<Void>> supplier = (params) -> knowledgeApi
.knowledgeModify(params.getKnowledgeId(), params);
return zAiClient.executeRequest(request, supplier, KnowledgeEditResponse.class);
}
@Override
public QueryKnowledgeApiResponse queryKnowledge(QueryKnowledgeRequest request) {
validateQueryKnowledgeParams(request);
RequestSupplier<QueryKnowledgeRequest, KnowledgePage> supplier = (params) -> knowledgeApi
.knowledgeQuery(params.getPage(), params.getSize());
return zAiClient.executeRequest(request, supplier, QueryKnowledgeApiResponse.class);
}
@Override
public KnowledgeEditResponse deleteKnowledge(String knowledgeId) {
validateDeleteKnowledgeParams(knowledgeId);
AsyncResultRetrieveParams params = AsyncResultRetrieveParams.builder().taskId(knowledgeId).build();
RequestSupplier<AsyncResultRetrieveParams, Response<Void>> supplier = (params1) -> knowledgeApi
.knowledgeDelete(params1.getTaskId());
return zAiClient.executeRequest(params, supplier, KnowledgeEditResponse.class);
}
@Override
public KnowledgeUsedResponse checkKnowledgeUsed() {
RequestSupplier<Void, KnowledgeUsed> supplier = (a) -> knowledgeApi.knowledgeUsed();
return zAiClient.executeRequest(null, supplier, KnowledgeUsedResponse.class);
}
private void validateCreateKnowledgeParams(KnowledgeBaseParams request) {
if (request == null) {
throw new IllegalArgumentException("request cannot be null");
}
}
private void validateModifyKnowledgeParams(KnowledgeBaseParams request) {
if (request == null) {
throw new IllegalArgumentException("request cannot be null");
}
if (StringUtils.isEmpty(request.getKnowledgeId())) {
throw new IllegalArgumentException("knowledge ID cannot be null or empty");
}
}
private void validateQueryKnowledgeParams(QueryKnowledgeRequest request) {
if (request == null) {
throw new IllegalArgumentException("request cannot be null");
}
}
private void validateDeleteKnowledgeParams(String knowledgeId) {
if (StringUtils.isEmpty(knowledgeId)) {
throw new IllegalArgumentException("knowledge ID cannot be null or empty");
}
}
}

View file

@ -1,31 +0,0 @@
package ai.z.openapi.service.knowledge;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents the usage statistics of the knowledge base.
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class KnowledgeStatistics {
/**
* Statistical word count
*/
@JsonProperty("word_num")
private Integer wordNum;
/**
* Length
*/
@JsonProperty("length")
private Integer length;
}

View file

@ -1,31 +0,0 @@
package ai.z.openapi.service.knowledge;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents the usage information of the knowledge base.
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class KnowledgeUsed {
/**
* Used amount
*/
@JsonProperty("used")
private KnowledgeStatistics used;
/**
* Total amount of knowledge base
*/
@JsonProperty("total")
private KnowledgeStatistics total;
}

View file

@ -1,20 +0,0 @@
package ai.z.openapi.service.knowledge;
import ai.z.openapi.core.model.ClientResponse;
import ai.z.openapi.service.model.ChatError;
import lombok.Data;
@Data
public class KnowledgeUsedResponse implements ClientResponse<KnowledgeUsed> {
private int code;
private String msg;
private boolean success;
private KnowledgeUsed data;
private ChatError error;
}

View file

@ -1,20 +0,0 @@
package ai.z.openapi.service.knowledge;
import ai.z.openapi.core.model.ClientResponse;
import ai.z.openapi.service.model.ChatError;
import lombok.Data;
@Data
public class QueryKnowledgeApiResponse implements ClientResponse<KnowledgePage> {
private int code;
private String msg;
private boolean success;
private KnowledgePage data;
private ChatError error;
}

View file

@ -1,24 +0,0 @@
package ai.z.openapi.service.knowledge;
import ai.z.openapi.core.model.ClientRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import java.util.HashMap;
import java.util.Map;
@EqualsAndHashCode(callSuper = false)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class QueryKnowledgeRequest implements ClientRequest<QueryKnowledgeRequest> {
private Integer page;
private Integer size;
}

View file

@ -1,67 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import com.fasterxml.jackson.annotation.JsonProperty;
import ai.z.openapi.core.model.ClientRequest;
import ai.z.openapi.service.CommonRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import java.util.List;
/**
* This class represents the parameters required for file creation and upload.
*/
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class DocumentCreateParams extends CommonRequest implements ClientRequest<DocumentCreateParams> {
/**
* local file
*/
private String filePath;
/**
* File and upload_detail are mutually exclusive and one is required.
*/
@JsonProperty("upload_detail")
private List<UploadDetail> uploadDetail;
/**
* The purpose of uploading the file. Supported values: "fine-tune", "retrieval",
* "batch".
* <ul>
* <li>For "retrieval", the supported file types are Doc, Docx, PDF, Xlsx, and URL,
* and the maximum file size is 5MB.</li>
* <li>For "fine-tune", the supported file type is .jsonl, and the maximum file size
* is 100MB.</li>
* </ul>
*/
@JsonProperty("purpose")
private String purpose;
/**
* Custom separator list. When the purpose is "retrieval" and the file type is pdf,
* url, or docx, upload with the default slicing rule as `\n`.
*/
@JsonProperty("custom_separator")
private List<String> customSeparator;
/**
* Knowledge Base ID. Required when the file upload purpose is "retrieval".
*/
@JsonProperty("knowledge_id")
private String knowledgeId;
/**
* Sentence size. Required when the file upload purpose is "retrieval".
*/
@JsonProperty("sentence_size")
private Integer sentenceSize;
}

View file

@ -1,75 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents the document data, including metadata and processing status.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DocumentData {
/**
* Knowledge unique ID
*/
@JsonProperty("id")
private String id;
/**
* Segmentation rules
*/
@JsonProperty("custom_separator")
private List<String> customSeparator;
/**
* Segment size
*/
@JsonProperty("sentence_size")
private String sentenceSize;
/**
* File size (bytes)
*/
@JsonProperty("length")
private Integer length;
/**
* File word count
*/
@JsonProperty("word_num")
private Integer wordNum;
/**
* File name
*/
@JsonProperty("name")
private String name;
/**
* File download link
*/
@JsonProperty("url")
private String url;
/**
* Vectorization status 0: Vectorizing 1: Vectorization completed 2: Vectorization
* failed
*/
@JsonProperty("embedding_stat")
private Integer embeddingStat;
/**
* Failure reason, present when vectorization fails
*/
@JsonProperty("failInfo")
private DocumentDataFailInfo failInfo;
}

View file

@ -1,33 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents the failure information of document data processing.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class DocumentDataFailInfo {
/**
* Failure code 10001: Knowledge unavailable, knowledge base space has reached the
* limit 10002: Knowledge unavailable, knowledge base space has reached the limit
* (word count exceeds limit)
*/
@JsonProperty("embedding_code")
private Integer embeddingCode;
/**
* Failure reason
*/
@JsonProperty("embedding_msg")
private String embeddingMsg;
}

View file

@ -1,20 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import ai.z.openapi.core.model.ClientResponse;
import ai.z.openapi.service.model.ChatError;
import lombok.Data;
@Data
public class DocumentDataResponse implements ClientResponse<DocumentData> {
private int code;
private String msg;
private boolean success;
private DocumentData data;
private ChatError error;
}

View file

@ -1,68 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import com.fasterxml.jackson.annotation.JsonProperty;
import ai.z.openapi.core.model.ClientRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import java.util.List;
import java.util.Map;
/**
* This class represents the parameters for editing a document in the knowledge base.
*/
@EqualsAndHashCode(callSuper = false)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class DocumentEditParams implements ClientRequest<DocumentEditParams> {
/**
* Knowledge ID
*/
@JsonProperty("id")
private String id;
/**
* Knowledge type:
* <ul>
* <li>1: Article knowledge: supports pdf, url, docx</li>
* <li>2: Q&A knowledge-document: supports pdf, url, docx</li>
* <li>3: Q&A knowledge-table: supports xlsx</li>
* <li>4: Product library-table: supports xlsx</li>
* <li>5: Custom: supports pdf, url, docx</li>
* </ul>
*/
@JsonProperty("knowledge_type")
private Integer knowledgeType;
/**
* Chunk rules when knowledge type is custom (knowledge_type=5), default \n
*/
@JsonProperty("custom_separator")
private List<String> customSeparator;
/**
* Chunk word count when knowledge type is custom (knowledge_type=5), range: 20-2000,
* default 300
*/
@JsonProperty("sentence_size")
private Integer sentenceSize;
/**
* Callback URL
*/
@JsonProperty("callback_url")
private String callbackUrl;
/**
* Headers to carry during callback
*/
@JsonProperty("callback_header")
private Map<String, String> callbackHeader;
}

View file

@ -1,21 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import ai.z.openapi.core.model.ClientResponse;
import ai.z.openapi.service.model.ChatError;
import lombok.Data;
import retrofit2.Response;
@Data
public class DocumentEditResponse implements ClientResponse<Response<Void>> {
private int code;
private String msg;
private boolean success;
private Response<Void> data;
private ChatError error;
}

View file

@ -1,38 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents the information of a failed document upload.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DocumentFailedInfo {
/**
* Reason for upload failure, including: unsupported file format, file size exceeds
* limit, knowledge base capacity is full, capacity limit is 500,000 words.
*/
@JsonProperty("failReason")
private String failReason;
/**
* File name
*/
@JsonProperty("filename")
private String filename;
/**
* Knowledge base ID
*/
@JsonProperty("documentId")
private String documentId;
}

View file

@ -1,32 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents the document information including success and failure details.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DocumentObject {
/**
* Information of successfully uploaded files
*/
@JsonProperty("successInfos")
private List<DocumentSuccessInfo> successInfos;
/**
* Information of failed uploaded files
*/
@JsonProperty("failedInfos")
private List<DocumentFailedInfo> failedInfos;
}

View file

@ -1,20 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import ai.z.openapi.core.model.ClientResponse;
import ai.z.openapi.service.model.ChatError;
import lombok.Data;
@Data
public class DocumentObjectResponse implements ClientResponse<DocumentObject> {
private int code;
private String msg;
private boolean success;
private DocumentObject data;
private ChatError error;
}

View file

@ -1,33 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents a page of document data, including a list of document entries and
* the object type.
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class DocumentPage {
/**
* List of document data entries.
*/
@JsonProperty("list")
private List<DocumentData> list;
/**
* The object type.
*/
@JsonProperty("object")
private String object;
}

View file

@ -1,31 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents the information of a successfully uploaded document.
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DocumentSuccessInfo {
/**
* File ID
*/
@JsonProperty("documentId")
private String documentId;
/**
* File name
*/
@JsonProperty("filename")
private String filename;
}

View file

@ -1,20 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import ai.z.openapi.core.model.ClientResponse;
import ai.z.openapi.service.model.ChatError;
import lombok.Data;
@Data
public class QueryDocumentApiResponse implements ClientResponse<DocumentPage> {
private int code;
private String msg;
private boolean success;
private DocumentPage data;
private ChatError error;
}

View file

@ -1,32 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import ai.z.openapi.core.model.ClientRequest;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import java.util.HashMap;
import java.util.Map;
@EqualsAndHashCode(callSuper = false)
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class QueryDocumentRequest implements ClientRequest<QueryDocumentRequest> {
@JsonProperty("knowledge_id")
private String knowledgeId;
private String purpose;
private Integer page;
private Integer limit;
private String order;
}

View file

@ -1,62 +0,0 @@
package ai.z.openapi.service.knowledge.document;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* This class represents the details required for uploading a file to the knowledge base.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class UploadDetail {
/**
* URL of the file to be uploaded.
*/
@JsonProperty("url")
private String url;
/**
* Knowledge type identifier.
*/
@JsonProperty("knowledge_type")
private int knowledgeType;
/**
* Optional file name.
*/
@JsonProperty("file_name")
private String fileName;
/**
* Optional sentence size for processing.
*/
@JsonProperty("sentence_size")
private Integer sentenceSize;
/**
* Optional list of custom separators.
*/
@JsonProperty("custom_separator")
private List<String> customSeparator;
/**
* Optional callback URL for notifications.
*/
@JsonProperty("callback_url")
private String callbackUrl;
/**
* Optional callback headers for the callback request.
*/
@JsonProperty("callback_header")
private Map<String, String> callbackHeader;
}

View file

@ -1,284 +0,0 @@
package ai.z.openapi.service.document;
import ai.z.openapi.ZaiClient;
import ai.z.openapi.core.config.ZaiConfig;
import ai.z.openapi.service.knowledge.document.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.*;
/**
* DocumentService test class for testing various functionalities of DocumentService and
* DocumentServiceImpl
*/
@DisplayName("DocumentService Tests")
public class DocumentServiceTest {
private static final Logger logger = LoggerFactory.getLogger(DocumentServiceTest.class);
private static final ObjectMapper mapper = new ObjectMapper();
private DocumentService documentService;
// Request ID template
private static final String REQUEST_ID_TEMPLATE = "document-test-%d";
// Test knowledge base ID (should be replaced with actual ID in real tests)
private static final String TEST_KNOWLEDGE_ID = "test-knowledge-id";
@BeforeEach
void setUp() {
ZaiConfig zaiConfig = new ZaiConfig();
String apiKey = zaiConfig.getApiKey();
if (apiKey == null) {
zaiConfig.setApiKey("id.test-api-key");
}
ZaiClient client = new ZaiClient(zaiConfig);
documentService = client.documents();
}
@Test
@DisplayName("Test DocumentService Instantiation")
void testDocumentServiceInstantiation() {
assertNotNull(documentService, "DocumentService should be properly instantiated");
assertInstanceOf(DocumentServiceImpl.class, documentService,
"DocumentService should be an instance of DocumentServiceImpl");
}
@Test
@DisplayName("Test Create Document with File Path")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testCreateDocumentWithFilePath() throws JsonProcessingException {
// Prepare test data
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
DocumentCreateParams request = DocumentCreateParams.builder()
.filePath("src/test/resources/document.pdf")
.purpose("retrieval")
.knowledgeId(TEST_KNOWLEDGE_ID)
.sentenceSize(200)
.customSeparator(Arrays.asList("\n", ""))
.requestId(requestId)
.build();
// Note: This test will fail in real execution due to file not existing
// It's mainly for testing the parameter validation and structure
try {
DocumentObjectResponse response = documentService.createDocument(request);
// If we reach here, verify the response structure
assertNotNull(response, "Response should not be null");
logger.info("Document creation response: {}", mapper.writeValueAsString(response));
}
catch (RuntimeException e) {
// Expected for non-existent file
assertTrue(e.getMessage().contains("file not found") || e.getMessage().contains("error"));
logger.info("Expected error for non-existent file: {}", e.getMessage());
}
}
@Test
@DisplayName("Test Create Document with Upload Detail")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testCreateDocumentWithUploadDetail() throws JsonProcessingException {
// Prepare test data
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
UploadDetail uploadDetail = new UploadDetail();
uploadDetail.setUrl("https://example.com/test-document.pdf");
uploadDetail.setKnowledgeType(1);
uploadDetail.setFileName("test-document.pdf");
uploadDetail.setSentenceSize(200);
DocumentCreateParams request = DocumentCreateParams.builder()
.uploadDetail(Collections.singletonList(uploadDetail))
.purpose("retrieval")
.knowledgeId(TEST_KNOWLEDGE_ID)
.sentenceSize(200)
.requestId(requestId)
.build();
DocumentObjectResponse response = documentService.createDocument(request);
// Verify results
assertNotNull(response, "Response should not be null");
logger.info("Document creation with upload detail response: {}", mapper.writeValueAsString(response));
}
@Test
@DisplayName("Test List Documents")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testListDocuments() throws JsonProcessingException {
// Prepare test data
QueryDocumentRequest request = QueryDocumentRequest.builder()
.knowledgeId(TEST_KNOWLEDGE_ID)
.purpose("retrieval")
.page(1)
.limit(10)
.order("desc")
.build();
QueryDocumentApiResponse response = documentService.listDocuments(request);
// Verify results
assertNotNull(response, "Response should not be null");
logger.info("List documents response: {}", mapper.writeValueAsString(response));
}
@Test
@DisplayName("Test Retrieve Document")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testRetrieveDocument() throws JsonProcessingException {
// Use a test document ID
String testDocumentId = "test-document-id-" + System.currentTimeMillis();
DocumentDataResponse response = documentService.retrieveDocument(testDocumentId);
// Verify results
assertNotNull(response, "Response should not be null");
logger.info("Retrieve document response: {}", mapper.writeValueAsString(response));
}
@Test
@DisplayName("Test Modify Document")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testModifyDocument() throws JsonProcessingException {
// Prepare test data
String testDocumentId = "test-document-id-" + System.currentTimeMillis();
DocumentEditParams request = DocumentEditParams.builder().id(testDocumentId).knowledgeType(1).build();
DocumentEditResponse response = documentService.modifyDocument(request);
// Verify results
assertNotNull(response, "Response should not be null");
logger.info("Modify document response: {}", mapper.writeValueAsString(response));
}
@Test
@DisplayName("Test Delete Document")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testDeleteDocument() throws JsonProcessingException {
// Use a test document ID
String testDocumentId = "test-document-id-" + System.currentTimeMillis();
DocumentEditResponse response = documentService.deleteDocument(testDocumentId);
// Verify results
assertNotNull(response, "Response should not be null");
logger.info("Delete document response: {}", mapper.writeValueAsString(response));
}
@Test
@DisplayName("Test Parameter Validation - Null Request")
void testValidation_NullRequest() {
assertThrows(NullPointerException.class, () -> {
documentService.createDocument(null);
}, "Null request should throw NullPointerException");
}
@Test
@DisplayName("Test Parameter Validation - Both FilePath and UploadDetail")
void testValidation_BothFilePathAndUploadDetail() {
UploadDetail uploadDetail = new UploadDetail();
uploadDetail.setUrl("https://example.com/test.pdf");
DocumentCreateParams request = DocumentCreateParams.builder()
.filePath("src/test/resources/document.pdf\"")
.uploadDetail(Collections.singletonList(uploadDetail))
.purpose("retrieval")
.knowledgeId(TEST_KNOWLEDGE_ID)
.build();
assertThrows(RuntimeException.class, () -> {
documentService.createDocument(request);
}, "Having both filePath and uploadDetail should throw RuntimeException");
}
@Test
@DisplayName("Test Parameter Validation - Empty Knowledge ID")
void testValidation_EmptyKnowledgeId() {
DocumentCreateParams request = DocumentCreateParams.builder()
.filePath("src/test/resources/document.pdf")
.purpose("retrieval")
.knowledgeId("")
.build();
// This should be handled by the API validation
try {
DocumentObjectResponse response = documentService.createDocument(request);
// If response is received, it should contain error information
if (response != null && !response.isSuccess()) {
assertNotNull(response.getError(), "Error should be present for invalid knowledge ID");
}
}
catch (Exception e) {
// Expected for invalid parameters
logger.info("Expected error for empty knowledge ID: {}", e.getMessage());
}
}
@Test
@DisplayName("Test Different Document Purposes")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testDifferentDocumentPurposes() throws JsonProcessingException {
String[] purposes = { "retrieval", "fine-tune", "batch" };
for (String purpose : purposes) {
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
UploadDetail uploadDetail = new UploadDetail();
uploadDetail.setUrl("https://example.com/test-" + purpose + ".pdf");
uploadDetail.setKnowledgeType(1);
DocumentCreateParams request = DocumentCreateParams.builder()
.uploadDetail(Collections.singletonList(uploadDetail))
.purpose(purpose)
.knowledgeId(TEST_KNOWLEDGE_ID)
.sentenceSize(200)
.requestId(requestId)
.build();
DocumentObjectResponse response = documentService.createDocument(request);
assertNotNull(response, "Response should not be null for purpose: " + purpose);
logger.info("Purpose {} response: {}", purpose, mapper.writeValueAsString(response));
}
}
@Test
@DisplayName("Test Document with Custom Separators")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testDocumentWithCustomSeparators() throws JsonProcessingException {
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
UploadDetail uploadDetail = new UploadDetail();
uploadDetail.setUrl("https://example.com/test-document.pdf");
uploadDetail.setKnowledgeType(1);
uploadDetail.setCustomSeparator(Arrays.asList("\n", "", "!", "?"));
DocumentCreateParams request = DocumentCreateParams.builder()
.uploadDetail(Collections.singletonList(uploadDetail))
.purpose("retrieval")
.knowledgeId(TEST_KNOWLEDGE_ID)
.sentenceSize(150)
.customSeparator(Arrays.asList("\n", "", "!", "?"))
.requestId(requestId)
.build();
DocumentObjectResponse response = documentService.createDocument(request);
assertNotNull(response, "Response should not be null");
logger.info("Document with custom separators response: {}", mapper.writeValueAsString(response));
}
}

View file

@ -1,363 +0,0 @@
package ai.z.openapi.service.knowledge;
import ai.z.openapi.ZaiClient;
import ai.z.openapi.core.config.ZaiConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.*;
/**
* KnowledgeService test class for testing various functionalities of KnowledgeService and
* KnowledgeServiceImpl
*/
@DisplayName("KnowledgeService Tests")
public class KnowledgeServiceTest {
private static final Logger logger = LoggerFactory.getLogger(KnowledgeServiceTest.class);
private static final ObjectMapper mapper = new ObjectMapper();
private KnowledgeService knowledgeService;
// Request ID template
private static final String REQUEST_ID_TEMPLATE = "knowledge-test-%d";
@BeforeEach
void setUp() {
ZaiConfig zaiConfig = new ZaiConfig();
String apiKey = zaiConfig.getApiKey();
if (apiKey == null) {
zaiConfig.setApiKey("id.test-api-key");
}
ZaiClient client = new ZaiClient(zaiConfig);
knowledgeService = client.knowledge();
}
@Test
@DisplayName("Test KnowledgeService Instantiation")
void testKnowledgeServiceInstantiation() {
assertNotNull(knowledgeService, "KnowledgeService should be properly instantiated");
assertInstanceOf(KnowledgeServiceImpl.class, knowledgeService,
"KnowledgeService should be an instance of KnowledgeServiceImpl");
}
@Test
@DisplayName("Test Create Knowledge Base")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testCreateKnowledge() throws JsonProcessingException {
// Prepare test data
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
KnowledgeBaseParams request = KnowledgeBaseParams.builder()
.embeddingId(1)
.name("Test Knowledge Base")
.description("Test knowledge base for unit testing")
.icon("question")
.background("blue")
.customerIdentifier("test-customer")
.knowledgeId(requestId)
.build();
// Execute test
CreateKnowledgeResponse response = knowledgeService.createKnowledge(request);
System.out.println(response.getError());
// Verify results
assertNotNull(response, "Response should not be null");
assertTrue(response.isSuccess(), "Response should be successful");
assertNotNull(response.getData(), "Response data should not be null");
assertNotNull(response.getData().getId(), "Knowledge ID should not be null");
assertNull(response.getError(), "Response error should be null");
logger.info("Create knowledge response: {}", mapper.writeValueAsString(response));
}
@Test
@DisplayName("Test Modify Knowledge Base")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testModifyKnowledge() throws JsonProcessingException {
// Prepare test data
String requestId = String.format(REQUEST_ID_TEMPLATE, System.currentTimeMillis());
KnowledgeBaseParams request = KnowledgeBaseParams.builder()
.knowledgeId("test-knowledge-id")
.embeddingId(1)
.name("Modified Test Knowledge Base")
.description("Modified test knowledge base for unit testing")
.icon("book")
.background("green")
.customerIdentifier("test-customer")
.knowledgeId(requestId)
.build();
// Execute test
KnowledgeEditResponse response = knowledgeService.modifyKnowledge(request);
// Verify results
assertNotNull(response, "Response should not be null");
logger.info("Modify knowledge response: {}", mapper.writeValueAsString(response));
}
@Test
@DisplayName("Test Query Knowledge")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testQueryKnowledge() throws JsonProcessingException {
// Prepare test data
QueryKnowledgeRequest request = QueryKnowledgeRequest.builder().page(1).size(10).build();
// Execute test
QueryKnowledgeApiResponse response = knowledgeService.queryKnowledge(request);
// Verify results
assertNotNull(response, "Response should not be null");
assertTrue(response.isSuccess(), "Response should be successful");
assertNotNull(response.getData(), "Response data should not be null");
assertNull(response.getError(), "Response error should be null");
logger.info("Query knowledge response: {}", mapper.writeValueAsString(response));
}
@Test
@DisplayName("Test Delete Knowledge Base")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testDeleteKnowledge() throws JsonProcessingException {
// Prepare test data
String knowledgeId = "test-knowledge-id-" + System.currentTimeMillis();
// Execute test
KnowledgeEditResponse response = knowledgeService.deleteKnowledge(knowledgeId);
// Verify results
assertNotNull(response, "Response should not be null");
logger.info("Delete knowledge response: {}", mapper.writeValueAsString(response));
}
@Test
@DisplayName("Test Check Knowledge Used")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testCheckKnowledgeUsed() throws JsonProcessingException {
// Execute test
KnowledgeUsedResponse response = knowledgeService.checkKnowledgeUsed();
// Verify results
assertNotNull(response, "Response should not be null");
assertTrue(response.isSuccess(), "Response should be successful");
assertNotNull(response.getData(), "Response data should not be null");
assertNull(response.getError(), "Response error should be null");
logger.info("Check knowledge used response: {}", mapper.writeValueAsString(response));
}
@Test
@DisplayName("Test Parameter Validation - Null Create Request")
void testValidation_NullCreateRequest() {
assertThrows(IllegalArgumentException.class, () -> {
knowledgeService.createKnowledge(null);
}, "Null create request should throw IllegalArgumentException");
}
@Test
@DisplayName("Test Parameter Validation - Null Modify Request")
void testValidation_NullModifyRequest() {
assertThrows(IllegalArgumentException.class, () -> {
knowledgeService.modifyKnowledge(null);
}, "Null modify request should throw IllegalArgumentException");
}
@Test
@DisplayName("Test Parameter Validation - Null Query Request")
void testValidation_NullQueryRequest() {
assertThrows(IllegalArgumentException.class, () -> {
knowledgeService.queryKnowledge(null);
}, "Null query request should throw IllegalArgumentException");
}
@Test
@DisplayName("Test Parameter Validation - Null Knowledge ID")
void testValidation_NullKnowledgeId() {
assertThrows(IllegalArgumentException.class, () -> {
knowledgeService.deleteKnowledge(null);
}, "Null knowledge ID should throw IllegalArgumentException");
}
@Test
@DisplayName("Test Parameter Validation - Empty Knowledge ID")
void testValidation_EmptyKnowledgeId() {
assertThrows(IllegalArgumentException.class, () -> {
knowledgeService.deleteKnowledge("");
}, "Empty knowledge ID should throw IllegalArgumentException");
}
@Test
@DisplayName("Test Create Knowledge with Invalid Parameters")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testCreateKnowledgeWithInvalidParams() {
// Test with missing required fields
KnowledgeBaseParams request = KnowledgeBaseParams.builder()
.name("") // Empty name
.build();
CreateKnowledgeResponse response = knowledgeService.createKnowledge(request);
// Should return error response
assertNotNull(response, "Response should not be null");
assertFalse(response.isSuccess(), "Response should not be successful with invalid parameters");
assertNotNull(response.getError(), "Response should contain error information");
}
@Test
@DisplayName("Test Modify Knowledge with Non-existent ID")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testModifyKnowledgeWithNonExistentId() {
KnowledgeBaseParams request = KnowledgeBaseParams.builder()
.knowledgeId("non-existent-id-" + System.currentTimeMillis())
.embeddingId(1)
.name("Test Knowledge Base")
.description("Test description")
.build();
KnowledgeEditResponse response = knowledgeService.modifyKnowledge(request);
// Should return error response
assertNotNull(response, "Response should not be null");
assertNotNull(response.getError(), "Response should contain error for non-existent knowledge ID");
}
@Test
@DisplayName("Test Delete Knowledge with Non-existent ID")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testDeleteKnowledgeWithNonExistentId() {
String nonExistentId = "non-existent-id-" + System.currentTimeMillis();
KnowledgeEditResponse response = knowledgeService.deleteKnowledge(nonExistentId);
// Should return error response
assertNotNull(response, "Response should not be null");
assertNotNull(response.getError(), "Response should contain error for non-existent knowledge ID");
}
@Test
@DisplayName("Test Query Knowledge with Invalid Page Parameters")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testQueryKnowledgeWithInvalidPageParams() {
// Test with negative page number
QueryKnowledgeRequest request = QueryKnowledgeRequest.builder().page(-1).size(10).build();
QueryKnowledgeApiResponse response = knowledgeService.queryKnowledge(request);
// Should handle invalid parameters gracefully
assertNotNull(response, "Response should not be null");
logger.info("Query knowledge with invalid page response: {}", response);
}
@Test
@DisplayName("Test Knowledge Base Name Length Validation")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testKnowledgeBaseNameLengthValidation() {
// Test with name exceeding 100 characters
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 101; i++) {
sb.append("a");
}
String longName = sb.toString();
KnowledgeBaseParams request = KnowledgeBaseParams.builder()
.embeddingId(1)
.name(longName)
.description("Test description")
.build();
// This should be validated either by the service or the API
assertDoesNotThrow(() -> {
CreateKnowledgeResponse response = knowledgeService.createKnowledge(request);
// If validation is done server-side, we expect an error response
if (!response.isSuccess()) {
assertNotNull(response.getError(), "Should contain validation error");
}
});
}
@Test
@DisplayName("Test Knowledge Base Description Length Validation")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testKnowledgeBaseDescriptionLengthValidation() {
// Test with description exceeding 500 characters
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 501; i++) {
sb.append("a");
}
String longDescription = sb.toString();
KnowledgeBaseParams request = KnowledgeBaseParams.builder()
.embeddingId(1)
.name("Test Knowledge Base")
.description(longDescription)
.build();
// This should be validated either by the service or the API
assertDoesNotThrow(() -> {
CreateKnowledgeResponse response = knowledgeService.createKnowledge(request);
// If validation is done server-side, we expect an error response
if (!response.isSuccess()) {
assertNotNull(response.getError(), "Should contain validation error");
}
});
}
@Test
@DisplayName("Test Customer Identifier Length Validation")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testCustomerIdentifierLengthValidation() {
// Test with customer identifier exceeding 32 characters
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 33; i++) {
sb.append("a");
}
String longCustomerIdentifier = sb.toString();
KnowledgeBaseParams request = KnowledgeBaseParams.builder()
.embeddingId(1)
.name("Test Knowledge Base")
.description("Test description")
.customerIdentifier(longCustomerIdentifier)
.build();
// This should be validated either by the service or the API
assertDoesNotThrow(() -> {
CreateKnowledgeResponse response = knowledgeService.createKnowledge(request);
// If validation is done server-side, we expect an error response
if (!response.isSuccess()) {
assertNotNull(response.getError(), "Should contain validation error");
}
});
}
@Test
@DisplayName("Test Knowledge ID Length Validation")
@EnabledIfEnvironmentVariable(named = "ZAI_API_KEY", matches = "^[^.]+\\.[^.]+$")
void testKnowledgeIdLengthValidation() {
// Test with bucket ID exceeding 32 characters
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 33; i++) {
sb.append("a");
}
String longKnowledgeId = sb.toString();
KnowledgeBaseParams request = KnowledgeBaseParams.builder()
.embeddingId(1)
.name("Test Knowledge Base")
.description("Test description")
.knowledgeId(longKnowledgeId)
.build();
// This should be validated either by the service or the API
assertDoesNotThrow(() -> {
CreateKnowledgeResponse response = knowledgeService.createKnowledge(request);
// If validation is done server-side, we expect an error response
if (!response.isSuccess()) {
assertNotNull(response.getError(), "Should contain validation error");
}
});
}
}