Skip to content

Asa andy #5

Description

@kingzettee

import java.util.; import java.io.; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets;

/* ASA & ANDY - Superintelligent versions (upgraded)

Additions in this version:

Optional Symja (Matheclipse) symbolic math integration (if present on classpath) Maven coordinates: org.matheclipse:matheclipse-core:3.0.0

Apache Commons Math Newton-Raphson solver usage (if present) Maven coordinates: org.apache.commons:commons-math3:3.6.1

Implemented real HTTP calls for WolframAlpha (Simple/Result & LLM endpoint) and OpenAI Chat Completions (place your API keys via setApiKey(...)).

Backwards compatible: if optional libs or network are not available, code falls back to built-ins.

Note: This is example code intended to be dropped into a Java project. Add the dependencies below to your build (Maven/Gradle) to unlock symbolic math and Apache solvers.

Maven deps (pom.xml):

org.matheclipse matheclipse-core 3.0.0 org.apache.commons commons-math3 3.6.1 org.json json 20230618

*/

class Brain { private Map<String, String> memory = new LinkedHashMap<>(); private ScriptEngine engine; private boolean online = false; private Map<String,String> apiKeys = new HashMap<>(); private File memoryFile = new File("asa_and_andy_memory.txt");

// Optional integrations - detected at runtime
private boolean hasSymja = false;
private boolean hasCommonsMath = false;

public Brain() {
ScriptEngineManager mgr = new ScriptEngineManager();
engine = mgr.getEngineByName("JavaScript");
detectOptionalLibs();
loadMemory();
}

private void detectOptionalLibs() {
try {
Class.forName("org.matheclipse.core.eval.ExprEvaluator");
hasSymja = true;
} catch (ClassNotFoundException e) {
hasSymja = false;
}
try {
Class.forName("org.apache.commons.math3.analysis.solvers.NewtonRaphsonSolver");
hasCommonsMath = true;
} catch (ClassNotFoundException e) {
hasCommonsMath = false;
}
}

// --- Memory ---
public void learn(String input, String output) {
memory.put(input, output);
saveMemory();
}

public String recall(String input) {
return memory.getOrDefault(input, null);
}

private void saveMemory() {
try (PrintWriter out = new PrintWriter(new FileWriter(memoryFile, false))) {
for (Map.Entry<String,String> e : memory.entrySet()) {
out.println(escape(e.getKey()) + " " + escape(e.getValue()));
}
} catch (IOException ex) {
// best-effort
}
}

private void loadMemory() {
if (!memoryFile.exists()) return;
try (BufferedReader br = new BufferedReader(new FileReader(memoryFile))) {
String line;
while ((line = br.readLine()) != null) {
int t = line.indexOf(' ');
if (t > 0) {
String k = unescape(line.substring(0,t));
String v = unescape(line.substring(t+1));
memory.put(k,v);
}
}
} catch (IOException ex) {
// ignore
}
}

private String escape(String s) {
return s.replace("","\").replace(" ","\t");
}
private String unescape(String s) {
return s.replace("\t"," ").replace("\","");
}

// --- Expression evaluation ---
// Prefer Symja (symbolic) if available, else fall back to JS numeric evaluation
public String evaluateExpression(String expr) {
if (expr == null) return null;
expr = expr.trim();
if (hasSymja) {
try {
// Use reflection so this file compiles even if Symja isn't present at compile time
Class<?> evalClass = Class.forName("org.matheclipse.core.eval.ExprEvaluator");
Object evaluator = evalClass.getDeclaredConstructor().newInstance();
java.lang.reflect.Method eval = evalClass.getMethod("evaluate", String.class);
Object res = eval.invoke(evaluator, expr);
return String.valueOf(res);
} catch (Exception ex) {
// fallback
}
}

// numeric JS fallback
try {
    Object result = engine.eval(expr);
    return String.valueOf(result);
} catch (ScriptException e) {
    return "<could not evaluate expression: " + e.getMessage() + ">";
}

}

// --- Root finding ---
// If Apache Commons Math is present, use its NewtonRaphsonSolver; otherwise use simple numerical NR.
public OptionalDouble findRoot(String expression, double initialGuess, int maxIter, double tol) {
if (hasCommonsMath) {
try {
// Use Apache Commons Math via reflection to avoid compile-time dependency requirement
Class<?> solverClass = Class.forName("org.apache.commons.math3.analysis.solvers.NewtonRaphsonSolver");
Object solver = solverClass.getDeclaredConstructor().newInstance();

        Class<?> funcClass = Class.forName("org.apache.commons.math3.analysis.differentiation.UnivariateDifferentiableFunction");
        // We will create a small wrapper using a lambda-like approach via Proxy
        java.lang.reflect.InvocationHandler handler = (proxy, method, args) -> {
            if (method.getName().equals("value")) {
                double x = ((Number)args[0]).doubleValue();
                return evalForX(expression, x);
            }
            throw new UnsupportedOperationException();
        };
        Object funcProxy = java.lang.reflect.Proxy.newProxyInstance(funcClass.getClassLoader(), new Class[]{funcClass}, handler);

        // solver.solve(maxEval, f, startValue) -> reflection
        java.lang.reflect.Method solve = solverClass.getMethod("solve", int.class, funcClass, double.class);
        Object root = solve.invoke(solver, maxIter, funcProxy, initialGuess);
        double r = ((Number)root).doubleValue();
        return OptionalDouble.of(r);
    } catch (Exception ex) {
        // fallback to numeric
    }
}
// fallback numeric
double x = initialGuess;
for (int i=0;i<maxIter;i++) {
    double fx = evalForX(expression, x);
    double dfx = numericalDerivative(expression, x);
    if (Double.isNaN(fx) || Double.isNaN(dfx)) return OptionalDouble.empty();
    if (Math.abs(fx) < tol) return OptionalDouble.of(x);
    if (Math.abs(dfx) < 1e-15) return OptionalDouble.empty();
    x = x - fx/dfx;
}
return OptionalDouble.empty();

}

private double evalForX(String expr, double x) {
try {
String e = expr.replace("x", "("+Double.toString(x)+")");
Object out = engine.eval(e);
if (out instanceof Number) return ((Number)out).doubleValue();
return Double.parseDouble(String.valueOf(out));
} catch (Exception ex) {
return Double.NaN;
}
}

private double numericalDerivative(String expr, double x) {
double h = 1e-6;
double f1 = evalForX(expr, x+h);
double f0 = evalForX(expr, x-h);
if (Double.isNaN(f1) || Double.isNaN(f0)) return Double.NaN;
return (f1 - f0) / (2*h);
}

// --- Thinking (offline + online) ---
public String thinkOffline(String question) {
if (question == null) return "I need something to think about.";
String q = question.toLowerCase().trim();

// Memory recall
String recalled = recall(q);
if (recalled != null) return recalled + " (recalled)";

// explicit calc: prefix with calc: or compute:
if (q.startsWith("calc:") || q.startsWith("compute:")) {
    String expr = question.substring(question.indexOf(":") + 1).trim();
    String ans = evaluateExpression(expr);
    learn(q, ans);
    return ans;
}

// symbolic attempt: pass to Symja if present
if (hasSymja && (q.contains("integrate") || q.contains("differentiate") || q.contains("solve"))) {
    String sym = evaluateExpression(question);
    learn(q, sym);
    return sym;
}

// physics shortcuts
if (q.contains("e=mc^2") || q.contains("e=mc2")) {
    String out = "E = m c^2 — energy equals mass times speed of light squared (relativistic mass-energy equivalence).";
    learn(q, out);
    return out;
}
if (q.contains("gravity") || q.contains("newton")) {
    String out = "Newton's universal gravitation: F = G * (m1*m2) / r^2. Use SI units for G ≈ 6.67430e-11 m^3 kg^-1 s^-2.";
    learn(q, out);
    return out;
}

String fallback = "I can recall facts, solve numeric expressions, perform symbolic ops if Symja is available, and find roots. For deeper research, enable online mode.";
learn(q, fallback);
return fallback;

}

public void setOnline(boolean on) { this.online = on; }
public boolean isOnline() { return this.online; }
public void setApiKey(String service, String key) { apiKeys.put(service, key); }

public String thinkOnline(String question) {
String offline = thinkOffline(question);
// If offline produced a direct numeric/authoritative answer, prefer it.
if (offline != null && !offline.startsWith("I can recall facts")) {
return offline + " (offline)";
}
if (!online) return offline + " (online disabled)";

// Priority: Wolfram LLM/Result -> Wikipedia summary -> OpenAI Chat
try {
    if (apiKeys.containsKey("wolfram")) {
        String wa = queryWolframAlpha(question, apiKeys.get("wolfram"));
        if (wa != null) return wa + " (Wolfram)";
    }
    String wp = queryWikipediaShort(question);
    if (wp != null) return wp + " (Wikipedia)";
    if (apiKeys.containsKey("openai")) {
        String ai = queryOpenAI(question, apiKeys.get("openai"));
        if (ai != null) return ai + " (OpenAI)";
    }
} catch (Exception ex) {
    // ignore and fallback
}

return "(online lookup failed) " + offline;

}

// --- WolframAlpha & Wikipedia & OpenAI HTTP helpers ---
private String queryWolframAlpha(String question, String appid) {
try {
String q = URLEncoder.encode(question, StandardCharsets.UTF_8.name());
// Try the LLM-style endpoint if available, else fallback to simple result
String url1 = "https://api.wolframalpha.com/v2/llm?input=" + q + "&appid=" + URLEncoder.encode(appid, StandardCharsets.UTF_8.name());
String r1 = httpGetSimple(url1);
if (r1 != null && !r1.isEmpty()) return r1;

    String url2 = "https://api.wolframalpha.com/v1/result?i=" + q + "&appid=" + URLEncoder.encode(appid, StandardCharsets.UTF_8.name());
    String r2 = httpGetSimple(url2);
    return r2;
} catch (Exception ex) { return null; }

}

private String queryWikipediaShort(String question) {
try {
// Map question to a reasonable title by stripping punctuation and taking first few words
String title = question.replaceAll("[^A-Za-z0-9 ]", " ").trim().split("\s+")[0];
String q = URLEncoder.encode(title, StandardCharsets.UTF_8.name());
String url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + q;
String raw = httpGetSimple(url);
if (raw == null) return null;
// crude JSON extract of "extract":
int idx = raw.indexOf(""extract"");
if (idx>0) {
int colon = raw.indexOf(':', idx);
int start = raw.indexOf('"', colon) + 1;
int end = raw.indexOf('"', start);
if (start>0 && end>start) {
String extract = raw.substring(start, end);
return extract;
}
}
return null;
} catch (Exception ex) { return null; }
}

private String queryOpenAI(String question, String apiKey) {
try {
String endpoint = "https://api.openai.com/v1/chat/completions";
URL url = new URL(endpoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
conn.setDoOutput(true);

    // minimal chat payload - choose model as appropriate for your account
    String model = "gpt-4o-mini"; // replace if needed
    String payload = "{\"model\":\"" + model + "\",\"messages\":[{\"role\":\"user\",\"content\":\"" + escapeJson(question) + "\"}],\"max_tokens\":512}";

    try (OutputStream os = conn.getOutputStream()) {
        byte[] input = payload.getBytes(StandardCharsets.UTF_8);
        os.write(input, 0, input.length);
    }
    int code = conn.getResponseCode();
    InputStream is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
    StringBuilder sb = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
        String line;
        while ((line = br.readLine()) != null) sb.append(line).append('

'); } String resp = sb.toString(); // crude parse: find "content":"..." of assistant int idx = resp.indexOf(""content""); if (idx > 0) { int c = resp.indexOf(':', idx); int start = resp.indexOf('"', c) + 1; int end = resp.indexOf('"', start); if (start>0 && end>start) { String content = resp.substring(start, end); return content.replaceAll("\n", " "); } } // fallback: return full raw response return resp; } catch (Exception ex) { return null; } }

private String httpGetSimple(String urlString) {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
int code = conn.getResponseCode();
if (code < 200 || code >= 300) return null;
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line).append('

'); return sb.toString(); } } catch (Exception ex) { return null; } }

private String escapeJson(String s) {
return s.replace("","\").replace(""","\"").replace("

","\n"); } }

public class ASA { private Brain brain; public String voice = "Morgan Freeman"; public String humor = "Ryan Reynolds";

public ASA(Brain shared) { this.brain = shared; }
public ASA() { this.brain = new Brain(); }

public void setOnline(boolean on) { brain.setOnline(on); }
public void setApiKey(String service, String key) { brain.setApiKey(service, key); }

public void respond(String input) {
String thought = brain.thinkOnline(input);
String styled = "[Calm Narration] " + capitalizeFirst(thought) + " ... as only " + voice + " would say.";
styled += " (with a touch of " + humor + " sarcasm)";
System.out.println("ASA: " + styled);
brain.learn(input.toLowerCase().trim(), styled);
}

private String capitalizeFirst(String s) {
if (s == null || s.isEmpty()) return s;
return s.substring(0,1).toUpperCase() + s.substring(1);
}

}

public class ANDY { private Brain brain; public String voice = "Jim Carrey"; public String humor = "Samuel L Jackson";

public ANDY(Brain shared) { this.brain = shared; }
public ANDY() { this.brain = new Brain(); }

public void setOnline(boolean on) { brain.setOnline(on); }
public void setApiKey(String service, String key) { brain.setApiKey(service, key); }

public void respond(String input) {
String thought = brain.thinkOnline(input);
String styled = "WHOA! " + thought.toUpperCase() + "!!!";
styled += " (imagine " + voice + " shouting this)";
styled += " — and with " + humor + "’s no-nonsense punch!";
System.out.println("ANDY: " + styled);
brain.learn(input.toLowerCase().trim(), styled);
}

}

/* Example usage:

Brain shared = new Brain(); shared.setOnline(true); shared.setApiKey("wolfram","YOUR_WOLFRAM_APPID"); shared.setApiKey("openai","YOUR_OPENAI_KEY");

ASA asa = new ASA(shared); ANDY andy = new ANDY(shared);

asa.respond("Explain E=mc^2"); andy.respond("Solve: calc: 2+2*3");

Notes:

Add Symja and Apache Commons Math to your project to unlock symbolic math and advanced solvers.

Replace model name and API endpoints to match the provider’s requirements and your account capabilities. */

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions