[Work In Progress] OpenAI Integration

Helpdesk for my helpdesk software

Moderator: mkoch227

Post Reply
bradheffernan
Posts: 5
Joined: Fri Jun 13, 2025 3:51 pm

[Work In Progress] OpenAI Integration

Post by bradheffernan »

Hi all,
I have been working on OpenAI integration to rewrite my reply's in a more professional manner.
Its a rough draft but functional.
Im sharing for the pro's to take it and run with it to make it so much better. My PHP programming knowledge is limited in comparison.

BACKUP OR MAKE COPIES BEFORE ALTERING!!

EDIT #2:
I have made more changes adding the settings to the Admin -> Hesk Settings option on Admin page.
OpenAI Hesk Documentation / Download
I have simplified it, Only manual edit is adding the settings to hesk_settings.inc.php
Then Extract the downloaded php files to your /admin or renamed admin folder.

This will allow you to tweak the OpenAI responses settings.

Image

OLD METHOD:

hesk_settings.inc.php
Add the following to your settings php.

Code: Select all


// --> OpenAI settings
$hesk_settings['openai_enable']=1;
$hesk_settings['openai_model']='gpt-4.1-nano-2025-04-14'; // change to your proffered model
$hesk_settings['openai_max_tokens']=300;
$hesk_settings['openai_temperature']=0.7;
$hesk_settings['openai_api_key'] = 'API_KEY_CHANGE_ME';
$hesk_settings['openai_system_prompt'] = "Your name is Theodore, Your role is a <YOUR COMPANY> IT Manager dedicated to supporting and helping staff and customers. Your mission is to solve issues, answer questions, and provide guidance on IT-related matters. You are here to assist with any technical challenges that arise, ensuring a smooth and efficient IT experience for everyone at <YOUR COMPANY>.";
$hesk_settings['openai_user_prompt'] = "Rewrite the draft reply to be more helpful and complete."

admin_ticket.php
Forum Post Edit: I added the button to click to create the AI suggestion. Sorry forgot to add this on original post.
Find:

Code: Select all

<div class="block--message" id="message-block">
Below Add:

Code: Select all

<?php
                if ($can_delete && $hesk_settings['openai_enable'] == 1) { ?>
                    <button type="button" id="openai-suggest" class="btn btn-border" style="margin-bottom:10px;">Suggest with AI</button>
                    <div id="openai-loading" style="display:none;">Generating suggestion...</div>
                <?php } ?>
Find:

Code: Select all

</script>

<!-- END REPLY FORM -->
above insert: (at the bottom of </script>)

Code: Select all

document.getElementById('openai-suggest').addEventListener('click', function() {
    var toxEditor = tinymce.get('message');
    // console.log(toxEditor.getContent({format: 'text'}));
    // console.log(document.getElementById('message').value);
    // var customerMessage = 'fetched ticket info; // get the ticket information or customer message if needed
    var draftReply = toxEditor ? toxEditor.getContent({format: 'text'}) : document.getElementById('message').value;
    if (!draftReply.trim()) {
        alert('Please enter some ticket details before requesting an AI suggestion.');
        return;
    }
    var prompt = /*"Customer message:\n" + customerMessage + "\n\n*/"Draft reply:\n" + draftReply + "\n\n" + <?php $hesk_settings['openai_user_prompt']; ?> 
    
    document.getElementById('openai-loading').style.display = 'block';
    fetch('openai_suggest.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'prompt=' + encodeURIComponent(prompt)
    })
    .then(response => response.json())
    .then(data => {
        document.getElementById('openai-loading').style.display = 'none';
        console.log(data); // debuging output
        if (data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content) {
            if (toxEditor) {
                toxEditor.setContent(data.choices[0].message.content.replace(/\n/g, '<br>'));
            } else {
                document.getElementById('message').value = data.choices[0].message.content;
            }
        } else if (data.error) {
            alert('AI suggestion failed: ' + (typeof data.error === 'object' ? JSON.stringify(data.error) : data.error));
        } else {
            alert('AI suggestion failed: Unknown error');
        }
    });
});
openai_suggest.php
Add this to the your admin folder (or your renamed admin folder)

Code: Select all

<?php
define('IN_SCRIPT', 1);
require_once('../hesk_settings.inc.php');

header('Content-Type: application/json');

if (!isset($_POST['prompt']) || empty($hesk_settings['openai_api_key'])) {
    echo json_encode(['error' => 'Missing prompt or API key']);
    exit;
}

$prompt = $_POST['prompt'];
$apiKey = $hesk_settings['openai_api_key'];

$prompt = isset($_POST['prompt']) ? trim($_POST['prompt']) : '';
if ($prompt === '') {
    echo json_encode(['error' => 'Prompt cannot be empty']);
    exit;
}
if (!isset($hesk_settings['openai_model']) || !isset($hesk_settings['openai_system_prompt']) || !isset($hesk_settings['openai_max_tokens']) || !isset($hesk_settings['openai_temperature'])) {
    echo json_encode(['error' => 'OpenAI settings are not properly configured']);
    exit;
}
if (!function_exists('curl_init')) {
    echo json_encode(['error' => 'cURL is not installed on the server']);
    exit;
}
$data = [
    'model' => $hesk_settings['openai_model'],
    'messages' => [
        ['role' => 'system', 'content' => $hesk_settings['openai_system_prompt']],
        ['role' => 'user', 'content' => $prompt]
    ],
    'max_tokens' => $hesk_settings['openai_max_tokens'],
    'temperature' => $hesk_settings['openai_temperature'],
];

$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey,
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
    echo json_encode(['error' => curl_error($ch)]);
    exit;
}
curl_close($ch);

$result = json_decode($response, true);

if ($http_code !== 200 || isset($result['error'])) {
    echo json_encode(['error' => $result['error']['message'] ?? 'Unknown error from OpenAI']);
    exit;
}

echo $response;
Last edited by bradheffernan on Sun Jun 22, 2025 12:45 am, edited 4 times in total.
shddcit
Posts: 60
Joined: Wed Mar 30, 2022 3:54 pm

Re: [Work In Progress] OpenAI Integration

Post by shddcit »

bradheffernan wrote: Sat Jun 21, 2025 9:46 am Hi all,
I have been working on OpenAI integration to rewrite my reply's in a more professional manner.
Its a rough draft but functional.
Im sharing for the pro's to take it and run with it to make it so much better. My PHP programming knowledge is limited in comparison.
Hello.

I’ve done something similar before, but using the Mistral API. The problem was that Mistral doesn't support server-to-server API communication directly. So I had to create a separate proxy script — Hesk would first call this file, and then the file itself would make the request to Mistral. But honestly, I got too lazy to finish it and eventually abandoned the idea.

So does OpenAI allow direct server-to-server communication?
bradheffernan
Posts: 5
Joined: Fri Jun 13, 2025 3:51 pm

Re: [Work In Progress] OpenAI Integration

Post by bradheffernan »

Im not sure to be honest. I just use the platform.openai.com to fine-tune AI models for my use-case.
If you are using self hosted LLM models then i cant comment on this sorry. I havent used them enough to know.

I have updated the original post with my update adding the settings to the Hesk Desk settings page on Admin.

Thanks, all.
bradheffernan
Posts: 5
Joined: Fri Jun 13, 2025 3:51 pm

Re: [Work In Progress] OpenAI Integration

Post by bradheffernan »

Update #3
Corrected issue with button click of openai suggestion button.
First post contains the link to documentation with download of updated files.

Fixed:
- fixed jQuery for button
- corrected permissions
- fixed settings saved issue for OpenAI Settings from admin
- works with TinyMCE

Still to fix:
- It is not linked to WYSIWYG yet.
Klemen
Site Admin
Posts: 10139
Joined: Fri Feb 11, 2005 4:04 pm

Re: [Work In Progress] OpenAI Integration

Post by Klemen »

Thank you very much for sharing this. I've been working on integrating OpenAI a while ago, but didn't have time for more than a proof of concept.

Definitely something we should include in the next larger Hesk release.
Klemen, creator of HESK and PHPJunkyardWas this helpful? You can buy me a drink here Image

Image You should follow me on Twitter here

Help desk software | Cloud help desk | Guestbook | Link manager | Click counter | more PHP Scripts ...

Also browse for php hosting companies, read php books, find php resources and use webmaster tools
shddcit
Posts: 60
Joined: Wed Mar 30, 2022 3:54 pm

Re: [Work In Progress] OpenAI Integration

Post by shddcit »

Klemen wrote: Sun Jun 22, 2025 8:05 am Thank you very much for sharing this. I've been working on integrating OpenAI a while ago, but didn't have time for more than a proof of concept.

Definitely something we should include in the next larger Hesk release.
Klemen, please also consider the possibility of using APIs from Mistral, QwenLM and Deepseek neural networks.
The problem is that OpenAI is unavailable in Russia, and using it via a PHP server through a VPN is not a very good idea.
I'm sure users from countries where the use of OpenAI is prohibited will appreciate your step.

In our mail server, the developer has also already implemented a kind of AI-based email formatting, and it has become really convenient. As for me, I personally use the email client EMClient, which also includes AI-powered formatting.
Post Reply