CopilotKit으로 AI 챗봇 만들기: Flask와 React를 사용한 단계별 가이드
Flask 백엔드와 통합된 CopilotKit을 사용하여 AI 챗봇을 만드는 것은 흥미로운 프로젝트가 될 수 있습니다. 다음은 프런트엔드(React 및 CopilotKit 사용)와 백엔드(Flask 사용)에 필요한 구성 요소를 포함하여 프로젝트를 설정하는 방법에 대한 단계별 가이드입니다.
프로젝트 개요
구성요소
- Flask 백엔드: API 요청을 처리하고 프런트엔드를 제공합니다.
- React Frontend: CopilotKit을 사용하여 대화형 AI 챗봇 인터페이스를 만듭니다.
- AI 통합: 응답 생성을 위해 AI 모델(예: Google의 Gemini)에 연결합니다.
1단계: Flask 백엔드 설정
1. 플라스크 설치
먼저 가상 환경을 만들고 Flask를 설치합니다.
mkdir chatbot-backend cd chatbot-backend python -m venv venv source venv/bin/activate # On Windows use `venv\Scripts\activate` pip install Flask flask-cors
2. Flask 앱 만들기
app.py라는 파일을 만듭니다.
from flask import Flask, request, jsonify from flask_cors import CORS import openai # Make sure to install OpenAI SDK if you're using it app = Flask(__name__) CORS(app) # Allow CORS for all domains # Set your OpenAI API key openai.api_key = 'YOUR_OPENAI_API_KEY' @app.route('/api/chat', methods=['POST']) def chat(): user_message = request.json.get('message') # Call the AI model (e.g., OpenAI GPT) response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": user_message}] ) bot_message = response.choices[0].message['content'] return jsonify({'response': bot_message}) if __name__ == '__main__': app.run(debug=True)
3. 플라스크 앱 실행
Flask 앱 실행:
python app.py
이제 백엔드는 http://127.0.0.1:5000에서 실행되어야 합니다.
2단계: CopilotKit을 사용하여 React 프런트엔드 설정
1. 리액트 앱 만들기
새 디렉터리에서 React 앱을 만듭니다.
npx create-react-app chatbot-frontend cd chatbot-frontend
2. CopilotKit 설치
API 호출을 위해 CopilotKit 및 Axios를 설치하세요.
npm install @copilotkit/react axios
3. 챗봇 컴포넌트 생성
src 디렉터리에 Chatbot.js라는 파일을 만듭니다.
import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { CopilotSidebar, useCopilotChat } from '@copilotkit/react'; import './Chatbot.css'; // Importing CSS file for styling const Chatbot = () => { const [message, setMessage] = useState(''); const [chatHistory, setChatHistory] = useState([]); const [selectedPrompt, setSelectedPrompt] = useState(''); const [conversations, setConversations] = useState([]); const [prompts, setPrompts] = useState([]); const [newPrompt, setNewPrompt] = useState(''); const [searchTerm, setSearchTerm] = useState(''); const [showPromptInput, setShowPromptInput] = useState(false); // State to toggle prompt input visibility const { addMessage } = useCopilotChat(); useEffect(() => { // Load conversations and prompts from local storage on component mount const storedChats = JSON.parse(localStorage.getItem('chatHistory')) || []; const storedPrompts = JSON.parse(localStorage.getItem('prompts')) || []; setConversations(storedChats); setPrompts(storedPrompts); // Load the most recent conversation into chat history if available if (storedChats.length > 0) { setChatHistory(storedChats[storedChats.length - 1].history); } }, []); const handleSendMessage = async () => { const userMessage = { sender: 'User', text: message }; const updatedChatHistory = [...chatHistory, userMessage]; setChatHistory(updatedChatHistory); setMessage(''); try { const response = await axios.post('http://127.0.0.1:5000/api/chat', { message }); const botMessage = { sender: 'Bot', text: response.data.response }; updatedChatHistory.push(botMessage); setChatHistory(updatedChatHistory); // Add messages to Copilot addMessage(userMessage); addMessage(botMessage); // Save updated chat history to local storage localStorage.setItem('chatHistory', JSON.stringify(updatedChatHistory)); } catch (error) { console.error('Error sending message:', error); } }; const handlePromptSelect = (prompt) => { setSelectedPrompt(prompt); setMessage(prompt); }; const handleConversationClick = (conversation) => { setChatHistory(conversation.history); }; const handleSaveConversation = () => { const title = prompt("Enter a title for this conversation:"); if (title) { const newConversation = { title, history: chatHistory }; const updatedConversations = [...conversations, newConversation]; setConversations(updatedConversations); localStorage.setItem('chatHistory', JSON.stringify(updatedConversations)); } }; const handleAddPrompt = () => { if (newPrompt.trim()) { const updatedPrompts = [...prompts, newPrompt.trim()]; setPrompts(updatedPrompts); localStorage.setItem('prompts', JSON.stringify(updatedPrompts)); setNewPrompt(''); setShowPromptInput(false); // Hide the input after adding } }; // Function to delete a conversation const handleDeleteConversation = (index) => { const updatedConversations = conversations.filter((_, i) => i !== index); setConversations(updatedConversations); localStorage.setItem('chatHistory', JSON.stringify(updatedConversations)); // Optionally reset chat history if the deleted conversation was currently loaded if (chatHistory === conversations[index].history) { setChatHistory([]); } }; // Filtered prompts based on search term const filteredPrompts = prompts.filter(prompt => prompt.toLowerCase().includes(searchTerm.toLowerCase()) ); // Filtered conversations based on search term const filteredConversations = conversations.filter(conversation => conversation.title.toLowerCase().includes(searchTerm.toLowerCase()) ); return ( <div className="chatbot-container"> <CopilotSidebar title="Recent Conversations"> <input type="text" placeholder="Search Conversations..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="search-input" /> {filteredConversations.map((conversation, index) => ( <div key={index} className="conversation-title"> <span onClick={() => handleConversationClick(conversation)}> {conversation.title} </span> <button className="delete-button" onClick={() => handleDeleteConversation(index)}> ?️ {/* Delete icon */} </button> </div> ))} <button onClick={handleSaveConversation} className="save-button">Save Conversation</button> </CopilotSidebar> <div className="chat-area"> <h2>AI Chatbot</h2> <div className="chat-history"> {chatHistory.map((chat, index) => ( <div key={index} className={`message ${chat.sender === 'User' ? 'user' : 'bot'}`}> <strong>{chat.sender}:</strong> {chat.text} </div> ))} </div> <div className="input-area"> <select value={selectedPrompt} onChange={(e) => handlePromptSelect(e.target.value)} className="prompt-select" > <option value="">Select a prompt...</option> {filteredPrompts.map((prompt, index) => ( <option key={index} value={prompt}>{prompt}</option> ))} </select> {/* Button to toggle visibility of the new prompt input */} <button onClick={() => setShowPromptInput(!showPromptInput)} className="toggle-prompt-button"> {showPromptInput ? "Hide Prompt Input" : "Add New Prompt"} </button> {/* New Prompt Input Field */} {showPromptInput && ( <input type="text" value={newPrompt} onChange={(e) => setNewPrompt(e.target.value)} placeholder="Add a new prompt..." className="new-prompt-input" /> )} {/* Button to add the new prompt */} {showPromptInput && ( <button onClick={handleAddPrompt} className="add-prompt-button">Add Prompt</button> )} {/* Message Input Field */} <input type="text" value={message} onChange={(e) => setMessage(e.target.value)} placeholder="Type your message..." className="message-input" /> <button onClick={handleSendMessage} className="send-button">Send</button> </div> </div> </div> ); }; export default Chatbot;
4. App.js 업데이트
src/App.js의 내용을 다음으로 바꾸세요.
import React from 'react'; import Chatbot from './Chatbot'; function App() { return ( <div className="App"> <Chatbot /> </div> ); } export default App;
5. Chatbot.css 생성
.chatbot-container { display: flex; height: 100vh; } .chat-area { margin-left: 20px; flex-grow: 1; padding: 20px; background-color: #f9f9f9; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); } .chat-history { border: 1px solid #ccc; padding: 10px; height: calc(100% - 120px); /* Adjust height based on input area */ overflow-y: scroll; border-radius: 8px; } .message { margin-bottom: 10px; } .user { text-align: right; } .bot { text-align: left; } .input-area { display: flex; align-items: center; } .prompt-select { margin-right: 10px; } .message-input { flex-grow: 1; padding: 10px; border-radius: 4px; border: 1px solid #ccc; } .send-button { padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; } .send-button:hover { background-color: #0056b3; } .conversation-title { padding: 10px; cursor: pointer; } .conversation-title:hover { background-color: #f0f0f0; } .save-button { margin-top: 10px; padding: 5px 10px; background-color: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; } .save-button:hover { background-color: #218838; } .prompt-select, .new-prompt-input, .message-input { margin-right: 10px; } .search-input { margin-bottom: 10px; } .new-prompt-input { flex-grow: 1; /* Allow it to take remaining space */ padding: 10px; border-radius: 4px; border: 1px solid #ccc; } .add-prompt-button, .send-button, .save-button { padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; } .add-prompt-button:hover, .send-button:hover, .save-button:hover { background-color: #0056b3; /* Darker shade for hover */ } .conversation-title { padding: 10px; cursor: pointer; } .conversation-title:hover { background-color: #f0f0f0; /* Highlight on hover */ } .toggle-prompt-button { margin-right: 10px; padding: 10px 15px; background-color: #17a2b8; /* Different color for visibility */ color: white; border: none; border-radius: 4px; cursor: pointer; } .toggle-prompt-button:hover { background-color: #138496; /* Darker shade for hover */ }
5. React 앱 실행
React 앱 시작:
npm start
이제 프런트엔드는 http://localhost:3000에서 실행되어야 합니다.
3단계: 챗봇 테스트
- Flask 백엔드와 React 프론트엔드가 모두 실행되고 있는지 확인하세요.
- 브라우저를 열고 http://localhost:3000으로 이동하세요.
- 입력란에 메시지를 입력하면 AI 챗봇의 답변을 확인할 수 있습니다.
CopilotKit, Flask 및 React를 사용하여 챗봇 구축에 대한 게시물을 개발할 때 GitHub 저장소 URL을 포함하려면 다음과 같이 형식을 지정하면 됩니다.
CopilotKit, Flask 및 React를 사용하여 AI Chatbot 구축
이 게시물에서는 프런트엔드에 CopilotKit, 백엔드에 Flask, 사용자 인터페이스에 React를 사용하여 대화형 AI 챗봇을 만드는 단계를 단계별로 살펴보겠습니다.
GitHub 저장소
GitHub에서 이 프로젝트의 전체 코드를 찾을 수 있습니다: CopilotKit이 포함된 Chatbot
결론
이제 프런트엔드용 CopilotKit과 백엔드용 Flask를 사용하여 기본 AI 챗봇을 구축했습니다! 사용자 인증, 채팅 기록 저장, UI/UX 디자인 개선 등의 기능을 추가하여 이 프로젝트를 향상시킬 수 있습니다.
위 내용은 CopilotKit으로 AI 챗봇 만들기: Flask와 React를 사용한 단계별 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Linux 터미널에서 Python 사용 ...

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Pythonasyncio에 대해 ...

Investing.com의 크롤링 전략 이해 많은 사람들이 종종 Investing.com (https://cn.investing.com/news/latest-news)에서 뉴스 데이터를 크롤링하려고합니다.

Python 3.6에 피클 파일 로딩 3.6 환경 오류 : ModulenotFounderRor : nomodulename ...

SCAPY 크롤러를 사용할 때 파이프 라인 파일을 작성할 수없는 이유에 대한 논의 지속적인 데이터 저장을 위해 SCAPY 크롤러를 사용할 때 파이프 라인 파일이 발생할 수 있습니다 ...
