如何優化大型 JSON 檔案以與 ChatGPT API 一起使用?
我正在嘗試使用 ChatGPT 作為我的 Magento 2 網站的聊天機器人,並且我想將產品資料傳遞給它。為此,我收集了所有產品並將它們儲存在一個 JSON 檔案中,然後讀取該檔案以將資料嵌入到系統角色的 systemRoleContent 中。然而,我面臨的問題是 JSON 檔案相當大。
{ "bot_response": "Error: ChatBot Error: Unexpected API response structure: {\n \"error\": {\n \"message\": \"Request too large for gpt-4o on tokens per min (TPM): Limit 30000, Requested 501140. The input or output tokens must be reduced in order to run successfully. Visit https://platform.openai.com/account/rate-limits to learn more.\",\n \"type\": \"tokens\",\n \"param\": null,\n \"code\": \"rate_limit_exceeded\"\n }\n}\n" }
我注意到需要在 API 配置中新增一個功能,該功能允許您執行查詢來根據名稱或描述中與使用者訊息中的關鍵字相符的關鍵字來選擇產品。挑戰在於用戶最初可能不知道產品的名稱;他們來到聊天機器人是為了發現他們。我該如何解決這個問題?
這是我現在正在使用的程式碼:
<?php namespace MetaCares\Chatbot\Model; use Magento\Framework\App\ObjectManager; class ChatBot { private $authorization; private $endpoint; private $conversationHistory = []; private $productsFile; private $fetchingDateFile; private $didFetchProducts = false; public function __construct() { $this->authorization = 'sk-proj-'; $this->endpoint = 'https://api.openai.com/v1/chat/completions'; $this->productsFile = __DIR__ . '/products.json'; $this->fetchingDateFile = __DIR__ . '/fetching_date.json'; $currentTime = time(); $timeDifferenceSeconds = 24 * 3600; if (!file_exists($this->fetchingDateFile)) { file_put_contents($this->fetchingDateFile, json_encode(['last_fetch_time' => 0])); } $fetchingData = json_decode(file_get_contents($this->fetchingDateFile), true); $lastFetchTime = $fetchingData['last_fetch_time'] ?? 0; if ($currentTime - $lastFetchTime > $timeDifferenceSeconds) { $products = $this->fetchProductsUsingModel(); $productsJson = json_encode($products); file_put_contents($this->productsFile, $productsJson); $fetchingData['last_fetch_time'] = $currentTime; file_put_contents($this->fetchingDateFile, json_encode($fetchingData)); $this->didFetchProducts = true; } $jsonSampleData = file_get_contents($this->productsFile); $systemRoleContent = <<<EOT Nom: Meta Cares Bot Description BOT Meta Cares répond aux questions sur les produits du site et fournit des conseils santé fiables. Tu aides les clients de Meta Cares à faire des choix éclairés tout en offrant un accompagnement personnalisé, sécurisé et adapté à leurs besoins. catalogue Meta Cares {$jsonSampleData} Liste des Sites Référencés : - PubMed : [https://pubmed.ncbi.nlm.nih.gov/](https://pubmed.ncbi.nlm.nih.gov/) - ScienceDirect : [https://www.sciencedirect.com/](https://www.sciencedirect.com/) --- - Génération d’images DALL·E : Désactivée EOT; $this->conversationHistory[] = [ 'role' => 'system', 'content' => $systemRoleContent ]; if (session_status() == PHP_SESSION_NONE) { session_start(); } if (isset($_SESSION['chat_history'])) { $this->conversationHistory = $_SESSION['chat_history']; } } public function fetchProductsUsingModel(): array { return $products; } private function getCategoryNames(array $categoryIds): array { return $categoryNames; } public function sendMessage(string $message): array { try { $this->conversationHistory[] = [ 'role' => 'user', 'content' => $message ]; $data = [ 'model' => 'gpt-4o', 'messages' => array_map(function ($msg) { return [ 'role' => $msg['role'] === 'bot' ? 'assistant' : $msg['role'], 'content' => $msg['content'] ]; }, $this->conversationHistory) ]; $response = $this->makeApiRequest($data); $arrResult = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new \Exception('Invalid API response format'); } if (!isset($arrResult['choices']) || !isset($arrResult['choices'][0]['message']['content'])) { throw new \Exception('Unexpected API response structure: ' . $response); } $assistantResponse = $arrResult['choices'][0]['message']['content']; $this->conversationHistory[] = [ 'role' => 'bot', 'content' => $assistantResponse ]; $_SESSION['chat_history'] = $this->conversationHistory; return [ "conversationHistory" => $_SESSION['chat_history'], 'didFetchProducts' => $this->didFetchProducts, 'response' => $assistantResponse, ]; } catch (\Exception $e) { throw new \Exception('ChatBot Error: ' . $e->getMessage()); } } private function makeApiRequest(array $data): string { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $this->endpoint, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'Authorization: Bearer ' . $this->authorization, ], CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0 ]); $response = curl_exec($ch); if (curl_errno($ch)) { $error = curl_error($ch); curl_close($ch); throw new \Exception('API request failed: ' . $error); } curl_close($ch); return $response; } }
以上是如何優化大型 JSON 檔案以與 ChatGPT API 一起使用?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

會話劫持可以通過以下步驟實現:1.獲取會話ID,2.使用會話ID,3.保持會話活躍。在PHP中防範會話劫持的方法包括:1.使用session_regenerate_id()函數重新生成會話ID,2.通過數據庫存儲會話數據,3.確保所有會話數據通過HTTPS傳輸。

RESTAPI設計原則包括資源定義、URI設計、HTTP方法使用、狀態碼使用、版本控制和HATEOAS。 1.資源應使用名詞表示並保持層次結構。 2.HTTP方法應符合其語義,如GET用於獲取資源。 3.狀態碼應正確使用,如404表示資源不存在。 4.版本控制可通過URI或頭部實現。 5.HATEOAS通過響應中的鏈接引導客戶端操作。

在PHP中,異常處理通過try,catch,finally,和throw關鍵字實現。 1)try塊包圍可能拋出異常的代碼;2)catch塊處理異常;3)finally塊確保代碼始終執行;4)throw用於手動拋出異常。這些機制幫助提升代碼的健壯性和可維護性。

匿名類在PHP中的主要作用是創建一次性使用的對象。 1.匿名類允許在代碼中直接定義沒有名字的類,適用於臨時需求。 2.它們可以繼承類或實現接口,增加靈活性。 3.使用時需注意性能和代碼可讀性,避免重複定義相同的匿名類。

在PHP中,include,require,include_once,require_once的區別在於:1)include產生警告並繼續執行,2)require產生致命錯誤並停止執行,3)include_once和require_once防止重複包含。這些函數的選擇取決於文件的重要性和是否需要防止重複包含,合理使用可以提高代碼的可讀性和可維護性。

PHP中有四種主要錯誤類型:1.Notice:最輕微,不會中斷程序,如訪問未定義變量;2.Warning:比Notice嚴重,不會終止程序,如包含不存在文件;3.FatalError:最嚴重,會終止程序,如調用不存在函數;4.ParseError:語法錯誤,會阻止程序執行,如忘記添加結束標籤。

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。
