DEV Community

Kartik Sharma
Kartik Sharma

Posted on

When ChatGPT interacts with your Code 🧑🏼‍💻

In this post, I'll guide you through the process of implementing function calling in your app. With this functionality, your app can feature a sophisticated chatbot that dynamically responds to users based on their context. By integrating function calling, the chatbot can execute actions—such as querying a database or triggering specific operations—directly from the conversation, making interactions more intelligent and seamless.

What the heck is Function calling anyway?

Function calling is a powerful feature within the OpenAI Assistant's API that enables applications to perform complex operations dynamically. It allows the Assistant to execute predefined actions, such as triggering database queries, making API calls, or invoking custom functions in your codebase, in response to user queries. This feature integrates seamlessly with your application's logic, making it a versatile tool for creating intelligent and interactive experiences.

Use Case of Function calling

  • Ditching Traditional Filtering in Your App

Filtering and sorting components are a staple in most applications, whether it's e-commerce or otherwise. However, instead of having users interact with traditional widgets to select product attributes like color, size, type, or budget, you can simplify the experience with plain English queries. For example, users can simply type something like, "White shirt in size medium for men under 2K," and let your app handle the rest.

Implementing Function Calling in the ChatGPT SDK

Implementing the function calling feature in the ChatGPT SDK is straightforward, especially if you're already familiar with the SDK. Here’s a simple step-by-step guide:

  1. Define the Function and Its Argument Types

    Start by specifying the function's behavior and clearly define its argument types. This ensures the Assistant understands how to call your function and what parameters it requires.

  2. Integrate the Function into the Assistant API

    Pass the defined function to the Assistant API using the tools parameter. This connects the function to the Assistant, enabling it to be called dynamically during interactions.

  3. Test Your Implementation

    Put your setup to the test! Run scenarios to ensure the function behaves as expected when invoked by the Assistant.

Define the Function and Its Argument Types

Defining a function tool is straightforward. It involves creating an object that specifies the actual function name to be triggered and its argument types. When defining arguments, you can also:

  • Specify the Data Type: Define the expected data type for each argument (e.g., string, number, boolean).
  • Set Argument Requirements: Indicate whether an argument is required or optional.
  • Enforce Specific Formats: Define any particular format the argument should follow, such as uppercase, lowercase, or specific patterns like date formats.

This level of customization ensures the function behaves predictably and meets the application's requirements.

Code Example of function definition:

{
  type: "function",
  function: {
    name: "search_product",
    description:
      "Search for a product in the e-commerce app based on user preferences.",
    parameters: {
      type: "object",
      properties: {
        color: {
          type: "string",
          description: "The color of the product (e.g., red, blue, white).",
        },
        item: {
          type: "string",
          description:
            "The type of item to search for (e.g., shirt, shoes, bag).",
        },
        name: {
          type: "string",
          description:
            "The name or brand of the product, if specified by the user.",
        },
        size: {
          type: "string",
          description:
            "The size of the product (e.g., small, medium, large, or numeric sizes).",
        },
        price: {
          type: "number",
          description:
            "The maximum price the user is willing to pay for the product.",
        },
      },
      required: ["item"],
    },
  },
}
Enter fullscreen mode Exit fullscreen mode

Integrate the Function into the Assistant API

Once the function is defined, the next step is to connect it to the Assistant API instance. This integration ensures that the ChatGPT instance is aware of the function's existence and can trigger it whenever appropriate.

By passing the function definition through the tools parameter during the Assistant setup, you enable the model to leverage your custom function dynamically, making it a valuable part of the application's interaction flow.

Code Example:

import OpenAI from "openai";

// Initialize the OpenAI client with your API key
const apiKey = "Your-api-key";
const openAiClient = new OpenAI({ apiKey });

// Define the tools array and pass the function definition created earlier
const tools = [shoppingTool];

const performProductLookup = async (userQuery) => {
        // Send the user's query to the Assistant API
        const response = await openAiClient.chat.completions.create({
            model: "gpt-3.5-turbo",
            messages: [
                {
                    role: "user",
                    content: userQuery,
                },
            ],
            tools,
        });

        // Check if the Assistant invoked a tool (function)
        const toolCalls = response.choices[0]?.message?.tool_calls;
        if (toolCalls?.length > 0) {
            const functionCall = toolCalls[0].function;

            // If the invoked function matches "shoppingTool", parse its arguments
            if (functionCall.name === "search_product") {
                const parsedArguments = JSON.parse(functionCall.arguments);
                return {
                    name: functionCall.name,
                    arguments: parsedArguments,
                };
            }
        }

        // Return the general content string if no tool was invoked
        return response.choices[0]?.message?.content || "No content returned.";
};

(async () => {
    const productResponse = await performProductLookup(
        "White Shirt in size medium under 2K"
    );
    console.log(productResponse);
})();
Enter fullscreen mode Exit fullscreen mode

Response from Assistant’s API:

{
  name: 'search_product',
  arguments: { color: 'white', item: 'shirt', size: 'medium', price: 2000 }
}
Enter fullscreen mode Exit fullscreen mode

Once the user query is parsed and the relevant arguments (such as color, item, size, etc.) are extracted, you can pass them to the actual function responsible for performing a real-time database lookup. This function will query your database, search for matching products, and return the results, which can then be presented to the user in a structured format.

By using these arguments, you ensure that the lookup is dynamic and tailored to the user’s specific request.

That’s it! Now you have the flexibility to define the logic based on your specific needs and implement custom functionality for your application. Whether you're handling product lookups, automating workflows, or performing any other operation, the possibilities are endless.

Let me know in the comments how you’ve implemented this and if you have any questions or feedback.

Thanks for reading!

Top comments (0)