openai-php / client

⚡️ OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.
MIT License
4.99k stars 523 forks source link

[Bug]: Cannot upload file from php://temp stream #498

Closed supriyo-biswas closed 2 weeks ago

supriyo-biswas commented 2 weeks ago

Description

I'm unable to use streams based on php://temp to upload files, which results in an OpenAI\Exceptions\ErrorException being thrown with the message The browser (or proxy) sent a request that this server could not understand.

However, I am able to use regular files in the upload files API.

For my use case, I'd like to avoid writing an on-disk file, and therefore would like to have the ability to upload a php://temp file.

Steps To Reproduce

Running the following code will help reproduce the error:

<?php

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

$client = OpenAI::client(getenv('OPENAI_API_KEY'));

$data = <<<'EOM'
{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}

EOM;

$stream = fopen('php://temp', 'r+');
fwrite($stream, $data);
rewind($stream);

$fileResponse = $client->files()->upload(
    parameters: [
        'purpose' => 'batch',
        'file' => $stream,
    ]
);

$fileId = $fileResponse->id;
dump($fileId);

Changing the above code to the following, and saving the content of the file in a batch.json file resolves the issue:

<?php
// ...
$stream = fopen('batch.jsonl', 'r+');

$fileResponse = $client->files()->upload(
    parameters: [
        'purpose' => 'batch',
        'file' => $stream,
    ]
);
// ...

OpenAI PHP Client Version

v0.10.2

PHP Version

8.3.6

Notes

No response

gehrisandro commented 2 weeks ago

Hi @supriyo-biswas

Not sure if this is something we can fix on our side.

If you find a solution, feel free to submit a PR.