[GenAI] Handling Invalid Commands and AI Errors in Local Scripts

import { ollama } from "ollama-ai-provider";
import { generateObject, generateText } from "ai";
import { z } from "zod";
import { globby } from "globby";
import { parseArgs } from "node:util";
import { readFile } from "node:fs/promises";

const files = await globby("**/*.json", { gitignore: true });

const isNonEmpty = (files: string[]): files is [string, ...string[]] => {
  return files.length > 0;
};

if (!isNonEmpty(files)) {
  console.error("No files found");
  process.exit(1);
}

const { positionals } = parseArgs({
  allowPositionals: true,
});

const model = ollama("gemma3:latest");

const objectPrompt = positionals[0];

const validCommands = ["summarize", "translate", "review"] as const;

const { object } = await generateObject({
  model,
  schema: z.object({
    command: z.string().describe("The command to execute"),
    filePath: z.enum(files).describe("The path to the files to prcess"),
  }),
  prompt: objectPrompt,
}).catch((err) => {
  console.error(`Model generated an invalid reponse for ${objectPrompt}`);
  process.exit(1);
});

type Command = (typeof validCommands)[number];
const isValidCommand = (cmd: unknown): cmd is Command => {
  return (
    typeof cmd === "string" &&
    (validCommands as readonly string[]).includes(cmd)
  );
};

if (!isValidCommand(object.command)) {
  console.error("Invalid command");
  process.exit(1);
}

const content = await readFile(object.filePath, "utf-8");

const textPrompt = `
<command>
${object.command}
</command>

<content>
${content}
</content>
`;

const { text } = await generateText({
  model,
  prompt: textPrompt,
});
console.log(text);

 

posted @ 2025-07-19 21:06  Zhentiw  阅读(17)  评论(0)    收藏  举报