Skip to content

Commit

Permalink
Feat: 테스트 페이지 추가
Browse files Browse the repository at this point in the history
chat.html추가
UserController 리다이렉션 수정
gradle파일에 의존성 추가
  • Loading branch information
Mouon committed Jan 6, 2024
1 parent dd266c8 commit fe1bd4d
Show file tree
Hide file tree
Showing 8 changed files with 205 additions and 2 deletions.
Binary file modified .gradle/8.5/fileHashes/fileHashes.lock
Binary file not shown.
Binary file modified .gradle/buildOutputCleanup/buildOutputCleanup.lock
Binary file not shown.
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ repositories {
}

dependencies {
implementation 'org.json:json:20220320'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
Expand Down
Binary file not shown.
Binary file modified build/tmp/compileJava/previous-compilation-data.bin
Binary file not shown.
50 changes: 50 additions & 0 deletions src/main/java/com/kuit/chatdiary/controller/ChatController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.kuit.chatdiary.controller;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
public class ChatController {

@Value("${OPEN_AI_KEY}")
private String OPEN_AI_KEY;
@PostMapping("/ask")
public ResponseEntity<String> ask(@RequestBody Map<String, String> prompt) {
RestTemplate restTemplate = new RestTemplate();
String apiUrl = "https://api.openai.com/v1/chat/completions";

// OpenAI 요청 본문 구성
JSONObject body = new JSONObject();
body.put("model", "gpt-3.5-turbo");
body.put("messages", new JSONObject[] {
new JSONObject().put("role", "system").put("content", "You are a playful and curious teenager. No matter the topic, you find everything fascinating and are always eager to ask lots of questions. korean"),
new JSONObject().put("role", "user").put("content", prompt.get("prompt"))
});

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setBearerAuth(OPEN_AI_KEY);


HttpEntity<String> entity = new HttpEntity<>(body.toString(), headers);

try {
ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, entity, String.class);
System.out.println("API Response: " + response.getBody());
return response;
} catch (Exception e) {
return ResponseEntity.status(500).body("Internal Server Error");
}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package com.kuit.chatdiary.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Controller
public class UserController {

@GetMapping("/chat")
public String chat() {
return "redirect:/chat.html";
}
@GetMapping("/user")
public String user() {
return "user";
return "redirect:/user.html";
}
}
147 changes: 147 additions & 0 deletions src/main/resources/static/chat.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>user</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<style>
body { font-family: Arial, sans-serif; }
.hide-link-text {
text-decoration: none !important;
color: inherit !important;
}
.section-title {
margin-top: 2rem;
margin-bottom: 1.5rem;
font-size: 1.5rem;
position: relative;
}

.project-details {
font-size: 1.1rem;
}
.project-description {
font-size: 1.2rem;
}
.role {
font-size: 1.1rem;
}
.footer-space {
margin-bottom: 6rem;
}
.chat-container {
width: 100%;
max-width: 400px;
margin: auto;
height: 350px;
border: 1px solid #ddd;
padding: 20px;
overflow-y: scroll;
}
.chat-box {
background: #eee;
padding: 5px;
margin: 10px 0;
border-radius: 5px;
max-width: 200px;
}
.mine {
background: lightblue;
margin-left: auto;
}
.input-area {
margin: auto;
display: flex;
margin-top: 10px;
max-width: 400px;
width: 100%;
}
input[type="text"] {
flex: 1;
padding: 10px;
margin-right: 5px;
border: 1px solid #ddd;
}
button {
padding: 10px;
border: none;
background: #5b9bd5;
color: white;
cursor: pointer;
}
button:hover {
background: #4a8bc2;
}
</style>
</head>
<body>

<br><br><br><br>
<br><br><br><br>
<div class="chat-container" id="chatContainer">
</div>

<div class="input-area">
<input type="text" id="inputBox" placeholder="Type a message...">
<button id="sendButton">Send</button>
</div>


<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script>
async function sendToOpenAI(message) {
try {
const response = await fetch('/ask', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ prompt: message })
});
const data = await response.json();
console.log("Response data:", data); // 서버 응답 로깅

// 서버 응답에서 필요한 텍스트 추출
if (data.choices && data.choices.length > 0 && data.choices[0].message && data.choices[0].message.content) {
const aiResponse = data.choices[0].message.content.trim();
displayMessage(aiResponse, 'yours');
} else {
console.error('Invalid response structure:', data);
}
} catch (error) {
console.error('Error:', error);
}
}


function sendMessage() {
var inputBox = document.querySelector('#inputBox');
var message = inputBox.value.trim();

if (message) {
displayMessage(message, 'mine');
sendToOpenAI(message);
inputBox.value = '';
}
}

function displayMessage(message, className) {
var chatContainer = document.querySelector('#chatContainer');
var messageElement = document.createElement('div');
messageElement.classList.add('chat-box', className);
messageElement.textContent = message;
chatContainer.appendChild(messageElement);
chatContainer.scrollTop = chatContainer.scrollHeight;
}

document.querySelector('#sendButton').addEventListener('click', sendMessage);
document.querySelector('#inputBox').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>

</body>
</html>

0 comments on commit fe1bd4d

Please sign in to comment.