openai更新的Chat Completions API支持 Function calling如何使用

583 阅读2分钟

openai在最近(2023.6.13)的一次更新中,针对gpt-4-0613和gpt-3.5-turbo-0613支持Function calling,通过官网提供的的示例,我们看到这次更新进一步增强了人工智能的外部能力和实效性,企业和开发人员可以结合自己的应用场景在人工智能的加持下给用户提供更加丰富多样的功能。

我们先来看下官网提供的调用外部天气接口的示例代码,分为三步:

1、使用函数和用户输入调用模型 此时模型会判断用户输入是否需要调用Function,如果符合调用条件,那么模型会返回方法名和参数

2、使用模型响应调用天气接口的API 这一步会调用服务端的get_current_weather方法,获取对应地区的天气情况

3、将响应发送回模型以进行总结 这一步会将用户的问题和天气数据再次发给模型,模型会总结后将结果发给用户

下面的代码使用了(github.com/openai-php/…) openai-php/client v0.6.1来实现调用流程,参考openai官网示例,将相应的functions参数修改成了中文,以支持中文的天气预,get_current_weather方法使用了高德提供的天气接口返回数据,大家使用的时候可以替换成实际的接口调用即可。

public function function_call($prompt)
    {

        $yourApiKey = ''; 

        try {
            $client = OpenAI::client($yourApiKey);
            if(isset($client)){
                
                //步骤一
                $response = $client->chat()->create([
                    'model' => 'gpt-3.5-turbo-0613',
                    'messages' => [
                        ['role' => 'user', 'content' => $prompt],
                    ],
                    'functions' => [
                        [
                            'name' => 'get_current_weather',
                            'description' => '获取给定位置的当前天气',
                            'parameters' => [
                                'type' => 'object',
                                'properties' => [
                                    'location' => [
                                        'type' => 'string',
                                        'description' => '城市和省或者区和市,例如北京市海淀区',
                                    ],
                                    'unit' => [
                                        'type' => 'string',
                                        'enum' => ['celsius', 'fahrenheit']
                                    ],
                                ],
                                'required' => ['location'],
                            ],
                        ]
                    ]
                ]);

                foreach ($response->choices as $result) {
                    $result->index; // 0
                    $result->message->role; // 'assistant'
                    $content = $result->message->content; // null
                    if(isset($result->message->functionCall->name)){
                        $name = $result->message->functionCall->name; // 'get_current_weather'
                    }
                    if(isset($result->message->functionCall->arguments)){
                        $arguments = $result->message->functionCall->arguments; // "{\n  "location": "Boston, MA"\n}"
                    }
                    if(isset($result->finishReason)){
                        $finishReason = $result->finishReason; // 'function_call'
                    }
                    if(isset($content)){                    

                    }
                    if(isset($name)){                    

                    }
                    if(isset($arguments)){

                    }
                    if(isset($finishReason)){

                    }

                }


                if($finishReason=="function_call"){

                    if(isset($arguments)){
                        $arr = json_decode(json_decode(json_encode($arguments)));
                        if(isset($arr->location)){

                        }
                    }

                    //步骤二
                    if(isset($name)){
                        $content_json = $this->$name($arr->location);
                    }

                    
                    //步骤三
                    unset($response);                    
                    $stream = $client->chat()->createStreamed([
                        'model' => 'gpt-3.5-turbo-0613',
                        'messages' => [
                            ['role' => 'user', 'content' => $prompt],
                            ['role' => 'function', 'name' => 'get_current_weather', 'content' => $content_json ],
                        ],
                    ]);

                    if(isset($stream)){
                        foreach($stream as $response){
                            $contentArr = $response->choices[0]->toArray();
                        }                    
                    }       
                }         

            }else{

            }
        } catch (\OpenAI\Exceptions\ErrorException $e) {
            $type = $e->getErrorType(); // "invalid_request_error"
            $errorCode = $e->getErrorCode(); // "invalid_api_key"
            $errorMessage = $e->getErrorMessage();
            if(isset($type)){

            }
            if(isset($errorCode)){

            }            
            if(isset($errorMessage)){

            }
        }
    }


    public function get_current_weather($location="北京市市辖区", $unit="fahrenheit"){
        
        $result = '{"status":"1","count":"1","info":"OK","infocode":"10000","lives":[{"province":"北京","city":"北京市","adcode":"110000","weather":"晴","temperature":"36","winddirection":"东南","windpower":"4","humidity":"25","reporttime":"2023-06-15 17:10:04","temperature_float":"36.0","humidity_float":"25.0"}]}';

        return json_encode($result);

    }    

prompt:北京的天气怎么样?可以推荐一些适合的户外活动吗?

实现效果可以看下图片,或者微信小程序搜索“AIWorkFlow”,自己亲自试试吧

WechatIMG22.jpeg