Skip to content

Commit

Permalink
feat: implement async ai request
Browse files Browse the repository at this point in the history
  • Loading branch information
nickchecan committed Jan 12, 2025
1 parent b46473d commit 62d22ae
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ function sendMessage() {
if (userInput.trim() === "") return;
try {
addUserMessage(userInput);
var answer = getAIResponse(userInput); // Java callback
addBotMessage(answer);
getAIResponse(userInput); // Java callback
} catch (e) {
}
updatePlaceholder();
Expand Down Expand Up @@ -33,6 +32,12 @@ function clearMessageAndScrollDown() {
chatBox.scrollTop = chatBox.scrollHeight;
}

function receiveMessage(output) {
addBotMessage(output);
updatePlaceholder();
clearMessageAndScrollDown();
}

function login() {
hideInstructions();
activateChat();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package com.developer.nefarious.zjoule.plugin.core.functions;

import java.util.concurrent.CompletableFuture;

import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.BrowserFunction;
import org.eclipse.swt.widgets.Display;

import com.developer.nefarious.zjoule.plugin.chat.ChatOrchestrator;
import com.developer.nefarious.zjoule.plugin.core.events.Initialization;

/**
* Handles user prompts from the browser and communicates with the chat orchestrator to generate responses.
Expand All @@ -13,6 +17,8 @@
* user input and generate AI-driven responses.
*/
public class PromptHandler extends BrowserFunction {

private Browser browser;

/** The {@link ChatOrchestrator} instance responsible for processing user prompts. */
private ChatOrchestrator chatOrchestrator;
Expand All @@ -36,21 +42,62 @@ public static PromptHandler create(final Browser browser, final String name) {
*/
public PromptHandler(final Browser browser, final String name) {
super(browser, name);
this.browser = browser;
chatOrchestrator = new ChatOrchestrator();
}

/**
* Handles the JavaScript function call from the browser.
* <p>
* This method takes the first argument as the user prompt, passes it to the
* {@link ChatOrchestrator#getAnswer(String)} method, and returns the generated AI response.
* Handles a user prompt from the browser and initiates asynchronous processing to generate an AI response.
*
* <p>This method is invoked via the {@link BrowserFunction} interface when a corresponding JavaScript
* function is called in the browser widget. It processes the first argument as a user prompt, retrieves
* an AI-generated response asynchronously using the {@link ChatOrchestrator}, and delivers the response
* back to the browser environment through the JavaScript function {@code receiveMessage}.</p>
*
* <p>The response is escaped to ensure it is safe for inclusion in JavaScript code, avoiding issues
* caused by special characters.</p>
*
* @param arguments an array of objects passed from JavaScript. The first element is expected to be
* a {@code String} representing the user prompt.
* @return always {@code null}, as the operation is asynchronous and does not provide an immediate result.
*
* @param arguments the arguments passed from the JavaScript function call.
* @return the AI-generated response as an {@link Object}.
* @throws IllegalArgumentException if {@code arguments} is {@code null}, empty, or if the first element is {@code null}.
*/
@Override
public Object function(final Object[] arguments) {
String userPrompt = arguments[0].toString();
return chatOrchestrator.getAnswer(userPrompt);

CompletableFuture<String> futureResponse = CompletableFuture.supplyAsync(() -> chatOrchestrator.getAnswer(userPrompt));

futureResponse.thenAccept(response -> {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
String escapedResponse = escapeForJavaScript(response);
browser.execute("receiveMessage(\"" + escapedResponse + "\");");
}
});
});

return null; // no need for return as answer will run asynchronously
}

/**
* Escapes a string for safe inclusion in JavaScript code.
*
* @param input the string to escape
* @return the escaped string
*/
private String escapeForJavaScript(String input) {
if (input == null) {
return "";
}
return input
.replace("\\", "\\\\") // Escape backslashes
.replace("\"", "\\\"") // Escape double quotes
.replace("\n", "\\n") // Escape newlines
.replace("\r", "\\r") // Escape carriage returns
.replace("'", "\\'"); // Escape single quotes
}

}

0 comments on commit 62d22ae

Please sign in to comment.