Unlock the Power of ChatGPT Functions and Supercharge Your Conversations!

lucgagan

Luc Gagan

Posted on June 26, 2023

Unlock the Power of ChatGPT Functions and Supercharge Your Conversations!

OpenAI's cutting-edge models, like gpt-3.5-turbo-0613 and gpt-4-0613, introduce an exciting feature called "function calling." It empowers developers to define and invoke functions within the model's responses, making it a breeze to retrieve structured data and accomplish a wide range of tasks. In this article, we'll dive into the world of ChatGPT functions, exploring what they are, how to use them, and providing you with inspiring examples of their boundless use cases.

Making ChatGPT use our locally defined functions

Let's start by unraveling the magic of ChatGPT functions!

What are ChatGPT Functions?

By embedding functions directly into the system prompt, you can guide the model to output a JSON object containing function arguments that seamlessly integrate with your code. It's important to note that the Chat Completions API doesn't execute the functions itself. Instead, it generates the necessary JSON to facilitate function calls, giving you complete control and flexibility.

The latest ChatGPT models have been fine-tuned to intelligently detect when to call functions based on the input and respond with JSON that perfectly matches the function's signature.

Exciting Use Cases for ChatGPT Functions

Let's explore some captivating use cases:

  1. Supercharged Chatbots: Energize your chatbots by defining functions that interact with external APIs. Your chatbot can now answer questions and provide information sourced from various services. Imagine defining functions like send_email(to: string, body: string) or get_current_weather(location: string, unit: 'celsius' | 'fahrenheit') to send emails or fetch weather information, respectively.

  2. Natural Language to API Calls: Convert user queries expressed in natural language into powerful API calls. Define functions that leverage context to transform queries like "Who are my top customers?" into API calls such as get_customers(min_revenue: int, created_before: string, limit: int). Seamlessly retrieve customer data from your internal API and dazzle your users with personalized insights.

  3. Unleashing Structured Data: Extract structured data from unstructured text with ease. Define functions like extract_data(name: string, birthday: string) or sql_query(query: string) to dive into text inputs and extract specific information. Turn mountains of unstructured data into actionable insights, giving you a competitive edge.

As another example, I use functions in my Playwright Job Board to extract the name of the company from a job description and pull information from Crunchbase.

These examples merely scratch the surface of what ChatGPT functions can achieve. They open doors to integrating AI-driven conversational agents with external services, automating workflows, and unlocking hidden gems in unstructured data.

How to Harness the Power of ChatGPT Functions

Now that we've ignited your curiosity, let's explore how to put ChatGPT functions into action using the completions JavaScript package. Buckle up, here's your guide:

1. Get started by installing the completions package via npm. A single command sets the stage for your ChatGPT adventure:

npm install completions
Enter fullscreen mode Exit fullscreen mode

2. Import the necessary modules and create a chat instance. It's time to rev up the engines!

import { createChat, CancelledCompletionError } from "completions";

const chat = createChat({
  apiKey: OPENAI_API_KEY,
  model: "gpt-3.5-turbo-0613",
});
Enter fullscreen mode Exit fullscreen mode

3. Define your functions within the createChat configuration. Get ready to unleash the magic!

const chat = createChat({
  apiKey: OPENAI_API_KEY,
  model: "gpt-3.5-turbo-0613",
  functions: [
    {
      name: "get_current_weather",
      description: "Get the current weather in a given location",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "The city and state, e.g. San Francisco, CA",
          },
          unit: { type: "string", enum: ["celsius", "fahrenheit"] },
        },
        required: ["location"],
      },
      function: async ({ location }) => {
        return {
          location: "Albuquerque",
          temperature: "72",
          unit: "fahrenheit",
          forecast: ["sunny", "windy"],
        };
      },
    },
  ],
  functionCall: "auto",
});
Enter fullscreen mode Exit fullscreen mode

4. Send a message to the chat:

const response = await chat.sendMessage("What is the weather in Albuquerque?");

console.log(response.content);
// Prepare to be amazed: "The weather in Albuquerque is 72 degrees Fahrenheit, sunny with a light breeze."
Enter fullscreen mode Exit fullscreen mode

As mentioned earlier, ChatGPT will automatically determine when and which function to call, but you can optionally tell it to call a specific function:

const response = await chat.sendMessage("What is the weather in Albuquerque?", {
  functionCall: {
    name: "get_current_weather"
  },
});

console.log(response.content);
// Output: "The weather in Albuquerque is 72 degrees fahrenheit, sunny with a light breeze."
Enter fullscreen mode Exit fullscreen mode

The latter is mostly useful if you have functions with similar descriptions. Otherwise, ChatGPT is doing Okay job at picking the right function to call automatically.

With a simple message to the chat, the model will work its magic and, if suitable, invoke the defined function to retrieve the current weather in Albuquerque. The response you receive will contain the generated text, including the weather information obtained through the function.

Conclusion

ChatGPT functions empower you to build captivating conversational AI experiences by seamlessly integrating external services, automating workflows, and extracting meaningful insights. With ChatGPT, the possibilities are endless! So let your creativity soar, follow the provided examples, and embrace the exhilarating world of ChatGPT functions. Get ready to make your applications intelligent, interactive, and truly extraordinary!

đź’– đź’Ş đź™… đźš©
lucgagan
Luc Gagan

Posted on June 26, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related