chatgpt Function calling简单函数调用示例
import openai
import glob
import difflib
import subprocess
import json
openai.api_key = "sk-**********"
potplayer_path = "Z:\PotPlayer\PotPlayer\PotPlayerMini64.exe"
def play_music(kw):
path = r"Z:\test_pro\*.mp3"
fs = glob.glob(path)
matches = difflib.get_close_matches(kw, fs, cutoff=0.01)
best = matches[0]
subprocess.call([potplayer_path, best])
def play_movie(kw):
path = r"Z:\test_pro\*.mp4"
fs = glob.glob(path)
matches = difflib.get_close_matches(kw, fs, cutoff=0.01)
best = matches[0]
subprocess.call([potplayer_path, best])
def run_conversation():
functions = [
{
"name": "play_music",
"description": "根据用户提供的曲名关键字播放音乐",
"parameters": {
"type": "object",
"properties": {
"kw": {
"type": "string",
"description": "曲名关键字",
}
},
"required": ["kw"],
},
},
{
"name": "play_movie",
"description": "根据用户提供的电影名关键字播放电影",
"parameters": {
"type": "object",
"properties": {
"kw": {
"type": "string",
"description": "电影名关键字",
}
},
"required": ["kw"],
},
}
]
messages = []
messages.append({"role": "system", "content": "Don't make assumptions about"})
messages.append({"role": "user", "content": "我想睡觉"})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=messages,
functions=functions,
function_call="auto",
)
response_message = response["choices"][0]["message"]
print(response_message)
if response_message.get("function_call"):
function_name = response_message["function_call"]["name"]
function_args = json.loads(response_message["function_call"]["arguments"])
if function_name == "play_music":
play_music(**function_args)
elif function_name == "play_movie":
play_movie(**function_args)
if __name__ == '__main__':
run_conversation()
自定义函数扩展可以向functions列表里追加
是不是写的足够简单明了!那就给个赞吧!!!