import openai
import json
import os
openai.api_key = os.environ.get('OPENAI_API_KEY')
def get_response(prompt):
# 第一步,向模型发送用户的问题和它可以访问的函数
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=[{"role": "user", "content": prompt}],
functions=[
{
"name": "hex2dec",
"description": "Convert hexadecimal to decimal",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "a hexadecimal expression, e.g. 0x1e, 1e",
},
},
},
},
{
"name": "arithmetic",
"description": "Perform arithmetic operations.",
"parameters": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "A arithmetic expression, e.g. 1x2, 1+3",
},
},
},
}
],
function_call="auto",
)
message = response["choices"][0]["message"]
# 第二步,检查模型是否想要调用一个函数
if message.get("function_call"):
function_name = message["function_call"]["name"]
functions = {
'hex2dec': lambda x: f'{int(x, 16)}',
'arithmetic': lambda x: f'{eval(x)}'
}
# 第三步,调用函数
# 注意:模型返回的 JSON 可能不是有效的 JSON
function_response = functions[function_name](
json.loads(message["function_call"]["arguments"]).get('expression', 0)
)
# 第四步,向模型发送函数调用和函数响应的信息
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0613",
messages=[
{"role": "user", "content": prompt},
message,
{
"role": "function",
"name": function_name,
"content": function_response,
},
],
)
return response["choices"][0]["message"]["content"]
print(get_response('985*396+(783-249)的结果是多少?'))
print(get_response('十六进制数AB2D的十进制是多少?'))