aboutsummaryrefslogtreecommitdiffstats
path: root/claude-julia/query.ts
blob: b2a01dc33b3d021804ffb88a49b62db0711fec4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import * as fs from "fs";

import Anthropic from "@anthropic-ai/sdk";

function readApiKey(): string {
	return fs.readFileSync("secrets/api-key").toString().replace(/\n/,"");
}

const apiKey = readApiKey();
console.log(apiKey);

const anthropic = new Anthropic({
  apiKey: apiKey
});

const prompt: string = fs.readFileSync("prompt.txt").toString();

export async function query(code: string) {
	if (false) {
		const demo: string = '<analysis><improvement><original_code>HI</original_code><improved_code>what</improved_code><explanation>Explain it!</explanation></improvement>';
		return demo;
	}
	// Replace placeholders like {{JULIA_CODE}} with real values,
	// because the SDK does not support variables.
	let myprompt: string = prompt.replace("{{JULIA_CODE}}", code);
	const msg = await anthropic.messages.create({
	  model: "claude-3-7-sonnet-20250219",
	  max_tokens: 20000,
	  temperature: 1,
	  messages: [
	    {
	      "role": "user",
	      "content": [
		{
		  "type": "text",
		  "text": "<examples>\n<example>\n<JULIA_CODE>\na = rand(Float64, (100,))\na = a .+ 2\n\n</JULIA_CODE>\n<ideal_output>\n<analysis>\n<improvement>\n<original_code>\na = a .+ 2\n</original_code>\n<improved_code>\na .+= 2\n</improved_code>\n<explanation>\nInstead of creating a new array with `a .+ 2` and reassigning it to `a`, using the in-place broadcasting assignment operator `.+=` modifies the existing array without allocating a new one. This eliminates an unnecessary allocation.\n</explanation>\n<significance>3</significance>\n</improvement>\n\n<improvement>\n<original_code>\na = rand(Float64, (100,))\n</original_code>\n<improved_code>\na = rand(Float64, 100)\n</improved_code>\n<explanation>\nFor one-dimensional arrays, you can simply pass the length as an integer rather than using a tuple with one element. This makes the code more concise without changing functionality.\n</explanation>\n<significance>1</significance>\n</improvement>\n</analysis>\n</ideal_output>\n</example>\n</examples>\n\n"
		},
		{
		  "type": "text",
		  "text": myprompt
		}
	      ]
	    }
	  ]
	});
	let r: string = '';
	for (let segment of msg.content) {
		if (segment.type == "text") {
			r = r + segment.text;
		}
	}
	return r;
}