用php语言写一个chatgpt3.5模型的例子

当然可以!使用PHP语言调用OpenAI API与ChatGPT-3.5模型进行交互。首先,确保你已经安装了PHP 7.2或更新版本,并具备可用的OpenAI API密钥。

下面是一个基本的PHP示例,展示了如何使用OpenAI API与ChatGPT-3.5模型进行对话:

```php
<?php

// 函数用于向OpenAI API发送请求
function openaiChat($messages) {
    $apiKey = 'YOUR_OPENAI_API_KEY';
    $url = 'https://api.openai.com/v1/engines/davinci-codex/completions';

    $headers = array(
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey
    );

    $data = array(
        'messages' => $messages
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

// 设置用户和AI的初始对话
$chat = array(
    array('role' => 'system', 'content' => 'You are a helpful assistant.'),
    array('role' => 'user', 'content' => 'Who won the world series in 2020?'),
    array('role' => 'assistant', 'content' => '')
);

// 与AI进行对话
while (true) {
    // 调用OpenAI API发送请求
    $response = openaiChat($chat);

    // 处理API响应
    $json = json_decode($response, true);
    $message = end($json['choices']);
    $chat[] = array('role' => 'user', 'content' => ''); // 准备用户输入的占位符

    if ($message['role'] == 'assistant') {
        // 显示AI的回复
        echo 'AI: ' . $message['message']['content'] . "\n";

        // 获取用户输入
        $userInput = trim(fgets(STDIN));

        // 更新对话
        $chat[count($chat) - 1]['content'] = $userInput;
    } else {
        // AI已经完成对话,退出循环
        break;
    }
}
```

以上是一个基本的例子,你可以根据自己的需求进行修改和扩展。记得将`YOUR_OPENAI_API_KEY`替换为你自己的OpenAI API密钥。

这段代码将实现一个简单的对话循环,直到AI完成对话。在每次循环中,它会向OpenAI API发送一个请求,获得AI的回复,然后等待用户输入下一条对话。AI的回复由`$message['message']['content']`提取。

请注意,此示例中的用户输入在命令行中使用`fgets(STDIN)`获取。如果你将代码用于Web应用程序等其他环境,你可能需要使用不同的方式来获取用户输入。

希望这个例子能对你有所帮助!如果需要进一步指导,请随时提问。

猜你喜欢

转载自blog.csdn.net/qq_26429153/article/details/132230611
今日推荐