Skip to content

Commit

Permalink
removed dependencies, refactored OpenAI code, addend anthropic Claude
Browse files Browse the repository at this point in the history
  • Loading branch information
haesleinhuepf committed Aug 24, 2024
1 parent b682698 commit 23a611b
Show file tree
Hide file tree
Showing 5 changed files with 261 additions and 66 deletions.
12 changes: 4 additions & 8 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -209,15 +209,11 @@
</dependency>

<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>client</artifactId>
<version>0.14.0</version>
</dependency>
<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>service</artifactId>
<version>0.14.0</version>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230227</version>
</dependency>

</dependencies>

<repositories>
Expand Down
84 changes: 84 additions & 0 deletions src/main/java/org/scijava/ui/swing/script/ClaudeApiClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package org.scijava.ui.swing.script;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class ClaudeApiClient {

public static String prompt(String prompt, String model, String apikey, String apiurl) throws IOException {

if (apiurl == null) {
apiurl = "https://api.anthropic.com/v1/messages";
}
if (apikey == null) {
apikey = System.getenv("ANTHROPIC_API_KEY");
}

System.out.println("API KEY:" + apikey);

URL url = new URL(apiurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("x-api-key", apikey);
connection.setRequestProperty("anthropic-version", "2023-06-01");
connection.setRequestProperty("content-type", "application/json");
connection.setDoOutput(true);

JSONObject requestBody = new JSONObject();
requestBody.put("model", model);
requestBody.put("max_tokens", 8192);
requestBody.put("messages", new JSONObject[]{
new JSONObject().put("role", "user").put("content", prompt)
});


// Send request
try (OutputStream os = connection.getOutputStream()) {
byte[] input = requestBody.toString().getBytes("utf-8");
os.write(input, 0, input.length);
}

int responseCode = connection.getResponseCode();

StringBuilder response = new StringBuilder();
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
responseCode >= 400 ? connection.getErrorStream() : connection.getInputStream(),
StandardCharsets.UTF_8
)
)) {
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
}

//System.out.println("Response Code: " + responseCode);
//System.out.println("Full response: " + response.toString());

if (responseCode >= 400) {
return "Error: " + response.toString();
}

try {
JSONObject jsonObject = new JSONObject(response.toString());
String content = jsonObject.getJSONArray("content").getJSONObject(0).getString("text");
return content;
} catch (Exception e) {
System.out.println("Error parsing JSON: " + e.getMessage());
return null;
}
}

public static void main(String[] args) throws IOException {
String input = "Hello, Claude! How are you today?";
String response = prompt(input, "claude-3-5-sonnet-20240620", null, null);
System.out.println("Claude's response: " + response);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,28 +38,43 @@
*
* @author Curtis Rueden
*/
@Plugin(type = OptionsPlugin.class, menuPath = "Edit>Options>OpenAI...")
public class OpenAIOptions extends OptionsPlugin {
@Plugin(type = OptionsPlugin.class, menuPath = "Edit>Options>LLM Service Options...")
public class LLMServicesOptions extends OptionsPlugin {

@Parameter(label = "OpenAI key", required = false)
private String openAIKey;
@Parameter(label = "OpenAI API key", required = false)
private String openAIAPIKey;

@Parameter(label = "Anthropic API key", required = false)
private String anthropicAPIKey;

@Parameter(label = "OpenAI Model name")
private String modelName = "gpt-3.5-turbo-0613";
private String openAIModelName = "gpt-4o-2024-08-06";

@Parameter(label = "Anthropic Model name")
private String anthropicModelName = "claude-3-5-sonnet-20240620";

@Parameter(label = "Prompt prefix (added before custom prompt)", style = "text area")
private String promptPrefix = "Write code in {programming_language}.\n" +
private String promptPrefix =
"You are an extremely talented Bio-image Analyst and programmer.\n" +
"You write code in {programming_language}.\n" +
"Write concise and high quality code for ImageJ/Fiji.\n" +
"Put minimal comments explaining what the code does.\n" +
"The code should do the following:\n" +
"Your task is the following:\n" +
"{custom_prompt}";

public String getOpenAIKey() {
return openAIKey;
public String getOpenAIAPIKey() {
return openAIAPIKey;
}

public void setOpenAIKey(final String openAIKey) {
this.openAIKey = openAIKey;
public String getAnthropicAPIKey() {
return anthropicAPIKey;
}

public void setOpenAIAPIKey(final String openAIAPIKey) {
this.openAIAPIKey = openAIAPIKey;
}
public void setAnthropicAPIKey(final String anthropicAPIKey) {
this.anthropicAPIKey = anthropicAPIKey;
}

public String getPromptPrefix() {
Expand All @@ -70,12 +85,20 @@ public void setPromptPrefix(final String promptPrefix) {
this.promptPrefix = promptPrefix;
}

public String getModelName() {
return modelName;
public String getOpenAIModelName() {
return openAIModelName;
}

public void setOpenAIModelName(final String openAIModelName) {
this.openAIModelName = openAIModelName;
}

public String getAnthropidModelName() {
return anthropicModelName;
}

public void setModelName(final String modelName) {
this.modelName = modelName;
public void setAnthropidModelName(final String anthropicModelName) {
this.anthropicModelName = anthropicModelName;
}


Expand Down
68 changes: 68 additions & 0 deletions src/main/java/org/scijava/ui/swing/script/OpenAIClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package org.scijava.ui.swing.script;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class OpenAIClient {

public static void main(String[] args) {
String prompt = "Hello, GPT-4!";
try {
String response = prompt(prompt, "gpt-4o-2024-08-06", null, null);
System.out.println("GPT-4 Response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}

public static String prompt(String prompt, String model, String apikey, String apiurl) throws Exception {

if (apiurl == null) {
apiurl = "https://api.openai.com/v1/chat/completions";
}
if (apikey == null) {
apikey = System.getenv("OPENAI_API_KEY");
}

URL url = new URL(apiurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Bearer " + apikey);
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);

// Create JSON request body
JSONObject requestBody = new JSONObject();
requestBody.put("model", model);
requestBody.put("messages", new JSONObject[]{
new JSONObject().put("role", "user").put("content", prompt)
});

System.out.println(connection);
System.out.println(requestBody);

// Send request
try (OutputStream os = connection.getOutputStream()) {
byte[] input = requestBody.toString().getBytes("utf-8");
os.write(input, 0, input.length);
}

// Read response
StringBuilder response = new StringBuilder();
try (BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "utf-8"))) {
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
}

// Parse JSON response
JSONObject jsonResponse = new JSONObject(response.toString());
return jsonResponse.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
}
}
Loading

0 comments on commit 23a611b

Please sign in to comment.