国产+高潮+在线,国产 av 仑乱内谢,www国产亚洲精品久久,51国产偷自视频区视频,成人午夜精品网站在线观看

分享一個(gè)單文件的 ChatGPT api接口實(shí)現(xiàn)

banro512

一個(gè)非常簡(jiǎn)單的單文件 ChatGPT api接口實(shí)現(xiàn)

最終效果圖如下.


使用說(shuō)明

  1. 基于webman,首先要安裝好webman

  2. 然后安裝 OpenAI 的官方php庫(kù)

    composer require openai-php/client
    composer require guzzlehttp/guzzle

  3. api在國(guó)內(nèi)已被墻,但官方庫(kù)(< v0.4.0)不支持使用代理,所以需要手動(dòng)修改官方庫(kù),添加代理支持

打開(kāi) vendor\openai-php\client\src\OpenAI.php
將在 第29行 附近的代碼 $client = new GuzzleClient(); 改為

  $client = new GuzzleClient([
            "proxy"=>"你的代理 http://ip:端口"
  ]);

比如我的代理地址是 127.0.0.1:7890 則修改后是:

        $client = new GuzzleClient([
            "proxy"=>"http://127.0.0.1:7890"
        ]);

新版 >= 0.4 以后 openai庫(kù)有變化,無(wú)需再改動(dòng)官方庫(kù)了

  1. 將該文件放在某個(gè)控制器目錄下,然后訪問(wèn) http://域名/chatgpt 如果有模塊,則訪問(wèn) http://域名/模塊/chatgpt

  2. php start.php restart 重啟你的應(yīng)用

全部代碼如下


<?php
namespace app\controller;
use support\Request;
use OpenAI\Client;
// openai 的 key
// 全局代理后,在這里注冊(cè)登錄 https://platform.openai.com/signup 
define('OPENAI_KEY', '填寫(xiě)你的key');
class ChatgptController
{   
    // 初始化獲取全部已回答
    public function all(Request $request){
        $messages = $request->session()->get('messages', []);
        return json([
            "code"=>0,
            "msg"=>"ok",
            "data"=>$messages
        ]);
    }
    // 單次查詢(xún)
    public function query(Request $request)
    {
        $messages = $request->session()->get('messages', []);
        $messages[] = ['role' => 'user', 'content' => $request->input('message')];
        $current=[];
        try {
            // 舊版 <0.4 OpenAI 庫(kù) 使用該代碼 
            $response = OpenAI::client(OPENAI_KEY)->chat()->create([
                'model' => 'gpt-3.5-turbo',
                'messages' => $messages
            ]);
            // 新版 >=0.4 OpenAI 庫(kù)使用該代碼 
            /*
            $response=OpenAI::factory()
                ->withApiKey(OPENAI_KEY)
                ->withHttpClient(new \GuzzleHttp\Client([
                        "proxy"=>"你的代理 http://ip:端口"
              ]))->make()->chat()->create([
                'model' => 'gpt-3.5-turbo',
                'messages' => $messages
            ])
            */
            $current = ['role' => 'assistant', 'content' => nl2br($response->choices[0]->message->content)];
        } catch (\Exception $e) {
            $current = ['role' => 'assistant', 'content' => $e->getMessage()];
        }
        $messages[]=$current;
        $request->session()->put('messages', $messages);
            return json([
                "code"=>0,
                "msg"=>"ok",
                "data"=>$current['content']
            ]);
    }
    // 清除
    public function clear(Request $request)
    {
        return redirect("/");
    }
     public function index(Request $request)
    {
        $html=<<<'EOF'
        <!DOCTYPE html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>ChatGPT</title>
            <link  type="text/css" rel="stylesheet" />
        </head>
        <body class="antialiased mx-auto" style="max-width:1000px">
            <div class="flex flex-col space-y-4 py-4 overflow-auto" id="body"></div>
            <div class="text-center text-red-400" id="loading"></div>
            <div class="py-4 flex flex-col space-x-1 justify-center items-center">
                <textarea required onkeypress="submit(this)" placeholder="輸入后 ctrl+回車(chē) 或點(diǎn)擊右側(cè) 發(fā)送 按鈕" name="message" class="border   p-2 flex-1 w-full" id="message"></textarea>
                <div class="flex justify-center items-center mt-2">
                    <input type="button" onclick="submit(this,'click')" class="cursor-pointer bg-green-500 text-white p-2  mx-1" value="發(fā)送請(qǐng)求" />
                    <a class="bg-gray-200 text-white p-2  mx-1" href="./clear" title="出現(xiàn)錯(cuò)誤時(shí),可嘗試清除提問(wèn)記錄">清除記錄</a>
                </div>
            </div>
            <script>
            // 名稱(chēng)
            window.chatgptConfig = {
                "assistant": "ChatGPT",
                "user": "我"
            };
            window.onload = function() {
                fetch("./all", {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: ''
                    })
                    .then(response => response.json()) 
                    .then(json => {
                        if (json.data) {
                            json.data.forEach(it => {
                                append(it['content'], window.chatgptConfig[it.role]);
                            });
                        }
                    })
                    .catch(error => {
                        console.error(error);
                    });
            };
            function submit(el, type) {
                if (type === 'click' || (event.ctrlKey && event.keyCode === 10)) {
                    if (el.getAttribute('disabled')) {
                        alert("正在等待上次提問(wèn)的回復(fù),請(qǐng)稍等");
                        return;
                    }
                    var msg = document.getElementById('message').value.trim();
                    if (!msg) {
                        alert("必須輸入問(wèn)題");
                        return;
                    }
                    el.setAttribute('disabled', 'disabled');
                    append(msg, window.chatgptConfig['user']);
                    document.getElementById('loading').innerHTML = "努力思考中,稍等哦...";
                    document.documentElement.scrollTop+=50;
                    fetch("./query", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-Requested-With': 'XMLHttpRequest'
                            },
                            body: JSON.stringify({ message: msg})
                        })
                        .then(response => response.json())
                        .then(json => {
                            append(json.data, window.chatgptConfig["assistant"]);
                            document.getElementById('loading').innerHTML = '';
                            document.getElementById('message').value = '';
                            el.removeAttribute('disabled', 'disabled');
                        })
                        .catch(error => {
                            console.error(error);
                            el.removeAttribute('disabled', 'disabled');
                        });
                }
            }
            function append(msg, name) {
                var html = `
                    <div class="ml-4">
                        <div class="text-lg">
                            <a href="#" class="font-medium ${name==window.chatgptConfig['assistant']?'text-green-400':'text-gray-900'}">${name}:</a>
                        </div>
                        <div class="mt-1">
                            <p class="text-gray-800">
                                ${msg}
                            </p>
                        </div>
                    </div>
                `;
                const newDiv = document.createElement("div");
                newDiv.className=`overflow-auto flex p-4 ${name==window.chatgptConfig['assistant']?'bg-gray-100 border flex-reverse':""}`;
                newDiv.innerHTML = html;
                const bodyDiv = document.getElementById("body");
                bodyDiv.appendChild(newDiv);
            }
            </script>
        </body>
        </html>
EOF;
        return $html;
    }
}
4771 6 4
6個(gè)評(píng)論

Tinywan

感謝分享

  • 暫無(wú)評(píng)論
liudada

https 域名的怎么代理呢

截圖
這里沒(méi)有$client = new GuzzleClient();這行代碼怎么整

  • banro512 2023-03-20

    新版的 OpenAI 庫(kù)有變化,不要手動(dòng)去修改官方庫(kù)了
    直接將請(qǐng)求時(shí)的代碼

    $response = OpenAI::client(OPENAI_KEY)->chat()->create([
                    'model' => 'gpt-3.5-turbo',
                    'messages' => $messages
                ]);

    改為

            $response=OpenAI::factory()
                ->withApiKey(OPENAI_KEY)
                ->withHttpClient(new \GuzzleHttp\Client([
                        "proxy"=>"你的代理 http://ip:端口"
              ]))->make()->chat()->create([
                'model' => 'gpt-3.5-turbo',
                'messages' => $messages
            ])
  • 島嶼可以找到海 2023-03-20

    {
    "code": 500,
    "msg": "OpenAI\Factory::withHttpClient(): Argument #1 ($client) must be of type Psr\Http\Client\ClientInterface, GuzzleHttp\Client given, called in D:\Desktop\chatGptApi\app\controller\ChatgptController.php on line 30",
    "traces": "TypeError: OpenAI\Factory::withHttpClient(): Argument #1 ($client) must be of type Psr\Http\Client\ClientInterface, GuzzleHttp\Client given, called in D:\Desktop\chatGptApi\app\controller\ChatgptController.php on line 30 and defined in D:\Desktop\chatGptApi\vendor\openai-php\client\src\Factory.php:73\nStack trace:\n#0 D:\Desktop\chatGptApi\app\controller\ChatgptController.php(30): OpenAI\Factory->withHttpClient(Object(GuzzleHttp\Client))\n#1 D:\Desktop\chatGptApi\vendor\workerman\webman-framework\src\App.php(319): app\controller\ChatgptController->query(Object(support\Request))\n#2 D:\Desktop\chatGptApi\vendor\workerman\webman-framework\src\App.php(141): Webman\App::Webman\{closure}(Object(support\Request))\n#3 D:\Desktop\chatGptApi\vendor\workerman\workerman\Connection\TcpConnection.php(646): Webman\App->onMessage(Object(Workerman\Connection\TcpConnection), Object(support\Request))\n#4 D:\Desktop\chatGptApi\vendor\workerman\workerman\Events\Select.php(311): Workerman\Connection\TcpConnection->baseRead(Resource id #130)\n#5 D:\Desktop\chatGptApi\vendor\workerman\workerman\Worker.php(1479): Workerman\Events\Select->loop()\n#6 D:\Desktop\chatGptApi\vendor\workerman\workerman\Worker.php(1399): Workerman\Worker::forkWorkersForWindows()\n#7 D:\Desktop\chatGptApi\vendor\workerman\workerman\Worker.php(560): Workerman\Worker::forkWorkers()\n#8 D:\Desktop\chatGptApi\vendor\workerman\webman-framework\src\support\App.php(131): Workerman\Worker::runAll()\n#9 D:\Desktop\chatGptApi\start.php(4): support\App::run()\n#10 {main}"
    }

    替換完之后報(bào)這個(gè)錯(cuò)了

截圖

  • banro512 2023-03-20

    <?php
    use OpenAI\Client;

    $response=OpenAI::factory()
                    ->withApiKey('sk-********************')
                    ->withHttpClient(new \GuzzleHttp\Client([
                            "proxy"=>"http://127.0.0.1:8581"
                  ]))->make()->chat()->create([
                    'model' => 'gpt-3.5-turbo',
                    'messages' => [['role' => 'user', 'content' => '寫(xiě)一段python代碼,輸出hello world']]
                ]);
    print_r($response);     
    

    實(shí)測(cè)無(wú)問(wèn)題,有可能你的 guzzlehttp庫(kù)太久了吧。更新下composer require guzzlehttp/guzzle

  • 島嶼可以找到海 2023-03-21

    升級(jí)后可以了,感謝分享

cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://api.openai.com/v1/chat/completions
這個(gè)怎么調(diào)

  • 暫無(wú)評(píng)論
lang

請(qǐng)問(wèn)這個(gè)代理和端口怎么配置?

  • 暫無(wú)評(píng)論
年代過(guò)于久遠(yuǎn),無(wú)法發(fā)表評(píng)論

banro512

1690
積分
0
獲贊數(shù)
0
粉絲數(shù)
2021-12-16 加入
??