Hello,
I would create my own chat, and have two files (index.html, and server.php):
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT Assistent</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.chat-box { border: 1px solid #ccc; padding: 10px; width: 100%; max-width: 600px; height: 400px; overflow-y: scroll; }
.input-area { margin-top: 10px; }
.input-area input { width: 30%; padding: 10px; }
.input-area button { padding: 10px 20px; }
</style>
</head>
<body>
<h1>ChatGPT Assistent</h1>
<!-- API-Key Eingabeformular -->
<div class="api-key-form">
<p>
<label for="api-key">API-Key eingeben:</label>
<input type="text" id="api-key" placeholder="API-Key hier eingeben" />
<button onclick="saveApiKey()">Speichern</button>
</p>
</div>
<!-- Dropdown-Menü zum Auswählen des Assistenten -->
<label for="assistant-type">Wähle einen Assistenten:</label>
<select id="assistant-type">
<option value="asst_0PFsPfI3hdaPArlcBwKpxfqo">Pascal-Support</option>
<option value="cafe_chat">Cafe Unterhaltung</option>
</select>
<div class="chat-box" id="chat-box"></div>
<div class="input-area">
<input type="text" id="user-input" placeholder="Deine Nachricht eingeben..." />
<button onclick="sendMessage()">Senden</button>
</div>
<script>
// API-Key speichern
function saveApiKey() {
const apiKey = document.getElementById('api-key').value;
if (apiKey) {
localStorage.setItem('apiKey', apiKey); // Speichert den API-Key lokal
alert("API-Key gespeichert!");
} else {
alert("Bitte API-Key eingeben.");
}
}
// Funktion zum HinzufĂĽgen von Nachrichten zum Chat
function addMessageToChat(message, sender) {
const chatBox = document.getElementById('chat-box');
const messageElement = document.createElement('p');
messageElement.textContent = sender + ": " + message;
chatBox.appendChild(messageElement);
chatBox.scrollTop = chatBox.scrollHeight;
}
function sendMessage() {
const userInput = document.getElementById('user-input').value;
if (userInput === "") return;
// Benutzer-Nachricht anzeigen
addMessageToChat(userInput, "Du");
// API-Key aus dem lokalen Speicher abrufen
const apiKey = localStorage.getItem('apiKey');
if (!apiKey) {
alert("Bitte einen API-Key eingeben.");
return;
}
// AJAX-Anfrage an PHP-Datei senden
const xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true); // PHP-Datei angeben
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
addMessageToChat(response.response, "Assistent");
}
};
const data = JSON.stringify({ message: userInput, apiKey: apiKey });
xhr.send(data);
// Eingabefeld zurĂĽcksetzen
document.getElementById('user-input').value = '';
}
</script>
</body>
</html>
and the php file server.php
<?php
// POST-Daten empfangen
$data = json_decode(file_get_contents('php://input'), true);
$user_message = $data['message'];
$api_key = $data['apiKey']; // Den API-Key aus der Anfrage abrufen
if (!$api_key) {
echo json_encode(['response' => 'Kein API-Key vorhanden.']);
exit();
}
// Anfrage an OpenAI senden
$openai_url = 'https://api.openai.com/v1/completions';
$prompt = "User: $user_message\nAI:";
$options = [
'http' => [
'header' => [
"Content-Type: application/json",
"Authorization: Bearer $api_key",
],
'method' => 'POST',
'content' => json_encode([
'prompt' => $prompt,
'max_tokens' => 150,
'temperature' => 0.7,
'model' => 'gpt-3.5-turbo'
]),
]
];
$context = stream_context_create($options);
$response = file_get_contents($openai_url, false, $context);
// Antwort parsen und zurĂĽckgeben
if ($response === FALSE) {
$error = error_get_last(); // Detaillierte Fehlernachricht abrufen
echo json_encode(['response' => 'Fehler beim Abrufen der Antwort von der OpenAI API.', 'error' => $error]);
exit();
} else {
$result = json_decode($response, true);
$assistant_response = $result['choices'][0]['text'];
echo json_encode(['error' => trim($assistant_response)]);
}
when I go to the browser, and save the api key, I get Error on Line: “if ($response === FALSE) {”.
So the Question is, how can I setup API and or fix the logging problem ?
1 Like
Heya. Welcome back. Good to see you again.
Are you getting an error message? I haven’t looked at your code, but checking the return object for an error message or checking server error logs might help.
1 Like
above the response: “Fehler beim Abrufen der Antwort von der OpenAI API.”
This is German, and translated to English: “Error during request the response from the OpenAI API.”
So, it looks like the API-key does not fit in case.
I have create a new security project key (user keys are out of date), copied this to the clipboard, and from there into the HTML Application.
Then save the key with the “Speichern” Button.
And when I enter text into the input line, and click the send button, the response will be empty.
Either my code is wrong, or something else goes on there.
1 Like
I’d try to get the error code in the response, but it sounds like a 429 or you didn’t set the new API key up with the right permissions?
Here’s a list of all the error codes for reference…
https://platform.openai.com/docs/guides/error-codes
I’m guessing one of these?
401 - Incorrect API key provided Cause: The requesting API key is not correct.
Solution: Ensure the API key used is correct, clear your browser cache, or generate a new one .
401 - You must be a member of an organization to use the API Cause: Your account is not part of an organization.
Solution: Contact us to get added to a new organization or ask your organization manager to invite you to an organization .
403 - Country, region, or territory not supported Cause: You are accessing the API from an unsupported country, region, or territory.
Solution: Please see this page for more information.
429 - Rate limit reached for requests Cause: You are sending requests too quickly.
Solution: Pace your requests. Read the Rate limit guide .
429 - You exceeded your current quota, please check your plan and billing details Cause: You have run out of credits or hit your maximum monthly spend.
Solution: Buy more credits or learn how to increase your limits .
I check the error result:
file_get_contents(https://api.openai.com/v1/completions ): Failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
so the api url is not correct ?
2 Likes
Sounds like it. Sorry, I didn’t look closely at your code.
I’d check Model Endpoint Compatibility in the docs.
https://platform.openai.com/docs/models/model-endpoint-compatibility
Are you using old code?
Think you need to use cURL and not send POST request…
I’d look around for current example. The API Docs should have current PHP code… or cURL…
yes, a little bit extended:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT Assistent</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.chat-box { border: 1px solid #ccc; padding: 10px; width: 100%; max-width: 600px; height: 400px; overflow-y: scroll; }
.input-area { margin-top: 10px; }
.input-area input { width: 30%; padding: 10px; }
.input-area button { padding: 10px 20px; }
</style>
</head>
<body>
<h1>ChatGPT Assistent</h1>
<!-- API-Key Eingabeformular -->
<div class="api-key-form">
<p>
<label for="api-key">API-Key eingeben:</label>
<input type="text" id="api-key" placeholder="API-Key hier eingeben" />
<button onclick="saveApiKey()">Speichern</button>
</p>
</div>
<!-- Dropdown-Menü zum Auswählen des Assistenten -->
<label for="assistant-type">Wähle einen Assistenten:</label>
<select id="assistant-type">
<option value="asst_0PFsPfI3hdaPArlcBwKpxfqo">Pascal-Support</option>
<option value="cafe_chat">Cafe Unterhaltung</option>
</select>
<div class="chat-box" id="chat-box"></div>
<div class="input-area">
<input type="text" id="user-input" placeholder="Deine Nachricht eingeben..." />
<button onclick="sendMessage()">Senden</button>
</div>
<script>
// API-Key speichern
function saveApiKey() {
const apiKey = document.getElementById('api-key').value;
if (apiKey) {
localStorage.setItem('apiKey', apiKey); // Speichert den API-Key lokal
alert("API-Key gespeichert!");
} else {
alert("Bitte API-Key eingeben.");
}
}
// Funktion zum HinzufĂĽgen von Nachrichten zum Chat
function addMessageToChat(message, sender) {
const chatBox = document.getElementById('chat-box');
const messageElement = document.createElement('p');
messageElement.textContent = sender + ": " + message;
chatBox.appendChild(messageElement);
chatBox.scrollTop = chatBox.scrollHeight;
}
function sendMessage() {
const userInput = document.getElementById('user-input').value;
if (userInput === "") return;
// Benutzer-Nachricht anzeigen
addMessageToChat(userInput, "Du");
// API-Key aus dem lokalen Speicher abrufen
const apiKey = localStorage.getItem('apiKey');
if (!apiKey) {
alert("Bitte einen API-Key eingeben.");
return;
}
// AJAX-Anfrage an PHP-Datei senden
const xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true); // PHP-Datei angeben
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 0)
alert("request not initialized ");
if (xhr.readyState === 1)
alert("server connection established");
if (xhr.readyState === 2)
alert("request received ");
if (xhr.readyState === 3)
alert("processing request ");
if (xhr.readyState === 4)
alert("request finished and response is ready");
if (xhr.status === 401)
alert("incorrect API key");
if (xhr.status === 429)
alert("rate limit");
if (xhr.status === 500)
alert("internal server error");
if (xhr.status === 503)
alert("engine overloaded, try later");
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
addMessageToChat(response.response, "Assistent");
addMessageToChat(response.error.message, "xxx");
}
};
const data = JSON.stringify({ message: userInput, apiKey: apiKey });
xhr.send(data);
// Eingabefeld zurĂĽcksetzen
document.getElementById('user-input').value = '';
}
</script>
</body>
</html>
I don’t have a ton of time at the moment, but I would check the docs.
I shared some PHP / cURL code here but for DALLE model…
After a request the other day from @Daller , I threw together a quick and simple solution with just two PHP files—one for the backend, one for the form—and some vanilla JavaScript (no libraries, just good old AJAX and cURL). Kept it basic to make things easy for those new to DALLE API.
The images are pulled from a URL that DALL·E 3 gives you, but they won’t last forever, so you’ll want to download them if you want to hang onto them. Or, if you’re feeling adventurous, you can modify the code to s…
Might give you some pointers, though!
Everything is laid out well here…
https://platform.openai.com/docs/api-reference/introduction
1 Like
ok, I get it done.
I give the wrong Endpoint.
Here comes the a working copy of a chat WebSite…
index.html:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT Assistent</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.chat-box { border: 1px solid #ccc; padding: 10px; width: 100%; max-width: 600px; height: 400px; overflow-y: scroll; }
.input-area { margin-top: 10px; }
.input-area input { width: 30%; padding: 10px; }
.input-area button { padding: 10px 20px; }
</style>
</head>
<body>
<h1>ChatGPT Assistent</h1>
<!-- API-Key Eingabeformular -->
<div class="api-key-form">
<p>
<label for="api-key">API-Key eingeben:</label>
<input type="text" id="api-key" placeholder="API-Key hier eingeben" />
<button onclick="saveApiKey()">Speichern</button>
</p>
</div>
<!-- Dropdown-Menü zum Auswählen des Assistenten -->
<label for="assistant-type">Wähle einen Assistenten:</label>
<select id="assistant-type">
<option value="asst_0PFsPfI3hdaPArlcBwKpxfqo">Pascal-Support</option>
<option value="cafe_chat">Cafe Unterhaltung</option>
</select>
<div class="chat-box" id="chat-box"></div>
<div class="input-area">
<input type="text" id="user-input" placeholder="Deine Nachricht eingeben..." />
<button onclick="sendMessage()">Senden</button>
</div>
<script>
// API-Key speichern
function saveApiKey() {
const apiKey = document.getElementById('api-key').value;
if (apiKey) {
localStorage.setItem('apiKey', apiKey); // Speichert den API-Key lokal
alert("API-Key gespeichert!");
} else {
alert("Bitte API-Key eingeben.");
}
}
// Funktion zum HinzufĂĽgen von Nachrichten zum Chat
function addMessageToChat(message, sender) {
const chatBox = document.getElementById('chat-box');
const messageElement = document.createElement('p');
messageElement.textContent = sender + ": " + message;
chatBox.appendChild(messageElement);
chatBox.scrollTop = chatBox.scrollHeight;
}
function sendMessage() {
const userInput = document.getElementById('user-input').value;
if (userInput === "") return;
// Benutzer-Nachricht anzeigen
addMessageToChat(userInput, "Du");
// API-Key aus dem lokalen Speicher abrufen
const apiKey = localStorage.getItem('apiKey');
if (!apiKey) {
alert("Bitte einen API-Key eingeben.");
return;
}
// AJAX-Anfrage an PHP-Datei senden
const xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true); // PHP-Datei angeben
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
if (response.error) {
addMessageToChat(response.error.message, "error");
}
addMessageToChat(response.response, "Assistent");
}
};
const data = JSON.stringify({ message: userInput, apiKey: apiKey });
xhr.send(data);
// Eingabefeld zurĂĽcksetzen
document.getElementById('user-input').value = '';
}
</script>
</body>
server.php:
<?php
// POST-Daten empfangen
$data = json_decode(file_get_contents('php://input'), true);
$user_message = $data['message'];
$api_key = $data['apiKey']; // Den API-Key aus der Anfrage abrufen
if (!$api_key) {
echo json_encode(['response' => 'Kein API-Key vorhanden.']);
exit();
}
// Korrekte API-URL fĂĽr chat-based completion
$openai_url = 'https://api.openai.com/v1/chat/completions';
// Anfrage-Daten vorbereiten
$post_fields = json_encode([
'model' => 'gpt-3.5-turbo', // gpt-3.5-turbo Modell
'messages' => [
['role' => 'user', 'content' => $user_message]
],
'max_tokens' => 150,
'temperature' => 0.7
]);
// Header und Optionen fĂĽr die Anfrage
$options = [
'http' => [
'header' => [
"Content-Type: application/json",
"Authorization: Bearer $api_key",
],
'method' => 'POST',
'content' => $post_fields,
]
];
// Anfrage senden
$context = stream_context_create($options);
$response = file_get_contents($openai_url, false, $context);
// Antwort parsen und zurĂĽckgeben
if ($response === FALSE) {
$error = error_get_last();
echo json_encode(['response' => 'Fehler beim Abrufen der Antwort von der OpenAI API.', 'error' => $error]);
exit();
}
$result = json_decode($response, true);
$assistant_response = $result['choices'][0]['message']['content'];
echo json_encode(['response' => trim($assistant_response)]);
?>
2 Likes