[chatGPT] How to use ChatGPT API in PHP : PHP에서 ChatGPT API를 사용하는 방법

The ChatGPT API is a tool that allows developers to integrate OpenAI's language model into their software applications. This Answer will guide you through the application of the ChatGPT API in PHP, from account setup and API key acquisition to executing requests to the ChatGPT API endpoint utilizing PHP’s cURL library.

 

Steps to use ChatGPT API in PHP

Acquire API credentials

To start using the ChatGPT API, you first need to obtain your API credentials. This involves creating an OpenAI account and generating your API key. This key is crucial as it grants access to your OpenAI resources.

Configure your PHP environment

Next, your development environment needs to be correctly configured. This entails the installation of cURL, a library enabling HTTP requests from PHP, and Composer, a dependency management utility for PHP. You'll also need to establish a new PHP project or utilize an existing one to incorporate the ChatGPT API.

Install the OpenAI PHP SDK

The OpenAI PHP SDK is a handy tool that lets you interact with the ChatGPT API from within your PHP software. You can install the SDK by executing the command composer require openai/api in your PHP project directory. Upon completion of the installation, you can import the OpenAI PHP SDK into your PHP files using the respective code:

 
 
 
 

Make API requests

With your PHP environment set up and the SDK installed, you can initiate API requests to the ChatGPT API. Here's a demonstration of how a chat-based response can be generated using the API.

 
 
 
 
Code explanation
  • Line 1: Instantiate the OpenAI class with your API key.

  • Line 3: Call the complete method on the OpenAI instance. The result of the method is stored in $response.

  • Line 4: Specify the model parameter as gpt-3.5-turbo.

  • Lines 5–8: Define the messages parameter as an array of message objects. Each object has a 'role' (either 'system' or 'user') and 'content' (the actual message).

  • Line 9: Set the temperature parameter to 0.6, controlling the randomness of the model's output.

Optimum practices

To ensure the efficiency of your implementation, consider the following optimal practices when employing the ChatGPT API in PHP:

  • Batching requests: Rather than executing individual API calls for each user interaction, consider batching multiple messages together to reduce latency and cost.

  • Managing rate limits: The ChatGPT API has rate limits implemented. Ensure you handle rate limit errors gracefully by implementing adequate error handling and retry logic.

  • Cleansing user inputs: Like any user-generated content, it’s crucial to sanitize and validate inputs to prevent any inappropriate content from being sent to the API.

  • Experimenting with parameters: Modifying the temperature parameter enables you to regulate the randomness of the response. Experiment with different values to find the right balance for your application.

Example

Consider a scenario where a lengthy text input exceeds the maximum token limit of the ChatGPT API. The text is a discussion between a user and an assistant about a complex topic. The conversation is too extensive to fit within the token limit, necessitating the need to fragment it into smaller sections.

Firstly, it is vital to understand that the ChatGPT API accepts a series of messages as input and delivers a model-generated message as output. Each message has a role (which can be 'system', 'user', or 'assistant') and content (the text of the message from the role).

To fragment the conversation, we can follow these steps:

  1. Identify natural breaks: Identify natural breaks in the conversation where the text can be split without losing context. These could be at the conclusion of a topic or question.

  2. Fragment the text: Split the text at the identified breaks to create smaller sections. Each section should be within the token limit of the ChatGPT API.

  3. Dispatch each section to the API: Send each section to the API as a separate message. The 'system' message can be used to define the behavior of the assistant, and the 'user' messages can be the sections of the conversation.

Here's an example of how you can fragment a longer conversation into smaller sections:

 
 
 
 

Conclusion

By adhering to the steps outlined in this Answer, you can effectively utilize the ChatGPT API in PHP. Remember to stick to the best practices, such as batching requests and cleansing user inputs, to ensure the efficiency and effectiveness of your implementation.

[출처] https://www.educative.io/answers/how-to-use-chatgpt-api-in-php

ChatGPT API는 개발자가 OpenAI의 언어 모델  소프트웨어 애플리케이션에 통합할 수 있는 도구입니다. 이 답변은 계정 설정 및 API 키 획득부터 PHP 라이브러리 를 활용하여 ChatGPT API 엔드포인트에 대한 요청 실행에 이르기까지 PHP에서 ChatGPT API를 적용하는 과정을 안내합니다 .cURL

 

PHP에서 ChatGPT API를 사용하는 단계

API 자격 증명 획득

ChatGPT API 사용을 시작하려면 먼저 API 자격 증명을 얻어야 합니다 . 여기에는 OpenAI 계정 생성 및 API 키 생성이 포함됩니다. 이 키는 OpenAI 리소스에 대한 액세스 권한을 부여하므로 매우 중요합니다.

PHP 환경 구성

다음으로 개발 환경을 올바르게 구성해야 합니다. 이를 위해서는 PHPcURL 의 HTTP 요청을 활성화하는 라이브러리인 와 PHP용 종속성 관리 유틸리티인 Composer를 설치해야 합니다 . 또한 ChatGPT API를 통합하려면 새 PHP 프로젝트를 설정하거나 기존 프로젝트를 활용해야 합니다.

OpenAI PHP SDK 설치

OpenAI PHP SDK는 PHP 소프트웨어 내에서 ChatGPT API와 상호 작용할 수 있는 편리한 도구입니다. composer require openai/apiPHP 프로젝트 디렉터리에서 명령을 실행하여 SDK를 설치할 수 있습니다 . 설치가 완료되면 해당 코드를 사용하여 OpenAI PHP SDK를 PHP 파일로 가져올 수 있습니다.

 
 
 
 

API 요청하기

PHP 환경이 설정되고 SDK가 설치되면 ChatGPT API에 대한 API 요청을 시작할 수 있습니다. 다음은 API를 사용하여 채팅 기반 응답을 생성하는 방법에 대한 데모입니다.

 
 
 
 
코드 설명
  • 1행 : API 키를 사용하여 OpenAI 클래스를 인스턴스화합니다.

    경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
    어린이용이며, 설치가 필요없는 브라우저 게임입니다.
    https://s1004games.com

  • 3행 : completeOpenAI 인스턴스에서 메서드를 호출합니다. 메소드의 결과는 에 저장됩니다 $response.

  • 4행 : model매개변수를 로 지정합니다 gpt-3.5-turbo.

  • 5~8행 : messages매개변수를 메시지 객체의 배열로 정의합니다. 각 개체에는 '역할'('시스템' 또는 '사용자')과 '콘텐츠'(실제 메시지)가 있습니다.

  • 9행 : temperature매개변수를 0.6으로 설정하여 모델 출력의 무작위성을 제어합니다.

최적의 사례

구현 효율성을 보장하려면 PHP에서 ChatGPT API를 사용할 때 다음과 같은 최적의 방법을 고려하십시오.

  • 요청 일괄 처리 : 각 사용자 상호 작용에 대해 개별 API 호출을 실행하는 대신 여러 메시지를 일괄 처리하여 대기 시간과 비용을 줄이는 것이 좋습니다.

  • 속도 제한 관리 : ChatGPT API에는 속도 제한이 구현되어 있습니다. 적절한 오류 처리 및 재시도 논리를 구현하여 비율 제한 오류를 원활하게 처리하도록 하세요.

  • 사용자 입력 정리 : 사용자 생성 콘텐츠와 마찬가지로 부적절한 콘텐츠가 API로 전송되는 것을 방지하기 위해 입력을 삭제하고 검증하는 것이 중요합니다.

  • 매개변수 실험 : 온도 매개변수를 수정하면 응답의 무작위성을 조절할 수 있습니다. 다양한 값으로 실험하여 애플리케이션에 적합한 균형을 찾으세요.

긴 텍스트 입력이 ChatGPT API의 최대 토큰 제한을 초과하는 시나리오를 생각해 보세요. 텍스트는 복잡한 주제에 관해 사용자와 어시스턴트 간의 토론입니다. 대화가 너무 광범위하여 토큰 한도에 맞지 않으므로 더 작은 섹션으로 분할해야 합니다.

첫째, ChatGPT API가 일련의 메시지를 입력으로 받아들이고 모델 생성 메시지를 출력으로 전달한다는 점을 이해하는 것이 중요합니다. 각 메시지에는 역할('시스템', '사용자' 또는 '도우미'일 수 있음)과 콘텐츠(역할의 메시지 텍스트)가 있습니다.

대화를 조각화하려면 다음 단계를 따르세요.

  1. 자연스러운 중단 식별 : 대화에서 맥락을 잃지 않고 텍스트를 분할할 수 있는 자연스러운 중단을 식별합니다. 이는 주제나 질문의 ​​결론일 수 있습니다.

  2. 텍스트 조각화 : 식별된 구분선에서 텍스트를 분할하여 더 작은 섹션을 만듭니다. 각 섹션은 ChatGPT API의 토큰 제한 내에 있어야 합니다 .

  3. 각 섹션을 API에 디스패치 : 각 섹션을 별도의 메시지로 API에 보냅니다. '시스템' 메시지는 어시스턴트의 동작을 정의하는 데 사용될 수 있으며 '사용자' 메시지는 대화의 섹션이 될 수 있습니다.

다음은 긴 대화를 더 작은 섹션으로 분할하는 방법에 대한 예입니다.

 
 
 
 

결론

이 답변에 설명된 단계를 따르면 PHP에서 ChatGPT API를 효과적으로 활용할 수 있습니다. 구현의 효율성과 효과를 보장하려면 일괄 요청 및 사용자 입력 정리와 같은 모범 사례를 준수해야 합니다.

 

 

 

 

 

 

 

 

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED