在Node.js中调用本地大语言模型API(Qwen模型)

在Node.js中调用本地大语言模型API(Qwen模型)

实验概述

现在大语言模型本地化越来越普及,如何将本地训练及添加好知识库的大语言模型对外提供服务,并且在我们的Web应用项目中进行调用,就是本节所要讲解的内容。

实验条件

  • 我们使用2.2节中的Qwen_1.8B_Int4语言模型提供的API
  • 前端我们使用Vue框架的axios进行接口调用

功能实现

启动Qwen_1.8B_Int4量化语言模型

服务端运行信息:
    OpenAI API Server: http://127.0.0.1:20000/v1
    Chatchat  API  Server: http://127.0.0.1:7861
    Chatchat WEBUI Server: http://127.0.0.1:8501

其中地址http://127.0.0.1:7861就是我们要调用的接口服务地址。在浏览器打开该地址,可以查看Langchain chatchat框架为我们提供的接口说明,如下图所示:
image.png

我们先来测试与语言模型对话

新建Vue项目

HomeView源码如下:

<template>
  <div class="home">
    <div><h2>QWen_1_8B_Int4_API测试</h2></div>
    <div>
      <input v-model="requestBody.query" type="text" />
    </div>
    <div>
      <button @click="doTest">测试请求</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: "HomeView",
  components: {},
  data() {
    return {
      requestBody: {
        query: "你好",
        conversation_id: "",
        history_len: -1,
        history: [],
        stream: false,
        model_name: "Qwen-1_8B-Chat-Int4",
        temperature: 0.7,
        max_tokens: 0,
        prompt_name: "default",
      },
    };
  },
  methods: {
    async doTest() {
      let res = await this.$http.post("api/chat/chat", this.requestBody);
      console.log(res);
    },
  },
};
</script>

注意:这里本地会有跨端口的请求发生,我们还需要进行跨域配置,在项目根目录中vue.config.js文件中添加代理信息:
完整代码如下:

const {
  defineConfig
} = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  // 公共路径(必须有的)
  publicPath: "./",
  // 输出文件目录
  outputDir: "dist",
  // 静态资源存放的文件夹(相对于ouputDir)
  assetsDir: "assets",
  // eslint-loader 是否在保存的时候检查(果断不用,这玩意儿我都没装)
  lintOnSave: false,
  // 我用的only,打包后小些
  runtimeCompiler: false,
  productionSourceMap: false, // 不需要生产环境的设置false可以减小dist文件大小,加速构建
  // productionGzip: true,

  devServer: {
    open: true, // npm run serve后自动打开页面
    host: '0.0.0.0', // 匹配本机IP地址(默认是0.0.0.0)
    port: 8089, // 开发服务器运行端口号
    // proxy:null,
    proxy: {
      '/api': {    //1
        target: 'http://127.0.0.1:7861/',    //2
        changOrigin: true,
        pathRewrite: {    //3
          '^/api': ''
        }
      }
    },
    // history模式下的url会请求到服务器端,但是服务器端并没有这一个资源文件,就会返回404,所以需要配置这一项

  },
})

修改axios封装文件中的默认请求地址:

//统一请求资源地址  http://localhost:8080/   
axios.defaults.baseURL = "/"

注意这里修改为:/,就是请求根目录。

运行项目:我们在页面输入框中输入请求文字内容,等待片刻就可以看到语言模型API给我们的反馈信息,如下图所示:
image.png

功能基本功能已实现。

注意:
接口响应的数据是字符串类型,并不是标准的json格式,我们需要对代码进行截取和转义:

JSON.parse(res.slice(5)).text

这样读取的内容就是程序输出的内容。

总结

这里我们的实现方式是修改本地代理解决跨域请求问题,在实际项目开发中,跨域请求问题我们使用的Nginx反向代理来解决的。

posted @ 2024-04-23 17:03  冰葉丶月  阅读(569)  评论(0)    收藏  举报