ChatGPT API를 프론트엔드에서 직접 통합하여 대화형 인터페이스를 구축하는 방법은, iframe이나 WebView 대신 API 호출을 통해 데이터를 가져와 사용자에게 대화를 표시하는 방식입니다. Enact 프론트엔드 프로젝트에서 이 작업을 어떻게 수행할 수 있는지 단계별로 설명하겠습니다.
ChatGPT API를 사용하기 위해서는 OpenAI API 키가 필요합니다. OpenAI의 API Documentation에 따라 API 키를 발급받고, 이를 활용해 API에 요청할 수 있습니다.
https://api.openai.com/v1/chat/completions
Enact에서 Axios 또는 Fetch API를 사용하여 API 호출을 수행할 수 있습니다. 예제는 Axios를 사용하는 방식으로 설명드리겠습니다.
먼저 axios
패키지를 설치합니다.
npm install axios
그 후, ChatGPT API와 통신하는 로직을 ChatGPTComponent.js
에 작성합니다.
import React, { useState } from "react";
import axios from "axios";
const ChatGPTComponent = () => {
const [inputText, setInputText] = useState("");
const [messages, setMessages] = useState([
{ role: "system", content: "You are a helpful assistant." },
]);
const [loading, setLoading] = useState(false);
const handleInputChange = (e) => {
setInputText(e.target.value);
};
const sendMessage = async () => {
if (!inputText) return;
setLoading(true);
// 사용자 입력 메시지 추가
const newMessages = [...messages, { role: "user", content: inputText }];
setMessages(newMessages);
setInputText("");
try {
const response = await axios.post(
"https://api.openai.com/v1/chat/completions",
{
model: "gpt-3.5-turbo",
messages: newMessages,
},
{
headers: {
Authorization: `Bearer YOUR_API_KEY`,
"Content-Type": "application/json",
},
}
);
// API 응답 메시지 추가
const gptMessage = response.data.choices[0].message;
setMessages([...newMessages, gptMessage]);
} catch (error) {
console.error("Error calling ChatGPT API:", error);
} finally {
setLoading(false);
}
};
return (
<div>
<div>
{messages.map((msg, index) => (
<div key={index} style={{ marginBottom: "10px" }}>
<strong>{msg.role === "user" ? "User" : "Assistant"}:</strong>
<p>{msg.content}</p>
</div>
))}
</div>
{loading && <p>Loading...</p>}
<input
type="text"
value={inputText}
onChange={handleInputChange}
placeholder="Ask something..."
/>
<button onClick={sendMessage} disabled={loading}>
Send
</button>
</div>
);
};
export default ChatGPTComponent;
messages
상태에는 시스템 메시지와 사용자 메시지를 저장합니다. OpenAI API는 대화를 위한 여러 메시지를 사용하여 응답을 생성합니다.sendMessage
함수에서 Axios를 사용해 ChatGPT API에 POST 요청을 보냅니다. 사용자 입력을 API 요청에 포함시키고, 응답이 도착하면 messages
상태에 추가해 대화 내용을 업데이트합니다.FloatingButton
컴포넌트에서 이 ChatGPTComponent를 Popup 형태로 사용하고, 버튼 클릭 시 ChatGPT 대화창을 열 수 있게 설정합니다.
import ChatGPTComponent from "./ChatGPTComponent";
const FloatingButton = () => {
const [isChatOpen, setIsChatOpen] = useState(false);
const openChat = () => {
setIsChatOpen(true);
};
const closeChat = () => {
setIsChatOpen(false);
};
return (
<div>
{/* 기존 버튼 코드 생략 */}
{/* Chat 팝업 */}
{isChatOpen && (
<Popup open={isChatOpen} onClose={closeChat} scrimType="none">
<ChatGPTComponent />
</Popup>
)}
</div>
);
};
API 호출 제한: OpenAI API에는 호출 제한이 있으니, 성능 최적화를 위해 호출 횟수를 최소화하는 로직을 고려해야 합니다.
보안: API 키는 민감한 정보이므로, 반드시 백엔드에서 API 호출을 중계하거나 환경 변수를 사용해 보호해야 합니다.
상태 관리: 대화 상태나 응답 데이터를 더 효과적으로 관리하기 위해 Redux와 같은 상태 관리 라이브러리를 고려할 수 있습니다.
이와 같은 방식으로 ChatGPT API를 Enact 프로젝트에 통합하면, 직접적으로 대화형 인터페이스를 구현할 수 있습니다.