Integrating an Azure AI Foundry Chatbot into Your Website

March 11, 2025

In a previous post, I detailed the process of deploying an AI model with Azure AI Foundry. Now, in this article, I’ll guide you through integrating it into a website as a chatbot.

The idea is to have a PHP file on the server that will deal with the AI endpoint. This file will receive JavaScript Ajax requests from the frontend, pass them to the AI endpoint, receive the reply then return it to the frontend.

We can check the endpoint in Postman. In the chat playground, go to ‘View Code’ to copy the endpoint URL and API key.

We make a new POST request in Postman using the endpoint address and the API key. We configure the headers like below:

For the body of the request we use the json paylod from chat playground, then we click send. If everything works we should see a response:

Now, we can go ahead and build the website chatbot.

A basic page with a text area for the response and input as below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI demo</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
        background-color:#000;
        }
         #textField {
            width: 100%; /* Full width on smaller screens */
            max-width: 300px; /* Maximum width on larger screens */
            padding: 10px;
            margin-bottom: 10px;
            box-sizing: border-box;
        }
        #responseArea {
            width: 100%; /* Full width on smaller screens */
            max-width: 400px; /* Maximum width on larger screens */
            height: 450px;
            padding: 10px;
            resize: vertical;
            box-sizing: border-box;
        }
    pre { text-wrap: auto; }
    </style>
</head>
<body>
    <input type="text" id="textField" placeholder="Enter text here"><br />
<div id="responseArea"></div>
    <script>
        function decodeHtml(html) {
            var txt = document.createElement("textarea");
            txt.innerHTML = html;
            return txt.value;
        }


        document.getElementById('textField').addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                var xhr = new XMLHttpRequest();
               
                xhr.open('POST', 'server.php', true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
               
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        var responseArea = document.getElementById('responseArea');
                        responseArea.innerHTML += '<div style="color:white;text-align:right">' + e.target.value + '<span style="background-color:#000;padding:10px;border-radius:5px;border:1px solid #ccc">you</span></div><br /><div style="color:#45d5bc"><span style="background-color:#000;padding:10px;border-radius:5px;border:1px solid #ccc">AI</span>' + decodeHtml(xhr.responseText) + "</div><br>";
                       
                        responseArea.scrollTop = responseArea.scrollHeight;
                       
                        document.getElementById('textField').value = '';
                    } else {
                        console.error('Request failed.  Returned status of ' + xhr.status);
                    }
                };
               
                xhr.send('text=' + encodeURIComponent(e.target.value));
                e.preventDefault();
            }
        });
    </script>
</body>
</html>

What the frontend does:

  • defines an input field for the user - textField
  • defines a text area to contain the chat replies - responseArea
  • listening for a keypress event for Enter key
  • when Enter key is pressed it send the payload to server.php file as a POST request
  • if server.php returns 200 then it appends the response to the responseArea

The server.php file will be like this:

<?php


$query = $_POST['text'];


// URL of the API endpoint
$url = 'https://ai-singularity032116301814.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2025-01-01-preview&api-key=3uzEKEBJM4c7pdiCDVvHywrlqdcwF3KzXkn3AukT3NhhCU54JhCtJQQJ99BCACfhMk5XJ3w3AAAAACOGflh1';


// JSON data to send
$data = [
    'messages' => [
        ['role' => 'system', 'content' => 'You are an AI assistant crested by Valentin Valeanu. Your job is to help Valentin to demonstrate how Azure AI Foundry works for a tutorial on his blog.'],
        ['role' => 'user', 'content' => $query]
    ],
    'max_tokens' => 1000,
    'model' => 'gpt-4',
    'temperature' => 0.7,
    'top_p' => 0.95,
    'stop' => null,
    'stream' => false,
    'frequency_penalty' => 0,
    'presence_penalty' => 0
];


// Encode the data to JSON
$payload = json_encode($data);
// Initialize cURL session
$ch = curl_init($url);


// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the transfer as a string of the return value of curl_exec()
curl_setopt($ch, CURLOPT_POST, true); // Set this to a POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); // Set the POST data
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);


// Execute the cURL session
$response = curl_exec($ch);


// Check if any error occurred
if(curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
} else {
    // Close cURL session
    curl_close($ch);
   
    // Decode the JSON response
    $decodedResponse = json_decode($response, true);
   
    // Output the response
    echo '<pre>';
    print_r($decodedResponse['choices'][0]['message']['content']);
    echo '</pre>';
}

?>

This file is a basic example, if you want to use it in production you should secure it, address the input sanitization, XSS protection and so on.

  • It will receive the user input from the JavaScript ajax request and store it in the $query variable.
  • It will construct the json paylod along with the system prompt.
  • It will initiate a cURL session to the API endpoint and return the response which will then returned to the frontend.

* no API keys survived this demo 😉

Featured image created with Grok.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.