搜尋
首頁後端開發Python教學使用 CopilotKit 建立 AI 聊天機器人:使用 Flask 和 React 的逐步指南

使用與 Flask 後端整合的 CopilotKit 創建人工智慧聊天機器人可能是一個令人興奮的專案。以下是有關如何設定專案的逐步指南,包括前端(使用 React 和 CopilotKit)和後端(使用 Flask)的必要元件。

Creating an AI Chatbot with CopilotKit: A Step-by-Step Guide Using Flask and React

項目概況

成分

  1. Flask 後端:處理 API 請求並為前端提供服務。
  2. React Frontend:使用 CopilotKit 建立互動式 AI 聊天機器人介面。
  3. 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 應用程式

運行你的 Flask 應用:

python app.py

您的後端現在應該在 http://127.0.0.1:5000 上運行。

步驟 2: 使用 CopilotKit 設定 React 前端

1. 建立一個 React 應用程式

在新目錄中,建立您的 React 應用程式:

npx create-react-app chatbot-frontend
cd chatbot-frontend

2.安裝CopilotKit

安裝 CopilotKit 和 Axios 以進行 API 呼叫:

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 id="AI-Chatbot">AI Chatbot</h2>
                <div classname="chat-history">
                    {chatHistory.map((chat, index) => (
                        <div key="{index}" classname="{`message" :>
                            <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></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 步:測試您的聊天機器人

  1. 確保您的 Flask 後端和 React 前端都在運作。
  2. 開啟瀏覽器並導航至 http://localhost:3000。
  3. 在輸入欄位中輸入訊息並查看 AI 聊天機器人的回應。

要在您的 dev.to 帖子中包含 GitHub 存儲庫 URL,以發布有關使用 CopilotKit、Flask 和 React 構建聊天機器人的信息,您可以將其格式化如下:


使用 CopilotKit、Flask 和 React 建立 AI 聊天機器人

在這篇文章中,我們將逐步介紹使用 CopilotKit 作為前端、Flask 作為後端、React 作為使用者介面來建立互動式 AI 聊天機器人的步驟。

GitHub 儲存庫

您可以在 GitHub 上找到該專案的完整程式碼:Chatbot with CopilotKit

結論

您現在已經有一個使用 CopilotKit 作為前端、使用 Flask 作為後端建立的基本 AI 聊天機器人!您可以透過新增使用者身分驗證、儲存聊天記錄或改進 UI/UX 設計等功能來增強此專案。

以上是使用 CopilotKit 建立 AI 聊天機器人:使用 Flask 和 React 的逐步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python vs. C:了解關鍵差異Python vs. C:了解關鍵差異Apr 21, 2025 am 12:18 AM

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

Python vs.C:您的項目選擇哪種語言?Python vs.C:您的項目選擇哪種語言?Apr 21, 2025 am 12:17 AM

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

達到python目標:每天2小時的力量達到python目標:每天2小時的力量Apr 20, 2025 am 12:21 AM

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。

最大化2小時:有效的Python學習策略最大化2小時:有效的Python學習策略Apr 20, 2025 am 12:20 AM

在兩小時內高效學習Python的方法包括:1.回顧基礎知識,確保熟悉Python的安裝和基本語法;2.理解Python的核心概念,如變量、列表、函數等;3.通過使用示例掌握基本和高級用法;4.學習常見錯誤與調試技巧;5.應用性能優化與最佳實踐,如使用列表推導式和遵循PEP8風格指南。

在Python和C之間進行選擇:適合您的語言在Python和C之間進行選擇:適合您的語言Apr 20, 2025 am 12:20 AM

Python適合初學者和數據科學,C 適用於系統編程和遊戲開發。 1.Python簡潔易用,適用於數據科學和Web開發。 2.C 提供高性能和控制力,適用於遊戲開發和系統編程。選擇應基於項目需求和個人興趣。

Python與C:編程語言的比較分析Python與C:編程語言的比較分析Apr 20, 2025 am 12:14 AM

Python更適合數據科學和快速開發,C 更適合高性能和系統編程。 1.Python語法簡潔,易於學習,適用於數據處理和科學計算。 2.C 語法複雜,但性能優越,常用於遊戲開發和系統編程。

每天2小時:Python學習的潛力每天2小時:Python學習的潛力Apr 20, 2025 am 12:14 AM

每天投入兩小時學習Python是可行的。 1.學習新知識:用一小時學習新概念,如列表和字典。 2.實踐和練習:用一小時進行編程練習,如編寫小程序。通過合理規劃和堅持不懈,你可以在短時間內掌握Python的核心概念。

Python與C:學習曲線和易用性Python與C:學習曲線和易用性Apr 19, 2025 am 12:20 AM

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境