此 HTML 文件包含聊天消息的容器、用户消息的输入字段和发送按钮。

CSS

接下来,创建一个名为 styles.css 的 CSS 文件来设置聊天应用程序的样式。

body {    font-family: Arial, sans-serif;    display: flex;    justify-content: center;    align-items: center;    height: 100vh;    background-color: #f0f0f0;    margin: 0;}#chat-container {    width: 400px;    border: 1px solid #ccc;    background-color: #fff;    border-radius: 8px;    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);    overflow: hidden;}#chat-window {    height: 300px;    padding: 10px;    overflow-y: auto;    border-bottom: 1px solid #ccc;}#messages {    display: flex;    flex-direction: column;}.message {    padding: 8px;    margin: 4px 0;    border-radius: 4px;}.user-message {    align-self: flex-end;    background-color: #007bff;    color: #fff;}.ai-message {    align-self: flex-start;    background-color: #e0e0e0;    color: #000;}#user-input {    width: calc(100% - 60px);    padding: 10px;    border: none;    border-radius: 0;    outline: none;}#send-button {    width: 60px;    padding: 10px;    border: none;    background-color: #007bff;    color: #fff;    cursor: pointer;}

此 CSS 文件可确保聊天应用程序看起来干净且现代。

JavaScript

创建一个名为 script.js 的 JavaScript 文件来处理前端功能。

document.getElementById(\\'send-button\\').addEventListener(\\'click\\', sendMessage);document.getElementById(\\'user-input\\').addEventListener(\\'keypress\\', function (e) {    if (e.key === \\'Enter\\') {        sendMessage();    }});function sendMessage() {    const userInput = document.getElementById(\\'user-input\\');    const messageText = userInput.value.trim();    if (messageText === \\'\\') return;    displayMessage(messageText, \\'user-message\\');    userInput.value = \\'\\';    // Send the message to the local AI and get the response    getAIResponse(messageText).then(aiResponse => {        displayMessage(aiResponse, \\'ai-message\\');    }).catch(error => {        console.error(\\'Error:\\', error);        displayMessage(\\'Sorry, something went wrong.\\', \\'ai-message\\');    });}function displayMessage(text, className) {    const messageElement = document.createElement(\\'div\\');    messageElement.textContent = text;    messageElement.className = `message ${className}`;    document.getElementById(\\'messages\\').appendChild(messageElement);    document.getElementById(\\'messages\\').scrollTop = document.getElementById(\\'messages\\').scrollHeight;}async function getAIResponse(userMessage) {    // Example AJAX call to a local server interacting with Ollama Llama 3    const response = await fetch(\\'http://localhost:5000/ollama\\', {        method: \\'POST\\',        headers: {            \\'Content-Type\\': \\'application/json\\',        },        body: JSON.stringify({ message: userMessage }),    });    if (!response.ok) {        throw new Error(\\'Network response was not ok\\');    }    const data = await response.json();    return data.response; // Adjust this based on your server\\'s response structure}

此 JavaScript 文件将事件侦听器添加到发送按钮和输入字段,将用户消息发送到后端,并显示用户和 AI 响应。

第 2 步:设置后端

Node.js 和 Express

确保您已安装 Node.js。然后,为后端创建一个server.js文件。

  1. 安装 Express:

    npm install express body-parser
  2. 创建 server.js 文件:

    const express = require(\\'express\\');const bodyParser = require(\\'body-parser\\');const app = express();const port = 5000;app.use(bodyParser.json());app.post(\\'/ollama\\', async (req, res) => {    const userMessage = req.body.message;    // Replace this with actual interaction with Ollama\\'s Llama 3    // This is a placeholder for demonstration purposes    const aiResponse = await getLlama3Response(userMessage);    res.json({ response: aiResponse });});// Placeholder function to simulate AI responseasync function getLlama3Response(userMessage) {    // Replace this with actual API call to Ollama\\'s Llama 3    return `Llama 3 says: ${userMessage}`;}app.listen(port, () => {    console.log(`Server running at http://localhost:${port}`);});
  3. 运行服务器:

    node server.js

在此设置中,您的 Node.js 服务器将处理传入请求,与 Ollama 的 Llama 3 模型交互,并返回响应。

结论

通过执行这些步骤,您已经创建了一个聊天应用程序,该应用程序将用户消息发送到 Ollama 的 Llama 3 模型并显示响应。此设置可以根据您的具体要求和 Llama 3 模型提供的功能进行扩展和定制。

随意探索和增强您的聊天应用程序的功能。快乐编码!

","image":"http://www.luping.net/uploads/20240730/172234584966a8e979668b5.jpg","datePublished":"2024-07-30T21:24:08+08:00","dateModified":"2024-07-30T21:24:08+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 JavaScript、HTML 和 CSS 与 Ollama 的 Llama odel 构建聊天应用程序

使用 JavaScript、HTML 和 CSS 与 Ollama 的 Llama odel 构建聊天应用程序

发布于2024-07-30
浏览:143

Building a Chat Application with Ollama

介绍

在这篇博文中,我们将逐步介绍创建一个与 Ollama 的 Llama 3 模型交互的简单聊天应用程序的过程。我们将使用 JavaScript、HTML 和 CSS 作为前端,并使用 Node.js 和 Express 作为后端。最后,您将拥有一个可以运行的聊天应用程序,它将用户消息发送到 AI 模型并实时显示响应。

先决条件

开始之前,请确保您的计算机上安装了以下软件:

  • Node.js
  • npm(节点包管理器)

第 1 步:设置前端

超文本标记语言

首先,创建一个名为 index.html 的 HTML 文件,它定义聊天应用程序的结构。



    
    
    Chat with Ollama's Llama 3
    


    

此 HTML 文件包含聊天消息的容器、用户消息的输入字段和发送按钮。

CSS

接下来,创建一个名为 styles.css 的 CSS 文件来设置聊天应用程序的样式。

body {
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f0f0;
    margin: 0;
}

#chat-container {
    width: 400px;
    border: 1px solid #ccc;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

#chat-window {
    height: 300px;
    padding: 10px;
    overflow-y: auto;
    border-bottom: 1px solid #ccc;
}

#messages {
    display: flex;
    flex-direction: column;
}

.message {
    padding: 8px;
    margin: 4px 0;
    border-radius: 4px;
}

.user-message {
    align-self: flex-end;
    background-color: #007bff;
    color: #fff;
}

.ai-message {
    align-self: flex-start;
    background-color: #e0e0e0;
    color: #000;
}

#user-input {
    width: calc(100% - 60px);
    padding: 10px;
    border: none;
    border-radius: 0;
    outline: none;
}

#send-button {
    width: 60px;
    padding: 10px;
    border: none;
    background-color: #007bff;
    color: #fff;
    cursor: pointer;
}

此 CSS 文件可确保聊天应用程序看起来干净且现代。

JavaScript

创建一个名为 script.js 的 JavaScript 文件来处理前端功能。

document.getElementById('send-button').addEventListener('click', sendMessage);
document.getElementById('user-input').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
        sendMessage();
    }
});

function sendMessage() {
    const userInput = document.getElementById('user-input');
    const messageText = userInput.value.trim();

    if (messageText === '') return;

    displayMessage(messageText, 'user-message');
    userInput.value = '';

    // Send the message to the local AI and get the response
    getAIResponse(messageText).then(aiResponse => {
        displayMessage(aiResponse, 'ai-message');
    }).catch(error => {
        console.error('Error:', error);
        displayMessage('Sorry, something went wrong.', 'ai-message');
    });
}

function displayMessage(text, className) {
    const messageElement = document.createElement('div');
    messageElement.textContent = text;
    messageElement.className = `message ${className}`;
    document.getElementById('messages').appendChild(messageElement);
    document.getElementById('messages').scrollTop = document.getElementById('messages').scrollHeight;
}

async function getAIResponse(userMessage) {
    // Example AJAX call to a local server interacting with Ollama Llama 3
    const response = await fetch('http://localhost:5000/ollama', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ message: userMessage }),
    });

    if (!response.ok) {
        throw new Error('Network response was not ok');
    }

    const data = await response.json();
    return data.response; // Adjust this based on your server's response structure
}

此 JavaScript 文件将事件侦听器添加到发送按钮和输入字段,将用户消息发送到后端,并显示用户和 AI 响应。

第 2 步:设置后端

Node.js 和 Express

确保您已安装 Node.js。然后,为后端创建一个server.js文件。

  1. 安装 Express:

    npm install express body-parser
    
  2. 创建 server.js 文件:

    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    const port = 5000;
    
    app.use(bodyParser.json());
    
    app.post('/ollama', async (req, res) => {
        const userMessage = req.body.message;
    
        // Replace this with actual interaction with Ollama's Llama 3
        // This is a placeholder for demonstration purposes
        const aiResponse = await getLlama3Response(userMessage);
    
        res.json({ response: aiResponse });
    });
    
    // Placeholder function to simulate AI response
    async function getLlama3Response(userMessage) {
        // Replace this with actual API call to Ollama's Llama 3
        return `Llama 3 says: ${userMessage}`;
    }
    
    app.listen(port, () => {
        console.log(`Server running at http://localhost:${port}`);
    });
    
  3. 运行服务器:

    node server.js
    

在此设置中,您的 Node.js 服务器将处理传入请求,与 Ollama 的 Llama 3 模型交互,并返回响应。

结论

通过执行这些步骤,您已经创建了一个聊天应用程序,该应用程序将用户消息发送到 Ollama 的 Llama 3 模型并显示响应。此设置可以根据您的具体要求和 Llama 3 模型提供的功能进行扩展和定制。

随意探索和增强您的聊天应用程序的功能。快乐编码!

版本声明 本文转载于:https://dev.to/koolkamalkishor/building-a-chat-application-with-ollamas-llama-3-model-using-javascript-html-and-css-40ec?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • 如何处理PHP文件系统功能中的UTF-8文件名?
    如何处理PHP文件系统功能中的UTF-8文件名?
    在PHP的Filesystem functions中处理UTF-8 FileNames 在使用PHP的MKDIR函数中含有UTF-8字符的文件很多flusf-8字符时,您可能会在Windows Explorer中遇到comploreer grounder grounder grounder gro...
    编程 发布于2025-03-28
  • 如何使用组在MySQL中旋转数据?
    如何使用组在MySQL中旋转数据?
    在关系数据库中使用mySQL组使用mySQL组进行查询结果,在关系数据库中使用MySQL组,转移数据的数据是指重新排列的行和列的重排以增强数据可视化。在这里,我们面对一个共同的挑战:使用组的组将数据从基于行的基于列的转换为基于列。 Let's consider the following ...
    编程 发布于2025-03-28
  • 为什么我的CSS背景图像出现?
    为什么我的CSS背景图像出现?
    故障排除:CSS背景图像未出现 ,您的背景图像尽管遵循教程说明,但您的背景图像仍未加载。图像和样式表位于相同的目录中,但背景仍然是空白的白色帆布。而不是不弃用的,您已经使用了CSS样式: bockent {背景:封闭图像文件名:背景图:url(nickcage.jpg); 如果您的html,css...
    编程 发布于2025-03-28
  • 如何在全高布局中有效地将Flexbox和垂直滚动结合在一起?
    如何在全高布局中有效地将Flexbox和垂直滚动结合在一起?
    在全高布局中集成flexbox和垂直滚动Traditional Flexbox Approach (Old Properties)Flexbox layouts using the old syntax (display: box) permit full-height apps with ver...
    编程 发布于2025-03-28
  • 如何使用Python理解有效地创建字典?
    如何使用Python理解有效地创建字典?
    在python中,词典综合提供了一种生成新词典的简洁方法。尽管它们与列表综合相似,但存在一些显着差异。与问题所暗示的不同,您无法为钥匙创建字典理解。您必须明确指定键和值。 For example:d = {n: n**2 for n in range(5)}This creates a dicti...
    编程 发布于2025-03-28
  • 为什么PYTZ最初显示出意外的时区偏移?
    为什么PYTZ最初显示出意外的时区偏移?
    与pytz 最初从pytz获得特定的偏移。例如,亚洲/hong_kong最初显示一个七个小时37分钟的偏移: 差异源利用本地化将时区分配给日期,使用了适当的时区名称和偏移量。但是,直接使用DateTime构造器分配时区不允许进行正确的调整。 example pytz.timezone(...
    编程 发布于2025-03-28
  • 如何配置Pytesseract以使用数字输出的单位数字识别?
    如何配置Pytesseract以使用数字输出的单位数字识别?
    Pytesseract OCR具有单位数字识别和仅数字约束 在pytesseract的上下文中,在配置tesseract以识别单位数字和限制单个数字和限制输出对数字可能会提出质疑。 To address this issue, we delve into the specifics of Te...
    编程 发布于2025-03-28
  • 如何检查对象是否具有Python中的特定属性?
    如何检查对象是否具有Python中的特定属性?
    方法来确定对象属性存在寻求一种方法来验证对象中特定属性的存在。考虑以下示例,其中尝试访问不确定属性会引起错误: >>> a = someClass() >>> A.property Trackback(最近的最新电话): 文件“ ”,第1行, AttributeError: SomeClass...
    编程 发布于2025-03-28
  • 如何在Java中执行命令提示命令,包括目录更改,包括目录更改?
    如何在Java中执行命令提示命令,包括目录更改,包括目录更改?
    在java 通过Java通过Java运行命令命令可能很具有挑战性。尽管您可能会找到打开命令提示符的代码段,但他们通常缺乏更改目录并执行其他命令的能力。 solution:使用Java使用Java,使用processBuilder。这种方法允许您:启动一个过程,然后将其标准错误重定向到其标准输出。...
    编程 发布于2025-03-28
  • 为什么尽管有效代码,为什么在PHP中捕获输入?
    为什么尽管有效代码,为什么在PHP中捕获输入?
    在php ;?>" method="post">The intention is to capture the input from the text box and display it when the submit button is clicked.但是,输出...
    编程 发布于2025-03-28
  • 如何在Java的全屏独家模式下处理用户输入?
    如何在Java的全屏独家模式下处理用户输入?
    Handling User Input in Full Screen Exclusive Mode in JavaIntroductionWhen running a Java application in full screen exclusive mode, the usual event ha...
    编程 发布于2025-03-28
  • Python读取CSV文件UnicodeDecodeError终极解决方法
    Python读取CSV文件UnicodeDecodeError终极解决方法
    在试图使用已内置的CSV模块读取Python中时,CSV文件中的Unicode Decode Decode Decode Decode decode Error读取,您可能会遇到错误的错误:无法解码字节 在位置2-3中:截断\ uxxxxxxxx逃脱当CSV文件包含特殊字符或Unicode的路径逃...
    编程 发布于2025-03-28
  • 找到最大计数时,如何解决mySQL中的“组函数\”错误的“无效使用”?
    找到最大计数时,如何解决mySQL中的“组函数\”错误的“无效使用”?
    如何在mySQL中使用mySql 检索最大计数,您可能会遇到一个问题,您可能会在尝试使用以下命令:理解错误正确找到由名称列分组的值的最大计数,请使用以下修改后的查询: 计数(*)为c 来自EMP1 按名称组 c desc订购 限制1 查询说明 select语句提取名称列和每个名称...
    编程 发布于2025-03-28
  • 为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    网格超过身体,用100%grid-template-columns 为什么在grid-template-colms中具有100%的显示器,当位置设置为设置的位置时,grid-template-colly修复了?问题: 考虑以下CSS和html: class =“ snippet-code”> g...
    编程 发布于2025-03-28
  • 如何使用Java.net.urlConnection和Multipart/form-data编码使用其他参数上传文件?
    如何使用Java.net.urlConnection和Multipart/form-data编码使用其他参数上传文件?
    使用http request 上传文件上传到http server,同时也提交其他参数,java.net.net.urlconnection and Multipart/form-data Encoding是普遍的。 Here's a breakdown of the process:Mu...
    编程 发布于2025-03-28

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3