Using PHP and curl to connect to Assistant

Hi, I am using the below code to point to a custom assistant that I created.
I can’t seem to get the code to actually give me results based on the assistant, it just connects me to a normal chatbot

I tried multiple variations of the code, but for the life of me, I can’t seem to get it to work. Please can someone assist

if (!$api_key) {
    echo json_encode(['error' => 'API key is missing.']);
    exit;
}

// User input from the front end
$user_input = trim($_POST['message'] ?? '');

// Ensure the user input is not empty
if (empty($user_input)) {
    echo json_encode(['error' => 'No message provided.']);
    exit;
}

// OpenAI API endpoint
$url = 'https://api.openai.com/v1/chat/completions';

// Set up the request headers
$headers = [
    'Content-Type: application/json',
    'Authorization: ' . 'Bearer ' . $api_key,
];

// Set up the request body
$data = [
    'model' => 'gpt-4o-mini',  // Adjust the model if necessary
    'messages' => [
        ['role' => 'system', 'content' => 'You are Assistant ID:  {assistant_id}. Behave accordingly. Restrict all answers to the Assistant and do not answer any other questions'],
        ['role' => 'user', 'content' => $user_input]
    ],
];

// Initialize cURL
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

// Execute the API request
$response = curl_exec($ch);

// Check for cURL errors
if ($response === false) {
    echo json_encode(['error' => 'Request Error: ' . curl_error($ch)]);
    curl_close($ch);
    exit;
}

// Close the cURL session
curl_close($ch);

// Decode the API response
$response_data = json_decode($response, true);

// Check for API errors in the response
if (isset($response_data['error'])) {
    echo json_encode(['error' => 'API Error: ' . $response_data['error']['message']]);
    exit;
}

// Validate the response structure
if (isset($response_data['choices']) && isset($response_data['choices'][0]['message']['content'])) {
    $bot_reply = $response_data['choices'][0]['message']['content'];
    $formatted_reply = nl2br(htmlspecialchars($bot_reply));  // Sanitize and format the response
    echo json_encode(['reply' => $formatted_reply]);
} else {
    echo json_encode(['error' => 'Invalid response structure from API.']);
}
?>
1 Like

Hi,

Welcome to the forum.

Assistant or Chat Completion?

https://platform.openai.com/docs/api-reference/assistants/createAssistant

https://platform.openai.com/docs/api-reference/chat

1 Like

I can connect perfectly fine to the chat/completions using my API key.
The problem comes in when I’m trying to access a specific Assistant.

I can create a new assistant from my code, but I can’t get it to access an existing one

https://platform.openai.com/docs/assistants/quickstart

https://platform.openai.com/docs/api-reference/threads

Sorry I haven’t used Assistants yet but believe your answer lies here

2 Likes

To access the Assistant API, you need to use the Assistant endpoint instead of the chatcompletions endpoint.

You can retrieve an Assistant object by specifying the Assistant ID in the following GET request:

curl https://api.openai.com/v1/assistants/asst_abc123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Beta: assistants=v2"

https://platform.openai.com/docs/api-reference/assistants/getAssistant

2 Likes

You could just use this instead of trying to bake your own solution GitHub - openai-php/client: ⚡️ OpenAI PHP is a supercharged community-maintained PHP API client that allows you to interact with OpenAI API.

Thank you. This helped considerably. I managed to call the assistant and create a thread successfully.

When I try to Add the messages, I get the below

[24-Oct-2024 12:13:41 UTC] Array
(
[error] => Array
(
[message] => Missing required parameter: ‘assistant_id’.
[type] => invalid_request_error
[param] => assistant_id
[code] => missing_required_parameter
)

)

Problem is, I have the assistant ID in the $data section, but it doesn’t seem to like that. I also tried adding the assistant ID to the $headers but that failed.

I am now trying to pass it in the $url as you can see, but that still doesnt work

function addMessageToThread($assistant_id, $thread_id, $user_input, $api_key) {
    $url = 'https://api.openai.com/v1/assistants/' . $assistant_id . 'threads/' . $thread_id . '/messages';

    $data = [
        'assistant_id' => $assistant_id,
        'role' => 'user',
        'content' => [
            'type' => 'text',
            'text' => $user_input,
        ]
    ];

    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key,
        'OpenAI-Beta: assistants=v2'
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    $response = curl_exec($ch);

    if ($response === false) {
        echo 'Request Error: ' . curl_error($ch);
        curl_close($ch);
        return null;
    }
    
    curl_close($ch);

    return json_decode($response, true);
}

Hey,

So I think the way this works is:

Sorry I misunderstood OP intent/progress here
  1. You Create Assistant
    This returns assistant_id

  2. You Create Thread
    This returns thread_id

  3. You Create Message where thread_id is known from endpoint
    https://api.openai.com/v1/threads/{thread_id}/messages
    No ‘message_id’ this is attached to thread

  4. You Create Runs where thread_id is known from endpoint assistant_id from payload
    a) https://api.openai.com/v1/threads/{thread_id}/runs
    b) Body: assistant_id=

I’m just reading the manual here and trying to push this forward :slight_smile: , I will sit down later and have another look in a few hours if you still don’t have a fix.

Thanks @phyde1001

Still struggling with this thing. Been staring at the API docs for a full day and I can’t seem to find any reference to the assistant_id being required in this process.

Updated the function and even asked chatgpt but it still throws out: ‘missing required parameters: assistant_id’

Its definitely getting the right assistant ID back and storing it in the session, so not sure

function addMessageToThread($thread_id, $user_input, $api_key) {
    $url = 'https://api.openai.com/v1/threads/' . $thread_id . '/messages';

    $data = [
        'role' => 'user',
        'content' => $user_input,
    ];

    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key,
        'OpenAI-Beta: assistants=v2'
    ];

    error_log('Message Data: ' . json_encode($data));
    error_log('Message Data: ' . json_encode($headers));

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

    $response = curl_exec($ch);

    if ($response === false) {
        echo 'Request Error: ' . curl_error($ch);
        curl_close($ch);
        return null;
    }

    curl_close($ch);

    return json_decode($response, true);
}

Hi!

You are using the chat completions endpoint as the URL.
Thus, you are actually connecting to a standard model instead of your assistant.

I have marked the post from @dignity_for_all as the solution.

Here is the assistants quick start guide from the docs. It should answer your question, as you only need to add your additional code.

https://platform.openai.com/docs/assistants/quickstart

Hope this helps!

1 Like

Ok so just an update here. I can now get my messages to attach to the sessions thread, but Its not sending me back a response, which is extremely weird.

It displays the User input on the thread, but n0o assistant responses

You have to listen for a response when using the threads/assistant API stuff.