首页 后端开发 Python教程 使用 CopilotKit 创建 AI 聊天机器人:使用 Flask 和 React 的分步指南

使用 CopilotKit 创建 AI 聊天机器人:使用 Flask 和 React 的分步指南

Oct 01, 2024 am 06:11 AM

使用与 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>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 步:测试您的聊天机器人

  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

热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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1677
14
CakePHP 教程
1431
52
Laravel 教程
1334
25
PHP教程
1280
29
C# 教程
1257
24
Python与C:学习曲线和易用性 Python与C:学习曲线和易用性 Apr 19, 2025 am 12:20 AM

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

学习Python:2小时的每日学习是否足够? 学习Python:2小时的每日学习是否足够? Apr 18, 2025 am 12:22 AM

每天学习Python两个小时是否足够?这取决于你的目标和学习方法。1)制定清晰的学习计划,2)选择合适的学习资源和方法,3)动手实践和复习巩固,可以在这段时间内逐步掌握Python的基本知识和高级功能。

Python vs.C:探索性能和效率 Python vs.C:探索性能和效率 Apr 18, 2025 am 12:20 AM

Python在开发效率上优于C ,但C 在执行性能上更高。1.Python的简洁语法和丰富库提高开发效率。2.C 的编译型特性和硬件控制提升执行性能。选择时需根据项目需求权衡开发速度与执行效率。

Python vs. C:了解关键差异 Python vs. C:了解关键差异 Apr 21, 2025 am 12:18 AM

Python和C 各有优势,选择应基于项目需求。1)Python适合快速开发和数据处理,因其简洁语法和动态类型。2)C 适用于高性能和系统编程,因其静态类型和手动内存管理。

Python标准库的哪一部分是:列表或数组? Python标准库的哪一部分是:列表或数组? Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

Python:自动化,脚本和任务管理 Python:自动化,脚本和任务管理 Apr 16, 2025 am 12:14 AM

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

科学计算的Python:详细的外观 科学计算的Python:详细的外观 Apr 19, 2025 am 12:15 AM

Python在科学计算中的应用包括数据分析、机器学习、数值模拟和可视化。1.Numpy提供高效的多维数组和数学函数。2.SciPy扩展Numpy功能,提供优化和线性代数工具。3.Pandas用于数据处理和分析。4.Matplotlib用于生成各种图表和可视化结果。

Web开发的Python:关键应用程序 Web开发的Python:关键应用程序 Apr 18, 2025 am 12:20 AM

Python在Web开发中的关键应用包括使用Django和Flask框架、API开发、数据分析与可视化、机器学习与AI、以及性能优化。1.Django和Flask框架:Django适合快速开发复杂应用,Flask适用于小型或高度自定义项目。2.API开发:使用Flask或DjangoRESTFramework构建RESTfulAPI。3.数据分析与可视化:利用Python处理数据并通过Web界面展示。4.机器学习与AI:Python用于构建智能Web应用。5.性能优化:通过异步编程、缓存和代码优

See all articles