-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction-calling.py
63 lines (52 loc) · 1.95 KB
/
function-calling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import requests
def get_weather(latitude, longitude):
response = requests.get(f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m")
data = response.json()
return data['current']['temperature_2m']
from openai import OpenAI
import json
client = OpenAI()
tools = [{
"type": "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
}]
input_messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]
print(f"1 -> Initial Input array {input_messages}")
response = client.responses.create(
model="gpt-4o",
input=input_messages,
tools=tools,
)
# Model extracts the tool call.
tool_call = response.output[0]
# Invoke the tool
args = json.loads(tool_call.arguments)
result = get_weather(args["latitude"], args["longitude"])
# Add the reult of the tool call to input messages so that it can be passed back to the model.
input_messages.append(tool_call)
input_messages.append({
"type": "function_call_output",
"call_id": tool_call.call_id,
"output": str(result)
})
response_2 = client.responses.create(
model="gpt-4o",
input=input_messages,
tools=tools,
)
print(f"2 -> Invoke the model")
print(f"3 -> Model outputs function to invoke with parameter -> {tool_call}")
print(f"4 -> Invoke the function and get the output - {str(result)}")
print(f"5 -> Append the function call and result of the function to input messages - {input_messages}")
print(f"6 -> Call the model again - {response_2.output_text}")