DEV Community

Cover image for OpenAI tool calling example
Talles L
Talles L

Posted on • Edited on

OpenAI tool calling example

from json import loads
from signal import signal, SIGINT

from requests import get  # pip install requests
from openai import OpenAI  # pip install openai

# suppressing 'KeyboardInterrupt' message
signal(SIGINT, lambda _, __: exit())


def get_weather(latitude, longitude):
    response = get(f'https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m')

    data = response.json()
    temperature = data['current']['temperature_2m']

    return str(temperature)


tools = [{
    'type': 'function',
    'function': {
        'name': 'get_weather',
        'description': 'Get current temperature for provided coordinates in celsius.',
        'parameters': {
            'type': 'object',
            'properties': {
                'latitude': {'type': 'number'},
                'longitude': {'type': 'number'}
            },
            'required': ['latitude', 'longitude'],
            'additionalProperties': False
        },
        'strict': True
    }
}]

# OpenAI client and chat history with the first (system) message
client = OpenAI()
messages = [{'role': 'system', 'content': 'You are a weather assistant.'}]

while True:

    # sending message and getting a response back (chat completion)
    completion = client.chat.completions.create(model='gpt-4o-mini', messages=messages, tools=tools)

    # getting the first choice (is it possible to get more than one at a time?)
    choice = completion.choices[0]

    # appending the message to the conversation history
    messages.append(choice.message)

    # switch based on the finish reason
    match choice.finish_reason:

        # stop (weirdly) means we got a message response
        case 'stop':

            # asking for the user for a prompt
            print('\nChatGPT:', choice.message.content)
            prompt = input('\nUser: ').strip()

            # appending the user message to the conversation history
            messages.append({'role': 'user', 'content': prompt})

        # in case we got a tool call
        case 'tool_calls':

            # getting the first tool call (is it possible to get more than one at a time?)
            tool_call = choice.message.tool_calls[0]

            # function name and arguments
            function_name = tool_call.function.name
            arguments = loads(tool_call.function.arguments)

            match function_name:

                # calling the function and appending the result to conversation history
                case 'get_weather':
                    result = get_weather(**arguments)
                    messages.append({'role': 'tool', 'tool_call_id': tool_call.id, 'content': result})

                case unexpected_function:
                    raise Exception(f'Unexpected function call: {unexpected_function}')

        case unexpected_reason:
            raise Exception(f'Unexpected "finish_reason": {unexpected_reason}')
Enter fullscreen mode Exit fullscreen mode

Running it:

ChatGPT: How can I assist you with the weather today?

User: whats the weather in ny right now

ChatGPT: The current temperature in New York is -2.9°C. If you need more information about the weather or forecast, just let me know!
Enter fullscreen mode Exit fullscreen mode

Using openai package at version 1.63.2.

Top comments (0)