mathsgod/openai-chat

OpenAI Chat 完成包装器。支持函数调用和变量赋值。

2.1.1 2024-06-26 10:09 UTC

This package is auto-updated.

Last update: 2024-09-26 10:47:57 UTC


README

安装

composer require mathsgod/openai-chat

使用

要使用 OpenAI chat,您需要创建一个新的 System 类实例,并将 OpenAI API 密钥作为第一个参数传递。

use OpenAI\Chat\System;

$system = new System($_ENV['OPENAI_API_KEY']);

echo $system->ask("Hello");

添加工具

use OpenAI\Chat\Attributes\Tool;
use OpenAI\Chat\Attributes\Parameter;

#[Tool(description: 'Get the release date of iphone')]
function getIPhoneReleaseDate(#[Parameter("model of the phone")] string $model)
{
    return ["date" => "2022-09-14", "model" => $model];
}

$system->addTool(Closure::fromCallable("getIPhoneReleaseDate"));

echo $system->ask("When will iPhone 14 be released?");

从类方法添加工具

class Controller
{
    public $price = "$799";

    #[Tool(description: 'Get the price of iphone')]
    public function getIPhonePrice(#[Parameter("model of the phone")] string $model)
    {
        return ["price" => $this->price, "model" => $model];
    }
}

$system->addTool(Closure::fromCallable([new Controller(), "getIPhonePrice"]));

echo $system->ask("What is the price and release date of iphone14?");

获取使用记录

运行以上代码后,您可以获取使用记录

print_r($system->getUsages());

流式传输

$stream = $system->askAsStream("What is the price and release date of iphone14?");

$stream->on('data', function ($data) {
    echo $data;
});