umstellen auf python

This commit is contained in:
2024-11-18 17:25:59 +01:00
parent e388918000
commit 5d9b1fa8a5
2 changed files with 41 additions and 10 deletions

23
api.php
View File

@@ -1,23 +1,26 @@
<?php <?php
// Einbinden der Konfigurationsdatei // Include the configuration file
require_once 'config.php'; require_once 'config.php';
// Überprüfen, ob eine POST-Anfrage gesendet wurde // Check if a POST request is sent
if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Lesen der Eingabe aus dem POST-Body
$input = json_decode(file_get_contents('php://input'), true); $input = json_decode(file_get_contents('php://input'), true);
$user_message = $input['message']; $user_message = $input['message'];
// Hier würden Sie den API-Aufruf an OpenAI mit den Konfigurationsvariablen durchführen // Prepare the command to execute the Python script
// Dies ist ein Platzhalter für die tatsächliche API-Implementierung // Note: Make sure `python` or `python3` is properly configured in your system's PATH.
$response = "Dies ist eine Beispielantwort vom ChatGPT-Assistenten."; $command = escapeshellcmd("python3 assistant.py '$user_message'");
$output = shell_exec($command);
// Senden der Antwort zurück an das Frontend // Decode the response from Python script
$response = json_decode($output, true);
// Send back the response
header('Content-Type: application/json'); header('Content-Type: application/json');
echo json_encode(['response' => $response]); echo json_encode(['response' => $response['response']]);
} else { } else {
// Wenn keine POST-Anfrage, senden Sie einen Fehler // If not a POST request, return an error
header('HTTP/1.1 405 Method Not Allowed'); header('HTTP/1.1 405 Method Not Allowed');
echo 'Nur POST-Anfragen sind erlaubt.'; echo 'Only POST requests are allowed.';
} }
?> ?>

28
assistant.py Normal file
View File

@@ -0,0 +1,28 @@
import sys
import openai
import json
def main(user_message):
# Set your OpenAI API key from the environment, or replace with your key here
openai.api_key = "sk-proj-CMVUSsmXIr-Da3a8bpAByG0v2FD1hxEahGs7CqTz7tcegAWGP03OitAAD5LQVf_z5ZUucDWZ10pSHXJVzoWZeGCHueskkC5IMLccUldlvTlsfUA"
try:
# Call the OpenAI ChatCompletion API
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": user_message}],
assistant_id="asst_0LyJEWQS90Sx0oEIYBVWE47C" # Assistant ID
)
assistant_message = response['choices'][0]['message']['content']
print(json.dumps({"response": assistant_message}))
except Exception as e:
print(json.dumps({"response": f"An error occurred: {str(e)}"}))
if __name__ == "__main__":
if len(sys.argv) > 1:
user_message = sys.argv[1]
main(user_message)
else:
print(json.dumps({"response": "No message provided"}))