这里提供一个简单的示例,使用jQuery和AJAX实现与OpenAI API对话,并在前端实现无刷新的聊天界面。

HTML部分:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat with GPT</title>
    <script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>  <!--GPT Chat UI-->
  <div id='dialogue-container'>
      <h2>Welcome to Chat with GPT!</h2>      <!--Dialogues-->
      <ul id='dialogue'></ul>      <!--Input Form-->
      <form action='#' id='chat-form'> 
          Message: 
          </br>  
              <input type='text' name='message'/>
          </br>    
              <input type ='submit' value= 'Send'/></p>  
          
      </form>
      
   </div><!--Javascript for chat display using AJAX -->
<script type = "text/javascript"> $(function() {
     
     //API request URL
     var api_url = "https://api.openai.com/v1/engines/gpt-3/completions";     
     
     //When the form is submitted
     $('form').submit(function(event){
         
        //Stop form from submitting normally.
         event.preventDefault();        //Get user input message and append it to dialog list   
         var msg = $('#chat-input').val();
         $('<li class="user-message"/>').text(msg).appendTo('#dialogue');
         
        //Make API call to Open AI's GPT engine        
        $.ajax({
            url: api_url,
            headers: {
                'Authorization': 'Bearer '+ YOUR_API_SECRET_KEY,
                'Content-Type': 'application/json'
                  },
                         method: "POST",
             data:
                 JSON.stringify(
                     {"prompt": msg,
                      "temperature":0.5,
                      "max_tokens":100}
                                ),               success:function(response){                    console.log(response);
                    
                    response_text=response.choices[0].text;   
                                       $('<li class="bot-message"/>').text(response_text.trim()).appendTo('#dialogue');                     
                  
                     
                    $("#chat-input").focus().val("");                    
              
            },            
             error:function(){
                 alert("Server Error");
                 
             }
             
         });
         
       
       return false;
     });  
    
});</script>
</body>
</html>

发表评论

电子邮件地址不会被公开。 必填项已用*标注