LoginSignup
0
0

More than 1 year has passed since last update.

ChatGPT API Ajax連携

Posted at

今日までの進捗まとめ

■HTML

ブラウザはシンプル
スクリーンショット 2023-03-03 12.12.34.png

ポイント id名
送信ボタン send-button
<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>OpenAI Chat Bot</title>
</head>
<body>
	<input type="text" id="input-field">
	<button id="send-button">送信</button> //■ポイント: ここです!!!!!!!!
  
  
 	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<script th:src="@{/js/start.js}"></script>
</body>
</html>

■JavaScript

ポイント

1 送信ボタン(id="send-button")を押す
 →sendRequestメソッドが動く
2 sendRequestメソッドの中でAjaxが動く
 →Javaに繋がる

$(function(){
	$('#send-button').on('click', function() {
		const message = $('#input-field').val();
		sendRequest(message);
	});//■ onの終わり
});//■ 1番上のready関数の最後

//OpenAI APIにリクエストを送信する関数
function sendRequest(message) {
    $.ajax({
    	url: "/openAiChat",
    	type: "POST",
    	contentType: "application/json",
        data: JSON.stringify({
        	message: message
        })
    }).done(function(response, textStatus, jqXHR) {
    	console.log(response);
    }).fail(function(jqXHR, textStatus, errorThrown) {
    	console.log("きてない");
    });
}

■Java

なんでJavaいるの?

セキュリティの観点から
Java側で環境変数内のAPIキーを取得

ポイント

ここでChatGPTのAPIとやりとりをする

package com.example.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.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

@Controller
@RequestMapping("")
public class TestChatAjaxController {

	@RequestMapping("")
	public String toStart() {
        return "start";
	}
	
    @PostMapping("/openAiChat")
    public ResponseEntity<String> openAiChat(@RequestBody String preMessage) {
    	String url = "https://api.openai.com/v1/chat/completions";
    	String api_key = System.getenv("OPENAI_API_KEY");
    	String model = "gpt-3.5-turbo";
    	String message = "{\"role\": \"system\", \"content\": \"返答は日本語で\"},{\"role\": \"user\", \"content\": \" + preMessage + \"}";
    	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();
    		
    		// レスポンスの出力
    		System.out.println(content);
    	} catch (Exception e) {
    		System.out.println(e);
    	}  
    	return new ResponseEntity<>(content, HttpStatus.OK);
    }
}

■Maven

なんでGoogleが出てくるの?

GoogleのGsonを使って
Json形式の値を操作できるようにする為
※Googleだからって何か特別な操作はいらない

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.8.8</version>
</dependency>
0
0
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
0
0