此 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
浏览:670

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]删除
最新教程 更多>
  • 如何解决AppEngine中“无法猜测文件类型,使用application/octet-stream...”错误?
    如何解决AppEngine中“无法猜测文件类型,使用application/octet-stream...”错误?
    appEngine静态文件mime type override ,静态文件处理程序有时可以覆盖正确的mime类型,在错误消息中导致错误消息:“无法猜测mimeType for for file for file for [File]。 application/application/octet...
    编程 发布于2025-05-11
  • 如何使用PHP从XML文件中有效地检索属性值?
    如何使用PHP从XML文件中有效地检索属性值?
    从php $xml = simplexml_load_file($file); foreach ($xml->Var[0]->attributes() as $attributeName => $attributeValue) { echo $attributeName,...
    编程 发布于2025-05-11
  • 如何使用Depimal.parse()中的指数表示法中的数字?
    如何使用Depimal.parse()中的指数表示法中的数字?
    在尝试使用Decimal.parse(“ 1.2345e-02”中的指数符号表示法表示的字符串时,您可能会遇到错误。这是因为默认解析方法无法识别指数符号。 成功解析这样的字符串,您需要明确指定它代表浮点数。您可以使用numbersTyles.Float样式进行此操作,如下所示:[&& && && ...
    编程 发布于2025-05-11
  • Async Void vs. Async Task在ASP.NET中:为什么Async Void方法有时会抛出异常?
    Async Void vs. Async Task在ASP.NET中:为什么Async Void方法有时会抛出异常?
    在ASP.NET async void void async void void void void void的设计无需返回asynchroncon而无需返回任务对象。他们在执行过程中增加未偿还操作的计数,并在完成后减少。在某些情况下,这种行为可能是有益的,例如未期望或明确预期操作结果的火灾和...
    编程 发布于2025-05-11
  • 如何从2D数组中提取元素?使用另一数组的索引
    如何从2D数组中提取元素?使用另一数组的索引
    Using NumPy Array as Indices for the 2nd Dimension of Another ArrayTo extract specific elements from a 2D array based on indices provided by a second ...
    编程 发布于2025-05-11
  • 找到最大计数时,如何解决mySQL中的“组函数\”错误的“无效使用”?
    找到最大计数时,如何解决mySQL中的“组函数\”错误的“无效使用”?
    如何在mySQL中使用mySql 检索最大计数,您可能会遇到一个问题,您可能会在尝试使用以下命令:理解错误正确找到由名称列分组的值的最大计数,请使用以下修改后的查询: 计数(*)为c 来自EMP1 按名称组 c desc订购 限制1 查询说明 select语句提取名称列和每个名称...
    编程 发布于2025-05-11
  • 切换到MySQLi后CodeIgniter连接MySQL数据库失败原因
    切换到MySQLi后CodeIgniter连接MySQL数据库失败原因
    Unable to Connect to MySQL Database: Troubleshooting Error MessageWhen attempting to switch from the MySQL driver to the MySQLi driver in CodeIgniter,...
    编程 发布于2025-05-11
  • Python高效去除文本中HTML标签方法
    Python高效去除文本中HTML标签方法
    在Python中剥离HTML标签,以获取原始的文本表示Achieving Text-Only Extraction with Python's MLStripperTo streamline the stripping process, the Python standard librar...
    编程 发布于2025-05-11
  • 哪种在JavaScript中声明多个变量的方法更可维护?
    哪种在JavaScript中声明多个变量的方法更可维护?
    在JavaScript中声明多个变量:探索两个方法在JavaScript中,开发人员经常遇到需要声明多个变量的需要。对此的两种常见方法是:在单独的行上声明每个变量: 当涉及性能时,这两种方法本质上都是等效的。但是,可维护性可能会有所不同。 第一个方法被认为更易于维护。每个声明都是其自己的语句,使其...
    编程 发布于2025-05-11
  • PHP与C++函数重载处理的区别
    PHP与C++函数重载处理的区别
    作为经验丰富的C开发人员脱离谜题,您可能会遇到功能超载的概念。这个概念虽然在C中普遍,但在PHP中构成了独特的挑战。让我们深入研究PHP功能过载的复杂性,并探索其提供的可能性。在PHP中理解php的方法在PHP中,函数超载的概念(如C等语言)不存在。函数签名仅由其名称定义,而与他们的参数列表无关。...
    编程 发布于2025-05-11
  • 如何从PHP中的Unicode字符串中有效地产生对URL友好的sl。
    如何从PHP中的Unicode字符串中有效地产生对URL友好的sl。
    为有效的slug生成首先,该函数用指定的分隔符替换所有非字母或数字字符。此步骤可确保slug遵守URL惯例。随后,它采用ICONV函数将文本简化为us-ascii兼容格式,从而允许更广泛的字符集合兼容性。接下来,该函数使用正则表达式删除了不需要的字符,例如特殊字符和空格。此步骤可确保slug仅包含...
    编程 发布于2025-05-11
  • FastAPI自定义404页面创建指南
    FastAPI自定义404页面创建指南
    response = await call_next(request) if response.status_code == 404: return RedirectResponse("https://fastapi.tiangolo.com") else: ...
    编程 发布于2025-05-11
  • 为什么我会收到MySQL错误#1089:错误的前缀密钥?
    为什么我会收到MySQL错误#1089:错误的前缀密钥?
    mySQL错误#1089:错误的前缀键错误descript [#1089-不正确的前缀键在尝试在表中创建一个prefix键时会出现。前缀键旨在索引字符串列的特定前缀长度长度,可以更快地搜索这些前缀。了解prefix keys `这将在整个Movie_ID列上创建标准主键。主密钥对于唯一识别...
    编程 发布于2025-05-11
  • 如何使用组在MySQL中旋转数据?
    如何使用组在MySQL中旋转数据?
    在关系数据库中使用mySQL组使用mySQL组进行查询结果,在关系数据库中使用MySQL组,转移数据的数据是指重新排列的行和列的重排以增强数据可视化。在这里,我们面对一个共同的挑战:使用组的组将数据从基于行的基于列的转换为基于列。 Let's consider the following ...
    编程 发布于2025-05-11
  • 如何在GO编译器中自定义编译优化?
    如何在GO编译器中自定义编译优化?
    在GO编译器中自定义编译优化 GO中的默认编译过程遵循特定的优化策略。 However, users may need to adjust these optimizations for specific requirements.Optimization Control in Go Compi...
    编程 发布于2025-05-11

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

Copyright© 2022 湘ICP备2022001581号-3