如何使用OpenAI API PHP sdk保持对话

j7dteeu8  于 2022-12-17  发布在  PHP
关注(0)|答案(1)|浏览(2032)

我尝试使用OpenAI PHP SDK的completion()方法来保持对话的进行。

  • 提示1:“你好吗?”
  • 提示#2:“我之前问你什么?”

但是人工智能似乎忘记了我之前问的问题,它对第二个提示的回答是随机的。
我用的代码为2调用是这些:

$call1 = $open_ai->completion([
            'model' => 'text-davinci-003', 
            'prompt' => 'How Are You?',

        ]);

        $call2 = $open_ai->completion([
            'model' => 'text-davinci-003', 
            'prompt' => 'What i asked you before?',
        ]);

我错过了什么?我如何才能在这两个调用之间保持会话活动,以便使AI记住我之前问过的问题?

sg2wtvxw

sg2wtvxw1#

第二个答案,因为the first one没有回答OP的问题。
基于this OpenAI Playground Example,只能通过向API发送两个命令来“询问”“会话”。
不要认为有一种方法可以在检索到回复后继续对话。
考虑这个例子,我们发送以下文本:

The following is a conversation with an AI assistant.

Human: Hello
Human: What is 3 * 3?
AI:
Human: What did I just asked?
AI:

我得到的回答是:

You asked me what 3 * 3 is. The answer is 9.

用于此操作的代码:

<?php

require __DIR__ . '/vendor/autoload.php';

use Orhanerday\OpenAi\OpenAi;

$open_ai_key = getenv('OPENAI_API_KEY');
$open_ai = new OpenAi($open_ai_key);

function ask($ai, $question, $model = 'text-davinci-003') {
    $res = $ai->completion([
        'model' => $model,
        'prompt' => $question,
        'temperature' => 0.9,
        'max_tokens' => 150,
        'frequency_penalty' => 0,
        'presence_penalty' => 0.6,
        'stop' => ["\nHuman:", "\nAI:"]
    ]);
    try {
        $json = @json_decode($res);
        foreach ($json->choices as $choice) {
            echo $choice->text . PHP_EOL;
        }
    } catch (Exception $e) {
        var_dump($e);
        return NULL;
    }
}

$text = <<<EOL
The following is a conversation with an AI assistant.

Human: Hello
Human: What is 3 * 3?
AI:
Human: What did I just asked?
AI:
EOL;

$res = ask($open_ai, $text);

请注意从文档中引用的**stop**数组:
最多4个序列,API将停止生成更多的标记。返回的文本将不包含停止序列。
这似乎让人工智能知道在哪里“读”和在哪里“写”
如果您从请求中删除该参数,则返回时不包含答案:

You asked what 3 times 3 is.

相关问题