# Function calling doesn't work for me

**URL:** <https://community.openai.com/t/function-calling-doesnt-work-for-me/562274>\
**Category:** API\
**Tags:** functions, function-calling\
**Created:** [December 17, 2023, 4:02pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274 "2023-12-17T16:02:44Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![inventing2022](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/inventing2022/32/147517_2.png) [@inventing2022](https://community.openai.com/u/inventing2022)\
**Post date:** [December 17, 2023, 4:02pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/1 "2023-12-17T16:02:44Z")

</div>

Function calling is just not working for me. functions = [  
{  
‘name’: ‘print\_text’,  
‘description’: ‘Prints text using a printer.’,  
‘parameters’: {  
‘type’: ‘object’,  
‘properties’: {  
‘body’: {  
‘type’: ‘string’,  
‘description’: ‘The text to print.’  
}

```
        }
    }
}

```

]

I’m building a chatbot, and I’ve put a real function above the definition:  
def  
print\_text(body):  
os.system(f’echo “{body}” | lp’)  
print(“printed”)

Whenever I ask the AI to print something, I’m assuming it’s trying to; its response just says “None”, but never calls the function.

---

<div class="post-metadata">

**Author:** ![gianluca.emaldi](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/gianluca.emaldi/32/164726_2.png) [@gianluca.emaldi](https://community.openai.com/u/gianluca.emaldi)\
**Post date:** [December 17, 2023, 5:53pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/2 "2023-12-17T17:53:18Z")

</div>

Hello @inventing2022 ,  
I would need more information. Anyway, I tried to do some tests.

Using your function definition and a prompt like “`some test to print`” the result was:

```auto
function call: yes
function name: print_text
function args: {
  "body": "This is a test message."
}

```

But the arg `"body":` is different from user prompt. So I added a system message like “`Your task is to always return text delimited by three hash as function argument`” and I used a prompt like “`###Whiskers of snow, purrs bring joy and quiet solace.###`”. Using your function definition, the result was:

```auto
function call: yes
function name: print_text
function args: {
  "body": "Whiskers of snow, purrs bring joy and quiet solace."
}

```

So, a first advice could be to use a system message. This help the model to better understand the task.

But what differ from my tests and your function definition is the definition itself. Beginning from November, older function definition are deprecated. The payload structure is changed. Now functions are array of `tools`.  
The following is my working `JSON` payload. Try to print your payload and compare if there are any difference:

```json
{
  "response_format": {
    "type": "text"
  },
  "tools": [
    {
      "function": {
        "parameters": {
          "type": "object",
          "properties": {
            "body": {
              "description": "The text to print.",
              "type": "string"
            }
          }
        },
        "name": "print_text",
        "description": "Prints text using a printer."
      },
      "type": "function"
    }
  ],
  "messages": [
    {
      "role": "system",
      "content": "Your task is to always return text delimited by three hash as function argument"
    },
    {
      "role": "user",
      "content": "###Whiskers of snow, purrs bring joy and quiet solace.###"
    }
  ],
  "model": "gpt-3.5-turbo",
  "tool_choice": "auto",
  "temperature": 0,
  "top_p": 1,
  "presence_penalty": 0,
  "frequency_penalty": 0,
  "n": 1,
  "max_tokens": 1000,
  "stream": false,
  "logprobs": false
}

```

Here some documentation about `tools` API: [https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools](https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools)

---

<div class="post-metadata">

**Author:** ![jlvanhulst](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/jlvanhulst/32/195305_2.png) [@jlvanhulst](https://community.openai.com/u/jlvanhulst)\
**Post date:** [December 17, 2023, 6:20pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/3 "2023-12-17T18:20:38Z")

</div>

Using [JSONlist.com](http://JSONlist.com) to check for syntax error. (You need to use double quotes not single),  
And you need to add the “required” parameter.

So correct syntax is:

````auto
{
  "name": "print_text",
  "parameters": {
    "type": "object",
    "properties": {
      "body": {
        "type": "string",
        "description": "The text to print."
      }
    },
    "required": [
      "body"
    ]
  },
  "description": "Prints text using a printer."
}```

Hightly recommend use the back end in the beginning - on the dashboard you can see the assitant and use the + button to add a function. It will refuse to add the function if the JSON is incorrect. Unfortunately it does NOT tell you what is wrong :)
````

---

<div class="post-metadata">

**Author:** ![inventing2022](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/inventing2022/32/147517_2.png) [@inventing2022](https://community.openai.com/u/inventing2022)\
**Post date:** [December 17, 2023, 6:53pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/4 "2023-12-17T18:53:50Z")

</div>

When printing the response, it returns:  
ChatCompletion(id=‘chatcmpl-8WqLKoBmHoCGjvFPhyB2wXaquk1Kv’, choices=[Choice(finish\_reason=‘tool\_calls’, index=0, message=ChatCompletionMessage(content=None, role=‘assistant’, function\_call=None, tool\_calls=[ChatCompletionMessageToolCall(id=‘call\_GT5nP68OqC46aaKfYmWQjmCP’, function=Function(arguments=‘{\n “text”: “Hello, world!”\n}’, name=‘print\_text’), type=‘function’)]), logprobs=None)], created=1702838394, model=‘gpt-3.5-turbo-0613’, object=‘chat.completion’, system\_fingerprint=None, usage=CompletionUsage(completion\_tokens=17, prompt\_tokens=133, total\_tokens=150))

But It never calls the function!

---

<div class="post-metadata">

**Author:** ![jlvanhulst](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/jlvanhulst/32/195305_2.png) [@jlvanhulst](https://community.openai.com/u/jlvanhulst)\
**Post date:** [December 17, 2023, 7:00pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/5 "2023-12-17T19:00:04Z")

</div>

You will have to call the function when you receive the ‘tool\_calls’ status… Many examples - here is post that I wrote a few weeks ago.

> **[Playing with the new OpenAI Assistant and function calling in Python](https://jlvalorvc.medium.com/playing-with-the-new-openai-assistant-and-function-calling-in-python-2a4ddf27a208)**
>
> I just updated our VicBot AI Assistant to support the new Assistant Structure that OpenAI released in Beta last week. I love it!

Openai docs have an example as well  
[https://platform.openai.com/docs/assistants/tools/code-interpreter](https://platform.openai.com/docs/assistants/tools/code-interpreter)

---

<div class="post-metadata">

**Author:** ![inventing2022](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/inventing2022/32/147517_2.png) [@inventing2022](https://community.openai.com/u/inventing2022)\
**Post date:** [December 17, 2023, 7:13pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/6 "2023-12-17T19:13:59Z")

</div>

Oh, I’m not using the assistant api, just the normal GPT-3.5 Turbo-0613.

---

<div class="post-metadata">

**Author:** ![jlvanhulst](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/jlvanhulst/32/195305_2.png) [@jlvanhulst](https://community.openai.com/u/jlvanhulst)\
**Post date:** [December 17, 2023, 7:18pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/7 "2023-12-17T19:18:30Z")

</div>

Its’ mostly the same mechanism.

---

<div class="post-metadata">

**Author:** ![inventing2022](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/inventing2022/32/147517_2.png) [@inventing2022](https://community.openai.com/u/inventing2022)\
**Post date:** [December 17, 2023, 8:22pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/8 "2023-12-17T20:22:59Z")

</div>

Ok, but could you provide me with some sample code for that? The Function calling Api refence is a bit confusing to me.

---

<div class="post-metadata">

**Author:** ![jlvanhulst](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/jlvanhulst/32/195305_2.png) [@jlvanhulst](https://community.openai.com/u/jlvanhulst)\
**Post date:** [December 17, 2023, 8:41pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/9 "2023-12-17T20:41:17Z")

</div>

Check out this cookbook?

> **[How to call functions with chat models | OpenAI Cookbook](https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models)**
>
> Open-source examples and guides for building with the OpenAI API. Browse a collection of snippets, advanced techniques and walkthroughs. Share your own examples and guides.

---

<div class="post-metadata">

**Author:** ![gianluca.emaldi](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/gianluca.emaldi/32/164726_2.png) [@gianluca.emaldi](https://community.openai.com/u/gianluca.emaldi)\
**Post date:** [December 18, 2023, 11:05am UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/10 "2023-12-18T11:05:54Z")

</div>

In your provided response the model choose to call function. You must check `finish_reason` key. In your response `finish_reason='tool_calls'`. It means model choose to call function.  
The older, and deprecated, `function_call` key is equal to `None`, but only because is deprecated.  
So, first you must check that `finish_reason='tool_calls'`. If `finish_reason` is equal to `tool_calls`, then you can extract function arguments.

I take it for granted that you put response in a variable, such as `'chat_response'`.  
First extract assistant message:

```python
message = chat_response.json()["choices"][0]["message"]['tool_calls']

```

Now `message` must contain:

```python
[{'id': 'call_BEvTzOZ8V4jTA3cT3qd3o2Lz', 'type': 'function', 'function': {'name': 'print_test', 'arguments': '{\n "text": "Hello, world!"\n}'}}]

```

Then extract `"text"` argument:

```python
text = json.loads(message[0]["function"]["arguments"])["text"]
print(text)
# 'Hello, world!'

```

Calling your application function:

```python
def print_text(body):
    os.system(f’echo “{body}” | lp’)
    print(“printed”)

print_text(text)

```

Hope it help.

---

<div class="post-metadata">

**Author:** ![jlvanhulst](https://sea2.discourse-cdn.com/openai1/user_avatar/community.openai.com/jlvanhulst/32/195305_2.png) [@jlvanhulst](https://community.openai.com/u/jlvanhulst)\
**Post date:** [December 18, 2023, 12:24pm UTC](https://community.openai.com/t/function-calling-doesnt-work-for-me/562274/11 "2023-12-18T12:24:34Z")

</div>

I noticed this morning that you now get a JSON error with line number when trying to save invalid JSON in the functions in the backend.
