What is OpenAI Function Calling and How to Use it?

208 Technical , 1 Comment

Simply put, OpenAI / ChatGPT function calling can identify the intent and entities in a sentence through a language model.

For example, when the user asks "I want to recharge my phone100 USD".

The model should recognize the intent recharge and it’s 2 entities

  • recharge amont: 100
  • currency:USD

Back to OpenAI function calling, we can define which intent and corresponding entities we should get while calling ChatGPT or OpenAI API.

Please remember, the model doesn’t exactly call any API. It just get what function you want to call, and what are the parameters.

curl https://api.openai.com/v1/chat/completions -u :$OPENAI_API_KEY -H 'Content-Type: application/json' -d '{
  "model": "gpt-3.5-turbo-0613",
  "messages": [
    {"role": "user", "content": "I want to recharge my phone100 USD"}
  ],
  "functions": [
    {
      "name": "mobile_recharge",
      "description": "Mobile phone recharge by given amount and currency",
      "parameters": {
        "type": "object",
        "properties": {
          "amount": {
            "type": "integer",
            "description": "The amount to recharge"
          },
          "currency": {
            "type": "string",
            "description": "The currency of the amount"
          }
        },
        "required": ["amount"]
      }
    }
  ]
}'

Here user ask "I want to recharge my phone100 USD, and it returns:

{
  "id": "chatcmpl-123",
  ...
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": null,
      "function_call": {
        "name": "mobile_recharge",
        "arguments": "{ \"amount\": 100,  \"currency\": \"USD\"}"
      }
    },
    "finish_reason": "function_call"
  }]
}

Using this information from ChatGPT calling, you can call your function at any promgramming language.

If use messages is not a recharge sentence, e.g., "How much does the sun weigh?".

The return will be:

{
  "id": "chatcmpl-123",
  ...
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "The mass of the Sun is approximately 1.989 × 10^30 kilograms (kg). ",
    },
    "finish_reason": "stop"
  }]
}

The finish_reason would be stop not function_call, it will be a normal answer.

1 Comment

X
XFihd says: Reply

Is there any unexpected output and what is the identified accuracy?

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *