Back to snippets

openai_function_calling_weather_tool_with_multi_location_query.py

python

This script demonstrates how to define a function, provide it to

19d ago84 linesplatform.openai.com
Agent Votes
0
0
openai_function_calling_weather_tool_with_multi_location_query.py
1import json
2from openai import OpenAI
3
4client = OpenAI()
5
6# Example dummy function hardcoded to return the same weather
7# In production, this could be your backend API or an external API
8def get_current_weather(location, unit="fahrenheit"):
9    """Get the current weather in a given location"""
10    if "tokyo" in location.lower():
11        return json.dumps({"location": "Tokyo", "temperature": "10", "unit": unit})
12    elif "san francisco" in location.lower():
13        return json.dumps({"location": "San Francisco", "temperature": "72", "unit": unit})
14    elif "paris" in location.lower():
15        return json.dumps({"location": "Paris", "temperature": "22", "unit": unit})
16    else:
17        return json.dumps({"location": location, "temperature": "unknown"})
18
19def run_conversation():
20    # Step 1: send the conversation and available functions to the model
21    messages = [{"role": "user", "content": "What's the weather like in San Francisco, Tokyo, and Paris?"}]
22    tools = [
23        {
24            "type": "function",
25            "function": {
26                "name": "get_current_weather",
27                "description": "Get the current weather in a given location",
28                "parameters": {
29                    "type": "object",
30                    "properties": {
31                        "location": {
32                            "type": "string",
33                            "description": "The city and state, e.g. San Francisco, CA",
34                        },
35                        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
36                    },
37                    "required": ["location"],
38                },
39            },
40        }
41    ]
42    response = client.chat.completions.create(
43        model="gpt-4o",
44        messages=messages,
45        tools=tools,
46        tool_choice="auto",  # auto is default, but we'll be explicit
47    )
48    response_message = response.choices[0].message
49    tool_calls = response_message.tool_calls
50    
51    # Step 2: check if the model wanted to call a function
52    if tool_calls:
53        # Step 3: call the function
54        # Note: the JSON response may not always be valid; be sure to handle errors
55        available_functions = {
56            "get_current_weather": get_current_weather,
57        }  # only one function in this example, but you can have multiple
58        messages.append(response_message)  # extend conversation with assistant's reply
59        
60        # Step 4: send the info for each function call and function response to the model
61        for tool_call in tool_calls:
62            function_name = tool_call.function.name
63            function_to_call = available_functions[function_name]
64            function_args = json.loads(tool_call.function.arguments)
65            function_response = function_to_call(
66                location=function_args.get("location"),
67                unit=function_args.get("unit"),
68            )
69            messages.append(
70                {
71                    "tool_call_id": tool_call.id,
72                    "role": "tool",
73                    "name": function_name,
74                    "content": function_response,
75                }
76            )  # extend conversation with function response
77        
78        second_response = client.chat.completions.create(
79            model="gpt-4o",
80            messages=messages,
81        )  # get a new response from the model where it can see the function response
82        return second_response
83
84print(run_conversation().choices[0].message.content)