OpenAI API 客户端是一个面向组件、可扩展的客户端库,用于 OpenAI API。它旨在比传统的 PHP 库更快且内存效率更高。

1.0.2 2023-05-26 17:34 UTC

README

这个库是 OpenAI API 的一个面向组件、可扩展的客户端库。它旨在比传统的 PHP 库更快且内存效率更高。

安装

您可以通过 composer 安装此包

// PHP 8.0, 8.1, 8.2

composer require mounirrquiba/openai

目录

快速入门

密钥配置

您可以将您的 API 密钥和组织密钥存储到您的环境变量中

Powershell

$Env:OPENAI_API_KEY = "sk-7nUNKsoMg...dxQYa5xN0BlDu"
$Env:OPENAI_ORGANIZATION_KEY = "org-bYCY6S...Po6sKXi"

命令提示符

set OPENAI_API_KEY=sk-7nUNKsoMg...dxQYa5xN0BlDu
set OPENAI_ORGANIZATION_KEY=org-bYCY6S...Po6sKXi

Linux 或 macOS

# create ~/.profile if not exists
echo 'export OPENAI_API_KEY=sk-7nUNKsoMg...dxQYa5xN0BlDu' >> ~/.profile
echo 'export OPENAI_ORGANIZATION_KEY=org-bYCY6S...Po6sKXi' >> ~/.profile
source ~/.profile

或者您可以在代码中设置它,您只需要做一次。如果您已经将变量放入了您的环境变量中,这一步不是必需的

use MounirRquiba\OpenAi\OpenAi;

$apiKey = 'sk-7nUNKsoMg...dxQYa5xN0BlDu';
$organizationKey = 'org-bYCY6S...Po6sKXi';

// For users without organization
OpenAi::init($apiKey);

// For users with organization
OpenAi::init($apiKey, $organizationKey);

自定义 API URL 配置

如果您不使用 OpenAI 端点,您可以更改它

// Set your custom api url
OpenAi::updateBaseUri('https://myurl.com');

// Get value of api url
OpenAi::getBaseUri();

代理配置

// Set proxy
OpenAi::setProxy([
    'http'  => 'tcp://:8125',
    'https' => 'tcp://:9124'
]);

// Remove proxy configuation
OpenAi::removeProxy();

头部配置

// Add your custom headers
OpenAi::addHeaders([ 'myCustomKey' => 'myCustomValue']);

// Get value of custom headers
OpenAi::getHeaders();

// Remove specific custom header
OpenAi::removeHeader('myCustomKey');

返回顶部

服务

模型

列出当前可用的模型,并提供了每个模型的基本信息,例如所有者和可用性。

请求(模型)

use MounirRquiba\OpenAi\Services\Models;

$models = (new Models())
    ->create();

var_dump($models->getResponse());

响应(模型)

array(2) {
  ["object"]=>
  string(4) "list"
  ["data"]=>
  array(69) {
    [0]=>
    array(7) {
      ["id"]=>
      string(9) "whisper-1"
      ["object"]=>
      string(5) "model"
      ["created"]=>
      int(1677532384)
      ["owned_by"]=>
      string(15) "openai-internal"
      ["permission"]=>
      array(1) {
        [0]=>
        array(12) {
          ["id"]=>
          string(34) "modelperm-KlsZlfft3Gma8pI6A8rTnyjs"
          ["object"]=>
          string(16) "model_permission"
          ["created"]=>
          int(1683912666)
          ["allow_create_engine"]=>
          bool(false)
          ["allow_sampling"]=>
          bool(true)
          ["allow_logprobs"]=>
          bool(true)
          ["allow_search_indices"]=>
          bool(false)
          ["allow_view"]=>
          bool(true)
          ["allow_fine_tuning"]=>
          bool(false)
          ["organization"]=>
          string(1) "*"
          ["group"]=>
          NULL
          ["is_blocking"]=>
          bool(false)
        }
      }
      ["root"]=>
      string(9) "whisper-1"
      ["parent"]=>
      NULL
    }
    ...
  }
}

返回顶部

模型

检索一个模型实例,提供有关模型的基本信息,例如所有者和权限。

请求(模型)

use MounirRquiba\OpenAi\Services\Model;

$model = (new Model())
   ->setModel('text-davinci-003')
   ->create();

// or
$model = (new Model('text-davinci-003')
   ->create();

var_dump($model->getResponse());

响应(模型)

array(7) {
  ["id"]=>
  string(16) "text-davinci-003"
  ["object"]=>
  string(5) "model"
  ["created"]=>
  int(1669599635)
  ["owned_by"]=>
  string(15) "openai-internal"
  ["permission"]=>
  array(1) {
    [0]=>
    array(12) {
      ["id"]=>
      string(34) "modelperm-07PTNFc1zx2v6uxZTQm1reTm"
      ["object"]=>
      string(16) "model_permission"
      ["created"]=>
      int(1684343723)
      ["allow_create_engine"]=>
      bool(false)
      ["allow_sampling"]=>
      bool(true)
      ["allow_logprobs"]=>
      bool(true)
      ["allow_search_indices"]=>
      bool(false)
      ["allow_view"]=>
      bool(true)
      ["allow_fine_tuning"]=>
      bool(false)
      ["organization"]=>
      string(1) "*"
      ["group"]=>
      NULL
      ["is_blocking"]=>
      bool(false)
    }
  }
  ["root"]=>
  string(16) "text-davinci-003"
  ["parent"]=>
  NULL
}

返回顶部

完成

给定一个提示,该模型将返回一个或多个预测的完成内容,并且还可以返回每个位置替代令牌的概率。

创建完成

为提供的提示和参数创建一个完成内容。

请求(创建完成)

use MounirRquiba\OpenAi\Services\Completions;

$completions = (new Completions())
    ->create([
        'model' => 'text-davinci-003',
        'prompt' => 'OpenAi is ',
    ]);

var_dump($completions->getResponse());

响应(创建完成)

array(6) {
  ["id"]=>
  string(34) "cmpl-7HEtOf4c7Qfq9XTszOgSdT0lDsnTA"
  ["object"]=>
  string(15) "text_completion"
  ["created"]=>
  int(1684343178)
  ["model"]=>
  string(16) "text-davinci-003"
  ["choices"]=>
  array(1) {
    [0]=>
    array(4) {
      ["text"]=>
      string(82) " an artificial intelligence (AI) company that provides a suite of services, tools,"
      ["index"]=>
      int(0)
      ["logprobs"]=>
      NULL
      ["finish_reason"]=>
      string(6) "length"
    }
  }
  ["usage"]=>
  array(3) {
    ["prompt_tokens"]=>
    int(5)
    ["completion_tokens"]=>
    int(16)
    ["total_tokens"]=>
    int(21)
  }
}

返回顶部

创建流完成

为提供的提示和参数使用流创建一个完成内容。

请求(创建流完成)

use MounirRquiba\OpenAi\Services\Completions;

$prompt = 'OpenAi is';
$completions = (new Completions())
    ->create([
        'model' => 'text-davinci-003',
        'prompt' => $prompt,
        'stream' => true
    ]);

echo $prompt;

foreach ($completions->getResponse() as $value) {
    if (isset($value['choices'][0]['text'])) {
        echo $value['choices'][0]['text'];
    }
}

echo PHP_EOL;

响应(创建流完成)

OpenAi is an Artificial Intelligence company founded in December, 2015 that is based out of San Francisco

返回顶部

聊天

给定一个描述对话的消息列表,该模型将返回一个响应。

创建聊天完成

为给定的聊天对话创建一个模型响应。

请求(创建聊天完成)

use MounirRquiba\OpenAi\Services\Completions;

$chat = (new Chat())
    ->create([
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            ['role' => 'user', 'content' => "Je ne comprends pas OpenAi tu peux m'aider ?"]
        ]
    ]);

var_dump($chat->getResponse());

响应(创建聊天完成)

array(6) {
  ["id"]=>
  string(38) "chatcmpl-7HEwwJrGnDKkq1vQv2JrOByCxxNLw"
  ["object"]=>
  string(15) "chat.completion"
  ["created"]=>
  int(1684343398)
  ["model"]=>
  string(18) "gpt-3.5-turbo-0301"
  ["usage"]=>
  array(3) {
    ["prompt_tokens"]=>
    int(21)
    ["completion_tokens"]=>
    int(136)
    ["total_tokens"]=>
    int(157)
  }
  ["choices"]=>
  array(1) {
    [0]=>
    array(3) {
      ["message"]=>
      array(2) {
        ["role"]=>
        string(9) "assistant"
        ["content"]=>
        string(564) "Bien sûr! OpenAI est une organisation de recherche spécialisée dans l'intelligence artificielle. Ils travaillent sur des projets de pointe en matière de traitement du langage naturel, d'apprentissage par renforcement, d'analyse de données et plus encore. Ils ont également conçu des outils de développement d'IA tels que TensorFlow et Gym. OpenAI est considéré comme l'un des principaux acteurs mondiaux de l'IA et collabore avec des partenaires industriels et universitaires pour faire avancer la recherche dans ce domaine. J'espère que cela vous aide!"
      }
      ["finish_reason"]=>
      string(4) "stop"
      ["index"]=>
      int(0)
    }
  }
}

返回顶部

创建流聊天完成

为给定的聊天对话使用流创建一个模型响应。

请求(创建流聊天完成)

use MounirRquiba\OpenAi\Services\Completions;

$chat = (new Chat())
    ->create([
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            [
                'role' => 'user',
                'content' => "Je ne comprends pas OpenAi tu peux m'aider ?"
            ]
        ],
        'stream' => true
    ]);

foreach ($chat->getResponse() as $value) {
    if (isset($value['choices'][0]['delta']['content'])) {
        echo $value['choices'][0]['delta']['content'];
    }
}

echo PHP_EOL;

响应(创建流聊天完成)

Bien sûr ! OpenAI est une entreprise de recherche en intelligence artificielle fondée en 2015 par plusieurs personnalités du monde technologique, notamment Elon Musk. Son objectif est de développer une IA avancée qui peut résoudre des problèmes complexes et améliorer de nombreux domaines, tels que la médecine, le transport, la finance et l'éducation. OpenAI est également connu pour développer des modèles de langage tels que GPT-3, qui est capable de produire des textes semblables à ceux écrits par des humains. En résumé, OpenAI est une entreprise qui travaille pour construire une intelligence artificielle avancée pour aider à résoudre des problèmes et améliorer notre monde.

返回顶部

编辑

为提供的输入、指令和参数创建一个新的编辑。

请求(编辑)

use MounirRquiba\OpenAi\Services\Edits;

$edits = (new Edits())
    ->create([
        'model' => "text-davinci-edit-001",
        'input' => "Coment va le marché français de l'or ?\n\nDans quels pays y a-t-il le plus d'or ?\n",
        'instruction' => "Corriger les fautes\nDonner la liste des 10 pays ou il y a le plus d'or dans l'ordre décroissant",
        'temperature' => 0.7,
        'top_p' => 1,
    ]);

var_dump($edits->getResponse());

响应(编辑)

array(4) {
  ["object"]=>
  string(4) "edit"
  ["created"]=>
  int(1684343572)
  ["choices"]=>
  array(1) {
    [0]=>
    array(2) {
      ["text"]=>
      string(243) "Comment va le marché français de l'or ?

Dans quels pays y a-t-il le plus d'or ?

La liste des dix pays où il y a le plus d'or dans l'ordre décroissant :
Etats-Unis, Allemagne, Italie, France, Chine, Russie, Suisse, Japon, Inde, Pays-Bas.
"
      ["index"]=>
      int(0)
    }
  }
  ["usage"]=>
  array(3) {
    ["prompt_tokens"]=>
    int(80)
    ["completion_tokens"]=>
    int(119)
    ["total_tokens"]=>
    int(199)
  }
}

返回顶部

图像

给定一个提示和/或一个输入图像,模型将生成一个新的图像。

图像生成

根据提示创建一个图像。

请求(图像生成)

use MounirRquiba\OpenAi\Services\ImagesGenerations;

$imagesGenerations = (new ImagesGenerations())
    ->create([
        'prompt' =>'un vélo dinosaur, qui roule sur la tour effel',
        'n' => 2
    ]);

var_dump($imagesGenerations->getResponse());

响应(图像生成)

array(2) {
  ["created"]=>
  int(1684458446)
  ["data"]=>
  array(2) {
    [0]=>
    array(1) {
      ["url"]=>
      string(472) "https://oaidalleapiprodscus.blob.core.windows.net/private/org-bYCY6SRU0TjFN5GBGPo6sKXi/user-WdcLONQGarCf7HGjXdwRUzg7/img-AhrLfzRIHfTLt2sEBEgOjNjQ.png?st=2023-05-19T00%3A07%3A26Z&se=2023-05-19T02%3A07%3A26Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-05-18T20%3A54%3A11Z&ske=2023-05-19T20%3A54%3A11Z&sks=b&skv=2021-08-06&sig=JuabiiK7cjQJxCdcv3A8jHaKCi6HAsHNBDJFCAaaKqQ%3D"
    }
    [1]=>
    array(1) {
      ["url"]=>
      string(472) "https://oaidalleapiprodscus.blob.core.windows.net/private/org-bYCY6SRU0TjFN5GBGPo6sKXi/user-WdcLONQGarCf7HGjXdwRUzg7/img-9XkQyXSada8cpZ1ptVTHybPc.png?st=2023-05-19T00%3A07%3A26Z&se=2023-05-19T02%3A07%3A26Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-05-18T20%3A54%3A11Z&ske=2023-05-19T20%3A54%3A11Z&sks=b&skv=2021-08-06&sig=QkD9Aa7dRdFLPwXU9Dl0MGC6iwbjCVUZ4fPN49X1mF8%3D"
    }
  }
}

返回顶部

图像编辑

根据原始图像和提示创建一个编辑或扩展的图像。

请求(图像编辑)

use MounirRquiba\OpenAi\Services\ImagesEdits;

$imagesEdits = (new ImagesEdits())
    ->create([
        'image' => __DIR__ . '/assets/image_edit_original.png',
        'mask' => __DIR__ . '/assets/image_edit_mask.png',
        'prompt' => 'A cute baby sea otter wearing a beret',
        'n' => 2
    ]);

var_dump($imagesEdits->getResponse());

响应(图像编辑)

array(2) {
  ["created"]=>
  int(1684458473)
  ["data"]=>
  array(2) {
    [0]=>
    array(1) {
      ["url"]=>
      string(472) "https://oaidalleapiprodscus.blob.core.windows.net/private/org-bYCY6SRU0TjFN5GBGPo6sKXi/user-WdcLONQGarCf7HGjXdwRUzg7/img-HDlBhDfbk3QIXEdpEWSgXVYa.png?st=2023-05-19T00%3A07%3A53Z&se=2023-05-19T02%3A07%3A53Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-05-18T20%3A52%3A38Z&ske=2023-05-19T20%3A52%3A38Z&sks=b&skv=2021-08-06&sig=aOAibUdcLhr3sjuu8L1I2vqkNBghaQOl6KvAD9BbpUY%3D"
    }
    [1]=>
    array(1) {
      ["url"]=>
      string(474) "https://oaidalleapiprodscus.blob.core.windows.net/private/org-bYCY6SRU0TjFN5GBGPo6sKXi/user-WdcLONQGarCf7HGjXdwRUzg7/img-2tWHWSaD11jizwLd8CsnynPm.png?st=2023-05-19T00%3A07%3A53Z&se=2023-05-19T02%3A07%3A53Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-05-18T20%3A52%3A38Z&ske=2023-05-19T20%3A52%3A38Z&sks=b&skv=2021-08-06&sig=CCI2VjThND9%2BJwW7MqJiBITR1PYVs7bk6QiAlDeKjvk%3D"
    }
  }
}

返回顶部

图像变体

创建给定图像的变体。

请求(图像变体)

use MounirRquiba\OpenAi\Services\ImagesVariations;

$imagesVariations = (new ImagesVariations())
    ->create([
        'image' => __DIR__ . '/assets/image_edit_original.png',
        'n' => 2
    ]);

var_dump($imagesVariations->getResponse());

响应(图像变体)

array(2) {
  ["created"]=>
  int(1684458458)
  ["data"]=>
  array(2) {
    [0]=>
    array(1) {
      ["url"]=>
      string(478) "https://oaidalleapiprodscus.blob.core.windows.net/private/org-bYCY6SRU0TjFN5GBGPo6sKXi/user-WdcLONQGarCf7HGjXdwRUzg7/img-f0xkAAbGa16cz39LnBAmxhan.png?st=2023-05-19T00%3A07%3A38Z&se=2023-05-19T02%3A07%3A38Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-05-18T20%3A55%3A27Z&ske=2023-05-19T20%3A55%3A27Z&sks=b&skv=2021-08-06&sig=SAeBm6Z/33%2B/P5fSW5WciH970tZif%2BOP6hxEZl9c%2BrM%3D"
    }
    [1]=>
    array(1) {
      ["url"]=>
      string(472) "https://oaidalleapiprodscus.blob.core.windows.net/private/org-bYCY6SRU0TjFN5GBGPo6sKXi/user-WdcLONQGarCf7HGjXdwRUzg7/img-yZi1zVNgq7jd52nzEfVIGrud.png?st=2023-05-19T00%3A07%3A38Z&se=2023-05-19T02%3A07%3A38Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-05-18T20%3A55%3A27Z&ske=2023-05-19T20%3A55%3A27Z&sks=b&skv=2021-08-06&sig=sAK0yu3GkiRfek2F/YH0wL0z3KpqRm8Hhj7eyWW3Si8%3D"
    }
  }
}

返回顶部

嵌入

获取一个给定输入的向量表示,可以轻松被机器学习模型和算法消费。 创建表示输入文本的嵌入向量。

请求(嵌入)

use MounirRquiba\OpenAi\Services\Embeddings;

$embeddings = (new Embeddings())
    ->create([
        'model' => 'text-embedding-ada-002',
        'input' => "Le paim etait bon et le boulanger..."
    ]);

var_dump($embeddings->getResponse());

响应(嵌入)

array(4) {
  ["object"]=>
  string(4) "list"
  ["data"]=>
  array(1) {
    [0]=>
    array(3) {
      ["object"]=>
      string(9) "embedding"
      ["index"]=>
      int(0)
      ["embedding"]=>
      array(1536) {
        [0]=>
        float(0.0046150074)
        ...
        [1535]=>
        float(0.010371089)
      }
    }
  }
  ["model"]=>
  string(25) "text-embedding-ada-002-v2"
  ["usage"]=>
  array(2) {
    ["prompt_tokens"]=>
    int(12)
    ["total_tokens"]=>
    int(12)
  }
}

返回顶部

音频

为提供的输入、指令和参数创建一个新的编辑。

音频转录

将音频转录成输入语言。

请求(音频转录)

use MounirRquiba\OpenAi\Services\AudioTranscriptions;

$audioTranscriptions = (new AudioTranscriptions())
    ->create([
        'file' => __DIR__ . '/assets/multilingual.mp3',
        'model' => 'whisper-1',
        'response_format' => 'json'
    ]);

var_dump($audioTranscriptions->getResponse());

响应(音频转录)

array(1) {
  ["text"]=>
  string(747) "Whisper est un système de reconnaissance automatique de la parole entraîné sur 680 000 heures de données multilingues et multitâches récoltées sur Internet. Nous établissons que l'utilisation de données d'un tel nombre et d'une telle diversité est la raison pour laquelle votre système est à même de comprendre de nombreux accents en dépit de bruit de fond, de comprendre un vocabulaire technique et de réussir la traduction depuis diverses langues en anglais. Nous distribuons en tant que logiciel libre le code source pour nos modèles et pour l'inférence afin que ceux-ci puissent servir comme un point de départ pour construire des applications utiles et pour aider à faire progresser la recherche en traitement de la parole."
}

返回顶部

音频翻译

将音频翻译成英语。

请求(音频翻译)

use MounirRquiba\OpenAi\Services\AudioTranslations;

$audioTranslations = (new AudioTranslations())
    ->create([
        'file' => __DIR__ . '/assets/multilingual.mp3',
        'model' => 'whisper-1',
        'response_format' => 'json'
    ]);

var_dump($audioTranslations->getResponse());

响应(音频转录)

array(1) {
  ["text"]=>
  string(637) "Whisper is an automatic recognition system of speech, trained on 680,000 hours of multilingual and multitask data, collected on the Internet. We establish that the use of such a large number of data is such a diversity, and the reason why our system is able to understand many accents, despite background noise, to understand technical vocabulary, and to succeed in translation from various languages into English. We distribute the source code for our models and for the inference as a free software, so that they can serve as a starting point for building useful applications, and to help to progress the research in speech processing."
}

返回顶部

文件

文件用于上传文档,可以用于具有微调等功能的特征。

列出文件

返回用户所属组织所属的文件列表。

请求(列出文件)

use MounirRquiba\OpenAi\Services\Files;

$files = (new Files())
    ->create();

var_dump($files->getResponse());

响应(列出文件)

array(2) {
  ["object"]=>
  string(4) "list"
  ["data"]=>
  array(1) {
    [0]=>
    array(8) {
      ["object"]=>
      string(4) "file"
      ["id"]=>
      string(29) "file-CaNvI5ua4WrAanl5kfDfE1gD"
      ["purpose"]=>
      string(9) "fine-tune"
      ["filename"]=>
      string(23) "FineTuningSample1.jsonl"
      ["bytes"]=>
      int(9099)
      ["created_at"]=>
      int(1684186918)
      ["status"]=>
      string(9) "processed"
      ["status_details"]=>
      NULL
    }
  }
}

返回顶部

上传文件

上传包含要用于各种端点/功能的文档的文件。目前,一个组织上传的所有文件的总大小可高达1 GB。如需增加存储限制,请联系我们。

请求(上传文件)

use MounirRquiba\OpenAi\Services\FileUpload;

$fileUpload = (new FileUpload())
    ->create([
        'file' => __DIR__ . '/assets/FineTuningSample1.jsonl',
        'purpose' => 'fine-tune',
    ]);

var_dump($fileUpload->getResponse());

响应(上传文件)

array(8) {
  ["object"]=>
  string(4) "file"
  ["id"]=>
  string(29) "file-UIsWSH2zoQ58stVPIFlapM4c"
  ["purpose"]=>
  string(9) "fine-tune"
  ["filename"]=>
  string(23) "FineTuningSample1.jsonl"
  ["bytes"]=>
  int(9099)
  ["created_at"]=>
  int(1684458834)
  ["status"]=>
  string(8) "uploaded"
  ["status_details"]=>
  NULL
}

删除文件

删除文件。

请求(删除文件)

use MounirRquiba\OpenAi\Services\FileDelete;

$fileDelete = (new FileDelete('file-UIsWSH2zoQ58stVPIFlapM4c'))
    ->create();

// or

$fileDelete = (new FileDelete())
    ->setFile('file-UIsWSH2zoQ58stVPIFlapM4c')
    ->create();

var_dump($fileDelete->getResponse());

响应(删除文件)

array(3) {
  ["object"]=>
  string(4) "file"
  ["id"]=>
  string(29) "file-UIsWSH2zoQ58stVPIFlapM4c"
  ["deleted"]=>
  bool(true)
}

返回顶部

检索文件

返回有关特定文件的信息。

请求(检索文件)

use MounirRquiba\OpenAi\Services\File;

$file = (new File('file-DILkImh8E8Gl3PEGY1kD95BA'))
    ->create();

// or

$file = (new FineTune())
    ->setFile('file-DILkImh8E8Gl3PEGY1kD95BA')
    ->create();

var_dump($file->getResponse());

响应(检索文件)

array(8) {
  ["object"]=>
  string(4) "file"
  ["id"]=>
  string(29) "file-DILkImh8E8Gl3PEGY1kD95BA"
  ["purpose"]=>
  string(9) "fine-tune"
  ["filename"]=>
  string(23) "FineTuningSample1.jsonl"
  ["bytes"]=>
  int(9099)
  ["created_at"]=>
  int(1684148376)
  ["status"]=>
  string(9) "processed"
  ["status_details"]=>
  NULL
}

返回顶部

检索文件内容

返回指定文件的正文内容

请求(检索文件内容)

use MounirRquiba\OpenAi\Services\FileContent;

$fileContent = (new FileContent('file-DILkImh8E8Gl3PEGY1kD95BA'))
    ->create();

// or

$fileContent = (new FineTune())
    ->setFile('file-DILkImh8E8Gl3PEGY1kD95BA')
    ->create();

var_dump($fileContent->getResponse());

响应(检索文件内容)

string(9099) "{"prompt":"Overjoyed with the new iPhone! ->", "completion":" positive"}
{"prompt":"@lakers disappoint for a third straight night https://#/38EFe43 ->", "completion":" negative"}
{"prompt":"Overjoyed with the new iPhone! ->", "completion":" positive"}
{"prompt":"@lakers disappoint for a third straight night https://#/38EFe43 ->", "completion":" negative"}
{"prompt":"Overjoyed with the new iPhone! ->", "completion":" positive"}
{"prompt":"@lakers disappoint for a third straight night https://#/38EFe43 ->", "completion":" negative"}
{"prompt":"Overjoyed with the new iPhone! ->", "completion":" positive"}
{"prompt":"@lakers disappoint for a third straight night https://#/38EFe43 ->", "completion":" negative"}"

返回顶部

微调

管理微调作业,以定制模型以符合您的特定训练数据。

创建微调

创建一个作业,从给定数据集中微调指定的模型。响应包括作业队列的详细信息,包括作业状态和一旦完成微调的模型名称。

请求(创建微调)

use MounirRquiba\OpenAi\Services\FineTuneCreate;

$fineTuneCreate = (new FineTuneCreate())
    ->create([
        'training_file' => 'file-rr52uDaNMcspoOZ4bAu3wbOS',
        'model' => 'curie'
    ]);

var_dump($fineTuneCreate->getResponse());

响应(创建微调)

array(13) {
  ["object"]=>
  string(9) "fine-tune"
  ["id"]=>
  string(27) "ft-I8JdQV6SbzTrhpkfCBiSXRYO"
  ["hyperparams"]=>
  array(4) {
    ["n_epochs"]=>
    int(4)
    ["batch_size"]=>
    NULL
    ["prompt_loss_weight"]=>
    float(0.01)
    ["learning_rate_multiplier"]=>
    NULL
  }
  ["organization_id"]=>
  string(28) "org-bYCY6SRU0TjFN5GBGPo6sKXi"
  ["model"]=>
  string(5) "curie"
  ["training_files"]=>
  array(1) {
    [0]=>
    array(8) {
      ["object"]=>
      string(4) "file"
      ["id"]=>
      string(29) "file-rr52uDaNMcspoOZ4bAu3wbOS"
      ["purpose"]=>
      string(9) "fine-tune"
      ["filename"]=>
      string(23) "FineTuningSample1.jsonl"
      ["bytes"]=>
      int(9099)
      ["created_at"]=>
      int(1684187069)
      ["status"]=>
      string(9) "processed"
      ["status_details"]=>
      NULL
    }
  }
  ["validation_files"]=>
  array(0) {
  }
  ["result_files"]=>
  array(0) {
  }
  ["created_at"]=>
  int(1684641945)
  ["updated_at"]=>
  int(1684641945)
  ["status"]=>
  string(7) "pending"
  ["fine_tuned_model"]=>
  NULL
  ["events"]=>
  array(1) {
    [0]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(46) "Created fine-tune: ft-I8JdQV6SbzTrhpkfCBiSXRYO"
      ["created_at"]=>
      int(1684641945)
    }
  }
}

返回顶部

列出微调

列出您组织的微调作业

请求(列出微调)

use MounirRquiba\OpenAi\Services\FineTunes;

$fineTunes = (new FineTunes())
    ->create();

var_dump($fineTunes->getResponse());

响应(列出微调)

array(2) {
  ["object"]=>
  string(4) "list"
  ["data"]=>
  array(1) {
    [0]=>
    array(12) {
      ["object"]=>
      string(9) "fine-tune"
      ["id"]=>
      string(27) "ft-kp36A6V0yCxixhdNOd1khEH1"
      ["hyperparams"]=>
      array(4) {
        ["n_epochs"]=>
        int(4)
        ["batch_size"]=>
        int(1)
        ["prompt_loss_weight"]=>
        float(0.01)
        ["learning_rate_multiplier"]=>
        float(0.1)
      }
      ["organization_id"]=>
      string(28) "org-bYCY6SRU0TjFN5GBGPo6sKXi"
      ["model"]=>
      string(5) "curie"
      ["training_files"]=>
      array(1) {
        [0]=>
        array(8) {
          ["object"]=>
          string(4) "file"
          ["id"]=>
          string(29) "file-DILkImh8E8Gl3PEGY1kD95BA"
          ["purpose"]=>
          string(9) "fine-tune"
          ["filename"]=>
          string(23) "FineTuningSample1.jsonl"
          ["bytes"]=>
          int(9099)
          ["created_at"]=>
          int(1684148376)
          ["status"]=>
          string(9) "processed"
          ["status_details"]=>
          NULL
        }
      }
      ["validation_files"]=>
      array(0) {
      }
      ["result_files"]=>
      array(0) {
      }
      ["created_at"]=>
      int(1684186072)
      ["updated_at"]=>
      int(1684186226)
      ["status"]=>
      string(9) "cancelled"
      ["fine_tuned_model"]=>
      NULL
    }
  }
}

返回顶部

检索微调

获取微调作业的信息。

请求(检索微调)

use MounirRquiba\OpenAi\Services\FineTune;

$fineTune = (new FineTune('ft-APj3KgkNKa8vjrt67WyFf1oU'))
    ->create();

// or

$fineTune = (new FineTune())
    ->setFineTune('ft-APj3KgkNKa8vjrt67WyFf1oU')
    ->create();

var_dump($fineTune->getResponse());

响应(检索微调)

array(13) {
  ["object"]=>
  string(9) "fine-tune"
  ["id"]=>
  string(27) "ft-APj3KgkNKa8vjrt67WyFf1oU"
  ["hyperparams"]=>
  array(4) {
    ["n_epochs"]=>
    int(4)
    ["batch_size"]=>
    int(1)
    ["prompt_loss_weight"]=>
    float(0.01)
    ["learning_rate_multiplier"]=>
    float(0.1)
  }
  ["organization_id"]=>
  string(28) "org-bYCY6SRU0TjFN5GBGPo6sKXi"
  ["model"]=>
  string(5) "curie"
  ["training_files"]=>
  array(1) {
    [0]=>
    array(8) {
      ["object"]=>
      string(4) "file"
      ["id"]=>
      string(29) "file-rr52uDaNMcspoOZ4bAu3wbOS"
      ["purpose"]=>
      string(9) "fine-tune"
      ["filename"]=>
      string(23) "FineTuningSample1.jsonl"
      ["bytes"]=>
      int(9099)
      ["created_at"]=>
      int(1684187069)
      ["status"]=>
      string(9) "processed"
      ["status_details"]=>
      NULL
    }
  }
  ["validation_files"]=>
  array(0) {
  }
  ["result_files"]=>
  array(1) {
    [0]=>
    array(8) {
      ["object"]=>
      string(4) "file"
      ["id"]=>
      string(29) "file-wLlZV8ebowFsXumRBkQ9LCQE"
      ["purpose"]=>
      string(17) "fine-tune-results"
      ["filename"]=>
      string(20) "compiled_results.csv"
      ["bytes"]=>
      int(17141)
      ["created_at"]=>
      int(1684192045)
      ["status"]=>
      string(9) "processed"
      ["status_details"]=>
      NULL
    }
  }
  ["created_at"]=>
  int(1684187099)
  ["updated_at"]=>
  int(1684192045)
  ["status"]=>
  string(9) "succeeded"
  ["fine_tuned_model"]=>
  string(37) "curie:ft-personal-2023-05-15-23-07-24"
  ["events"]=>
  array(13) {
    [0]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(46) "Created fine-tune: ft-APj3KgkNKa8vjrt67WyFf1oU"
      ["created_at"]=>
      int(1684187099)
    }
    [1]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(21) "Fine-tune costs $0.02"
      ["created_at"]=>
      int(1684191198)
    }
    [2]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(35) "Fine-tune enqueued. Queue number: 2"
      ["created_at"]=>
      int(1684191198)
    }
    [3]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(42) "Fine-tune is in the queue. Queue number: 1"
      ["created_at"]=>
      int(1684191679)
    }
    [4]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(42) "Fine-tune is in the queue. Queue number: 0"
      ["created_at"]=>
      int(1684191796)
    }
    [5]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(17) "Fine-tune started"
      ["created_at"]=>
      int(1684191892)
    }
    [6]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Completed epoch 1/4"
      ["created_at"]=>
      int(1684191970)
    }
    [7]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Completed epoch 2/4"
      ["created_at"]=>
      int(1684191987)
    }
    [8]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Completed epoch 3/4"
      ["created_at"]=>
      int(1684192005)
    }
    [9]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Completed epoch 4/4"
      ["created_at"]=>
      int(1684192022)
    }
    [10]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(53) "Uploaded model: curie:ft-personal-2023-05-15-23-07-24"
      ["created_at"]=>
      int(1684192044)
    }
    [11]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(51) "Uploaded result file: file-wLlZV8ebowFsXumRBkQ9LCQE"
      ["created_at"]=>
      int(1684192045)
    }
    [12]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Fine-tune succeeded"
      ["created_at"]=>
      int(1684192045)
    }
  }
}

返回顶部

取消微调

立即取消微调作业。

请求(取消微调)

use MounirRquiba\OpenAi\Services\FineTuneCancel;

$fineTuneCancel = (new FineTuneCancel('ft-kp36A6V0yCxixhdNOd1khEH1'))
    ->create();

// or

$fineTuneCancel = (new FineTuneCancel())
    ->setFineTune('ft-APj3KgkNKa8vjrt67WyFf1oU')
    ->create();

var_dump($fineTuneCancel->getResponse());

响应(取消微调)

array(13) {
  ["object"]=>
  string(9) "fine-tune"
  ["id"]=>
  string(27) "ft-SyOpGKgquTE2wYBEMI2X3pJl"
  ["hyperparams"]=>
  array(4) {
    ["n_epochs"]=>
    int(4)
    ["batch_size"]=>
    NULL
    ["prompt_loss_weight"]=>
    float(0.01)
    ["learning_rate_multiplier"]=>
    NULL
  }
  ["organization_id"]=>
  string(28) "org-bYCY6SRU0TjFN5GBGPo6sKXi"
  ["model"]=>
  string(5) "curie"
  ["training_files"]=>
  array(1) {
    [0]=>
    array(8) {
      ["object"]=>
      string(4) "file"
      ["id"]=>
      string(29) "file-rr52uDaNMcspoOZ4bAu3wbOS"
      ["purpose"]=>
      string(9) "fine-tune"
      ["filename"]=>
      string(23) "FineTuningSample1.jsonl"
      ["bytes"]=>
      int(9099)
      ["created_at"]=>
      int(1684187069)
      ["status"]=>
      string(9) "processed"
      ["status_details"]=>
      NULL
    }
  }
  ["validation_files"]=>
  array(0) {
  }
  ["result_files"]=>
  array(0) {
  }
  ["created_at"]=>
  int(1684642234)
  ["updated_at"]=>
  int(1684642248)
  ["status"]=>
  string(9) "cancelled"
  ["fine_tuned_model"]=>
  NULL
  ["events"]=>
  array(2) {
    [0]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(46) "Created fine-tune: ft-SyOpGKgquTE2wYBEMI2X3pJl"
      ["created_at"]=>
      int(1684642234)
    }
    [1]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Fine-tune cancelled"
      ["created_at"]=>
      int(1684642248)
    }
  }
}

返回顶部

列出微调事件

获取微调作业的详细状态更新。

请求(列出微调事件)

use MounirRquiba\OpenAi\Services\FineTuneEvents;

$fineTuneEvents = (new FineTuneEvents('ft-APj3KgkNKa8vjrt67WyFf1oU'))
    ->create();

// or

$fineTuneEvents = (new FineTuneEvents())
    ->setFineTune('ft-APj3KgkNKa8vjrt67WyFf1oU')
    ->create();

var_dump($fineTuneEvents->getResponse());

响应(列出微调事件)

array(2) {
  ["object"]=>
  string(4) "list"
  ["data"]=>
  array(11) {
    [0]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(46) "Created fine-tune: ft-5oS3cDvnkPJylOVcqUXUaMcl"
      ["created_at"]=>
      int(1684640314)
    }
    [1]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(21) "Fine-tune costs $0.02"
      ["created_at"]=>
      int(1684640417)
    }
    [2]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(35) "Fine-tune enqueued. Queue number: 0"
      ["created_at"]=>
      int(1684640418)
    }
    [3]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(17) "Fine-tune started"
      ["created_at"]=>
      int(1684641626)
    }
    [4]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Completed epoch 1/4"
      ["created_at"]=>
      int(1684641705)
    }
    [5]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Completed epoch 2/4"
      ["created_at"]=>
      int(1684641723)
    }
    [6]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Completed epoch 3/4"
      ["created_at"]=>
      int(1684641741)
    }
    [7]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Completed epoch 4/4"
      ["created_at"]=>
      int(1684641759)
    }
    [8]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(53) "Uploaded model: curie:ft-personal-2023-05-21-04-02-58"
      ["created_at"]=>
      int(1684641778)
    }
    [9]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(51) "Uploaded result file: file-NxV8qq6jYEOStE1aT3OGiF7D"
      ["created_at"]=>
      int(1684641779)
    }
    [10]=>
    array(4) {
      ["object"]=>
      string(15) "fine-tune-event"
      ["level"]=>
      string(4) "info"
      ["message"]=>
      string(19) "Fine-tune succeeded"
      ["created_at"]=>
      int(1684641779)
    }
  }
}

返回顶部

删除微调模型

删除微调模型。您必须拥有组织中的所有者角色。

请求(删除微调模型)

use MounirRquiba\OpenAi\Services\FineTuneDelete;

$fineTuneDelete = (new FineTuneDelete())
    ->setModel('curie:ft-personal-2023-05-15-22-35-28')
    ->create();

// or

$fineTuneDelete = (new FineTuneDelete('curie:ft-personal-2023-05-15-22-35-28'))
   ->create();

var_dump($fineTuneDelete->getResponse());

响应(删除微调模型)

array(3) {
  ["id"]=>
  string(37) "curie:ft-personal-2023-05-21-04-02-58"
  ["object"]=>
  string(5) "model"
  ["deleted"]=>
  bool(true)
}

返回顶部

审查

给定一个输入文本,输出模型是否将其分类为违反OpenAI的内容政策。 判断文本是否违反OpenAI的内容政策

请求(审查)

use MounirRquiba\OpenAi\Services\Moderations;

$moderations = (new Moderations())
    ->create([
        'input' => ['la vie est belle', "il va le tuer"]
    ]);

var_dump($moderations->getResponse());

响应(审查)

array(3) {
  ["id"]=>
  string(34) "modr-7HjGIr3itczNK6ypzfBtPgoJOi849"
  ["model"]=>
  string(19) "text-moderation-004"
  ["results"]=>
  array(2) {
    [0]=>
    array(3) {
      ["flagged"]=>
      bool(false)
      ["categories"]=>
      array(7) {
        ["sexual"]=>
        bool(false)
        ["hate"]=>
        bool(false)
        ["violence"]=>
        bool(false)
        ["self-harm"]=>
        bool(false)
        ["sexual/minors"]=>
        bool(false)
        ["hate/threatening"]=>
        bool(false)
        ["violence/graphic"]=>
        bool(false)
      }
      ["category_scores"]=>
      array(7) {
        ["sexual"]=>
        float(9.854588E-5)
        ["hate"]=>
        float(1.8268647E-5)
        ["violence"]=>
        float(8.085035E-7)
        ["self-harm"]=>
        float(2.9571123E-7)
        ["sexual/minors"]=>
        float(1.06537414E-7)
        ["hate/threatening"]=>
        float(2.2165905E-9)
        ["violence/graphic"]=>
        float(1.0610097E-8)
      }
    }
    [1]=>
    array(3) {
      ["flagged"]=>
      bool(true)
      ["categories"]=>
      array(7) {
        ["sexual"]=>
        bool(false)
        ["hate"]=>
        bool(false)
        ["violence"]=>
        bool(true)
        ["self-harm"]=>
        bool(false)
        ["sexual/minors"]=>
        bool(false)
        ["hate/threatening"]=>
        bool(false)
        ["violence/graphic"]=>
        bool(false)
      }
      ["category_scores"]=>
      array(7) {
        ["sexual"]=>
        float(0.0005990547)
        ["hate"]=>
        float(0.0016128556)
        ["violence"]=>
        float(0.79453164)
        ["self-harm"]=>
        float(4.4971974E-5)
        ["sexual/minors"]=>
        float(6.0204526E-5)
        ["hate/threatening"]=>
        float(2.81084E-5)
        ["violence/graphic"]=>
        float(2.5406101E-5)
      }
    }
  }
}

返回顶部

异常

提供的代码演示了用于处理异常的try-catch块。

try {
    $audioTranslations = (new AudioTranslations())
        ->create([
            'file' => __DIR__ . '/assets/multilingual.mp3',
            'model' => 'whisper-1',
            'response_format' => 'json'
        ]);
        var_dump($audioTranslations->getResponse());
}
catch(FileNotFoundException $e) {
    var_dump($e->getMessage());
}
catch(BadResponseException $e) {
    var_dump($e->getMessage());
}
catch(InvalidParameterException $e) {
    var_dump($e->getMessage());
}
catch(RequiredParameterException $e) {
    var_dump($e->getMessage());
}
catch(\Exception $e) {
    var_dump($e->getMessage());
}


if (isset($audioTranslations)) {
    var_dump($audioTranslations->getResponse());
}

异常列表

  • FileNotFoundException:用于处理与找不到或无法访问的文件相关的异常。
  • BadResponseException:用于处理与错误或意外的响应相关的异常。
  • InvalidParameterException:用于处理与传递无效参数相关的异常。
  • RequiredParameterException:用于处理与必需参数相关的异常。

返回顶部

测试

git clone git@github.com:mounirrquiba/openai-php-client.git

cd ./openai-php-client

composer install

composer composer run-script test

返回顶部

许可协议

MIT许可(MIT)

版权所有(c)Mounir R'Quiba | https://www.linkedin.com/in/mounir-r-quiba-14aa84ba/

在此特此授予任何获得本软件及其相关文档副本(“软件”)的人,免费使用该软件的权利,不受限制,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售软件副本的权利,并允许向软件提供的人这样做,但须遵守以下条件

上述版权声明和本许可声明应包含在软件的所有副本或实质性部分中。

软件按“原样”提供,不提供任何形式的保证,无论是明示的、暗示的,包括但不限于适销性、适用于特定目的和不侵犯版权。在任何情况下,作者或版权所有者不对任何索赔、损害或其他责任承担责任,无论是因为合同行为、侵权行为或其他行为,无论该索赔、损害或其他责任源于、由或与软件或软件的使用或其他处理方式有关。