api/lookup.php now branches on \$AI_PROVIDER in config.php ('anthropic' or
'openai'). Claude uses the existing Anthropic SDK path; OpenAI is called
via a plain cURL request (Chat Completions, JSON response_format) to avoid
a second SDK dependency. Only the selected provider's key needs to be set.
162 lines
5.9 KiB
PHP
162 lines
5.9 KiB
PHP
<?php
|
|
// Serverseitiger Endpunkt: nimmt eine frei getippte Automarke/Modell entgegen und lässt eine
|
|
// KI plausible Kofferraum-Kenndaten dafür schätzen. Welcher Anbieter genutzt wird (Claude oder
|
|
// OpenAI), legt config.php fest — der jeweilige API-Key bleibt ausschließlich auf dem Server
|
|
// und wird nie an den Browser ausgeliefert.
|
|
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
header('Cache-Control: no-store');
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405);
|
|
echo json_encode(['error' => 'Nur POST erlaubt.']);
|
|
exit;
|
|
}
|
|
|
|
$provider = getenv('AI_PROVIDER') ?: null;
|
|
$anthropicKey = getenv('ANTHROPIC_API_KEY') ?: null;
|
|
$openaiKey = getenv('OPENAI_API_KEY') ?: null;
|
|
$openaiModel = null;
|
|
|
|
$configFile = __DIR__ . '/config.php';
|
|
if (file_exists($configFile)) {
|
|
require $configFile;
|
|
$provider = $provider ?: ($AI_PROVIDER ?? null);
|
|
$anthropicKey = $anthropicKey ?: ($ANTHROPIC_API_KEY ?? null);
|
|
$openaiKey = $openaiKey ?: ($OPENAI_API_KEY ?? null);
|
|
$openaiModel = $OPENAI_MODEL ?? null;
|
|
}
|
|
|
|
$provider = $provider ?: 'anthropic';
|
|
$openaiModel = $openaiModel ?: 'gpt-4o-mini';
|
|
|
|
$body = json_decode(file_get_contents('php://input'), true);
|
|
$query = trim((string)($body['query'] ?? ''));
|
|
|
|
if ($query === '' || mb_strlen($query) > 80) {
|
|
http_response_code(400);
|
|
echo json_encode(['error' => 'Ungültige Anfrage.']);
|
|
exit;
|
|
}
|
|
|
|
$systemPrompt = <<<SYS
|
|
Du lieferst Kenndaten für ein 3D-Vorschau-Tool eines Auto-HiFi-Shops, das aus Marke/Modell
|
|
eine stark vereinfachte, parametrische Kofferraum-Näherung generiert.
|
|
|
|
Antworte AUSSCHLIESSLICH mit einem einzelnen JSON-Objekt, keine Erklärung, kein Markdown, keine Code-Fences.
|
|
|
|
Wenn du das Fahrzeug erkennst, exakt dieses Format:
|
|
{"found":true,"brand":"...","model":"...","bodyType":"Kombi|Kompaktklasse|Limousine|Kompakt-SUV|Mittelklasse-SUV|Van|Kleinwagen|Sportwagen|...","cargoLiters":000,"cargoLitersMax":000,"length_mm":000,"widthFloor_mm":000,"widthShoulder_mm":000,"height_mm":000,"sillHeight_mm":000,"underFloorDepth_mm":000}
|
|
|
|
Wenn du das Fahrzeug nicht plausibel zuordnen kannst:
|
|
{"found":false}
|
|
|
|
Regeln:
|
|
- length_mm/widthFloor_mm/widthShoulder_mm/height_mm sind die INNENMASSE des Laderaums (nicht die Außenmaße des Autos), realistisch in der Größenordnung 400-1300mm.
|
|
- widthShoulder_mm ist die Breite oben (Schulterhöhe) und immer >= widthFloor_mm (Breite unten zwischen den Radkästen).
|
|
- cargoLitersMax ist das Volumen bei umgeklappten Rücksitzen; falls nicht sinnvoll (z. B. 2-Sitzer), null.
|
|
- underFloorDepth_mm ist die Tiefe der Reserverad-/Staumulde unter dem Ladeboden; falls es die nicht gibt, null.
|
|
- Werte sind grobe, plausible Schätzungen basierend auf deinem Wissen über das Fahrzeug, keine exakten Herstellerangaben.
|
|
- Wenn die Anfrage kein erkennbares Auto ist (z. B. Unsinn oder ein anderes Objekt), antworte {"found":false}.
|
|
SYS;
|
|
|
|
try {
|
|
if ($provider === 'openai') {
|
|
if (!$openaiKey) {
|
|
throw new RuntimeException('Kein OpenAI API-Key konfiguriert. api/config.example.php nach api/config.php kopieren, AI_PROVIDER auf "openai" setzen und OPENAI_API_KEY eintragen.');
|
|
}
|
|
$text = lookupViaOpenAI($query, $systemPrompt, $openaiKey, $openaiModel);
|
|
} else {
|
|
if (!$anthropicKey) {
|
|
throw new RuntimeException('Kein Anthropic API-Key konfiguriert. api/config.example.php nach api/config.php kopieren und ANTHROPIC_API_KEY eintragen.');
|
|
}
|
|
$text = lookupViaClaude($query, $systemPrompt, $anthropicKey);
|
|
}
|
|
} catch (\Throwable $e) {
|
|
http_response_code(502);
|
|
echo json_encode(['error' => 'KI-Anfrage fehlgeschlagen: ' . $e->getMessage()]);
|
|
exit;
|
|
}
|
|
|
|
if (!preg_match('/\{.*\}/s', $text, $m)) {
|
|
http_response_code(502);
|
|
echo json_encode(['error' => 'Antwort konnte nicht gelesen werden.']);
|
|
exit;
|
|
}
|
|
|
|
$data = json_decode($m[0], true);
|
|
if (!is_array($data)) {
|
|
http_response_code(502);
|
|
echo json_encode(['error' => 'Antwort konnte nicht gelesen werden.']);
|
|
exit;
|
|
}
|
|
|
|
echo json_encode($data);
|
|
|
|
// ---------- Anbieter ----------
|
|
|
|
function lookupViaClaude(string $query, string $systemPrompt, string $apiKey): string
|
|
{
|
|
require __DIR__ . '/vendor/autoload.php';
|
|
|
|
$client = new \Anthropic\Client(apiKey: $apiKey);
|
|
|
|
$message = $client->messages->create(
|
|
model: 'claude-opus-5',
|
|
maxTokens: 1024,
|
|
outputConfig: ['effort' => 'low'],
|
|
system: $systemPrompt,
|
|
messages: [
|
|
['role' => 'user', 'content' => $query],
|
|
],
|
|
);
|
|
|
|
$text = '';
|
|
foreach ($message->content as $block) {
|
|
if ($block->type === 'text') {
|
|
$text .= $block->text;
|
|
}
|
|
}
|
|
return $text;
|
|
}
|
|
|
|
function lookupViaOpenAI(string $query, string $systemPrompt, string $apiKey, string $model): string
|
|
{
|
|
$payload = [
|
|
'model' => $model,
|
|
'response_format' => ['type' => 'json_object'],
|
|
'max_tokens' => 1024,
|
|
'messages' => [
|
|
['role' => 'system', 'content' => $systemPrompt],
|
|
['role' => 'user', 'content' => $query],
|
|
],
|
|
];
|
|
|
|
$ch = curl_init('https://api.openai.com/v1/chat/completions');
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_POST => true,
|
|
CURLOPT_HTTPHEADER => [
|
|
'Content-Type: application/json',
|
|
'Authorization: Bearer ' . $apiKey,
|
|
],
|
|
CURLOPT_POSTFIELDS => json_encode($payload),
|
|
CURLOPT_TIMEOUT => 30,
|
|
]);
|
|
$raw = curl_exec($ch);
|
|
$curlError = curl_error($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
|
|
if ($raw === false) {
|
|
throw new RuntimeException('OpenAI-Verbindung fehlgeschlagen: ' . $curlError);
|
|
}
|
|
|
|
$decoded = json_decode($raw, true);
|
|
if ($httpCode >= 400) {
|
|
$msg = $decoded['error']['message'] ?? ('HTTP ' . $httpCode);
|
|
throw new RuntimeException('OpenAI-Fehler: ' . $msg);
|
|
}
|
|
|
|
return $decoded['choices'][0]['message']['content'] ?? '';
|
|
}
|