Как интегрировать ChatGPT в WordPress?

Ссылка скопирована
1 ответ

Необходимо сделать в личном кабинете пользователя на сайте (WordPress) вкладку, где он сможет в поле вставить свой текст на немецком языке и нажать кнопку "Проверить" и там же в личном кабинете он получит анализ своего текста с указанием ошибок. В ChatGPT такое есть. Хотелоьс бы понимать, вожно ли это интегрировать в личный кабинет пользователя. Есть преположение что такое можно по API, предоставляет ли ChatGPT такое?

Дополнительно:

ChatGPT сам не может?)

  • Спрашивали у него) Не хочет..
  • Ответы:

    Да, на сайте есть документация по API https://platform.openai.com/docs/guides/gpt

    Вот пример запроса и работы функции. 100% работу не гарантирую, т.к. несколько раз переписывал функцию, а у них выходят новые модели и изменения в запросах API, поэтому вам нужно будет все проверить и сделать настройки передаваемых аргументов под конкретную задачу

    if ( ! function_exists( 'get_chatgpt_responce' ) ) {  	/** 	 * Returns query result or error 	 * 	 * @param string $question Text API question. 	 * @param string $promt    Text API promt (for chat). 	 * @param string $model    API model. 	 * @param string $api_key  API key. 	 * 	 * @return void 	 */ 	function get_chatgpt_responce( $question = null, $promt = null, $model = 'gpt-3.5-turbo', $api_key = 'sk-le000000000000000000000000000000000000' ) {  		if ( is_null( $question ) ) { 			return null; 		}  		$type = 'text';  		if ( $model === 'davinci-codex' ) { 			$type = 'codex'; 		}  		if ( in_array( $model, array( 'gpt-4', 'gpt-4-0314', 'gpt-4-32k', 'gpt-4-32k-0314', 'gpt-3.5-turbo', 'gpt-3.5-turbo-0301' ), true ) ) { 			$type = 'chat'; 		}  		$headers = "Content-Type: application/jsonrn" . "Authorization: Bearer " . $api_key . "rn";  		$params = array( 			'model'       => $model, 			'temperature' => 0.7, 			'top_p'       => 1, 		);  		if ( $type === 'chat' ) { 			$url         = 'https://api.openai.com/v1/chat/completions'; 			$params['n'] = 1; 			if ( ! is_null( $promt ) ) { 				$params['messages'][] = array( 					'role'    => 'system', 					'content' => $promt, 				); 			} 			$params['messages'][] = array( 				'role'    => 'user', 				'content' => $question, 			); 		} elseif( $type === 'codex' ) { 			$url                  = 'https://api.openai.com/v1/engines/davinci-codex/completions'; 			$params['prompt']     = $question; 			$params['max_tokens'] = 4096 - iconv_strlen( $question ); 		} else { 			$url                  = 'https://api.openai.com/v1/completions'; 			$params['prompt']     = $question; 			$params['max_tokens'] = 4096 - iconv_strlen( $question ); 		}  		$args = array( 			'method'       => 'POST', 			'timeout'      => 240, 			'redirection'  => 5, 			'httpversion'  => '1.0', 			'blocking'     => true, 			'headers'      => $headers, 			'body'         => json_encode( $params ), 			'sslverify'    => true, 		);  		$response = wp_remote_request( $url, $args );  		if ( is_wp_error( $response ) ) { 			$notification = $response->get_error_message(); 		} elseif ( in_array( wp_remote_retrieve_response_code( $response ), array( 400, 401, 403, 404 ), true ) ) { 			$body         = json_decode( wp_remote_retrieve_body( $response ), true ); 			$notification = $body['error']['message']; 		} elseif ( wp_remote_retrieve_response_code( $response ) === 200 ) { 			$body         = json_decode( wp_remote_retrieve_body( $response ), true ); 			$notification = 'Расход GPT токенов: ' . $body['usage']['total_tokens'] . '. Причина остановки: ' . $body['choices'][0]['finish_reason'];  			if ( $type === 'chat' ) { 				return $body['choices'][0]['message']['content']; 			} else { 				return $body['choices'][0]['text']; 			} 		}  		if ( function_exists( 'telegram_notification' ) ) { 			telegram_notification( $notification ); 		}  		return false; 	} }  $query   = 'Write a list frequently asked questions about the get_the_title() WordPress function.'; $chatgpt = get_chatgpt_responce( $query ); var_dump( $chatgpt );

    if ( ! function_exists( 'get_chatgpt_responce' ) ) { /** * Returns query result or error * * @param string $question Text API question. * @param string $promt Text API promt (for chat). * @param string $model API model. * @param string $api_key API key. * * @return void */ function get_chatgpt_responce( $question = null, $promt = null, $model = 'gpt-3.5-turbo', $api_key = 'sk-le000000000000000000000000000000000000' ) { if ( is_null( $question ) ) { return null; } $type = 'text'; if ( $model === 'davinci-codex' ) { $type = 'codex'; } if ( in_array( $model, array( 'gpt-4', 'gpt-4-0314', 'gpt-4-32k', 'gpt-4-32k-0314', 'gpt-3.5-turbo', 'gpt-3.5-turbo-0301' ), true ) ) { $type = 'chat'; } $headers = "Content-Type: application/jsonrn" . "Authorization: Bearer " . $api_key . "rn"; $params = array( 'model' => $model, 'temperature' => 0.7, 'top_p' => 1, ); if ( $type === 'chat' ) { $url = 'https://api.openai.com/v1/chat/completions'; $params['n'] = 1; if ( ! is_null( $promt ) ) { $params['messages'][] = array( 'role' => 'system', 'content' => $promt, ); } $params['messages'][] = array( 'role' => 'user', 'content' => $question, ); } elseif( $type === 'codex' ) { $url = 'https://api.openai.com/v1/engines/davinci-codex/completions'; $params['prompt'] = $question; $params['max_tokens'] = 4096 - iconv_strlen( $question ); } else { $url = 'https://api.openai.com/v1/completions'; $params['prompt'] = $question; $params['max_tokens'] = 4096 - iconv_strlen( $question ); } $args = array( 'method' => 'POST', 'timeout' => 240, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => $headers, 'body' => json_encode( $params ), 'sslverify' => true, ); $response = wp_remote_request( $url, $args ); if ( is_wp_error( $response ) ) { $notification = $response->get_error_message(); } elseif ( in_array( wp_remote_retrieve_response_code( $response ), array( 400, 401, 403, 404 ), true ) ) { $body = json_decode( wp_remote_retrieve_body( $response ), true ); $notification = $body['error']['message']; } elseif ( wp_remote_retrieve_response_code( $response ) === 200 ) { $body = json_decode( wp_remote_retrieve_body( $response ), true ); $notification = 'Расход GPT токенов: ' . $body['usage']['total_tokens'] . '. Причина остановки: ' . $body['choices'][0]['finish_reason']; if ( $type === 'chat' ) { return $body['choices'][0]['message']['content']; } else { return $body['choices'][0]['text']; } } if ( function_exists( 'telegram_notification' ) ) { telegram_notification( $notification ); } return false; } } $query = 'Write a list frequently asked questions about the get_the_title() WordPress function.'; $chatgpt = get_chatgpt_responce( $query ); var_dump( $chatgpt );

    Нужно решить такую задачу?

    Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

    Заказать помощь
    Лучший ответ
    1
    Артём Dev Ответ

    Да, такую проверку текста можно встроить в личный кабинет WordPress через API OpenAI. Архитектура должна быть такой: пользователь отправляет текст AJAX-запросом на ваш сервер, WordPress проверяет авторизацию и nonce, сервер делает запрос к OpenAI API, получает ответ и возвращает результат пользователю. API-ключ нельзя хранить на фронтенде.

    Минимальный серверный обработчик лучше делать в отдельном плагине:

    add_action('wp_ajax_check_german_text', function () {
        check_ajax_referer('check_german_text');
     
        if (! is_user_logged_in()) {
            wp_send_json_error('Требуется авторизация', 403);
        }
     
        $text = isset($_POST['text']) ? wp_strip_all_tags(wp_unslash($_POST['text'])) : '';
     
        if ($text === '') {
            wp_send_json_error('Передан пустой текст', 400);
        }
     
        $response = wp_remote_post('https://api.openai.com/v1/responses', [
            'timeout' => 60,
            'headers' => [
                'Authorization' => 'Bearer ' . OPENAI_API_KEY,
                'Content-Type'  => 'application/json',
            ],
            'body' => wp_json_encode([
                'model' => 'gpt-4.1-mini',
                'input' => 'Проверь немецкий текст, перечисли ошибки и предложи исправленную версию: ' . $text,
            ]),
        ]);
     
        if (is_wp_error($response)) {
            wp_send_json_error($response->get_error_message(), 500);
        }
     
        wp_send_json_success(json_decode(wp_remote_retrieve_body($response), true));
    });

    add_action('wp_ajax_check_german_text', function () { check_ajax_referer('check_german_text'); if (! is_user_logged_in()) { wp_send_json_error('Требуется авторизация', 403); } $text = isset($_POST['text']) ? wp_strip_all_tags(wp_unslash($_POST['text'])) : ''; if ($text === '') { wp_send_json_error('Передан пустой текст', 400); } $response = wp_remote_post('https://api.openai.com/v1/responses', [ 'timeout' => 60, 'headers' => [ 'Authorization' => 'Bearer ' . OPENAI_API_KEY, 'Content-Type' => 'application/json', ], 'body' => wp_json_encode([ 'model' => 'gpt-4.1-mini', 'input' => 'Проверь немецкий текст, перечисли ошибки и предложи исправленную версию: ' . $text, ]), ]); if (is_wp_error($response)) { wp_send_json_error($response->get_error_message(), 500); } wp_send_json_success(json_decode(wp_remote_retrieve_body($response), true)); });

    В продакшене добавьте лимиты: максимальная длина текста, ограничение количества проверок на пользователя, логирование ошибок без хранения лишних персональных данных и обработку стоимости запросов. Если личный кабинет сделан WooCommerce/MemberPress/Elementor, вкладку лучше добавлять штатными hooks конкретного кабинета, а не правкой core или файлов плагина.

    Другие ответы (0)

    Пока нет других ответов. Будьте первым, кто поможет автору.

    Ответить на вопрос

    комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    Вам также может быть интересно