‘openai’function_calling不执行函数

问题描述 投票:0回答:1

使用函数调用,openai并不执行函数,而是打印带有参数的函数,请参见下面:

我在colab中使用本地法学硕士(Llama2)。

openai版本已安装0.27.8

!pip install openai==0.27.8

os.environ['OPENAI_API_KEY'] = 'NULL'
os.environ['OPENAI_API_BASE'] = "http://localhost:8000/v1"

#import OpenAI from "openai";
openai.api_base = os.getenv('OPENAI_API_BASE')
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.api_version = "2023-07-01-preview"

这里的功能:

def get_current_weather(location):
"""Get the current weather in a given location"""

url = "https://weatherapi-com.p.rapidapi.com/forecast.json"

querystring = {"q":location, "days":"1"}

headers = {
    "X-RapidAPI-Key": "xxxxx",
    "X-RapidAPI-Host": "weatherapi-com.p.rapidapi.com"
}

response = requests.get(url, headers=headers, params=querystring)

weather_info = {
    "location": response.json()['location']['name'],
    "temperature": response.json()['current']['temp_c'],
}

print(json.dumps(weather_info))

return json.dumps(weather_info)

它返回以下结果:

response=get_current_weather('Naples, Italy')
{"location": "Naples", "temperature": 17.0}

这里是函数的架构

function_descriptions = [{
    "name": "get_current_weather",
    "description": "Get the current weather",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA"
            },
        },
        "required": ["location"],
    },
}]

这里聊天完成

completion = openai.ChatCompletion.create(
model="gpt-35-turbo-0613",
messages=[{"role": "user", "content": user_prompt}],
functions=function_descriptions,
function_call={"name": "get_current_weather"}
#function_call="auto"
)
output = completion.choices[0].message
print(output)
{
   "role": "assistant",
   "content": "Ah, thank you for asking! The current temperature in Naples, Italy is approximately {get_current_weather({location: \"Naples, Italy\"})}. Would you like me to tell you more about the weather there?<|END_OF_ASSISTANT|></s>"
 }

为什么它不执行函数而只是打印调用 {get_current_weather({location: "Naples, Italy"})} ???

openai-api function-call large-language-model
1个回答
1
投票

大型语言模型(LLM)无法直接运行代码。他们的专业知识在于处理和生成文本,其中包括代码片段,但并未扩展到实际执行。如果目标是执行代码,有两种选择:

  • 服务器端执行: 在这种方法中,代码在 OpenAI 或 Google 等实体拥有的服务器上执行。然而,由于存在任意代码执行的风险,这种方法会带来安全问题。请务必注意,您并未将实际函数

    get_current_weather
    传递给模型,您只是在
    function_descriptions
    中提供描述。

  • 客户端处理: 许多公司选择客户端处理,将模型识别的参数发送到客户端,以便用户处理(功能选择和参数识别是该功能的实际好处)。为了实现这一点,需要在客户端仔细管理模型的输出。 收到模型的响应后,您可以通过检查

    finish_reason
    中的
    response.choices[0].finish_reason
    来解析结果。如果您使用
    function_call="auto"
    并且模型识别出函数调用的需要,它将返回
    finish_reason='function_call'
    。您可以使用此信息智能地解析输出并在服务器上执行代码,从而保持对执行过程的控制。

© www.soinside.com 2019 - 2024. All rights reserved.