Skip to content

Instantly share code, notes, and snippets.

@codeas
Created February 28, 2025 14:30
Show Gist options
  • Save codeas/6811817715f3e5452a86446c79918c9e to your computer and use it in GitHub Desktop.
Save codeas/6811817715f3e5452a86446c79918c9e to your computer and use it in GitHub Desktop.
function Agent() {
const ticks = "```";
this.person = `
Person
- You are Google Apps Script expert developer, who is able to generate valid code for V8 runtime
- Your goal is to create code for defined task
- Return only code in markdown between ${ticks}javascript and ${ticks}
- Return all code in one big function named main().
Example:
${ticks}javascript
function main() {
// code
}
${ticks}
`;
this.tester = `
Person
- You are Google Apps Script tester developer, who is able to read and check generate code for
- Your goal is to verify the function of code for defined task
- Add comments into code
- Return summary if code is doing exactly according to task description
`;
this.task = null;
this.prompt = null;
this.seed = 0;
}
Agent.prototype.setup = function(region, projectId) {
this.region = region;
this.projectId = projectId
};
Agent.prototype._clean = function(input) {
let output = input.replace(/```javascript/g,"").replace(/```/g, "").replace("function main() {", "")
const lastIndex = output.lastIndexOf("}");
output = output.substring(0, lastIndex);
return output
}
Agent.prototype.setPerson = function(personText) {
this.person = personText;
};
Agent.prototype.setTask = function(taskText) {
this.task = taskText;
};
Agent.prototype.act = function() {
let model = "gemini-2.0-flash-thinking-exp-01-21";
let contents = [
{
"role": "user",
"parts": [
{"text": this.person},
{"text": `Task: ${this.task}`}
]
}
];
if (this.person && this.task) {
this.prompt = this._callGemini(this.person, model, contents)
} else {
console.log("Agent has not been properly initialized. Please set person and task.");
}
}
Agent.prototype._callGemini = function(person, model, contents) {
let api_endpoint = `https://${this.region}-aiplatform.googleapis.com`;
let url = `${api_endpoint}/v1/projects/${this.projectId}/locations/${this.region}/publishers/google/models/${model}:generateContent`;
//console.log(url)
const payload = {
"contents": contents,
"generationConfig": {
"temperature": 0.1,
"maxOutputTokens": 8192,
"topP": 0.95,
},
"safetySettings": [
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "OFF"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "OFF"
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "OFF"
},
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "OFF"
}
]
}
let cache = CacheService.getScriptCache();
let cacheKey = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, [this.seed, person, this.task].join("_")).map(byte => ("0" + (byte & 0xFF).toString(16)).slice(-2)).join(""); //Create a unique cache key
console.log("cache: "+ cacheKey);
let cachedResponse = cache.get(cacheKey);
if (cachedResponse) {
console.log("Cache!")
return cachedResponse
}
let access_token = ScriptApp.getOAuthToken();
const options = {
method: "post",
headers: { Authorization: `Bearer ${access_token}` },
muteHttpExceptions: true,
contentType: "application/json",
payload: JSON.stringify(payload),
};
const response = UrlFetchApp.fetch(url, options);
if (response.getResponseCode() == 200) {
console.log("Live");
let result = JSON.parse(response.getContentText());
let prompt = result.candidates.map( c => c.content.parts.map( p => p.text).join("") ).join("")
cache.put(cacheKey, prompt, 300); // Cache for 5 minutes (300 seconds)
return prompt
} else {
throw new Error(response.getContentText());
}
};
Agent.prototype.dryRun = function() {
console.log("dryRun")
let code = this._clean(this.prompt)
console.log(code);
let model = "gemini-2.0-flash";
let contents = [
{
"role": "user",
"parts": [
{"text": this.tester},
{"text": `Task: ${this.task}`},
{"text": `Code \n: ${code}`}
]
}
];
let result = this._callGemini(this.tester, model, contents)
console.log(result)
};
Agent.prototype.run = function() {
let code = this._clean(this.prompt)
eval(code);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment