openai-php/client

OpenAI PHP 是一个增强型的 PHP API 客户端,允许您与 Open AI API 交互

v0.10.1 2024-06-06 20:27 UTC

This package is auto-updated.

Last update: 2024-09-19 21:15:36 UTC


README

OpenAI PHP

GitHub Workflow Status (main) Total Downloads Latest Version License

OpenAI PHP 是一个由社区维护的 PHP API 客户端,允许您与 Open AI API 交互。如果您或您的业务依赖此包,支持那些投入时间和精力创建和维护此宝贵工具的开发者非常重要

目录

开始使用

需要 PHP 8.1+

首先,通过 Composer 包管理器安装 OpenAI

composer require openai-php/client

确保允许 php-http/discovery Composer 插件运行或手动安装客户端,如果您的项目尚未集成 PSR-18 客户端。

composer require guzzlehttp/guzzle

然后,与 OpenAI 的 API 交互

$yourApiKey = getenv('YOUR_API_KEY');
$client = OpenAI::client($yourApiKey);

$result = $client->chat()->create([
    'model' => 'gpt-4',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
    ],
]);

echo $result->choices[0]->message->content; // Hello! How can I assist you today?

如果需要,可以配置和创建一个单独的客户端。

$yourApiKey = getenv('YOUR_API_KEY');

$client = OpenAI::factory()
    ->withApiKey($yourApiKey)
    ->withOrganization('your-organization') // default: null
    ->withProject('Your Project') // default: null
    ->withBaseUri('openai.example.com/v1') // default: api.openai.com/v1
    ->withHttpClient($client = new \GuzzleHttp\Client([])) // default: HTTP client found using PSR-18 HTTP Client Discovery
    ->withHttpHeader('X-My-Header', 'foo')
    ->withQueryParam('my-param', 'bar')
    ->withStreamHandler(fn (RequestInterface $request): ResponseInterface => $client->send($request, [
        'stream' => true // Allows to provide a custom stream handler for the http client.
    ]))
    ->make();

用法

模型 资源

list

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

$response = $client->models()->list();

$response->object; // 'list'

foreach ($response->data as $result) {
    $result->id; // 'gpt-3.5-turbo-instruct'
    $result->object; // 'model'
    // ...
}

$response->toArray(); // ['object' => 'list', 'data' => [...]]

retrieve

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

$response = $client->models()->retrieve('gpt-3.5-turbo-instruct');

$response->id; // 'gpt-3.5-turbo-instruct'
$response->object; // 'model'
$response->created; // 1642018370
$response->ownedBy; // 'openai'

$response->toArray(); // ['id' => 'gpt-3.5-turbo-instruct', ...]

delete

删除一个微调模型。

$response = $client->models()->delete('curie:ft-acmeco-2021-03-03-21-44-20');

$response->id; // 'curie:ft-acmeco-2021-03-03-21-44-20'
$response->object; // 'model'
$response->deleted; // true

$response->toArray(); // ['id' => 'curie:ft-acmeco-2021-03-03-21-44-20', ...]

完成 资源

create

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

$response = $client->completions()->create([
    'model' => 'gpt-3.5-turbo-instruct',
    'prompt' => 'Say this is a test',
    'max_tokens' => 6,
    'temperature' => 0
]);

$response->id; // 'cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7'
$response->object; // 'text_completion'
$response->created; // 1589478378
$response->model; // 'gpt-3.5-turbo-instruct'

foreach ($response->choices as $result) {
    $result->text; // '\n\nThis is a test'
    $result->index; // 0
    $result->logprobs; // null
    $result->finishReason; // 'length' or null
}

$response->usage->promptTokens; // 5,
$response->usage->completionTokens; // 6,
$response->usage->totalTokens; // 11

$response->toArray(); // ['id' => 'cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7', ...]

create streamed

为提供的提示和参数创建一个流式完成。

$stream = $client->completions()->createStreamed([
        'model' => 'gpt-3.5-turbo-instruct',
        'prompt' => 'Hi',
        'max_tokens' => 10,
    ]);

foreach($stream as $response){
    $response->choices[0]->text;
}
// 1. iteration => 'I'
// 2. iteration => ' am'
// 3. iteration => ' very'
// 4. iteration => ' excited'
// ...

聊天 资源

create

为聊天消息创建一个完成。

$response = $client->chat()->create([
    'model' => 'gpt-3.5-turbo',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
    ],
]);

$response->id; // 'chatcmpl-6pMyfj1HF4QXnfvjtfzvufZSQq6Eq'
$response->object; // 'chat.completion'
$response->created; // 1677701073
$response->model; // 'gpt-3.5-turbo-0301'

foreach ($response->choices as $result) {
    $result->index; // 0
    $result->message->role; // 'assistant'
    $result->message->content; // '\n\nHello there! How can I assist you today?'
    $result->finishReason; // 'stop'
}

$response->usage->promptTokens; // 9,
$response->usage->completionTokens; // 12,
$response->usage->totalTokens; // 21

$response->toArray(); // ['id' => 'chatcmpl-6pMyfj1HF4QXnfvjtfzvufZSQq6Eq', ...]

为聊天消息创建一个带有工具调用的完成。

$response = $client->chat()->create([
    'model' => 'gpt-3.5-turbo-0613',
    'messages' => [
        ['role' => 'user', 'content' => 'What\'s the weather like in Boston?'],
    ],
    'tools' => [
        [
            'type' => 'function',
            'function' => [
                'name' => 'get_current_weather',
                'description' => 'Get the current weather in a given location',
                'parameters' => [
                    'type' => 'object',
                    'properties' => [
                        'location' => [
                            'type' => 'string',
                            'description' => 'The city and state, e.g. San Francisco, CA',
                        ],
                        'unit' => [
                            'type' => 'string',
                            'enum' => ['celsius', 'fahrenheit']
                        ],
                    ],
                    'required' => ['location'],
                ],
            ],
        ]
    ]
]);

$response->id; // 'chatcmpl-6pMyfj1HF4QXnfvjtfzvufZSQq6Eq'
$response->object; // 'chat.completion'
$response->created; // 1677701073
$response->model; // 'gpt-3.5-turbo-0613'

foreach ($response->choices as $result) {
    $result->index; // 0
    $result->message->role; // 'assistant'
    $result->message->content; // null
    $result->message->toolCalls[0]->id; // 'call_123'
    $result->message->toolCalls[0]->type; // 'function'
    $result->message->toolCalls[0]->function->name; // 'get_current_weather'
    $result->message->toolCalls[0]->function->arguments; // "{\n  \"location\": \"Boston, MA\"\n}"
    $result->finishReason; // 'tool_calls'
}

$response->usage->promptTokens; // 82,
$response->usage->completionTokens; // 18,
$response->usage->totalTokens; // 100

为聊天消息创建一个带有函数调用的完成。

$response = $client->chat()->create([
    'model' => 'gpt-3.5-turbo-0613',
    'messages' => [
        ['role' => 'user', 'content' => 'What\'s the weather like in Boston?'],
    ],
    'functions' => [
        [
            'name' => 'get_current_weather',
            'description' => 'Get the current weather in a given location',
            'parameters' => [
                'type' => 'object',
                'properties' => [
                    'location' => [
                        'type' => 'string',
                        'description' => 'The city and state, e.g. San Francisco, CA',
                    ],
                    'unit' => [
                        'type' => 'string',
                        'enum' => ['celsius', 'fahrenheit']
                    ],
                ],
                'required' => ['location'],
            ],
        ]
    ]
]);

$response->id; // 'chatcmpl-6pMyfj1HF4QXnfvjtfzvufZSQq6Eq'
$response->object; // 'chat.completion'
$response->created; // 1677701073
$response->model; // 'gpt-3.5-turbo-0613'

foreach ($response->choices as $result) {
    $result->index; // 0
    $result->message->role; // 'assistant'
    $result->message->content; // null
    $result->message->functionCall->name; // 'get_current_weather'
    $result->message->functionCall->arguments; // "{\n  \"location\": \"Boston, MA\"\n}"
    $result->finishReason; // 'function_call'
}

$response->usage->promptTokens; // 82,
$response->usage->completionTokens; // 18,
$response->usage->totalTokens; // 100

create streamed

为聊天消息创建一个流式完成。

$stream = $client->chat()->createStreamed([
    'model' => 'gpt-4',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
    ],
]);

foreach($stream as $response){
    $response->choices[0]->toArray();
}
// 1. iteration => ['index' => 0, 'delta' => ['role' => 'assistant'], 'finish_reason' => null]
// 2. iteration => ['index' => 0, 'delta' => ['content' => 'Hello'], 'finish_reason' => null]
// 3. iteration => ['index' => 0, 'delta' => ['content' => '!'], 'finish_reason' => null]
// ...

在流中使用时,您可以在 stream_options 中使用 include_usage 来获取使用报告。

$stream = $client->chat()->createStreamed([
    'model' => 'gpt-4',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
    ],
    'stream_options'=>[
        'include_usage' => true,
    ]
]);

foreach($stream as $response){
    if($response->usage !== null){
        $response->usage->promptTokens; // 9,
        $response->usage->completionTokens; // 12,
        $response->usage->totalTokens; // 21
    }
}

usage 总是 null,除非是最后一个块,其中包含整个请求的令牌使用统计信息。

Audio 资源

speech

从输入文本生成音频。

$client->audio()->speech([
    'model' => 'tts-1',
    'input' => 'The quick brown fox jumped over the lazy dog.',
    'voice' => 'alloy',
]); // audio file content as string

speechStreamed

从输入文本生成流式音频。

$stream = $client->audio()->speechStreamed([
    'model' => 'tts-1',
    'input' => 'The quick brown fox jumped over the lazy dog.',
    'voice' => 'alloy',
]);

foreach($stream as $chunk){
    $chunk; // chunk of audio file content as string
}

转录

将音频转录为输入语言。

$response = $client->audio()->transcribe([
    'model' => 'whisper-1',
    'file' => fopen('audio.mp3', 'r'),
    'response_format' => 'verbose_json',
    'timestamp_granularities' => ['segment', 'word']
]);

$response->task; // 'transcribe'
$response->language; // 'english'
$response->duration; // 2.95
$response->text; // 'Hello, how are you?'

foreach ($response->segments as $segment) {
    $segment->index; // 0
    $segment->seek; // 0
    $segment->start; // 0.0
    $segment->end; // 4.0
    $segment->text; // 'Hello, how are you?'
    $segment->tokens; // [50364, 2425, 11, 577, 366, 291, 30, 50564]
    $segment->temperature; // 0.0
    $segment->avgLogprob; // -0.45045216878255206
    $segment->compressionRatio; // 0.7037037037037037
    $segment->noSpeechProb; // 0.1076972484588623
    $segment->transient; // false
}

foreach ($response->words as $word) {
    $word->word; // 'Hello'
    $word->start; // 0.31
    $word->end; // 0.92
}

$response->toArray(); // ['task' => 'transcribe', ...]

翻译

将音频翻译成英语。

$response = $client->audio()->translate([
    'model' => 'whisper-1',
    'file' => fopen('german.mp3', 'r'),
    'response_format' => 'verbose_json',
]);

$response->task; // 'translate'
$response->language; // 'english'
$response->duration; // 2.95
$response->text; // 'Hello, how are you?'

foreach ($response->segments as $segment) {
    $segment->index; // 0
    $segment->seek; // 0
    $segment->start; // 0.0
    $segment->end; // 4.0
    $segment->text; // 'Hello, how are you?'
    $segment->tokens; // [50364, 2425, 11, 577, 366, 291, 30, 50564]
    $segment->temperature; // 0.0
    $segment->avgLogprob; // -0.45045216878255206
    $segment->compressionRatio; // 0.7037037037037037
    $segment->noSpeechProb; // 0.1076972484588623
    $segment->transient; // false
}

$response->toArray(); // ['task' => 'translate', ...]

嵌入资源

create

创建代表输入文本的嵌入向量。

$response = $client->embeddings()->create([
    'model' => 'text-similarity-babbage-001',
    'input' => 'The food was delicious and the waiter...',
]);

$response->object; // 'list'

foreach ($response->embeddings as $embedding) {
    $embedding->object; // 'embedding'
    $embedding->embedding; // [0.018990106880664825, -0.0073809814639389515, ...]
    $embedding->index; // 0
}

$response->usage->promptTokens; // 8,
$response->usage->totalTokens; // 8

$response->toArray(); // ['data' => [...], ...]

文件资源

list

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

$response = $client->files()->list();

$response->object; // 'list'

foreach ($response->data as $result) {
    $result->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
    $result->object; // 'file'
    // ...
}

$response->toArray(); // ['object' => 'list', 'data' => [...]]

delete

删除文件。

$response = $client->files()->delete($file);

$response->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
$response->object; // 'file'
$response->deleted; // true

$response->toArray(); // ['id' => 'file-XjGxS3KTG0uNmNOK362iJua3', ...]

retrieve

返回特定文件的信息。

$response = $client->files()->retrieve('file-XjGxS3KTG0uNmNOK362iJua3');

$response->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
$response->object; // 'file'
$response->bytes; // 140
$response->createdAt; // 1613779657
$response->filename; // 'mydata.jsonl'
$response->purpose; // 'fine-tune'
$response->status; // 'succeeded'
$response->status_details; // null

$response->toArray(); // ['id' => 'file-XjGxS3KTG0uNmNOK362iJua3', ...]

上传

上传包含要用于各种端点/功能的文档的文件。

$response = $client->files()->upload([
        'purpose' => 'fine-tune',
        'file' => fopen('my-file.jsonl', 'r'),
    ]);

$response->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
$response->object; // 'file'
$response->bytes; // 140
$response->createdAt; // 1613779657
$response->filename; // 'mydata.jsonl'
$response->purpose; // 'fine-tune'
$response->status; // 'succeeded'
$response->status_details; // null

$response->toArray(); // ['id' => 'file-XjGxS3KTG0uNmNOK362iJua3', ...]

下载

返回指定文件的内容。

$client->files()->download($file); // '{"prompt": "<prompt text>", ...'

微调资源

创建作业

创建一个作业,从给定的数据集中微调指定的模型。

$response = $client->fineTuning()->createJob([
    'training_file' => 'file-abc123',
    'validation_file' => null,
    'model' => 'gpt-3.5-turbo',
    'hyperparameters' => [
        'n_epochs' => 4,
    ],
    'suffix' => null,
]);

$response->id; // 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F'
$response->object; // 'fine_tuning.job'
$response->model; // 'gpt-3.5-turbo-0613'
$response->fineTunedModel; // null
// ...

$response->toArray(); // ['id' => 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F', ...]

列出作业

列出您组织的微调作业。

$response = $client->fineTuning()->listJobs();

$response->object; // 'list'

foreach ($response->data as $result) {
    $result->id; // 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F'
    $result->object; // 'fine_tuning.job'
    // ...
}

$response->toArray(); // ['object' => 'list', 'data' => [...]]

您可以向 listJobs 方法传递额外的参数以缩小结果。

$response = $client->fineTuning()->listJobs([
    'limit' => 3, // Number of jobs to retrieve (Default: 20)
    'after' => 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F', // Identifier for the last job from the previous pagination request.
]);

检索作业

获取微调作业的信息。

$response = $client->fineTuning()->retrieveJob('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F');

$response->id; // 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F'
$response->object; // 'fine_tuning.job'
$response->model; // 'gpt-3.5-turbo-0613'
$response->createdAt; // 1614807352
$response->finishedAt; // 1692819450
$response->fineTunedModel; // 'ft:gpt-3.5-turbo-0613:jwe-dev::7qnxQ0sQ'
$response->organizationId; // 'org-jwe45798ASN82s'
$response->resultFiles[0]; // 'file-1bl05WrhsKDDEdg8XSP617QF'
$response->status; // 'succeeded'
$response->validationFile; // null
$response->trainingFile; // 'file-abc123'
$response->trainedTokens; // 5049

$response->hyperparameters->nEpochs; // 9

$response->toArray(); // ['id' => 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F', ...]

取消作业

立即取消微调作业。

$response = $client->fineTuning()->cancelJob('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F');

$response->id; // 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F'
$response->object; // 'fine_tuning.job'
// ...
$response->status; // 'cancelled'
// ...

$response->toArray(); // ['id' => 'ftjob-AF1WoRqd3aJAHsqc9NY7iL8F', ...]

列出作业事件

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

$response = $client->fineTuning()->listJobEvents('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F');

$response->object; // 'list'

foreach ($response->data as $result) {
    $result->object; // 'fine_tuning.job.event' 
    $result->createdAt; // 1614807352
    // ...
}

$response->toArray(); // ['object' => 'list', 'data' => [...]]

您可以向 listJobEvents 方法传递额外的参数以缩小结果。

$response = $client->fineTuning()->listJobEvents('ftjob-AF1WoRqd3aJAHsqc9NY7iL8F', [
    'limit' => 3, // Number of events to retrieve (Default: 20)
    'after' => 'ftevent-kLPSMIcsqshEUEJVOVBVcHlP', // Identifier for the last event from the previous pagination request.
]);

微调资源(已弃用)

create

创建一个作业,从给定的数据集中微调指定的模型。

$response = $client->fineTunes()->create([
    'training_file' => 'file-ajSREls59WBbvgSzJSVWxMCB',
    'validation_file' => 'file-XjSREls59WBbvgSzJSVWxMCa',
    'model' => 'curie',
    'n_epochs' => 4,
    'batch_size' => null,
    'learning_rate_multiplier' => null,
    'prompt_loss_weight' => 0.01,
    'compute_classification_metrics' => false,
    'classification_n_classes' => null,
    'classification_positive_class' => null,
    'classification_betas' => [],
    'suffix' => null,
]);

$response->id; // 'ft-AF1WoRqd3aJAHsqc9NY7iL8F'
$response->object; // 'fine-tune'
// ...

$response->toArray(); // ['id' => 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', ...]

list

列出您组织的微调作业。

$response = $client->fineTunes()->list();

$response->object; // 'list'

foreach ($response->data as $result) {
    $result->id; // 'ft-AF1WoRqd3aJAHsqc9NY7iL8F'
    $result->object; // 'fine-tune'
    // ...
}

$response->toArray(); // ['object' => 'list', 'data' => [...]]

retrieve

获取微调作业的信息。

$response = $client->fineTunes()->retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

$response->id; // 'ft-AF1WoRqd3aJAHsqc9NY7iL8F'
$response->object; // 'fine-tune'
$response->model; // 'curie'
$response->createdAt; // 1614807352
$response->fineTunedModel; // 'curie => ft-acmeco-2021-03-03-21-44-20'
$response->organizationId; // 'org-jwe45798ASN82s'
$response->resultFiles; // [
$response->status; // 'succeeded'
$response->validationFiles; // [
$response->trainingFiles; // [
$response->updatedAt; // 1614807865

foreach ($response->events as $result) {
    $result->object; // 'fine-tune-event' 
    $result->createdAt; // 1614807352
    $result->level; // 'info'
    $result->message; // 'Job enqueued. Waiting for jobs ahead to complete. Queue number =>  0.'
}

$response->hyperparams->batchSize; // 4 
$response->hyperparams->learningRateMultiplier; // 0.1 
$response->hyperparams->nEpochs; // 4 
$response->hyperparams->promptLossWeight; // 0.1

foreach ($response->resultFiles as $result) {
    $result->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
    $result->object; // 'file'
    $result->bytes; // 140
    $result->createdAt; // 1613779657
    $result->filename; // 'mydata.jsonl'
    $result->purpose; // 'fine-tune'
    $result->status; // 'succeeded'
    $result->status_details; // null
}

foreach ($response->validationFiles as $result) {
    $result->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
    // ...
}

foreach ($response->trainingFiles as $result) {
    $result->id; // 'file-XjGxS3KTG0uNmNOK362iJua3'
    // ...
}

$response->toArray(); // ['id' => 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', ...]

取消

立即取消微调作业。

$response = $client->fineTunes()->cancel('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

$response->id; // 'ft-AF1WoRqd3aJAHsqc9NY7iL8F'
$response->object; // 'fine-tune'
// ...
$response->status; // 'cancelled'
// ...

$response->toArray(); // ['id' => 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', ...]

列出事件

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

$response = $client->fineTunes()->listEvents('ft-AF1WoRqd3aJAHsqc9NY7iL8F');

$response->object; // 'list'

foreach ($response->data as $result) {
    $result->object; // 'fine-tune-event' 
    $result->createdAt; // 1614807352
    // ...
}

$response->toArray(); // ['object' => 'list', 'data' => [...]]

列出流式事件

获取微调作业的流式细粒度状态更新。

$stream = $client->fineTunes()->listEventsStreamed('ft-y3OpNlc8B5qBVGCCVsLZsDST');

foreach($stream as $response){
    $response->message;
}
// 1. iteration => 'Created fine-tune: ft-y3OpNlc8B5qBVGCCVsLZsDST'
// 2. iteration => 'Fine-tune costs $0.00'
// ...
// xx. iteration => 'Uploaded result file: file-ajLKUCMsFPrT633zqwr0eI4l'
// xx. iteration => 'Fine-tune succeeded'

审核资源

create

分类文本是否违反OpenAI的内容政策。

$response = $client->moderations()->create([
    'model' => 'text-moderation-latest',
    'input' => 'I want to k*** them.',
]);

$response->id; // modr-5xOyuS
$response->model; // text-moderation-003

foreach ($response->results as $result) {
    $result->flagged; // true

    foreach ($result->categories as $category) {
        $category->category->value; // 'violence'
        $category->violated; // true
        $category->score; // 0.97431367635727
    }
}

$response->toArray(); // ['id' => 'modr-5xOyuS', ...]

图像资源

create

根据提示创建图像。

$response = $client->images()->create([
    'model' => 'dall-e-3',
    'prompt' => 'A cute baby sea otter',
    'n' => 1,
    'size' => '1024x1024',
    'response_format' => 'url',
]);

$response->created; // 1589478378

foreach ($response->data as $data) {
    $data->url; // 'https://oaidalleapiprodscus.blob.core.windows.net/private/...'
    $data->b64_json; // null
}

$response->toArray(); // ['created' => 1589478378, data => ['url' => 'https://oaidalleapiprodscus...', ...]]

编辑

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

$response = $client->images()->edit([
    'image' => fopen('image_edit_original.png', 'r'),
    'mask' => fopen('image_edit_mask.png', 'r'),
    'prompt' => 'A sunlit indoor lounge area with a pool containing a flamingo',
    'n' => 1,
    'size' => '256x256',
    'response_format' => 'url',
]);

$response->created; // 1589478378

foreach ($response->data as $data) {
    $data->url; // 'https://oaidalleapiprodscus.blob.core.windows.net/private/...'
    $data->b64_json; // null
}

$response->toArray(); // ['created' => 1589478378, data => ['url' => 'https://oaidalleapiprodscus...', ...]]

变体

创建给定图像的变体。

$response = $client->images()->variation([
    'image' => fopen('image_edit_original.png', 'r'),
    'n' => 1,
    'size' => '256x256',
    'response_format' => 'url',
]);

$response->created; // 1589478378

foreach ($response->data as $data) {
    $data->url; // 'https://oaidalleapiprodscus.blob.core.windows.net/private/...'
    $data->b64_json; // null
}

$response->toArray(); // ['created' => 1589478378, data => ['url' => 'https://oaidalleapiprodscus...', ...]]

助手资源

注意:如果您从工厂手动创建客户端,请确保您提供必要的头信息

$factory->withHttpHeader('OpenAI-Beta', 'assistants=v2')

create

使用模型和说明创建助手。

$response = $client->assistants()->create([
    'instructions' => 'You are a personal math tutor. When asked a question, write and run Python code to answer the question.',
    'name' => 'Math Tutor',
    'tools' => [
        [
            'type' => 'code_interpreter',
        ],
    ],
    'model' => 'gpt-4',
]);

$response->id; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->object; // 'assistant'
$response->createdAt; // 1623936000
$response->name; // 'Math Tutor'
$response->instructions; // 'You are a personal math tutor. When asked a question, write and run Python code to answer the question.'
$response->model; // 'gpt-4'
$response->description; // null
$response->tools[0]->type; // 'code_interpreter'
$response->toolResources; // []
$response->metadata; // []
$response->temperature: // null
$response->topP: // null
$response->format: // 'auto'

$response->toArray(); // ['id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd', ...]

retrieve

检索助手。

$response = $client->assistants()->retrieve('asst_gxzBkD1wkKEloYqZ410pT5pd');

$response->id; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->object; // 'assistant'
$response->createdAt; // 1623936000
$response->name; // 'Math Tutor'
$response->instructions; // 'You are a personal math tutor. When asked a question, write and run Python code to answer the question.'
$response->model; // 'gpt-4'
$response->description; // null
$response->tools[0]->type; // 'code_interpreter'
$response->toolResources; // []
$response->metadata; // []
$response->temperature: // null
$response->topP: // null
$response->format: // 'auto'

$response->toArray(); // ['id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd', ...]

修改

修改助手。

$response = $client->assistants()->modify('asst_gxzBkD1wkKEloYqZ410pT5pd', [
        'name' => 'New Math Tutor',
    ]);

$response->id; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->object; // 'assistant'
$response->createdAt; // 1623936000
$response->name; // 'New Math Tutor'
$response->instructions; // 'You are a personal math tutor. When asked a question, write and run Python code to answer the question.'
$response->model; // 'gpt-4'
$response->description; // null
$response->tools[0]->type; // 'code_interpreter'
$response->toolResources; // []
$response->metadata; // []
$response->temperature: // null
$response->topP: // null
$response->format: // 'auto'

$response->toArray(); // ['id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd', ...]

delete

删除助手。

$response = $client->assistants()->delete('asst_gxzBkD1wkKEloYqZ410pT5pd');

$response->id; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->object; // 'assistant.deleted'
$response->deleted; // true

$response->toArray(); // ['id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd', ...]

list

返回助手列表。

$response = $client->assistants()->list([
    'limit' => 10,
]);

$response->object; // 'list'
$response->firstId; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->lastId; // 'asst_reHHtAM0jKLDIxanM6gP6DaR'
$response->hasMore; // true

foreach ($response->data as $result) {
    $result->id; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
    // ...
}

$response->toArray(); // ['object' => 'list', ...]]

线程资源

create

创建线程。

$response = $client->threads()->create([]);

$response->id; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->object; // 'thread'
$response->createdAt; // 1623936000
$response->toolResources; // null
$response->metadata; // []

$response->toArray(); // ['id' => 'thread_tKFLqzRN9n7MnyKKvc1Q7868', ...]

创建并运行

在一个请求中创建线程并运行它。

$response = $client->threads()->createAndRun(
    [
        'assistant_id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd',
        'thread' => [
            'messages' =>
                [
                    [
                        'role' => 'user',
                        'content' => 'Explain deep learning to a 5 year old.',
                    ],
                ],
        ],
    ],
);

$response->id; // 'run_4RCYyYzX9m41WQicoJtUQAb8'
$response->object; // 'thread.run'
$response->createdAt; // 1623936000
$response->assistantId; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->threadId; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->status; // 'queued'
$response->requiredAction; // null
$response->lastError; // null
$response->startedAt; // null
$response->expiresAt; // 1699622335
$response->cancelledAt; // null
$response->failedAt; // null
$response->completedAt; // null
$response->incompleteDetails; // null
$response->lastError; // null
$response->model; // 'gpt-4'
$response->instructions; // null
$response->tools; // []
$response->metadata; // []
$response->usage->total_tokens; // 579
$response->temperature; // null
$response->topP; // null
$response->maxPromptTokens; // 1000
$response->maxCompletionTokens; // 1000
$response->truncationStrategy->type; // 'auto'
$response->responseFormat; // 'auto'
$response->toolChoice; // 'auto'

$response->toArray(); // ['id' => 'run_4RCYyYzX9m41WQicoJtUQAb8', ...]

retrieve

检索线程。

$response = $client->threads()->retrieve('thread_tKFLqzRN9n7MnyKKvc1Q7868');

$response->id; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->object; // 'thread'
$response->createdAt; // 1623936000
$response->toolResources; // null
$response->metadata; // []

$response->toArray(); // ['id' => 'thread_tKFLqzRN9n7MnyKKvc1Q7868', ...]

修改

修改线程。

$response = $client->threads()->modify('thread_tKFLqzRN9n7MnyKKvc1Q7868', [
        'metadata' => [
            'name' => 'My new thread name',
        ],
    ]);

$response->id; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->object; // 'thread'
$response->createdAt; // 1623936000
$response->toolResources; // null
$response->metadata; // ['name' => 'My new thread name']

$response->toArray(); // ['id' => 'thread_tKFLqzRN9n7MnyKKvc1Q7868', ...]

delete

删除线程。

$response = $client->threads()->delete('thread_tKFLqzRN9n7MnyKKvc1Q7868');

$response->id; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->object; // 'thread.deleted'
$response->deleted; // true

$response->toArray(); // ['id' => 'thread_tKFLqzRN9n7MnyKKvc1Q7868', ...]

线程消息资源

create

创建消息。

$response = $client->threads()->messages()->create('thread_tKFLqzRN9n7MnyKKvc1Q7868', [
    'role' => 'user',
    'content' => 'What is the sum of 5 and 7?',
]);

$response->id; // 'msg_SKYwvF3zcigxthfn6F4hnpdU'
$response->object; // 'thread.message'
$response->createdAt; // 1623936000
$response->threadId; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->status; // 'in_progress
$response->incompleteDetails; // null
$response->completedAt; // null
$response->incompleteAt; // null
$response->role; // 'user'
$response->content[0]->type; // 'text'
$response->content[0]->text->value; // 'What is the sum of 5 and 7?'
$response->content[0]->text->annotations; // []
$response->assistantId; // null
$response->runId; // null
$response->attachments; // []
$response->metadata; // []

$response->toArray(); // ['id' => 'msg_SKYwvF3zcigxthfn6F4hnpdU', ...]

retrieve

检索消息。

$response = $client->threads()->messages()->retrieve(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    messageId: 'msg_SKYwvF3zcigxthfn6F4hnpdU',
);

$response->id; // 'msg_SKYwvF3zcigxthfn6F4hnpdU'
$response->object; // 'thread.message'
$response->createdAt; // 1623936000
$response->threadId; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->status; // 'in_progress
$response->incompleteDetails; // null
$response->completedAt; // null
$response->incompleteAt; // null
$response->role; // 'user'
$response->content[0]->type; // 'text'
$response->content[0]->text->value; // 'What is the sum of 5 and 7?'
$response->content[0]->text->annotations; // []
$response->assistantId; // null
$response->runId; // null
$response->attachments; // []
$response->metadata; // []

$response->toArray(); // ['id' => 'msg_SKYwvF3zcigxthfn6F4hnpdU', ...]

修改

修改消息。

$response = $client->threads()->messages()->modify(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    messageId: 'msg_SKYwvF3zcigxthfn6F4hnpdU',
    parameters:  [
        'metadata' => [
            'name' => 'My new message name',
        ],
    ],
);

$response->id; // 'msg_SKYwvF3zcigxthfn6F4hnpdU'
$response->object; // 'thread.message'
$response->createdAt; // 1623936000
$response->threadId; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->status; // 'in_progress
$response->incompleteDetails; // null
$response->completedAt; // null
$response->incompleteAt; // null
$response->role; // 'user'
$response->content[0]->type; // 'text'
$response->content[0]->text->value; // 'What is the sum of 5 and 7?'
$response->content[0]->text->annotations; // []
$response->assistantId; // null
$response->runId; // null
$response->attachments; // []
$response->metadata; // ['name' => 'My new message name']

$response->toArray(); // ['id' => 'msg_SKYwvF3zcigxthfn6F4hnpdU', ...]

delete

删除消息。

$response = $client->threads()->messages()->delete(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    messageId: 'msg_SKYwvF3zcigxthfn6F4hnpdU'
);

$response->id; // 'msg_SKYwvF3zcigxthfn6F4hnpdU'
$response->object; // 'thread.message.deleted'
$response->deleted; // true

$response->toArray(); // ['id' => 'msg_SKYwvF3zcigxthfn6F4hnpdU', ...]

list

返回给定线程的消息列表。

$response = $client->threads()->messages()->list('thread_tKFLqzRN9n7MnyKKvc1Q7868', [
    'limit' => 10,
]);

$response->object; // 'list'
$response->firstId; // 'msg_SKYwvF3zcigxthfn6F4hnpdU'
$response->lastId; // 'msg_SKYwvF3zcigxthfn6F4hnpdU'
$response->hasMore; // false

foreach ($response->data as $result) {
    $result->id; // 'msg_SKYwvF3zcigxthfn6F4hnpdU'
    // ...
}

$response->toArray(); // ['object' => 'list', ...]]

线程运行资源

create

创建运行。

$response = $client->threads()->runs()->create(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868', 
    parameters: [
        'assistant_id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd',
    ],
);

$response->id; // 'run_4RCYyYzX9m41WQicoJtUQAb8'
$response->object; // 'thread.run'
$response->createdAt; // 1623936000
$response->assistantId; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->threadId; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->status; // 'queued'
$response->startedAt; // null
$response->expiresAt; // 1699622335
$response->cancelledAt; // null
$response->failedAt; // null
$response->completedAt; // null
$response->incompleteDetails; // null
$response->lastError; // null
$response->model; // 'gpt-4'
$response->instructions; // null
$response->tools; // []
$response->metadata; // []
$response->usage->total_tokens; // 579
$response->temperature; // null
$response->topP; // null
$response->maxPromptTokens; // 1000
$response->maxCompletionTokens; // 1000
$response->truncationStrategy->type; // 'auto'
$response->toolChoice; // 'auto'
$response->responseFormat; // 'auto'

$response->toArray(); // ['id' => 'run_4RCYyYzX9m41WQicoJtUQAb8', ...]

create streamed

创建流式运行。

OpenAI 助手事件

$stream = $client->threads()->runs()->createStreamed(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    parameters: [
        'assistant_id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd',
    ],
);

foreach($stream as $response){
    $response->event // 'thread.run.created' | 'thread.run.in_progress' | .....
    $response->response // ThreadResponse | ThreadRunResponse | ThreadRunStepResponse | ThreadRunStepDeltaResponse | ThreadMessageResponse | ThreadMessageDeltaResponse
}

// ...

使用函数调用创建流式

使用函数调用创建流式运行

OpenAI 助手事件

$stream = $client->threads()->runs()->createStreamed(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    parameters: [
        'assistant_id' => 'asst_gxzBkD1wkKEloYqZ410pT5pd',
    ],
);


do{
    foreach($stream as $response){
        $response->event // 'thread.run.created' | 'thread.run.in_progress' | .....
        $response->response // ThreadResponse | ThreadRunResponse | ThreadRunStepResponse | ThreadRunStepDeltaResponse | ThreadMessageResponse | ThreadMessageDeltaResponse

        switch($response->event){
            case 'thread.run.created':
            case 'thread.run.queued':
            case 'thread.run.completed':
            case 'thread.run.cancelling':
                $run = $response->response;
                break;
            case 'thread.run.expired':
            case 'thread.run.cancelled':
            case 'thread.run.failed':
                $run = $response->response;
                break 3;
            case 'thread.run.requires_action':
                // Overwrite the stream with the new stream started by submitting the tool outputs
                $stream = $client->threads()->runs()->submitToolOutputsStreamed(
                    threadId: $run->threadId,
                    runId: $run->id,
                    parameters: [
                        'tool_outputs' => [
                            [
                                'tool_call_id' => 'call_KSg14X7kZF2WDzlPhpQ168Mj',
                                'output' => '12',
                            ]
                        ],
                    ]
                );
                break;
        }
    }
} while ($run->status != "completed")

// ...

retrieve

检索运行。

$response = $client->threads()->runs()->retrieve(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    runId: 'run_4RCYyYzX9m41WQicoJtUQAb8',
);

$response->id; // 'run_4RCYyYzX9m41WQicoJtUQAb8'
$response->object; // 'thread.run'
$response->createdAt; // 1623936000
$response->assistantId; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->threadId; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->status; // 'queued'
$response->startedAt; // null
$response->expiresAt; // 1699622335
$response->cancelledAt; // null
$response->failedAt; // null
$response->completedAt; // null
$response->incompleteDetails; // null
$response->lastError; // null
$response->model; // 'gpt-4'
$response->instructions; // null
$response->tools; // []
$response->metadata; // []
$response->usage->promptTokens; // 25,
$response->usage->completionTokens; // 32,
$response->usage->totalTokens; // 57
$response->temperature; // null
$response->topP; // null
$response->maxPromptTokens; // 1000
$response->maxCompletionTokens; // 1000
$response->truncationStrategy->type; // 'auto'
$response->toolChoice; // 'auto'
$response->responseFormat; // 'auto'

$response->toArray(); // ['id' => 'run_4RCYyYzX9m41WQicoJtUQAb8', ...]

修改

修改运行。

$response = $client->threads()->runs()->modify(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    runId: 'run_4RCYyYzX9m41WQicoJtUQAb8',
    parameters:  [
        'metadata' => [
            'name' => 'My new run name',
        ],
    ],
);

$response->id; // 'run_4RCYyYzX9m41WQicoJtUQAb8'
$response->object; // 'thread.run'
$response->createdAt; // 1623936000
$response->assistantId; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->threadId; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->status; // 'queued'
$response->startedAt; // null
$response->expiresAt; // 1699622335
$response->cancelledAt; // null
$response->failedAt; // null
$response->completedAt; // null
$response->incompleteDetails; // null
$response->lastError; // null
$response->model; // 'gpt-4'
$response->instructions; // null
$response->tools; // []
$response->usage->total_tokens; // 579
$response->temperature; // null
$response->topP; // null
$response->maxPromptTokens; // 1000
$response->maxCompletionTokens; // 1000
$response->truncationStrategy->type; // 'auto'
$response->toolChoice; // 'auto'
$response->responseFormat; // 'auto'
$response->metadata; // ['name' => 'My new run name']

$response->toArray(); // ['id' => 'run_4RCYyYzX9m41WQicoJtUQAb8', ...]

取消

取消状态为 in_progress 的运行。

$response = $client->threads()->runs()->cancel(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    runId: 'run_4RCYyYzX9m41WQicoJtUQAb8',
);

$response->id; // 'run_4RCYyYzX9m41WQicoJtUQAb8'
$response->object; // 'thread.run'
$response->createdAt; // 1623936000
$response->assistantId; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->threadId; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->status; // 'cancelling'
$response->startedAt; // null
$response->expiresAt; // 1699622335
$response->cancelledAt; // null
$response->failedAt; // null
$response->completedAt; // null
$response->incompleteDetails; // null
$response->lastError; // null
$response->model; // 'gpt-4'
$response->instructions; // null
$response->tools; // []
$response->usage?->total_tokens; // 579
$response->temperature; // null
$response->topP; // null
$response->maxPromptTokens; // 1000
$response->maxCompletionTokens; // 1000
$response->truncationStrategy->type; // 'auto'
$response->toolChoice; // 'auto'
$response->responseFormat; // 'auto'
$response->metadata; // []

$response->toArray(); // ['id' => 'run_4RCYyYzX9m41WQicoJtUQAb8', ...]

提交工具输出

当运行的状态为:requires_actionrequired_action.typesubmit_tool_outputs 时,可以使用此端点提交工具调用的输出。所有输出必须在单个请求中提交。

$response = $client->threads()->runs()->submitToolOutputs(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    runId: 'run_4RCYyYzX9m41WQicoJtUQAb8',
    parameters: [
        'tool_outputs' => [
            [
                'tool_call_id' => 'call_KSg14X7kZF2WDzlPhpQ168Mj',
                'output' => '12',
            ],
        ],
    ]
);

$response->id; // 'run_4RCYyYzX9m41WQicoJtUQAb8'
$response->object; // 'thread.run'
$response->createdAt; // 1623936000
$response->assistantId; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->threadId; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->status; // 'in_progress'
$response->startedAt; // null
$response->expiresAt; // 1699622335
$response->cancelledAt; // null
$response->failedAt; // null
$response->completedAt; // null
$response->incompleteDetails; // null
$response->lastError; // null
$response->model; // 'gpt-4'
$response->instructions; // null
$response->usage->total_tokens; // 579
$response->temperature; // null
$response->topP; // null
$response->maxPromptTokens; // 1000
$response->maxCompletionTokens; // 1000
$response->truncationStrategy->type; // 'auto'
$response->responseFormat; // 'auto'
$response->tools[0]->type; // 'function'
$response->toolChoice; // 'auto'
$response->metadata; // []

$response->toArray(); // ['id' => 'run_4RCYyYzX9m41WQicoJtUQAb8', ...]

list

返回属于线程的运行列表。

$response = $client->threads()->runs()->list(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    parameters: [
        'limit' => 10,
    ],
);

$response->object; // 'list'
$response->firstId; // 'run_4RCYyYzX9m41WQicoJtUQAb8'
$response->lastId; // 'run_4RCYyYzX9m41WQicoJtUQAb8'
$response->hasMore; // false

foreach ($response->data as $result) {
    $result->id; // 'run_4RCYyYzX9m41WQicoJtUQAb8'
    // ...
}

$response->toArray(); // ['object' => 'list', ...]]

线程运行步骤资源

retrieve

检索运行步骤。

$response = $client->threads()->runs()->steps()->retrieve(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    runId: 'run_4RCYyYzX9m41WQicoJtUQAb8',
    stepId: 'step_1spQXgbAabXFm1YXrwiGIMUz',
);

$response->id; // 'step_1spQXgbAabXFm1YXrwiGIMUz'
$response->object; // 'thread.run.step'
$response->createdAt; // 1699564106
$response->runId; // 'run_4RCYyYzX9m41WQicoJtUQAb8'
$response->assistantId; // 'asst_gxzBkD1wkKEloYqZ410pT5pd'
$response->threadId; // 'thread_tKFLqzRN9n7MnyKKvc1Q7868'
$response->type; // 'message_creation'
$response->status; // 'completed'
$response->cancelledAt; // null
$response->completedAt; // 1699564119
$response->expiresAt; // null
$response->failedAt; // null
$response->lastError; // null
$response->stepDetails->type; // 'message_creation'
$response->stepDetails->messageCreation->messageId; // 'msg_i404PxKbB92d0JAmdOIcX7vA'

$response->toArray(); // ['id' => 'step_1spQXgbAabXFm1YXrwiGIMUz', ...]

list

返回属于运行的运行步骤列表。

$response = $client->threads()->runs()->steps()->list(
    threadId: 'thread_tKFLqzRN9n7MnyKKvc1Q7868',
    runId: 'run_4RCYyYzX9m41WQicoJtUQAb8',
    parameters: [
        'limit' => 10,
    ],
);

$response->object; // 'list'
$response->firstId; // 'step_1spQXgbAabXFm1YXrwiGIMUz'
$response->lastId; // 'step_1spQXgbAabXFm1YXrwiGIMUz'
$response->hasMore; // false

foreach ($response->data as $result) {
    $result->id; // 'step_1spQXgbAabXFm1YXrwiGIMUz'
    // ...
}

$response->toArray(); // ['object' => 'list', ...]]

批处理资源

create

创建批处理。

$fileResponse = $client->files()->upload(
     parameters: [
          'purpose' => 'batch',
          'file' => fopen('commands.jsonl', 'r'),
    ]
);

$fileId = $fileResponse->id;

$response = $client->batches()->create(
    parameters: [
        'input_file_id' => $fileId,
        'endpoint' => '/v1/chat/completions',
        'completion_window' => '24h'
    ]
 );

$response->id; // 'batch_abc123'
$response->object; // 'batch'
$response->endpoint; // /v1/chat/completions
$response->errors; // null
$response->completionWindow; // '24h'
$response->status; // 'validating'
$response->outputFileId; // null
$response->errorFileId; // null
$response->createdAt; // 1714508499
$response->inProgressAt; // null
$response->expiresAt; // 1714536634
$response->completedAt; // null
$response->failedAt; // null
$response->expiredAt; // null
$response->requestCounts; // null
$response->metadata; // ['name' => 'My batch name']

$response->toArray(); // ['id' => 'batch_abc123', ...]

retrieve

检索批处理。

$response = $client->batches()->retrieve(id: 'batch_abc123');

$response->id; // 'batch_abc123'
$response->object; // 'batch'
$response->endpoint; // /v1/chat/completions
$response->errors; // null
$response->completionWindow; // '24h'
$response->status; // 'validating'
$response->outputFileId; // null
$response->errorFileId; // null
$response->createdAt; // 1714508499
$response->inProgressAt; // null
$response->expiresAt; // 1714536634
$response->completedAt; // null
$response->failedAt; // null
$response->expiredAt; // null
$response->requestCounts->total; // 100
$response->requestCounts->completed; // 95
$response->requestCounts->failed; // 5
$response->metadata; // ['name' => 'My batch name']

$response->toArray(); // ['id' => 'batch_abc123', ...]

取消

取消批处理。

$response = $client->batches()->cancel(id: 'batch_abc123');

$response->id; // 'batch_abc123'
$response->object; // 'batch'
$response->endpoint; // /v1/chat/completions
$response->errors; // null
$response->completionWindow; // '24h'
$response->status; // 'cancelling'
$response->outputFileId; // null
$response->errorFileId; // null
$response->createdAt; // 1711471533
$response->inProgressAt; // 1711471538
$response->expiresAt; // 1711557933
$response->cancellingAt; // 1711475133
$response->cancelledAt; // null
$response->requestCounts->total; // 100
$response->requestCounts->completed; // 23
$response->requestCounts->failed; // 1
$response->metadata; // ['name' => 'My batch name']

$response->toArray(); // ['id' => 'batch_abc123', ...]

list

返回批处理列表。

$response = $client->batches()->list(
    parameters: [
        'limit' => 10, 
    ],
);

$response->object; // 'list'
$response->firstId; // 'batch_abc123'
$response->lastId; // 'batch_abc456'
$response->hasMore; // true

foreach ($response->data as $result) {
    $result->id; // 'batch_abc123'
    // ...
}

$response->toArray(); // ['object' => 'list', ...]]

向量存储资源

create

创建向量存储。

$response = $client->vectorStores()->create([
    'file_ids' => [
        'file-fUU0hFRuQ1GzhOweTNeJlCXG',
    ],
    'name' => 'My first Vector Store',
]);

$response->id; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->object; // 'vector_store'
$response->createdAt; // 1717703267
$response->name; // 'My first Vector Store'
$response->usageBytes; // 0
$response->fileCounts->inProgress; // 1
$response->fileCounts->completed; // 0
$response->fileCounts->failed; // 0
$response->fileCounts->cancelled; // 0
$response->fileCounts->total; // 1
$response->status; // 'in_progress'
$response->expiresAfter; // null
$response->expiresAt; // null
$response->lastActiveAt; // 1717703267

$response->toArray(); // ['id' => 'vs_vzfQhlTWVUl38QGqQAoQjeDF', ...]

retrieve

检索向量存储。

$response = $client->vectorStores()->retrieve(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
);

$response->id; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->object; // 'vector_store'
$response->createdAt; // 1717703267
$response->name; // 'My first Vector Store'
$response->usageBytes; // 0
$response->fileCounts->inProgress; // 1
$response->fileCounts->completed; // 0
$response->fileCounts->failed; // 0
$response->fileCounts->cancelled; // 0
$response->fileCounts->total; // 1
$response->status; // 'in_progress'
$response->expiresAfter; // null
$response->expiresAt; // null
$response->lastActiveAt; // 1717703267

$response->toArray(); // ['id' => 'vs_vzfQhlTWVUl38QGqQAoQjeDF', ...]

修改

修改向量存储。

$response = $client->vectorStores()->modify(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
    parameters:  [
        'name' => 'New name',
    ],
);

$response->id; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->object; // 'vector_store'
$response->createdAt; // 1717703267
$response->name; // 'New name'
$response->usageBytes; // 0
$response->fileCounts->inProgress; // 1
$response->fileCounts->completed; // 0
$response->fileCounts->failed; // 0
$response->fileCounts->cancelled; // 0
$response->fileCounts->total; // 1
$response->status; // 'in_progress'
$response->expiresAfter; // null
$response->expiresAt; // null
$response->lastActiveAt; // 1717703267

$response->toArray(); // ['id' => 'vs_vzfQhlTWVUl38QGqQAoQjeDF', ...]

delete

删除向量存储。

$response = $client->vectorStores()->delete(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
);

$response->id; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->object; // 'vector_store.deleted'
$response->deleted; // true

$response->toArray(); // ['id' => 'vs_vzfQhlTWVUl38QGqQAoQjeDF', ...]

list

返回向量存储列表。

$response = $client->vectorStores()->list(
    parameters: [
        'limit' => 10,
    ],
);

$response->object; // 'list'
$response->firstId; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->lastId; // 'vs_D5DPOgBxSoEBTmYBgUESdPpa'
$response->hasMore; // true

foreach ($response->data as $result) {
    $result->id; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
    // ...
}

$response->toArray(); // ['object' => 'list', ...]]

向量存储文件资源

create

通过将文件附加到向量存储来创建向量存储文件。

$response = $client->vectorStores()->files()->create(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
    parameters: [
        'file_id' => 'file-fUU0hFRuQ1GzhOweTNeJlCXG',
    ]
);

$response->id; // 'file-fUU0hFRuQ1GzhOweTNeJlCXG'
$response->object; // 'vector_store.file'
$response->usageBytes; // 4553
$response->createdAt; // 1717703267
$response->vectorStoreId; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->status; // 'completed'
$response->lastError; // null
$response->chunkingStrategy->type; // 'static'
$response->chunkingStrategy->maxChunkSizeTokens; // 800
$response->chunkingStrategy->chunkOverlapTokens; // 400

$response->toArray(); // ['id' => 'file-fUU0hFRuQ1GzhOweTNeJlCXG', ...]

retrieve

检索向量化存储文件。

$response = $client->vectorStores()->files()->retrieve(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
    fileId: 'file-fUU0hFRuQ1GzhOweTNeJlCXG',
);

$response->id; // 'file-fUU0hFRuQ1GzhOweTNeJlCXG'
$response->object; // 'vector_store.file'
$response->usageBytes; // 4553
$response->createdAt; // 1717703267
$response->vectorStoreId; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->status; // 'completed'
$response->lastError; // null
$response->chunkingStrategy->type; // 'static'
$response->chunkingStrategy->maxChunkSizeTokens; // 800
$response->chunkingStrategy->chunkOverlapTokens; // 400

$response->toArray(); // ['id' => 'file-fUU0hFRuQ1GzhOweTNeJlCXG', ...]

delete

删除向量化存储文件。这将从向量化存储中移除文件,但文件本身不会被删除。要删除文件,请使用删除文件端点。

$response = $client->vectorStores()->files()->delete(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
    fileId: 'file-fUU0hFRuQ1GzhOweTNeJlCXG',
);

$response->id; // 'file-fUU0hFRuQ1GzhOweTNeJlCXG'
$response->object; // 'vector_store.file.deleted'
$response->deleted; // true

$response->toArray(); // ['id' => 'file-fUU0hFRuQ1GzhOweTNeJlCXG', ...]

list

返回向量化存储文件列表。

$response = $client->vectorStores()->files()->list(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
    parameters: [
        'limit' => 10,
    ],
);

$response->object; // 'list'
$response->firstId; // 'file-fUU0hFRuQ1GzhOweTNeJlCXG'
$response->lastId; // 'file-D5DPOgBxSoEBTmYBgUESdPpa'
$response->hasMore; // true

foreach ($response->data as $result) {
    $result->id; // 'file-fUU0hFRuQ1GzhOweTNeJlCXG'
    // ...
}

$response->toArray(); // ['object' => 'list', ...]]

向量存储文件批次 资源

create

创建向量化存储文件批次。

$response = $client->vectorStores()->batches()->create(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
    parameters: [
        'file_ids' => [
            'file-fUU0hFRuQ1GzhOweTNeJlCXG',
        ],
    ]
);

$response->id; // 'vsfb_123'
$response->object; // 'vector_store.files_batch'
$response->createdAt; // 1698107661
$response->vectorStoreId; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->status; // 'completed'
$response->fileCounts->inProgress; // 1
$response->fileCounts->completed; // 0
$response->fileCounts->failed; // 0
$response->fileCounts->cancelled; // 0
$response->fileCounts->total; // 1

$response->toArray(); // ['id' => 'vsfb_123', ...]

retrieve

检索向量化存储文件批次。

$response = $client->vectorStores()->batches()->retrieve(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
    fileBatchId: 'vsfb_123',
);

$response->id; // 'vsfb_123'
$response->object; // 'vector_store.files_batch'
$response->createdAt; // 1698107661
$response->vectorStoreId; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->status; // 'completed'
$response->fileCounts->inProgress; // 1
$response->fileCounts->completed; // 0
$response->fileCounts->failed; // 0
$response->fileCounts->cancelled; // 0
$response->fileCounts->total; // 1

$response->toArray(); // ['id' => 'vsfb_123', ...]

取消

取消向量化存储文件批次。这会尽快尝试取消该批次中文件的处理。

$response = $client->vectorStores()->batches()->cancel(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
    fileBatchId: 'vsfb_123',
);

$response->id; // 'vsfb_123'
$response->object; // 'vector_store.files_batch'
$response->createdAt; // 1698107661
$response->vectorStoreId; // 'vs_vzfQhlTWVUl38QGqQAoQjeDF'
$response->status; // 'cancelling'
$response->fileCounts->inProgress; // 1
$response->fileCounts->completed; // 0
$response->fileCounts->failed; // 0
$response->fileCounts->cancelled; // 0
$response->fileCounts->total; // 1

$response->toArray(); // ['id' => 'vsfb_123', ...]

list

返回向量化存储文件列表。

$response = $client->vectorStores()->batches()->listFiles(
    vectorStoreId: 'vs_vzfQhlTWVUl38QGqQAoQjeDF',
    fileBatchId: 'vsfb_123',
    parameters: [
        'limit' => 10,
    ],
);

$response->object; // 'list'
$response->firstId; // 'file-fUU0hFRuQ1GzhOweTNeJlCXG'
$response->lastId; // 'file-D5DPOgBxSoEBTmYBgUESdPpa'
$response->hasMore; // true

foreach ($response->data as $result) {
    $result->id; // 'file-fUU0hFRuQ1GzhOweTNeJlCXG'
    // ...
}

$response->toArray(); // ['object' => 'list', ...]]

编辑 资源(已弃用)

OpenAI 已弃用 Edits API,并将于 2024 年 1 月 4 日停止工作。https://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api

create

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

$response = $client->edits()->create([
    'model' => 'text-davinci-edit-001',
    'input' => 'What day of the wek is it?',
    'instruction' => 'Fix the spelling mistakes',
]);

$response->object; // 'edit'
$response->created; // 1589478378

foreach ($response->choices as $result) {
    $result->text; // 'What day of the week is it?'
    $result->index; // 0
}

$response->usage->promptTokens; // 25,
$response->usage->completionTokens; // 32,
$response->usage->totalTokens; // 57

$response->toArray(); // ['object' => 'edit', ...]

元信息

在所有响应对象中,您可以通过 meta() 方法访问 API 返回的元信息。

$response = $client->completions()->create([
    'model' => 'gpt-3.5-turbo-instruct',
    'prompt' => 'Say this is a test',
]);

$meta = $response->meta();

$meta->requestId; // '574a03e2faaf4e9fd703958e4ddc66f5'

$meta->openai->model; // 'gpt-3.5-turbo-instruct'
$meta->openai->organization; // 'org-jwe45798ASN82s'
$meta->openai->version; // '2020-10-01'
$meta->openai->processingMs; // 425

$meta->requestLimit->limit; // 3000
$meta->requestLimit->remaining; // 2999
$meta->requestLimit->reset; // '20ms'

$meta->tokenLimit->limit; // 250000
$meta->tokenLimit->remaining; // 249984
$meta->tokenLimit->reset; // '3ms'

toArray() 方法返回 API 原始返回的元信息形式。

$meta->toArray();

// [ 
//   'x-request-id' => '574a03e2faaf4e9fd703958e4ddc66f5',
//   'openai-model' => 'gpt-3.5-turbo-instruct',
//   'openai-organization' => 'org-jwe45798ASN82s',
//   'openai-processing-ms' => 402,
//   'openai-version' => '2020-10-01',
//   'x-ratelimit-limit-requests' => 3000,
//   'x-ratelimit-remaining-requests' => 2999,
//   'x-ratelimit-reset-requests' => '20ms',
//   'x-ratelimit-limit-tokens' => 250000,
//   'x-ratelimit-remaining-tokens' => 249983,
//   'x-ratelimit-reset-tokens' => '3ms',
// ]

在流式响应中,您可以在响应流对象上访问元信息。

$stream = $client->completions()->createStreamed([
    'model' => 'gpt-3.5-turbo-instruct',
    'prompt' => 'Say this is a test',
]);
    
$stream->meta(); 

有关速率限制的详细信息以及达到限制时如何操作,请访问OpenAI 文档

故障排除

超时

当向 API 发送请求时,您可能会遇到超时。默认超时取决于所使用的 HTTP 客户端。

您可以通过配置 HTTP 客户端并将配置传递给工厂来增加超时时间。

此示例说明了如何使用 Guzzle 增加超时时间。

OpenAI::factory()
    ->withApiKey($apiKey)
    ->withOrganization($organization)
    ->withHttpClient(new \GuzzleHttp\Client(['timeout' => $timeout]))
    ->make();

测试

该软件包提供了一个 OpenAI\Client 类的伪实现,允许您模拟 API 响应。

为确保您的代码正确运行,请确保在测试用例中将 OpenAI\Client 类与 OpenAI\Testing\ClientFake 类进行交换。

伪响应按创建伪客户端时提供的顺序返回。

所有响应都包含一个 fake() 方法,允许您通过仅提供与您的测试用例相关的参数来轻松创建响应对象。

use OpenAI\Testing\ClientFake;
use OpenAI\Responses\Completions\CreateResponse;

$client = new ClientFake([
    CreateResponse::fake([
        'choices' => [
            [
                'text' => 'awesome!',
            ],
        ],
    ]),
]);

$completion = $client->completions()->create([
    'model' => 'gpt-3.5-turbo-instruct',
    'prompt' => 'PHP is ',
]);

expect($completion['choices'][0]['text'])->toBe('awesome!');

在流式响应的情况下,您可以可选地提供一个包含伪响应数据的资源。

use OpenAI\Testing\ClientFake;
use OpenAI\Responses\Chat\CreateStreamedResponse;

$client = new ClientFake([
    CreateStreamedResponse::fake(fopen('file.txt', 'r'););
]);

$completion = $client->chat()->createStreamed([
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            ['role' => 'user', 'content' => 'Hello!'],
        ],
]);

expect($response->getIterator()->current())
        ->id->toBe('chatcmpl-6yo21W6LVo8Tw2yBf7aGf2g17IeIl');

在请求发送后,有各种方法可以确保发送了预期的请求。

// assert completion create request was sent
$client->assertSent(Completions::class, function (string $method, array $parameters): bool {
    return $method === 'create' &&
        $parameters['model'] === 'gpt-3.5-turbo-instruct' &&
        $parameters['prompt'] === 'PHP is ';
});
// or
$client->completions()->assertSent(function (string $method, array $parameters): bool {
    // ...
});

// assert 2 completion create requests were sent
$client->assertSent(Completions::class, 2);

// assert no completion create requests were sent
$client->assertNotSent(Completions::class);
// or
$client->completions()->assertNotSent();

// assert no requests were sent
$client->assertNothingSent();

要编写期望 API 请求失败的测试,请提供一个 Throwable 对象作为响应。

$client = new ClientFake([
    new \OpenAI\Exceptions\ErrorException([
        'message' => 'The model `gpt-1` does not exist',
        'type' => 'invalid_request_error',
        'code' => null,
    ])
]);

// the `ErrorException` will be thrown
$completion = $client->completions()->create([
    'model' => 'gpt-3.5-turbo-instruct',
    'prompt' => 'PHP is ',
]);

服务

Azure

要使用 Azure OpenAI 服务,您需要手动使用工厂构建客户端。

$client = OpenAI::factory()
    ->withBaseUri('{your-resource-name}.openai.azure.com/openai/deployments/{deployment-id}')
    ->withHttpHeader('api-key', '{your-api-key}')
    ->withQueryParam('api-version', '{version}')
    ->make();

要使用 Azure,您必须部署一个模型(由 {deployment-id} 标识),该模型已包含在 API 调用中。因此,在调用过程中不需要提供模型,因为它已包含在 BaseUri 中。

因此,一个基本的示例完成调用可以是

$result = $client->completions()->create([
    'prompt' => 'PHP is'
]);

OpenAI PHP 是一个开源软件,采用 MIT 许可证