搭建一个人工智能大模型网站

一、准备模型

1、开通阿里云百炼大模型服务平台:https://bailian.console.aliyun.com

2、创建一个大模型应用,记下应用ID

3、在平台内创建一个API KEY

二、准备Python环境

1、准备一台ECS服务器,并开放80端口;

2、部署conda

1)安装conda:yum -y install conda

2)创建一个工作环境:conda create --name python3.8

3)激活工作环境:conda activate python3.8

4)安装python3.8:conda install python=3.8.10

5)查看工作环境:conda env list

3、准备Python包

1)安装百炼SDK:pip install dashscope

2)安装Flask模块:pip install flask

三、编写前端网页

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>千问万象</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        body {
            fond-family: Arial, snas-sarif
        }
        .container {
            max-width: 1000px;
            margin: 50px auto;
            padding: 20px;
            border: 1px solid #ccc;
            background-color: #f9f9f9;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        input[type="text"], button {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
        }
        button {
            background-color: #007BFF;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        #response {
            margin-top: 20px;
            padding: 10px;
            background-color: #e0f7fa;
            border: 1px solid #b2ebf2;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>千问万象</h1>
    <input type="text" id="question" placeholder="请描述您的问题……">
    <button id="submit">提交</button>
    <div id="response">答:</div>
</div>

<script>
$(document).ready(function() {
    $('#submit').click(function() {
        var question = $('#question').val();
        if (!question) {
            alert('Please enter a question!');
            return;
        }

        $.ajax({
            url: '/ask',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ "question": question }),
            success: function(response) {
                $('#response').html('<p>Answer: ' + response + '</p>');
            },
            error: function(xhr, status, error) {
                $('#response').html('<p>Error: ' + xhr.responseText + '</p>');
            }
        });
    });
});
</script>
</body>
</html>

四、编写后端代码

import random

import dashscope

from http import HTTPStatus

from dashscope import Application

from flask import Flask, request, make_response

app = flask(_name_)

dashscope.api_key = 'sk-*******'

SEARCH_APPID = '*******'

def call_with_messages(user_input):

    response = Application.call(

        app_id = SEARCH_APPID,

        prompt = user_input,

        api_key = dashscope.api_key

    )

    if response.status_code != HTTPStatu.OK:

        print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (

            response.request_id, response.status_code, response.code, response.message ))

        return None

    else:

        print(f'Response output: {response.output}')

        if hasattr(response.output, 'text'):

            return response.output.text

        else:

            print("Error: Response dose not contain valid 'text'")

            return None

@app.route('/ask', methods=['POST'])

def ask_question():

    try:

        data = request.get_json()

        question = request.get('question')

        if not question:

            return make_response("Error: Missing question parameter", 400)

        answer = call.with.messages(question)

        if answer is not none:

            return make_response(answer, 200)

        else:

            return make_response("Error: Failed to get a response from the model", 500)

    except Exception as e:

        return make_response(str(e), 500)

@app.route('/')

def serve_html():

    with open('html/index.html', 'r') as file:

        content = file.read()

    return content

if _name_ == '_main_':

    app.run(host='0.0.0.0', port=80)

五、测试服务

1、启动脚本:nohup python app.py >> app.log &

2、浏览器访问本机80端口进行测试。

搭建大语言模型需经过多个步骤。首先,大型学习模型必须进行预训练,然后经过微调,以使其能够处理人类语言,解决文本分类、文本生成、问题解答和文档摘要等任务[^2]。 随着Llama 2、通义千问7B等大语言模型开源,开发者可基于这些开源模型搭建自己的对话系统、Agent等,但在搭建过程中,因国情需要对模型进行特殊的“安全性”考虑,例如搭建敏感词过滤系统,保证与用户的交互不会出现“有害信息”[^3]。 为了让更多人能参与到大语言模型技术中,有关于对话AI构建者从基础到应用的大语言模型全景培训,可帮助学习者掌握搭建大语言模型所需的理论基础和实践经验,以便将大语言模型应用于实际项目中[^1]。 ### 相关代码示例 以下是一个简单的示意代码,展示如何使用Python和一些常见库来模拟一个简单的文本生成模型(此代码并非完整的大语言模型搭建代码): ```python import torch import torch.nn as nn import torch.optim as optim # 简单的语言模型示例 class SimpleLanguageModel(nn.Module): def __init__(self, vocab_size, embedding_dim, hidden_dim): super(SimpleLanguageModel, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim) self.rnn = nn.RNN(embedding_dim, hidden_dim, batch_first=True) self.fc = nn.Linear(hidden_dim, vocab_size) def forward(self, x): embedded = self.embedding(x) output, _ = self.rnn(embedded) logits = self.fc(output) return logits # 示例参数 vocab_size = 1000 embedding_dim = 128 hidden_dim = 256 model = SimpleLanguageModel(vocab_size, embedding_dim, hidden_dim) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) # 模拟训练数据 input_data = torch.randint(0, vocab_size, (10, 20)) # 10个序列,每个序列长度为20 target_data = torch.randint(0, vocab_size, (10, 20)) # 训练模型 for epoch in range(10): optimizer.zero_grad() output = model(input_data) loss = criterion(output.view(-1, vocab_size), target_data.view(-1)) loss.backward() optimizer.step() print(f'Epoch {epoch+1}, Loss: {loss.item()}') ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值