2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ChatGPT APIを、SpringBootを用いて実装してみる。

Posted at

作ったものはこんな感じ

Ajaxを用いて、非同期処理を実行し、JSON形式でChatGPT APIにアクセスしています。
解説が雑で申し訳ありません。タイミングをみて解説を記載します

ezgif.com-video-to-gif.gif

■HTML

index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>OpenAI Chat Bot</title>
<script th:src="@{/js/chatgpt.js}"></script>
</head>
<body>
	<div class="chat-input-area">
		<input type="text" id="input-field"/>
		<input type="button" value="送信" id="send-button">
	</div>
	<div class="chat-response-area">
	</div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
</html>

■JS

chatgpt.js
window.onload = function(){
	$('#send-button').on('click', function() {
		const message = $('#input-field').val();
		sendRequest(message);
	});
};
//OpenAI APIにリクエストを送信する処理
function sendRequest(message) {
	$.ajax({
		url: "/openAiChat",
		type: "POST",
		contentType: "application/json",
		data: JSON.stringify({
			message : message
		})
	}).done(function(response) {
		$('.chat-response-area').html('<p>' + insertNewlines(response) + '</p>');
	}).fail(function() {
		console.log("きてない");
	});
}

// 。(句点)ごとに改行コードを挿入する。
function insertNewlines(str) {
  var result = '';
  var len = str.length;
  var i = 0;
  while (i < len) {
    var substr = str.substring(i, i + 10);
    var idx = substr.lastIndexOf('');
    if (idx !== -1) {
      result += substr.substring(0, idx + 1) + '<br>';
      i += idx + 1;
    } else {
      result += substr;
      i += 10;
    }
  }
  return result;
}

■Java(Controller)

ChatAjaxController.java
package com.chatgpt.web.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import com.chatgpt.web.dto.Message;
import com.chatgpt.web.utility.PropertyUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

@RestController
@RequestMapping("")
public class ChatAjaxController {
    // APIのURL
	private static final String URL = PropertyUtil.getProperty("api.url");
    // API Keyを取得(本来は環境変数に設定しておく方が良いです。現状はプロパティファイルから取得しています。)
	private static final String API_KEY = PropertyUtil.getProperty("api.key");

	@PostMapping("/openAiChat")
    public ResponseEntity<String> openAiChat(@RequestBody Message messages) { 
        //ChatGPTのバージョン
    	String model = "gpt-3.5-turbo";
        // 送信したいメッセージ
    	String message = "{\"role\": \"system\", \"content\": \"返答は日本語で\"},{\"role\": \"user\", \"content\": \" "+ messages.getMessage() +" \"}";
    	String content =  "";
    	try {
    		// HTTPリクエストの作成
    		URL obj = new URL(URL);
    		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    		con.setRequestMethod("POST");
    		con.setRequestProperty("Content-Type", "application/json");
    		con.setRequestProperty("Authorization", "Bearer " + API_KEY);
    		con.setDoOutput(true);

    		// リクエストの送信
    		OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
    		out.write("{\"model\": \"" + model + "\", \"messages\": [" + message + "]}");
    		out.close();

    		// レスポンスの取得
    		BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    		Gson gson = new Gson();
    		JsonObject jsonResponse = gson.fromJson(in, JsonObject.class);
    		JsonArray choicesArray = jsonResponse.getAsJsonArray("choices");
    		JsonObject messageObject = choicesArray.get(0).getAsJsonObject().get("message").getAsJsonObject();
    		content = messageObject.get("content").getAsString();

    	} catch (Exception e) {
    		System.out.println(e);
    	}  
    	return new ResponseEntity<>(content, HttpStatus.OK);
    }
}

 ■参考(ほぼこの方のパクリです。)

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?