phpopenai-apichatgpt-apigpt-4chat-gpt-4

Chat GPT 4 API connect with PHP using file upload feature


I am trying to connect to gpt-4 API using php. I have a paid account and a valid API key. I use the API key all the time, with gpt-3.5.-turbo model.

I have created an assistant in my account. I want to connect to that assistant and create a new thread for each user that uploads a file. For each file uploaded, I need to return 3 email subjects regarding the file content.

Here is my code:

$api_key = 'sk-xx'; // Replace with your actual OpenAI API Key
$assistant_id = 'asst_xx'; // Your assistant ID

// Handle file upload from the form
$file_path = "test.txt";

// Step 1: Upload the file
$ch = curl_init('https://api.openai.com/v1/files');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $api_key));
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'purpose' => 'assistants',
    'file' => new CURLFile($file_path),
));
$response_upload = curl_exec($ch);
$info_upload = curl_getinfo($ch);
curl_close($ch);

$file_response = json_decode($response_upload, true);

if (isset($file_response['id'])) {
    $file_id = $file_response['id'];

    // Step 2: Create a new thread with the user's message and the attached file
    $ch = curl_init("https://api.openai.com/v1/threads?assistant_id=$assistant_id"); // Include assistant_id as a URL parameter
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key,
        'OpenAI-Beta: assistants=v1'
    ]);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        'messages' => [
            [
                'role' => 'user',
                'content' => 'I want 3 email subjects based on the content of the uploaded file',
                'file_ids' => [$file_id]
            ]
            
        ]
    ]));

    $thread_creation_response = curl_exec($ch);
    curl_close($ch);

    // Output the response for debugging
    print_r($file_response);
    print_r($thread_creation_response);
    $thread_creation_data = json_decode($thread_creation_response, true);
    echo 'thread-id: ' . $thread_creation_data['id'] . '<br>';

    // Step 3: Get the assistant's response
    $ch = curl_init("https://api.openai.com/v1/threads/".$thread_creation_data['id']."/messages");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $api_key,
        'OpenAI-Beta: assistants=v1',
        'Content-Type: application/json', // Add this line to specify the content type
    ]);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        'role' => 'user',
        'content' => 'I want 3 email subjects based on the content of the uploaded file',
        'file_ids' => [$file_id]
    ]));

    $thread_response = curl_exec($ch);
    curl_close($ch);

    // Decode the JSON response from the assistant
    $thread_data = json_decode($thread_response, true);

    // Extract and display the entire assistant's response
    echo "Assistant's Response:<br>";
    print_r($thread_data);


} else {
    // Handle the case where the file upload response does not contain the expected data
    echo "Error uploading file.";
}

The output is:

Array ( 
    [object] => file 
    [id] => file-yyy 
    [purpose] => assistants 
    [filename] => test.txt 
    [bytes] => 1174 
    [created_at] => 1701688272 
    [status] => processed 
    [status_details] => 
    ) 
    { 
        "id": "thread_mmm", 
        "object": "thread", 
        "created_at": 1701688274,
        "metadata": {} 
    }
    thread-id: thread_mmm 

Assistant's Response:

Array ( 
    [id] => msg_uuu 
    [object] => thread.message 
    [created_at] => 1701688275 
    [thread_id] => thread_mmm 
    [role] => user 
    [content] => Array ( 
        [0] => Array ( 
            [type] => text 
            [text] => Array ( 
                [value] => I want 3 email subjects based on the content of the uploaded file 
                [annotations] => Array ( ) 
            ) 
        ) 
    ) 
    [file_ids] => Array ( 
        [0] => file-yyy 
    ) 
    [assistant_id] => 
    [run_id] => 
    [metadata] => Array ( ) 
)

It seems to upload the file, returns the file id, creates a new thread, it returns the thread id but then it does not return the 3 email subjects that I asked for.

Please help!

Thank you!


Solution

  • Got it! The 'run' link should be re-runned (maybe with a sleep of 2-3 seconds) until status is 'completed', or 'failed' or 'cancelled' or 'expired'. Then, if 'completed' (means everything ok), retrieve messages from "https://api.openai.com/v1/threads/".$thread_data['id']."/messages", and it should contain the required output.

    Thank you!