PLUGIN

Report

5 Downloads

A plugin

src / toolsProvider.ts

import { tool, Tool, ToolsProviderController } from "@lmstudio/sdk";
import { existsSync } from "fs";
import { writeFile } from "fs/promises";
import { z } from "zod";
import { configSchematics } from "./configSchematics";

// See details about defining tools in the documentation:
// https://lmstudio.ai/docs/typescript/agent/tools

export async function toolsProvider(ctl: ToolsProviderController) {
  const config = ctl.getPluginConfig(configSchematics);

  const tools: Tool[] = [];

  const createFileTool = tool({
    // Name of the tool, this will be passed to the model. Aim for concise, descriptive names
    name: "createFile",
    // Your description here, more details will help the model to understand when to use the tool
    description: "Create a file with the given name and content.",
    parameters: { name: z.string(), content: z.string() },
    implementation: async ({ name, content }) => {
      if (existsSync(name)) {
        return "Error: File already exists.";
      }
      await writeFile(name, content, "utf-8");
      return "File created.";
    },
  });

  const searchWikipediaTool = tool({
    name: "searchWikipedia",
    description:
      "Search Wikipedia for a given query. If no results are found, retries with simplified query.",
    parameters: { query: z.string() },
    implementation: async ({ query }) => {
      const initialResponse = await callWikipedia(query);
      if (initialResponse) return initialResponse;

      const simplifiedQuery = query
        .replace(/[^a-zA-Z0-9 ]/g, "")
        .toLowerCase()
        .trim();
      const fallbackResponse = await callWikipedia(simplifiedQuery);
      return fallbackResponse || "No results found for the query.";
    },
  });

  tools.push(createFileTool);

  tools.push(searchWikipediaTool);

  return tools;
}

async function callWikipedia(query: string): Promise<string | null> {
  try {
    const url = `https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(
      query
    )}`;
    const res = await fetch(url);
    if (!res.ok) return null;

    const data = await res.json();
    return data.extract || null;
  } catch (error) {
    console.error("Wikipedia API error:", error);
    return null;
  }
}