Documentation fix to code for Function calling

Hi I noticed a code example in the docs that produces errors and does not run successfully. Is there a way I can provide fixes to help future devs?
https://platform.openai.com/docs/guides/function-calling#function-tool-example

It seems like it has some Python syntax mixed into the JavaScript (e.g. json.dumps, using a colon instead of a curly bracket for a code block, etc) and has one other mistake that prevents it from running successfully.

I’m new to this community. Is there a way I can provide the fixed code? What’s the preferred/recommended way to do this? Thanks

Here’s the corrected code for convenience. (You’ll have to run a formatter b/c it seems to be stripping the leading spaces)

// 1. Define a list of callable tools for the model
const tools = [
{
type: “function”,
name: “get_horoscope”,
description: “Get today’s horoscope for an astrological sign.”,
parameters: {
type: “object”,
properties: {
sign: {
type: “string”,
description: “An astrological sign like Taurus or Aquarius”,
},
},
required: [“sign”],
},
},
];

function getHoroscope({ sign }) {
return sign + " Next Tuesday you will befriend a baby otter.";
}

// Create a running input list we will add to over time
let input = [
{ role: “user”, content: “What is my horoscope? I am an Aquarius.” },
];

// 2. Prompt the model with tools defined
let response = await openai.responses.create({
model: “gpt-5”,
tools,
input,
});

// Save function call outputs for subsequent requests
response.output.forEach((item) => {
input.push(item);
});

response.output.forEach((item) => {
if (item.type == “function_call”) {
if (item.name == “get_horoscope”) {
// 3. Execute the function logic for get_horoscope
const horoscope = getHoroscope(JSON.parse(item.arguments));

  // 4. Provide function call results to the model
  input.push({
    type: "function_call_output",
    call_id: item.call_id,
    output: JSON.stringify({ horoscope }),
  });
}

}
});

console.log(“Final input:”);
console.log(JSON.stringify(input, null, 2));

response = await openai.responses.create({
model: “gpt-5”,
instructions: “Respond only with a horoscope generated by a tool.”,
tools,
input,
});

// 5. The model should be able to give a response!
console.log(“Final output:”);
console.log(JSON.stringify(response.output, null, 2));

Forum formatting

You can provide a block of code in the forum by surrounding it with lines that have triple-backticks (```). The “preformatted text” in the format bar also will provide this. Otherwise, code is extremely damaged, such as directional quote characters being used.

Already “reported” here

This was already noted, but no action has been taken:


Letting GPT-5.2 coding pal loose on the Python vs Javascript versions:

What to edit (errors only)

Using your JS snippet’s approximate line numbers:

  1. Line 23: getHoroscope is written to accept a string, but you pass it the parsed arguments object. Fix by changing the function signature to accept { sign }.

  2. After line 37: you must append the model’s first response.output back into the running input array:

    • add input.push(...response.output);
  3. Line 41: if (...) : is Python syntax and will crash parsing in JS. Replace with a normal JS if (...) { ... }.

  4. Line 43: get_horoscope is not defined (your function is getHoroscope). Call the right function name.

  5. Line 46: input_list is not defined (your list is input). Push into input.

  6. Line 49: json.dumps doesn’t exist in JS. Use JSON.stringify(...).


Patch (unified diff)

--- a/horoscope.js
+++ b/horoscope.js
@@
-function getHoroscope(sign) {
+function getHoroscope({ sign }) {
   return sign + " Next Tuesday you will befriend a baby otter.";
 }
@@
 let response = await openai.responses.create({
   model: "gpt-5",
   tools,
   input,
 });
 
+input.push(...response.output);
+
 response.output.forEach((item) => {
   if (item.type == "function_call") {
-    if (item.name == "get_horoscope"):
-      // 3. Execute the function logic for get_horoscope
-      const horoscope = get_horoscope(JSON.parse(item.arguments))
-      
-      // 4. Provide function call results to the model
-      input_list.push({
-          type: "function_call_output",
-          call_id: item.call_id,
-          output: json.dumps({
-            horoscope
-          })
-      })
+    if (item.name == "get_horoscope") {
+      // 3. Execute the function logic for get_horoscope
+      const horoscope = getHoroscope(JSON.parse(item.arguments));
+
+      // 4. Provide function call results to the model
+      input.push({
+        type: "function_call_output",
+        call_id: item.call_id,
+        output: JSON.stringify({ horoscope }),
+      });
+    }
   }
 });

Complete corrected code

import OpenAI from "openai";
const openai = new OpenAI();

// 1. Define a list of callable tools for the model
const tools = [
  {
    type: "function",
    name: "get_horoscope",
    description: "Get today's horoscope for an astrological sign.",
    parameters: {
      type: "object",
      properties: {
        sign: {
          type: "string",
          description: "An astrological sign like Taurus or Aquarius",
        },
      },
      required: ["sign"],
    },
  },
];

function getHoroscope({ sign }) {
  return sign + " Next Tuesday you will befriend a baby otter.";
}

// Create a running input list we will add to over time
let input = [
  { role: "user", content: "What is my horoscope? I am an Aquarius." },
];

// 2. Prompt the model with tools defined
let response = await openai.responses.create({
  model: "gpt-5",
  tools,
  input,
});

input.push(...response.output);

response.output.forEach((item) => {
  if (item.type == "function_call") {
    if (item.name == "get_horoscope") {
      // 3. Execute the function logic for get_horoscope
      const horoscope = getHoroscope(JSON.parse(item.arguments));

      // 4. Provide function call results to the model
      input.push({
        type: "function_call_output",
        call_id: item.call_id,
        output: JSON.stringify({ horoscope }),
      });
    }
  }
});

console.log("Final input:");
console.log(JSON.stringify(input, null, 2));

response = await openai.responses.create({
  model: "gpt-5",
  instructions: "Respond only with a horoscope generated by a tool.",
  tools,
  input,
});

// 5. The model should be able to give a response!
console.log("Final output:");
console.log(JSON.stringify(response.output, null, 2));

Functions return request shape - Responses

If you just want to send a call and see the AI answer with the required message sequence of a strict structured tool call and a tool response as input, not have it use your fake function, I created a “get code” on the “playground”:

import OpenAI from "openai";

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

const response = await openai.responses.create({
  model: "gpt-4.1",
  input: [
    {
      "role": "system",
      "content": [
        {
          "type": "input_text",
          "text": "Horoscopes: Respond only with a tool-generated horoscope."
        }
      ]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "input_text",
          "text": "What is my horoscope? I am an Aquarius."
        }
      ]
    },
    {
      "type": "function_call",
      "id": "fc_05cc35f2b4b0667a0169628083c55881908b6b5e57a74037a8",
      "call_id": "call_tZlYuKgqFz03Hrd3suLXFxDX",
      "name": "get_horoscope",
      "arguments": "{\"sign\":\"Aquarius\"}"
    },
    {
      "type": "function_call_output",
      "call_id": "call_tZlYuKgqFz03Hrd3suLXFxDX",
      "output": " Aquarius Next Tuesday you will befriend a baby otter."
    }
  ],
  tools: [
    {
      "type": "function",
      "name": "get_horoscope",
      "description": "Get today's horoscope for an astrological sign.",
      "parameters": {
        "type": "object",
        "properties": {
          "sign": {
            "type": "string",
            "description": "An astrological sign like Taurus or Aquarius"
          }
        },
        "required": [
          "sign"
        ],
        "additionalProperties": false
      },
      "strict": true
    }
  ],
  max_output_tokens: 2048,
  top_p: 0.5,
  store: false,
});

PS: first to have a fortune-telling function?

1 Like

Thanks for raising this (again)!
I have flagged this to the team for review.

4 Likes

Thanks @vb . I appreciate it.

3 Likes

Teamwork makes the dream (community) work! I love this place haha. :slight_smile:

3 Likes