定制 ruscoe/openai-php 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

ruscoe/openai-php

Composer 安装命令:

composer require ruscoe/openai-php

包简介

PHP library for the OpenAI API

README 文档

README

openai_php_banner

PHP library for the OpenAI API

An unofficial library for OpenAI's API.

release

Used by

Requirements

Quick set up

git clone git@github.com:ruscoe/openai-php.git

cd openai-php

composer install

Usage examples

The following examples assume you store your API key in an environment variable. To do this on a Linux or MacOS system, run:

export OPENAI_API_KEY=sk-XA0yN...

Be sure to substitute your own API key after OPENAI_API_KEY=.

Completions

This example asks the gpt-4o model to describe a keyboard. It instructs the OpenAI API to use more than the default number of tokens so a reasonable length description can be returned.

<?php

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

// @see https://platform.openai.com/docs/api-reference/authentication
$api_key = getenv('OPENAI_API_KEY');

$api = new OpenAI\OpenAICompletions($api_key);

$parameters = [
    'max_completion_tokens' => 128,
];

$messages = [
    (object) ['role' => 'user', 'content' => 'Describe a keyboard']
];

$response = $api->create('gpt-4o', $messages, 1, $parameters);

var_dump($response);

The response:

object(stdClass)#35 (8) {
  ["id"]=>
  string(38) "chatcmpl-BLXYoMfybsQQjP1xlKjUtEL6chvHE"
  ["object"]=>
  string(15) "chat.completion"
  ["created"]=>
  int(1744473594)
  ["model"]=>
  string(17) "gpt-4o-2024-08-06"
  ["choices"]=>
  array(1) {
    [0]=>
    object(stdClass)#33 (4) {
      ["index"]=>
      int(0)
      ["message"]=>
      object(stdClass)#19 (4) {
        ["role"]=>
        string(9) "assistant"
        ["content"]=>
        string(604) "A keyboard is an input device used primarily to input text and commands into a computer or other electronic devices. Here are some key features and components of a typical keyboard:

1. **Keys**: A standard keyboard contains a variety of keys, each with a specific function. These include:
   - **Alphanumeric keys**: These are similar to those on a typewriter and include letters (A-Z), numbers (0-9), and punctuation symbols.
   - **Function keys**: Usually labeled F1 through F12, these keys are located at the top of the keyboard and offer shortcuts for various system and application functions.
   -"
        ["refusal"]=>
        NULL
        ["annotations"]=>
        array(0) {
        }
      }
      ["logprobs"]=>
      NULL
      ["finish_reason"]=>
      string(6) "length"
    }
  }
  ["usage"]=>
  object(stdClass)#29 (5) {
    ["prompt_tokens"]=>
    int(10)
    ["completion_tokens"]=>
    int(128)
    ["total_tokens"]=>
    int(138)
    ["prompt_tokens_details"]=>
    object(stdClass)#22 (2) {
      ["cached_tokens"]=>
      int(0)
      ["audio_tokens"]=>
      int(0)
    }
    ["completion_tokens_details"]=>
    object(stdClass)#20 (4) {
      ["reasoning_tokens"]=>
      int(0)
      ["audio_tokens"]=>
      int(0)
      ["accepted_prediction_tokens"]=>
      int(0)
      ["rejected_prediction_tokens"]=>
      int(0)
    }
  }
  ["service_tier"]=>
  string(7) "default"
  ["system_fingerprint"]=>
  string(13) "fp_b7faba9ef5"

Chat

This example sends a simple chat message.

<?php

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

// @see https://platform.openai.com/docs/api-reference/authentication
$api_key = getenv('OPENAI_API_KEY');

$api = new OpenAI\OpenAIChat($api_key);

$messages = [
    (object) ['role' => 'user', 'content' => 'Hello, friend!'],
];

$response = $api->create('gpt-4o', $messages);

var_dump($response);

The response:

object(stdClass)#35 (8) {
  ["id"]=>
  string(38) "chatcmpl-BLXdCiHRU78QMKpj9q7D36Kb6UIVg"
  ["object"]=>
  string(15) "chat.completion"
  ["created"]=>
  int(1744473866)
  ["model"]=>
  string(17) "gpt-4o-2024-08-06"
  ["choices"]=>
  array(1) {
    [0]=>
    object(stdClass)#33 (4) {
      ["index"]=>
      int(0)
      ["message"]=>
      object(stdClass)#19 (4) {
        ["role"]=>
        string(9) "assistant"
        ["content"]=>
        string(34) "Hello! How can I assist you today?"
        ["refusal"]=>
        NULL
        ["annotations"]=>
        array(0) {
        }
      }
      ["logprobs"]=>
      NULL
      ["finish_reason"]=>
      string(4) "stop"
    }
  }
  ["usage"]=>
  object(stdClass)#29 (5) {
    ["prompt_tokens"]=>
    int(11)
    ["completion_tokens"]=>
    int(10)
    ["total_tokens"]=>
    int(21)
    ["prompt_tokens_details"]=>
    object(stdClass)#22 (2) {
      ["cached_tokens"]=>
      int(0)
      ["audio_tokens"]=>
      int(0)
    }
    ["completion_tokens_details"]=>
    object(stdClass)#20 (4) {
      ["reasoning_tokens"]=>
      int(0)
      ["audio_tokens"]=>
      int(0)
      ["accepted_prediction_tokens"]=>
      int(0)
      ["rejected_prediction_tokens"]=>
      int(0)
    }
  }
  ["service_tier"]=>
  string(7) "default"
  ["system_fingerprint"]=>
  string(13) "fp_b7faba9ef5"

Images

Create image

This example asks for two images of a jungle waterfall.

<?php

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

// @see https://platform.openai.com/docs/api-reference/authentication
$api_key = getenv('OPENAI_API_KEY');

$api = new OpenAI\OpenAIImages($api_key);

$response = $api->createAsURL('A jungle waterfall', 2, '256x256');

var_dump($response);

The response

img-idDF5Pwt0q3X35QNJ65zJl0s img-Idq18QuOHuNE5us729mOKa2P

Create image variation

<?php

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

// @see https://platform.openai.com/docs/api-reference/authentication
$api_key = getenv('OPENAI_API_KEY');

$api = new OpenAI\OpenAIImages($api_key);

$response = $api->createVariationAsURL('variation.png', 1, '256x256');

var_dump($response);

The source and response

variation img-ARP7fJQMVNwHsz1fVkKnCudb

Create image edit

<?php

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

// @see https://platform.openai.com/docs/api-reference/authentication
$api_key = getenv('OPENAI_API_KEY');

$api = new OpenAI\OpenAIImages($api_key);

$response = $api->createEditAsURL('edit.png', 'a duck driving a car', 'edit_mask.png', 1, '256x256');

var_dump($response);

The source and response

edit edit_mask edit1

Fine-tuning a model

First, take a look at the official documentation on fine-tuning.

Create and upload your training file. Example:

training.jsonl

{"messages": [{"role": "system", "content": "A chatbot that knows the difference between animals and rocks."}, {"role": "user", "content": "What is a dog?"}, {"role": "assistant", "content": "A dog is an animal."}]}
{"messages": [{"role": "system", "content": "A chatbot that knows the difference between animals and rocks."}, {"role": "user", "content": "What is a cat?"}, {"role": "assistant", "content": "A cat is an animal."}]}
{"messages": [{"role": "system", "content": "A chatbot that knows the difference between animals and rocks."}, {"role": "user", "content": "What is a bird?"}, {"role": "assistant", "content": "A bird is an animal."}]}
{"messages": [{"role": "system", "content": "A chatbot that knows the difference between animals and rocks."}, {"role": "user", "content": "What is a dolphin?"}, {"role": "assistant", "content": "A dolphin is an animal."}]}
{"messages": [{"role": "system", "content": "A chatbot that knows the difference between animals and rocks."}, {"role": "user", "content": "What is a lion?"}, {"role": "assistant", "content": "A lion is an animal."}]}
{"messages": [{"role": "system", "content": "A chatbot that knows the difference between animals and rocks."}, {"role": "user", "content": "What is limestone?"}, {"role": "assistant", "content": "Limestone is a rock."}]}
{"messages": [{"role": "system", "content": "A chatbot that knows the difference between animals and rocks."}, {"role": "user", "content": "What is marble?"}, {"role": "assistant", "content": "Marble is a rock."}]}
{"messages": [{"role": "system", "content": "A chatbot that knows the difference between animals and rocks."}, {"role": "user", "content": "What is granite?"}, {"role": "assistant", "content": "Granite is a rock."}]}
{"messages": [{"role": "system", "content": "A chatbot that knows the difference between animals and rocks."}, {"role": "user", "content": "What is shale?"}, {"role": "assistant", "content": "Shale is a rock."}]}
{"messages": [{"role": "system", "content": "A chatbot that knows the difference between animals and rocks."}, {"role": "user", "content": "What is basalt?"}, {"role": "assistant", "content": "Basalt is a rock."}]}
<?php

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

// @see https://platform.openai.com/docs/api-reference/authentication
$api_key = getenv('OPENAI_API_KEY');

$api = new OpenAI\OpenAIFiles($api_key);

$file = $api->uploadFile('training.jsonl');

List your files to get the file ID:

$api = new OpenAI\OpenAIFiles($api_key);

$files = $api->getFiles();

var_dump($files);

Create a new training job using the file ID you've obtained:

$api = new OpenAI\OpenAIFineTunes($api_key);

$api->create('gpt-4o-mini-2024-07-18', 'file-mQy...');

Fine-tuning can take a while. Check the Fine-tuning UI for updates.

List models to get the name of your new fine-tuned model:

$api = new OpenAI\OpenAIModels($api_key);

$models = $api->getModels();

var_dump($models);

The model name will look something like this: ft:gpt-4o-mini-2024-07-18:personal::ABCABC

Create a new completion using your fine-tuned model.

$api = new OpenAI\OpenAICompletions($api_key);

$messages = [
    (object) ['role' => 'user', 'content' => 'What is a dog?'],
];

$response = $api->create('ft:gpt-4o-mini-2024-07-18:personal::ABCABC', $messages);

var_dump($response);

The response should be "A dog is an animal."

$api = new OpenAI\OpenAICompletions($api_key);

$messages = [
    (object) ['role' => 'user', 'content' => 'What is marble?'],
];

$response = $api->create('ft:gpt-4o-mini-2024-07-18:personal::ABCABC', $messages);

var_dump($response);

The response should be "Marble is a rock."

Available functions

Models

Class Function Description
OpenAIModels getModels Gets available OpenAI models.
OpenAIModels getModel Gets a specific OpenAI model.

Completions

Class Function Description
OpenAICompletions create Creates one or more completions from a given input.

Chat

Class Function Description
OpenAIChat create Creates one or more completions from a chat conversation.

Edits

Class Function Description
OpenAIEdits create Performs an edit on a given input.

Images

Class Function Description
OpenAIImages createAsURL Generates a number of images and returns URLs.
OpenAIImages createAsBase64 Generates a number of images and returns Base64 encoded image(s).
OpenAIImages createVariationAsURL Generates a number of image variations and returns URL(s).
OpenAIImages createVariationAsBase64 Generates a number of image variations and returns Base64 encoded image(s).
OpenAIImages createVariation Generates a number of image variations from a given image.
OpenAIImages createEditAsURL Generates a number of image edits and returns URL(s).
OpenAIImages createEditAsBase64 Generates a number of image edits and returns Base64 encoded image(s).
OpenAIImages createEdit Generates a number of image edits from a given image.

Embeddings

Class Function Description
OpenAIEmbeddings create Creates an embedding vector from given input.

Audio

Class Function Description
OpenAIAudio transcribe Transcribes text from an audio file.

Files

Class Function Description
OpenAIFiles getFiles Gets files owned by the user's organization.
OpenAIFiles uploadFile Uploads a file.
OpenAIFiles deleteFile Deletes a file.
OpenAIFiles getFile Gets information about a file.
OpenAIFiles getFileContent Gets the content of a file.

Fine-Tunes

Class Function Description
OpenAIFineTunes create Creates a fine-tune job.
OpenAIFineTunes getFineTunes Gets existing fine-tunes.
OpenAIFineTunes cancelFineTune Cancels a fine-tune job.
OpenAIFineTunes getFineTuneEvents Gets status updates of a fine-tune job.
OpenAIFineTunes deleteModel Deletes a fine-tuned model.

Moderations

Class Function Description
OpenAIModerations create Requests a moderation result from OpenAI.

License

MIT

ruscoe/openai-php 适用场景与选型建议

ruscoe/openai-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 30 次下载、GitHub Stars 达 3, 最近一次更新时间为 2023 年 05 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 ruscoe/openai-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 ruscoe/openai-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 ruscoe/openai-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 30
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 15
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-05-06