npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ai-fns

v1.0.1

Published

Instantly convert your JavaScript functions into functions which can be called by GPT-3.5 and GPT-4.

Downloads

3

Readme

ai-fns

Convert any function into a ChatGPT function.

ai-fns is a tiny library that convert any function into a function that can be called by ChatGPT.

The underlying spec is based on OpenAI's new function calling feature.

Features

  • 🛠️ 8+ built-in functions - comes included with functions for math, rss, requests, clock and more
  • 🪄 100% Type-safe - uses zod to validate the input and output of your functions
  • 👶 Easy to use - simple API that makes it easy to create your own functions
  • 💨 Lightweight - is a small library with minimal dependencies

Install

pnpm install ai-fns zod

Before

😮‍💨 Create a JSON schema for your function manually and pass it to ChatGPT

import openai, { OpenAI } from "openai";

const openai = new OpenAI({
  apiKey: env.OPENAI_API_KEY,
});

const weather = async ({
  latitude,
  longitude,
}: {
  latitude: number;
  longitude: number;
}) => {
  try {
    const res = await fetch(
      `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current_weather=true`
    );
    return await res.json();
  } catch (error) {
    return error;
  }
};

const completion = await openai.chat.completions.create({
  model: "gpt-3.5-turbo-16k",
  messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
  functions: [
    {
      name: "weather",
      description: "Get the current weather in a given location",
      parameters: {
        type: "object",
        properties: {
          longitude: {
            type: "number",
            minimum: -180,
            maximum: 180,
            description: "Longitude",
          },
          latitude: {
            type: "number",
            minimum: -90,
            maximum: 90,
            description: "Latitude",
          },
        },
        required: ["longitude", "latitude"],
        additionalProperties: false,
      },
    },
  ],
});

After

✨ Use ai-fns to automatically generate a schema for your function and pass it to ChatGPT

import openai, { OpenAI } from "openai";
import { z } from "zod";
import { aifn } from "ai-fns";

const openai = new OpenAI({
  apiKey: env.OPENAI_API_KEY,
});

const { schema, fn } = aifn(
  "weather",
  "Get the current weather in a given location",
  z.object({
    longitude: z.number().min(-180).max(180).describe("Longitude"),
    latitude: z.number().min(-90).max(90).describe("Latitude"),
  }),
  async ({ latitude, longitude }) => {
    try {
      const res = await fetch(
        `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current_weather=true`
      );
      return await res.json();
    } catch (error) {
      return error;
    }
  }
);

// Ask the AI a question
const completion = await openai.chat.completions.create({
  model: "gpt-3.5-turbo-16k",
  messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
  functions: [schema],
});

Examples

Here's an example of a function that calculates the output of a given mathematical expression:

import { Parser } from "expr-eval";
import { z } from "zod";
import { aifn } from "ai-fns";

const parser = new Parser();

export default aifn(
  "calculator",
  "Calculate the output of a given mathematical expression",
  z.object({
    expression: z.string(),
  }),
  ({ expression }) => {
    try {
      const result = parser.parse(expression).evaluate();
      return result;
    } catch (error) {
      return `Failed to execute script: ${error.message}`;
    }
  }
);

Now, you can just ask ChatGPT to do some math for you:

User: What's 45^(2.12) / 45?
Assistant: The result of 45^(2.12) / 45 is approximately 71.06.

Here's an example of a function that fetches the latest news from an rss feed:

import { z } from "zod";
import { aifn } from "ai-fns";

const name = "reddit";
const description = "Get stories from reddit";
const schema = z.object({
  subreddit: z.string().optional().default("all").describe("Subreddit"),
  limit: z.number().optional().default(5).describe("Limit"),
  category: z
    .enum(["hot", "new", "random", "top", "rising", "controversial"])
    .default("hot")
    .describe("category"),
});

const reddit = async ({
  subreddit,
  category,
  limit,
}: z.infer<typeof schema>) => {
  try {
    const params = new URLSearchParams({
      limit: limit.toString(),
    });
    const url = `https://www.reddit.com/r/${subreddit}/${category}.json?${params.toString()}`;
    const res = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
    return error;
  }
};

export default aifn(name, description, schema, reddit);
User: What's the top story on /r/programming today?
Assistant: The top story on /r/programming is "Crumb: A New Programming Language Where There are No Keywords, and Everything is a Function". You can read more about it [here](https://github.com/liam-ilan/crumb). It has received 201 upvotes and has 25 comments.

Why?

OpenAI's new function calling feature allows you to call functions from within ChatGPT.

However, it requires you to pass as JSON schema for your function containing the input and output types of your function. This is a bit cumbersome to do manually.

This library automatically handles the conversion for you ✨

Where can I use this?

  • ✅ You are building AI agents which need to call functions
  • ✅ You want ChatGPT to output structured data (e.g. JSON)

Contributing

Do you have an idea for a function? Feel free to open a pull request!

Simply create a new file in the src/functions directory and add your function. Make sure to add a description and schema for your function.

import { z } from "zod";
import { aifn } from "ai-fns";

export const name = "name";
export const description = "description";
export const schema = z.object({
  // schema
});
export const fn = async ({}: /* schema */ z.infer<typeof schema>) => {
  // function body
};

export default aifn(name, description, schema, fn);