apiBase}/sources/add-file"); $cfile = new CURLFile($pdfPath, 'application/pdf', basename($pdfPath)); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => ['file' => $cfile], CURLOPT_HTTPHEADER => [ "x-api-key: {$this->apiKey}" ], CURLOPT_RETURNTRANSFER => true, ]); $response = curl_exec($ch); curl_close($ch); $result = json_decode($response, true); return $result['sourceId'] ?? null; } // Esegue una domanda al PDF caricato public function askPdf($sourceId, $question) { $apiKey = $_ENV['CHATPDF_API_KEY'] ?? null; if (!$apiKey) { throw new Exception("ChatPDF API key not found in .env"); } $url = "https://api.chatpdf.com/v1/chats/message"; $payload = json_encode([ "sourceId" => $sourceId, "messages" => [ [ "role" => "user", "content" => $question ] ] ]); $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => [ "x-api-key: $apiKey", "Content-Type: application/json" ], CURLOPT_POSTFIELDS => $payload, ]); $response = curl_exec($ch); if (curl_errno($ch)) { throw new Exception('cURL error: ' . curl_error($ch)); } curl_close($ch); $data = json_decode($response, true); // Debug temporaneo file_put_contents( __DIR__ . '/../debug_chatpdf.log', "Question: {$question}\nResponse: {$response}\n\n", FILE_APPEND ); if (isset($data['content'])) { return trim($data['content']); } // ChatPDF a volte restituisce una lista di risposte if (isset($data[0]['content'])) { return trim($data[0]['content']); } return null; } }