public static String callGPT(String prompt,String base64Image) {
ChatModel chatModel = OpenAiChatModel.builder()
.apiKey(ApiKeys.OPENAI_API_KEY) // Please use your own OpenAI API key
.modelName(GPT_4_O_MINI)
.maxTokens(50)
.build();
SystemMessage systemMessage = SystemMessage.from(Prompts.SYSTEM_PROMPT_TEXT_ONLY);
UserMessage userMessage = UserMessage.from(
TextContent.from(prompt),
ImageContent.from(base64Image, "image/png")
);
String response = chatModel.chat(systemMessage,userMessage).aiMessage().text();
System.out.println("AI Response: " + response);
String[] responseParts = response.split("Thought:|Action:|Observation:");
//extract action and thought pattern = r'Thought:|Action:|Observation:'
String thought = responseParts[1].trim();
String action = responseParts[2].trim();
// System.out.println("Thought: " + thought);
return action;
}
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://the-internet.herokuapp.com/login");
try{
driver.findElement(By.tagName("body")).click();
}catch (Exception e){
System.out.println(e.toString());
}
((JavascriptExecutor) driver).executeScript("window.onkeydown = function(e) {if(e.keyCode == 32 && e.target.type != 'text' && e.target.type != 'textarea') {e.preventDefault();}};");
Object[] raw = Utils.getWebWementRect(driver);
List<WebElement> rects = (List<WebElement>) raw[0];
List<WebElement> elements = (List<WebElement>) raw[1];
List<String> webText = (List<String>) raw[2];
String base64Image = Utils.base64EncodeImage(driver);
String promptTask = formatPrompt("Type tomsmith into username textbox", String.valueOf(webText));
String action = Utils.callGPT(promptTask, base64Image);
System.out.println(action);
Pattern typePattern = Pattern.compile("Type \\[?(\\d+)]?[; ]+\\[?(.[^]]*)]?");
Matcher matcher = typePattern.matcher(action);
Map<String, String> actionMap = new HashMap<>();
while (matcher.find()) {
System.out.println("Found action: " + matcher.group());
String key = matcher.group(1);
String value = matcher.group(2);
actionMap.put("action", "type");
actionMap.put("elementIndex", key);
actionMap.put("content", value);
}
int elementIndex = Integer.parseInt(actionMap.get("elementIndex"));
System.out.println(webText.get(elementIndex));
WebElement targetElement = elements.get(elementIndex);
for (WebElement rect : rects) {
((JavascriptExecutor) driver).executeScript("arguments[0].remove()",rect);
}
targetElement.sendKeys(actionMap.get("content"));
Utils.takeScreenshot(driver, "screenshot-after-action.png");
driver.quit();
}
public static String formatPrompt(String task,String webText) {
return """
## tasks
{task}
## context
Observation: please analyze the attached screenshot and give the Thought and Action.
```
{web_text}
```
""".replace("{task}", task).replace("{web_text}", webText);
}
// Some codecode
package voyager;
public class Prompts {
public static String SYSTEM_PROMPT_TEXT_ONLY = """
Imagine you are a robot browsing the web, just like humans. Now you need to complete a task. In each iteration, you will receive an Accessibility Tree with numerical label representing information about the page, then follow the guidelines and choose one of the following actions:
1. Click a Web Element.
2. Delete existing content in a textbox and then type content.
3. Scroll up or down. Multiple scrolls are allowed to browse the webpage. Pay attention!! The default scroll is the whole window. If the scroll widget is located in a certain area of the webpage, then you have to specify a Web Element in that area. I would hover the mouse there and then scroll.
4. Wait. Typically used to wait for unfinished webpage processes, with a duration of 5 seconds.
5. Go back, returning to the previous webpage.
6. Google, directly jump to the Google search page. When you can't find information in some websites, try starting over with Google.
7. Answer. This action should only be chosen when all questions in the task have been solved.
Correspondingly, Action should STRICTLY follow the format:
- Click [Numerical_Label]
- Type [Numerical_Label]; [Content]
- Scroll [Numerical_Label or WINDOW]; [up or down]
- Wait
- GoBack
- Google
- ANSWER; [content]
Key Guidelines You MUST follow:
* Action guidelines *
1) To input text, NO need to click textbox first, directly type content. After typing, the system automatically hits `ENTER` key. Sometimes you should click the search button to apply search filters. Try to use simple language when searching.
2) You must Distinguish between textbox and search button, don't type content into the button! If no textbox is found, you may need to click the search button first before the textbox is displayed.
3) Execute only one action per iteration.
4) STRICTLY Avoid repeating the same action if the webpage remains unchanged. You may have selected the wrong web element or numerical label. Continuous use of the Wait is also NOT allowed.
5) When a complex Task involves multiple questions or steps, select "ANSWER" only at the very end, after addressing all of these questions (steps). Flexibly combine your own abilities with the information in the web page. Double check the formatting requirements in the task when ANSWER.
* Web Browsing Guidelines *
1) Don't interact with useless web elements like Login, Sign-in, donation that appear in Webpages. Pay attention to Key Web Elements like search textbox and menu.
2) Vsit video websites like YouTube is allowed BUT you can't play videos. Clicking to download PDF is allowed and will be analyzed by the Assistant API.
3) Focus on the date in task, you must look for results that match the date. It may be necessary to find the correct year, month and day at calendar.
4) Pay attention to the filter and sort functions on the page, which, combined with scroll, can help you solve conditions like 'highest', 'cheapest', 'lowest', 'earliest', etc. Try your best to find the answer that best fits the task.
Your reply should strictly follow the format:
Thought: {Your brief thoughts (briefly summarize the info that will help ANSWER)}
Action: {One Action format you choose}
Then the User will provide:
Observation: {Accessibility Tree of a web page}
""";
}