2023年的深度学习入门指南(3) - 前端同学如何进行chatgpt开发

news2025/5/18 1:11:18

2023年的深度学习入门指南(3) - 前端同学如何进行chatgpt开发

在第二篇,我们使用openai的python库封装,搞得它有点像之前学习的PyTorch一样的库。这一节我们专门给它正下名,前端就是字面意义上的前端。

给gpt4写前端

下面我们写一个最土的使用gpt4 API的页面,就一个输入框加一个回显的区域。

我们先写HTML页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>gpt4聊天机器人</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet"
          href="default.min.css">
    <script src="highlight.min.js"></script>
</head>
<body>
<div class="container">
    <h1>gpt4聊天机器人</h1>
    <form id="inputForm">
        <label for="userInput">请输入聊天内容:</label>
        <input type="text" id="userInput" name="userInput">
        <button type="submit">提交</button>
    </form>
    <div id="response">
        <h2>来自gpt4的回复:</h2>
        <div id="responseText"></div>
    </div>
</div>
<script src="script.js"></script>
</body>
</html>

我对代码的显示格式比较看重,所以增加了highlight.js来高亮代码,可以到https://highlightjs.org/download/ 这里去下载最新版本放到本地。
其它的就是一个form加上一个div。

然后是javascript,首先是响应submit事件的处理:

document.getElementById("inputForm").addEventListener("submit", async (event) => {
    event.preventDefault();
    const userInput = document.getElementById("userInput").value;

    if (userInput) {
        const responseText = document.getElementById("responseText");
        responseText.innerHTML = "gpt4正在思考中...";
        const apiResponse = await callOpenAI(userInput);
    }
});

接着是调用OpenAI API的部分了,因为我们没有后端,所以key暂时先明文写到网页里。

async function callOpenAI(userInput) {
    const apiKey = "你的openai api key";
    const apiURL = "https://api.openai.com/v1/chat/completions";

    const requestOptions = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${apiKey}`
        },
        body: JSON.stringify({
            model: "gpt-4",
            messages: [
                {role: "system", content: "You are a skilled software engineer."},
                {role: "user", content: userInput}
            ],
            max_tokens: 4096,
            n: 1,
            stop: null,
            temperature: 1
        })
    };

    try {
        const response = await fetch(apiURL, requestOptions);
        const data = await response.json();
        const responseTextElement = document.getElementById("responseText");
        responseTextElement.innerHTML = parseAndHighlightCode(data.choices[0].message.content);
        // Apply highlight to all <code> elements
        const codeBlocks = responseTextElement.getElementsByTagName("code");
        for (const codeBlock of codeBlocks) {
            hljs.highlightBlock(codeBlock);
        }
    } catch (error) {
        console.error("Error:", error);
        responseText.innerHTML = "An error occurred while fetching the response.";
    }
}

大家注意这部分参数:

            model: "gpt-4",
            messages: [
                {role: "system", content: "You are a skilled software engineer."},
                {role: "user", content: userInput}
            ],

模型根据需要来选择,一般选择chatgpt,也就是’gpt-3.5-turbo’.
另外还有角色的部分,根据场景的不同,可以给system角色以更多的提示。

最后是解析代码并高亮的部分:

function parseAndHighlightCode(text) {
    text = String(text); // Ensure 'text' is a string
    const regex = /```(\w+)?\s*([\s\S]*?)```/g;
    return text.replace(regex, (match, language, code) => {
        const langClass = language ? ` class="${language}"` : '';
        return `<pre><code${langClass}>${code.trim()}</code></pre>`;
    });
}

该函数的作用是在输入的文本中搜索用三个反引号包裹的代码块,并将其包裹在 HTML 的 <pre><code> 标签中,如果代码块开头的反引号中指定了编程语言,还会在 <code> 标签中添加一个 class 属性。

这个函数首先将 text 参数转换为字符串类型,确保它是一个字符串。然后,它使用 RegExp 构造函数创建一个正则表达式对象,这个正则表达式对象可以匹配以三个反引号开始和结束的代码块,并且可以在反引号内指定编程语言。

样式都是chatgpt给生成的,我只是改了下支持换行显示:

body {
    font-family: Arial, sans-serif;
    background-color: #f0f0f0;
    margin: 0;
    padding: 0;
}

.container {
    max-width: 800px;
    margin: 0 auto;
    padding: 2rem;
    background-color: #ffffff;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}

form {
    display: flex;
    flex-direction: column;
}

input {
    margin-bottom: 1rem;
    padding: 0.5rem;
    font-size: 1rem;
}

button {
    background-color: #0077cc;
    color: #ffffff;
    padding: 0.5rem;
    font-size: 1rem;
    border: none;
    cursor: pointer;
    margin-bottom: 2rem;
}

button:hover {
    background-color: #0055a5;
}
#responseText {
    white-space: pre-wrap;
}

修改输入框高度

只支持一行看起来不太好,那干脆我们多支持几行:

<div class="container">
    <h1>gpt4聊天机器人</h1>
    <form id="inputForm">
        <label for="userInput">请输入聊天内容:</label>
        <!--input type="text" id="userInput" name="userInput"-->
        <textarea id="userInput" rows="10" cols="50" placeholder="请输入内容"></textarea>
        <button type="submit">提交</button>
    </form>
    <div id="response">
        <h2>来自gpt4的回复:</h2>
        <div id="responseText"></div>
    </div>
</div>

这样输入大段文本的时候能更舒服一点。

我们还可以将其改成文本区域自动适应的。

我们可以给textarea增加一个oninput事件处理函数:

<textarea id="userInput" rows="1" cols="80" placeholder="请输入内容" oninput="autoResize(this)"></textarea>

实现起来也很简单,将高度改成auto:

function autoResize(textarea) {
    textarea.style.height = 'auto'; // Reset the height to 'auto'
    textarea.style.height = textarea.scrollHeight + 'px'; // Set the new height based on scrollHeight
}

为了能够让页面加载时也根据内容调整,我们给DOMContentLoaded事件上注册一个函数:

document.addEventListener('DOMContentLoaded', () => {
    const userInput = document.getElementById('userInput');
    autoResize(userInput);
});

让chatgpt成为有身份的人

我们知道,在chatgpt的使用中,告诉chatgpt具体的情境会大大提升准确率。
于是我们给角色增加一个输入框吧:

<div class="container">
    <h1>gpt4聊天机器人</h1>
    <form id="inputForm">
        <label for="userInput">请输入聊天内容:</label>
        <!--input type="text" id="userInput" name="userInput"-->
        <textarea id="userInput" rows="1" cols="80" placeholder="请输入内容" oninput="autoResize(this)"></textarea>
        <button type="submit">提交</button>
    </form>
    <div id="system-input">
        <h2>你希望gpt4扮演一个什么样的角色</h2>
        <input id="systemInput" type="text" placeholder="你是一个友好的聊天机器人"/>
    </div>
    <div id="response">
        <h2>来自gpt4的回复:</h2>
        <div id="responseText"></div>
    </div>
</div>

然后将用户输入发给openai:

    const systemInput = document.getElementById("systemInput").value;

    const requestOptions = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${apiKey}`
        },
        body: JSON.stringify({
            model: "gpt-4",
            messages: [
                {role: "system", content: systemInput},
                {role: "user", content: userInput}
            ],
            max_tokens: 4096,
            n: 1,
            stop: null,
            temperature: 1
        })
    };

样式有点难看啊,我们写个样式吧:

#system-input {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
}

#system-input h2 {
    margin-bottom: 10px;
}

#systemInput {
    font-size: 16px;
    padding: 8px 12px;
    width: 100%;
    max-width: 500px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
    outline: none;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

#systemInput:focus {
    border-color: #66afe9;
    box-shadow: 0 0 4px rgba(102, 175, 233, 0.6);
}

chatgpt回复部分也稍微调下样式:

#response {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
}

#response h2 {
    margin-bottom: 10px;
}

#responseText {
    font-size: 16px;
    padding: 15px;
    width: 100%;
    max-width: 600px;
    border: 1px solid #ccc;
    border-radius: 4px;
    background-color: #f8f9fa;
    box-sizing: border-box;
    white-space: pre-wrap; /* Ensures line breaks are maintained */
    word-wrap: break-word; /* Allows long words to wrap onto the next line */
}

总之调整下样式吧。

样子写下来大致是:

body {
    font-family: 'Noto Sans SC', sans-serif;
    font-size: 16px;
    line-height: 1.6;
    color: #333;
}

.container {
    max-width: 800px;
    margin: 0 auto;
    padding: 2rem;
    background-color: #ffffff;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}

h1 {
    font-size: 2.5em;
    font-weight: bold;
    text-align: center;
    margin: 20px 0;
    color: #333;
}

h2 {
    margin-bottom: 10px;
    font-weight: bold;
    text-align: center;
}

form {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
    
}

label {
    display: inline-block;
    font-size: 1.2em;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
}

#userInput {
    font-size: 16px;
    padding: 8px 12px;
    width: 100%;
    max-width: 500px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
    outline: none;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
    margin-bottom: 20px;
}

#userInput:focus {
    border-color: #66afe9;
    box-shadow: 0 0 4px rgba(102, 175, 233, 0.6);
}

button {
    font-size: 1em;
    font-weight: bold;
    color: #fff;
    background-color: #007bff;
    border: none;
    border-radius: 4px;
    padding: 7px 20px;
    cursor: pointer;
    transition: background-color 0.2s ease-in-out;
    margin-bottom: 20px;
}

button:hover {
    background-color: #0056b3;
}


#response {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
}

#responseText {
    font-size: 16px;
    padding: 15px;
    width: 100%;
    max-width: 600px;
    border: 1px solid #ccc;
    border-radius: 4px;
    background-color: #f8f9fa;
    box-sizing: border-box;
    white-space: pre-wrap; /* Ensures line breaks are maintained */
    word-wrap: break-word; /* Allows long words to wrap onto the next line */
}

#systemInput {
    font-size: 16px;
    padding: 8px 12px;
    width: 100%;
    max-width: 500px;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-sizing: border-box;
    outline: none;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
    margin-bottom: 20px;
}

#systemInput:focus {
    border-color: #66afe9;
    box-shadow: 0 0 4px rgba(102, 175, 233, 0.6);
}

增加模型选择功能

我们再增加一个选择使用gpt4还是chatgpt的功能吧,先加元素:

<div class="container">
    <h1>gpt4聊天机器人</h1>
    <form id="inputForm">
        <label for="userInput">请输入聊天内容</label>
        <textarea id="userInput" rows="1" cols="80" placeholder="请输入内容" oninput="autoResize(this)"></textarea>
        <label for="systemInput">你希望gpt4扮演一个什么样的角色</label>
        <input id="systemInput" type="text" placeholder="你是一个友好的聊天机器人"/>
        <div id="model-selection">
            <label for="modelSelect">选择模型类型</label>
            <select id="modelSelect">
                <option value="gpt-4">GPT-4</option>
                <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
            </select>
        </div>
        <button type="submit">提交</button>
    </form>
    <div id="response">
        <h2>来自gpt4的回复:</h2>
        <div id="responseText"></div>
    </div>
</div>

再加代码:

    const systemInput = document.getElementById("systemInput").value;
    const model = document.getElementById("modelSelect").value;

    const requestOptions = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${apiKey}`
        },
        body: JSON.stringify({
            model: model,
            messages: [
                {role: "system", content: systemInput},
                {role: "user", content: userInput}
            ],
            max_tokens: 4096,
            n: 1,
            stop: null,
            temperature: 1
        })
    };

最后加上样式:

#model-selection {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;
}

#modelSelect {
    font-size: 1em;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 4px;
    outline: none;
    cursor: pointer;
}

看看效果:
在这里插入图片描述

小结

从上面一步一步的例子,我们可以看到,前端对于用户更好地使用大模型有着不可替代的重要作用。
上面的功能我们还可以不断增加下去,比如我们可以增加例子,保存记录,反馈错误等等。

虽然没有写一行python代码,也没有微调模型(当然是可以做的),但是这里面是有对于AI的深刻理解的。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/482722.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Web】前端框架对微软老旧浏览器的支持

零、原因 最近要做一个项目&#xff0c;要能在学校机房运行的&#xff0c;也要在手机上运行。电脑和手机&#xff0c;一次性开发&#xff0c;那最好的就是响应式前端框架了。手机和正常的电脑兼容性问题应该都不大&#xff0c;但是学校机房都是Win7的系统&#xff0c;自带的都…

【Linux内核解析-linux-5.14.10-内核源码注释】MM内存管理内核启动初始化源码解析

源码 这是Linux内核中的mm_init函数的代码&#xff0c;其作用是初始化内存管理相关的组件和数据结构。 static: 这是一个函数声明修饰符&#xff0c;表示该函数只在当前文件中可见。 void __init: 这是函数的返回类型和修饰符&#xff0c;表示该函数是内核初始化代码。 page…

SpringCloud详解

SpringCloud是一个基于SpringBoot的分布式系统开发框架&#xff0c;它能够帮助我们快速、稳定地构建分布式系统。本篇博客将对SpringCloud进行详细解析&#xff0c;介绍SpringCloud的主要组件和相关应用场景&#xff0c;同时提供代码示例以帮助读者更好地掌握SpringCloud的实际…

nodejs+vue学生考勤请假管理系统java python php

用户登录模块&#xff1a;用来区分二种用户&#xff0c;学生、管理员。 个人信息管理&#xff1a;用户登录后可以修改用户表中的个人信息。 主页模块&#xff1a;在信息表中读取信息并按照一定模板显示在首页。 信息搜索模块&#xff1a;将信息表中所有信息的标题或内容关键字与…

析构函数/拷贝构造/赋值重载

析构函数&#xff1a; // 析构函数~Stack(){_top 0;_capacity 0;free(_a);_a nullptr;} 1 、2两点与构造函数类似。 3、当我们未显示定义时&#xff0c;编译器会自动生成默认的析构函数。C中&#xff0c;对于内置类型不进行任何处理&#xff0c;对于自定义类型&#xff0…

【SAS应用统计分析】方差分析

声明&#xff1a;本文知识参考内容来自网络&#xff0c;如有侵权请联系删除。 目录 【anova过程】 1.anova过程的语句格式 2.语句说明 【glm过程】 1.glm过程的语句格式 2.语句说明 【实例分析】 【实验步骤】 总结 【anova过程】 SAS系统的START软件提供了anova过程…

TensorRT:自定义插件学习与实践 001

文章简述 本文简单列出了编写Tensorrt插件所需要的关键方法,分为两个部分&#xff0c;一是插件类的具体实现方法&#xff0c;另外是插件工厂的调用方法,插件类最终将编译为.so文件,使用时在c或python中调用,所以插件类的方法调用在其他部分&#xff0c;在本文中难以直观的体现调…

PyQt5

最近在学习pyqt5&#xff0c; 使用pyqt5的时候出现了一些莫名奇妙的问题&#xff0c;解决之后决定把它记录下来&#xff0c;方面pyqt5的初学者使用。 每个问题会按照如下方式进行描述 1、问题描述&#xff1a; 2、解决方法&#xff1a; 问题1&#xff1a; 使用pyinstaller打…

计算机网络笔记:TCP三次握手和四次挥手过程

TCP是面向连接的协议&#xff0c;连接的建立和释放是每一次面向连接的通信中必不可少的过程。TCP连接的管理就是使连接的建立和释放都能正常地进行。 三次握手 TCP连接的建立—三次握手建立TCP连接 ① 若主机A中运行了一个客户进程&#xff0c;当它需要主机B的服务时&#xff0…

迁移学习

迁移学习 什么是迁移学习 迁移学习【斯坦福21秋季&#xff1a;实用机器学习中文版】 迁移学习&#xff08;Transfer Learning&#xff09;是一种机器学习方法&#xff0c;它通过将一个领域中的知识和经验迁移到另一个相关领域中&#xff0c;来加速和改进新领域的学习和解决问…

OS开源项目周报0105

由OpenDigg 出品的iOS开源项目周报第四期来啦。iOS开源周报集合了OpenDigg一周来新收录的优质的iOS开发方面的开源项目&#xff0c;方便iOS开发人员便捷的找到自己需要的项目工具等。 Hero 酷炫的iOS动画引擎 Traits 实时修改原生iOS 应用属性 JSDBanTangHomeDemo 仿半糖首页…

【Git】‘git‘ 不是内部或外部命令,也不是可运行的程序

一、问题 我想利用git clone命令从github上下载项目源代码&#xff0c;发现报错&#xff1a; git 不是内部或外部命令&#xff0c;也不是可运行的程序或批处理文件。我用cmd跑一下git命令&#xff0c;发现报错&#xff1a; 二、问题分析 这个错误提示表明您的系统中没有安装…

Illustrator如何使用基础功能?

文章目录 0.引言1.菜单栏2.工具箱 0.引言 因科研等多场景需要进行绘图处理&#xff0c;笔者对Illustrator进行了学习&#xff0c;本文通过《Illustrator CC2018基础与实战》及其配套素材结合网上相关资料进行学习笔记总结&#xff0c;本文对软件界面基本功能进行阐述。    1…

第四章 数据关联分析方法

基本概念和方法 关联规则和算法应用 基本概念和术语 关联规则算法应用&#xff1a; 一个关联规则分析的例子—————超市购物篮分析 不要看 后面数字看不懂 项集&#xff1a;是指项的集合。包含k个项的项集称为k-项集 支持度&#xff1a;若A是一个项集&#xff0c;则A的…

Vue3 +TypeScript 引入 BabylonJs(Vue3实现3D)【一篇文章精通系列】

本文主要介绍如何使用Vue3和TypeScript引入BabylonJs技术实现3D效果。结合实际案例&#xff0c;详细讲解了如何在Vue3项目中引入BabylonJs&#xff0c;并了解其相关知识。通过本文的学习&#xff0c;相信读者可以轻松掌握Vue3实现3D效果以及BabylonJs的相关知识。 Vue3 TypeS…

天梯赛L1-001 ~ 010

&#x1f442; White Lie - Jhameel - 单曲 - 网易云音乐 &#x1f442; 丁丁猫儿 - 施鑫文月 - 单曲 - 网易云音乐 今年蓝桥 / 天梯都陪跑&#xff0c;希望明年&#xff0c;蓝桥杯省一&#xff08;CA组60分&#xff09;&#xff0c;天梯赛国三&#xff08;180分&#xff09;…

详细的实用技巧,让你轻松成为WEB自动化测试大师

目录 一、什么是WEB自动化测试 二、WEB自动化测试工具 三、SeleniumPython环境搭建 1. 安装Python解释器 2. 安装Selenium库 3. 下载浏览器驱动程序 4. 配置环境变量 四、WEB自动化测试实战 1. 编写测试脚本 2. 使用Page Object模式 3. 使用数据驱动测试 五、总结 …

【PowerDesigner】一款超好用的E-R图工具,快速构建出高质量的数据库结构,提高开发效率和代码质量

博主简介&#xff1a;努力学习的大一在校计算机专业学生&#xff0c;热爱学习和创作。目前在学习和分享&#xff1a;数据结构、Go&#xff0c;Java等相关知识。博主主页&#xff1a; 是瑶瑶子啦所属专栏: Mysql从入门到精通 近期目标&#xff1a;写好专栏的每一篇文章 文章目录…

IPsec IKE第一阶段主模式和野蛮模式

国密标准GMT 0022-2014 IPSec VPN 技术规范&#xff0c;IPsec IKE过程中交换类型的定义将主模式Main mode分配值为2&#xff0c;快速模式-quick mode分配值为32。标准中并没有提现分配值为4的交换类型。在实际应用中&#xff0c;IKE第一阶段经常会出现交换类型为4的情况&#x…

留守儿童爱心网站

摘要 随着留守儿童爱心管理的不断发展&#xff0c;留守儿童爱心网站在现实生活中的使用和普及&#xff0c;留守儿童爱心管理成为近年内出现的一个热门话题&#xff0c;并且能够成为大众广为认可和接受的行为和选择。设计留守儿童爱心网站的目的就是借助计算机让复杂的管理操作…