Last active
March 21, 2024 14:42
-
-
Save dm4/3571352e85558508f930b454105c035e to your computer and use it in GitHub Desktop.
試用 OpenAI 的 Function Calling API https://blog.dm4.tw/2024/03/21/try-gpt-function-calling.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import json | |
import logging | |
from openai import OpenAI | |
logging.basicConfig(format="[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s") | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logging.INFO) | |
def get_home_temperature(): | |
return { | |
"living_room": 26, | |
"bed_room": 24, | |
"dining_room": 23, | |
} | |
if __name__ == "__main__": | |
client = OpenAI(api_key="sk-...") | |
messages = [] | |
messages.append({"role": "user", "content": "如果客廳的溫度大於 25 度的話,就幫我開冷氣和電風扇。"}) | |
tools = [] | |
tools.append({ | |
"type": "function", | |
"function": { | |
"name": "get_home_temperature", | |
"description": "取得家裡所有地方的溫度", | |
} | |
}) | |
tools.append({ | |
"type": "function", | |
"function": { | |
"name": "control_appliance", | |
"description": "控制家裡的電器開關", | |
"parameters": { | |
"type": "object", | |
"properties": { | |
"appliance": { | |
"type": "string", | |
"description": "電器名稱", | |
"enum": ["air_conditioner", "heater", "light", "fan"] | |
}, | |
"status": {"type": "string", "enum": ["on", "off"]}, | |
}, | |
"required": ["appliance", "status"], | |
}, | |
} | |
}) | |
while True: | |
response = client.chat.completions.create( | |
model="gpt-4-turbo-preview", | |
messages=messages, | |
tools=tools, | |
) | |
messages.append(response.choices[0].message) | |
if not response.choices[0].message.tool_calls: | |
logger.info(response.choices[0].message.content) | |
break | |
else: | |
logger.info("Calling %d tool(s):", len(response.choices[0].message.tool_calls)) | |
for tool_call in response.choices[0].message.tool_calls: | |
if tool_call.function.name == "get_home_temperature": | |
logger.info("-> %s(%s)", tool_call.function.name, tool_call.function.arguments) | |
messages.append({ | |
"role": "tool", | |
"tool_call_id": tool_call.id, | |
"name": tool_call.function.name, | |
"content": json.dumps(get_home_temperature()), | |
}) | |
else: | |
logger.info("-> %s(%s)", tool_call.function.name, tool_call.function.arguments) | |
messages.append({ | |
"role": "tool", | |
"tool_call_id": tool_call.id, | |
"name": tool_call.function.name, | |
"content": "", | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment