Back to roadmaps openai Course

Defining Tools using JSON Schema in OpenAI

OpenAI models cannot perform real-world actions directly (such as calling database records or sending shipping updates). However, you can declare Tools to inform the model about available functions it can request.


1. What is Function Calling?

Instead of returning standard text, the model returns a Tool Call payload containing:

  1. The name of the function to invoke.
  2. Formatted parameter arguments matching a JSON Schema specification.

You parse the request, run the local function, and return the result back to the model to continue.


2. Declaring Tools via JSON Schema

Pass your function definitions inside the tools array parameter:

// src/config/tools.ts
import { ChatCompletionTool } from "openai/resources/chat/completions";

export const chatTools: ChatCompletionTool[] = [
  {
    type: "function",
    function: {
      name: "getUserSubscription",
      description: "Query the billing and active membership state of a user in the local database.",
      parameters: {
        type: "object",
        properties: {
          email: {
            type: "string",
            description: "The customer email address to look up.",
          },
        },
        required: ["email"],
        additionalProperties: false,
      },
    },
  },
  {
    type: "function",
    function: {
      name: "applyStoreRefund",
      description: "Trigger a customer refund for a specific payment transaction ID.",
      parameters: {
        type: "object",
        properties: {
          transactionId: {
            type: "string",
            description: "The unique order or payment transaction reference code.",
          },
          reason: {
            type: "string",
            description: "Detailed context explaining why the refund is applied.",
          },
        },
        required: ["transactionId", "reason"],
        additionalProperties: false,
      },
    },
  },
];

3. Best Practices for Descriptions

  • Be Explicit: The model relies on the description attribute to decide whether to invoke a tool. Provide clear context (for example, instead of database check, write Check user membership roles and limits in PostgreSQL).
  • Keep Schemas Concise: Large schemas consume significant context token overhead, increasing latency and API costs.
Published on Last updated: