35428-vm/api/analyze_chat.php
Flatlogic Bot 2e3424ad5c v.2
2025-11-02 19:42:55 +00:00

104 lines
4.1 KiB
PHP

<?php
// api/analyze_chat.php
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/config.php';
header('Content-Type: application/json');
$json = file_get_contents('php://input');
$data = json_decode($json, true);
if (!isset($data['session_id'], $data['persona'], $data['history'])) {
http_response_code(400);
echo json_encode(['error' => 'Invalid input. session_id, persona, and history are required.']);
exit;
}
$sessionId = $data['session_id'];
$persona = $data['persona'];
$history = $data['history'];
// --- System Prompt & API Call (remains the same) ---
$system_prompt = "You are a market research analyst. Your task is to analyze a conversation between an entrepreneur and a potential customer persona. The persona's details and the conversation are provided below.\n\n"
. "**Persona Profile:**\n"
. "- Name: {$persona['name']}\n"
. "- Age: {$persona['age']}\n"
. "- Occupation: {$persona['occupation']}\n"
. "- Traits: {$persona['traits']}\n"
. "- Concerns: {$persona['concerns']}\n"
. "- Style: {$persona['style']}\n\n"
. "**Your Analysis Should Include:**\n"
. "1. **Key Takeaways:** A bulleted list of the most important points from the conversation.\n"
. "2. **Persona's Sentiment:** A brief assessment (Positive, Negative, Neutral, Mixed) of the persona's overall feeling about the business idea, with a brief justification.\n"
. "3. **Actionable Insights:** A bulleted list of concrete suggestions for the entrepreneur to improve their idea based on the persona's feedback.\n\n"
. "Please format your response in simple HTML, using <h3> for titles and <ul> and <li> for lists. Do not include <html>, <head>, or <body> tags.";
$conversation_text = "";
foreach ($history as $msg) {
$sender = $msg['sender'] === 'user' ? 'Entrepreneur' : $persona['name'];
$conversation_text .= "**{$sender}:** {$msg['message']}\n";
}
$user_content = "Please analyze the following conversation:\n\n{$conversation_text}";
$messages = [[ 'role' => 'user', 'content' => $user_content ]];
$apiKey = defined('ANTHROPIC_API_KEY') ? ANTHROPIC_API_KEY : '';
if (empty($apiKey) || $apiKey === 'YOUR_ANTHROPIC_API_KEY') {
http_response_code(500);
echo json_encode(['error' => 'Anthropic API key is not configured.']);
exit;
}
$payload = [
'model' => 'claude-3-sonnet-20240229',
'system' => $system_prompt,
'messages' => $messages,
'max_tokens' => 1024,
'temperature' => 0.5,
];
$ch = curl_init('https://api.anthropic.com/v1/messages');
// ... (cURL options remain the same)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'x-api-key: ' . $apiKey,
'anthropic-version: 2023-06-01'
]);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($curl_error || $httpcode >= 400) {
http_response_code($httpcode > 0 ? $httpcode : 500);
$error_details = json_decode($response, true);
echo json_encode(['error' => 'Anthropic API Error', 'details' => $error_details, 'curl_error' => $curl_error]);
exit;
}
$result = json_decode($response, true);
$analysisContent = $result['content'][0]['text'] ?? null;
if ($analysisContent) {
// --- Save analysis to DB ---
try {
$pdo = db();
// Use INSERT ... ON DUPLICATE KEY UPDATE to avoid creating multiple analyses for one session.
// Note: This requires a UNIQUE index on session_id in the analyses table.
// For simplicity here, we'll just insert. A more robust app would handle this better.
$stmt = $pdo->prepare("INSERT INTO analyses (session_id, content) VALUES (?, ?)");
$stmt->execute([$sessionId, $analysisContent]);
} catch (Exception $e) {
error_log('Database error while saving analysis: ' . $e->getMessage());
}
echo json_encode(['analysis' => $analysisContent]);
} else {
http_response_code(500);
echo json_encode(['error' => 'Unexpected API response structure for analysis.', 'details' => $result]);
}