import * as jsonpatch from "npm:jsonpatch";
import { ai } from "https://esm.town/v/yawnxyz/ai";
import { covertest as test } from "https://esm.town/v/yawnxyz/covertest";
export async function getPatchFromPrompt(obj, prompt) {
const input = `Given this JSON document:
<json>${JSON.stringify(obj, null, 2)}</json>
<instructions>${prompt}
| Respond with a valid JSON patch array that would transform the original document as requested.
| Only add Remove operations to the end of the patch array
| Prefer to move (op: 'move' instead of 'add') objects/keys/values to the enrichedData object — this lets you avoid specifying exact values as the json patch will be reused for multiple objects.
| Only include the JSON patch array in your response, nothing else.
</instructions>`
const aiResponse = await ai(input,
{
provider: "anthropic",
model: "claude-3-sonnet-20240229",
}
);
try {
const jsonPatch = JSON.parse(aiResponse);
return jsonPatch;
} catch (error) {
console.error("Error parsing AI response as JSON:", error);
throw new Error("Failed to generate valid JSON patch");
}
}
export function patchObject (obj, patch) {
return jsonpatch.apply_patch(obj, patch);
}
export function patchArray(arr, patch) {
return arr.map(obj => patchObject(obj, patch));
}
export async function patchObjectFromPrompt(obj, prompt) {
try {
const patch = await getPatchFromPrompt(obj, prompt);
const patchedData = patchObject(obj, patch);
return patchedData;
} catch (error) {
console.error("Error modifying JSON with instructions:", error);
throw new Error("Failed to modify JSON based on given instructions");
}
}
export async function patchArrayFromPrompt(arr, prompt) {
try {
const patch = await getPatchFromPrompt(arr[0], prompt);
console.log('patchArrayFromPrompt/patch', patch);
const patchedArray = patchArray(arr, patch);