[]
        
(Showing Draft Content)

AI Assistant

DsExcel Java provides AI functions and model request handlers, allowing you to send user prompts and data to specified large language models, write model return results to target cells, and seamlessly integrate complex artificial intelligence processing workflows into calculation chains. With AI functions, you can easily achieve text query, data analysis, text generation, text translation, and text sentiment analysis in your spreadsheets.

Prerequisites

Before using the AI Assistant, please ensure you have obtained a valid API key from OpenAI or other AI service providers.

Model Request Handler

DsExcel Java provides the IAIModelRequestHandler interface to help users implement complete custom interaction flows with AI models.

The sendRequestAsync method is used to submit AI requests and return asynchronous results. You can refer to the sample code for AI functions, or implement this method yourself as needed to manage the request lifecycle, including building requests, sending them, handling responses and errors. You can also manage access credentials, model selection, and parameter configuration; ensure invocation security (such as credential protection, encrypted transmission, etc.); integrate middleware as needed (such as sensitive word filtering and log auditing); and set policies such as retry and timeout to improve the security and stability of invocations.

When using the model request handler, DsExcel Java will not intervene in the model request workflow initiated via IAIModelRequestHandler, nor will it store your API keys or any request/response data.

/**
 * Implementation of IAIModelRequestHandler for OpenAI API.
 */
public class OpenAIModelRequestHandler implements IAIModelRequestHandler {
    private String _apiEndpoint;
    private String _apiKey;
    private String _model;
    public OpenAIModelRequestHandler(String apiEndpoint, String apiKey, String model) {
        if (apiEndpoint == null || apiEndpoint.trim().isEmpty())
            throw new IllegalArgumentException("API endpoint cannot be null or empty.");
        if (apiKey == null || apiKey.trim().isEmpty())
            throw new IllegalArgumentException("API key cannot be null or empty.");
        _apiEndpoint = apiEndpoint.replaceAll("/$", "");
        _apiKey = apiKey;
        _model = model;
    }
    @Override
    public CompletableFuture<AIModelResponse> sendRequestAsync(AIModelRequest request) {
        CompletableFuture<AIModelResponse> result = new CompletableFuture<>();
        if (request == null) {
            AIModelResponse modelResponse = new AIModelResponse();
            modelResponse.setSuccess(false);
            System.err.println("Request cannot be null.");
            result.complete(modelResponse);
            return result;
        }
        OpenAIClientAsync openAIClient = OpenAIOkHttpClientAsync.builder()
                .apiKey(_apiKey)
                .baseUrl(_apiEndpoint)
                .build();
        ChatCompletionCreateParams.Builder builder = ChatCompletionCreateParams.builder();
        for (AIMessage item : request.getMessages()) {
            switch (item.getRole().toLowerCase()) {
                case "system":
                    builder.addSystemMessage(item.getContent());
                    break;
                case "user":
                    builder.addUserMessage(item.getContent());
                    break;
                default:
                    throw new RuntimeException("Unknown message role:" + item.getRole());
            }
        }
        builder.model(_model);
        ChatCompletionCreateParams params = builder.build();
        CompletableFuture<ChatCompletion> chatCompletion = openAIClient.chat().completions().create(params);
        chatCompletion.whenComplete((response, exception) -> {
            try {
                if (exception != null) {
                    AIModelResponse errorResponse = new AIModelResponse();
                    errorResponse.setSuccess(false);
                    System.err.println("An error occurred: " + exception.getMessage());
                    result.complete(errorResponse);
                } else {
                    if (response != null && !response.choices().isEmpty()) {
                        StringBuilder contentBuilder = new StringBuilder();
                        for (ChatCompletion.Choice choice : response.choices()) {
                            choice.message();
                            if (choice.message().content().isPresent()) {
                                contentBuilder.append(choice.message().content().get());
                            }
                        }
                        AIModelResponse successResponse = new AIModelResponse();
                        successResponse.setSuccess(true);
                        successResponse.setContent(contentBuilder.toString());
                        result.complete(successResponse);
                    } else {
                        AIModelResponse noContentResponse = new AIModelResponse();
                        noContentResponse.setSuccess(false);
                        System.err.println("No content received from the model.");
                        result.complete(noContentResponse);
                    }
                }
            } finally {
                try {
                    openAIClient.close();
                } catch (Exception e) {
                    System.err.println("Error closing OpenAI client: " + e.getMessage());
                }
            }
        });
        return result;
    }
}

Error Types

When the AI function returns the error values below, please refer to the table to troubleshoot possible reasons.

Error Value

Description

#VALUE!

This error is caused by invalid input parameters or internal errors, resulting in function execution failure.

#BUSY!

This error indicates that the function is being calculated asynchronously and the result is not yet available.

#CONNECT!

This error occurs when the IAIModelRequestHandler returns an error response or when a network connection failure occurs.

#NA!

This error indicates that no Workbook.AIModelRequestHandler is registered.

Security Best Practices

Data Protection

  • Always clean and de-identify sensitive spreadsheet data.

  • For results returned by requests, ensure sensitive fields are de-identified.

Validation

  • Verify all AI-generated content.

  • Perform security checks on output results.

AI-Generated Content Disclaimer

  1. Content Generation Risks

    This service utilizes third-party AI models injected by users to generate outputs. Results may contain inaccuracies, omissions, or misleading content due to inherent limitations in model architectures and training data. While we implement prompt engineering and technical constraints to optimize outputs, we cannot eliminate all error risks stemming from fundamental model deficiencies.

  2. User Verification Obligations

    By using this service, you acknowledge and agree to:

    • Conduct manual verification of all generated content

    • Refrain from using unvalidated outputs in high-risk scenarios (legal, medical, financial, etc.)

    • Hold us harmless for any direct/indirect damages caused by reliance on generated content

  3. Technical Limitations

    We disclaim responsibility for:

    • Output failures caused by third-party model defects or logic errors

    • Unsuccessful error recovery attempts through fault-tolerant procedures

    • Technical constraints inherent in current AI technologies

  4. Intellectual Property Compliance

    You must ensure:

    • Injected models/content do not infringe third-party rights

    • No illegal/sensitive material is processed through the service

    • Compliance with model providers' IP agreements

  5. Agreement Updates

    We reserve the right to modify these terms to align with:

    • Technological advancements (e.g. new AI safety protocols)

    • Regulatory changes (e.g. updated AI governance frameworks)

    • Service architecture improvements

Limitations

Because AI models are non-deterministic, the same formula may produce different results when recalculated.