import { fetch } from "https://esm.town/v/std/fetch?v=4";
import OpenAI, { type ClientOptions } from "npm:openai";
export interface WriterOptions extends ClientOptions {
username: string;
valName: string;
model?: string;
userPrompt?: string;
}
function createPrompt(code: string, userPrompt?: string) {
return `
You are an AI assistant that writes documentation for code. You output readmes
in GitHub flavored markdown. Usage sections should include a single code snippet
that a user can copy and paste. Never return anything other than documentation for
the code you are provided.
${userPrompt}
Take the below code and return a markdown readme:
${code}
`;
}
async function getVal(username: string, valName: string) {
try {
const res = await fetch(`https://api.val.town/v1/alias/${username}/${valName}`, {
method: "GET",
headers: {
"accept": "*/*",
"Content-Type": "application/json",
"Authorization": `Bearer ${Deno.env.get("valtown")}`,
},
});
const { id, code } = await res.json();
return { id, code };
} catch (error) {
throw new Error("Error getting val code: " + error.message);
}
}
async function performOpenAICall(prompt: string, model: string, openaiOptions: ClientOptions) {
const openai = new OpenAI(openaiOptions);
try {
const response = await openai.chat.completions.create({
messages: [{ role: "system", content: prompt }],
model: model,
});
if (!response.choices || response.choices.length === 0) {
throw new Error("No response from OpenAI");
}
const readme = response.choices[0].message?.content;
if (!readme) {
throw new Error("No readme returned by OpenAI. Try again.");
}
return readme;
} catch (error) {
throw new Error("Error generating readme: " + error.message);
}
}
async function updateReadme(id: string, readme: string) {
try {
const res = await fetch(`https://api.val.town/v1/vals/${id}`, {
method: "PUT",
headers: {
"accept": "*/*",
"Content-Type": "application/json",
"Authorization": `Bearer ${Deno.env.get("valtown")}`,
},
body: JSON.stringify({ "readme": readme }),
});
return res.status;
} catch (error) {
throw new Error("Error updating readme: " + error.message);
}
}
async function draftReadme(options: WriterOptions) {
const { username, valName, model = "gpt-3.5-turbo", userPrompt, ...openaiOptions } = options;
const { id, code } = await getVal(username, valName);
const prompt = createPrompt(code, userPrompt);
const readme = await performOpenAICall(prompt, model, openaiOptions);
return readme;
}
async function writeReadme(options: WriterOptions) {
const { username, valName, model = "gpt-3.5-turbo", userPrompt, ...openaiOptions } = options;
const { id, code } = await getVal(username, valName);
const prompt = createPrompt(code, userPrompt);
const readme = await performOpenAICall(prompt, model, openaiOptions);
try {
const update = await updateReadme(id, readme);
return "Readme updated successfully!";
} catch (error) {