NewBingダイアログ機能をNode端末上で実現

目次

序文

準備

動作原理

機能設計

実装プロセス

基本的な考え方

演技

聞く

ソケット

コンソール入力モジュール

設定ファイル

bingサーバーリクエスト

bingソケットメッセージ

サブスレッド入力部

メインスレッド部分

ツール機能

結果を示す

最後に書きます


序文

ChatGPT は現在ホットな話題になっており、GPT-4 のリリースに伴い、そのインターフェイスに関する記事がインターネット上に増えています。しかし今日は、GPT について話す代わりに、その古い友人である newbing について話しましょう。

以前、openAI と chatGPT のドッキングに関するいくつかの記事を公開しました: Node builds GPT インターフェイスNode robot音声認識と合成. 誰もがそのような記事に非常に興味を持っているので、NewBing のインターフェイスと対話メソッドを詳しく調査することにしました. 興味がある場合は、引き続き読んでください。

準備

動作原理

まず、NewBing の実装原理を見てみましょう

VPN に接続し、Bing を開き、Bing アカウントにログインします。

[Edge で開く] と表示されている場合は、Edge をダウンロードするか、chathubプラグインを使用できます。

ここでは Edge を例に挙げます。Edge では、[今すぐチャット] をクリックして使用を開始できます。

F12を開き、ハッキングするネットワークメニューに入り、ダイアログを入力して送信し、newbingとのチャットを開きます

ダイアログを送受信するときに、ブラウザーは新しいダイアログを作成するリクエストを送信し、WebSocket 接続を確立し、最後にダイアログの結果をページに送信することがわかります。

機能設計

プログラムの動作原理を理解したので、その機能を実現するアイデアがあり、ノードのコンソールに NewBing と対話する機能を実装する予定です。

上記のプロセスを簡単に説明すると、ユーザーはコマンドを通じて newBing コンソールを開き、送信されるダイアログに直接入力し、一定時間待機し、メッセージのフィードバックを受信して​​、次のダイアログを続行します。

このメソッドはコンソールで使用できるだけでなく、クライアントが呼び出すインターフェイスやメッセージを提供するためにサービスまたは WebSocket の形式で記述することもできます。ここでは、レンガを投げて翡翠を引き付け、フォローアップ機能をマスターに任せます。

実装プロセス

基本的な考え方

演技

プロキシ エージェント モジュールを使用して、VPN が配置されているポートに要求とソケットをプロキシし、プロキシ経由で Bing にアクセスしてメッセージを取得します。

import ProxyAgent from "proxy-agent"
const agent = ProxyAgent('http://127.0.0.1:10240')// 访问vpn代理地址

エージェントパラメータを介してエージェント機能を使用する

聞く

request 関数は以前に作成したツールキットを使用しており、対応する catchAwait 関数と一緒に使用することをお勧めします。

import { Request, catchAwait } from "utils-lib-js"
const bingRequest = new Request('https://www.bing.com')// 初始化请求地址
bingRequest.use("error", console.error)// 拦截抛错
const [err, res] = await catchAwait(this.bingRequest.GET("/turing/conversation/create"))// 发起请求

ソケット

WebSocketの使い方は前回の記事を参照してください。

コンソール入力モジュール

readline モジュールを使用してコンソール入力を受信します

import readline from "readline";
readline.createInterface({
    input: process.stdin,
    output: process.stdout,
}).question('请输入:', ()=>{
    // 输入完成,敲击了回车
})

設定ファイル

bing の cookie は、任意のブラウザでNewBing Web サイトを開いて F12 キーを押すことで取得でき (アカウントがログインしている場合)、document.cookie を直接入力して取得できることに注意してください。

export const config = {
  cookie: "必应的cookie",
  bingUrl: "https://www.bing.com",
  proxyUrl: "http://127.0.0.1:10240",
  bingSocketUrl: "wss://sydney.bing.com",
};
export const conversationTemplate = {
  arguments: [
    {
      source: "cib",
      optionsSets: [
        "deepleo",
        "nlu_direct_response_filter",
        "disable_emoji_spoken_text",
        "responsible_ai_policy_235",
        "enablemm",
        "dtappid",
        "rai253",
        "dv3sugg",
        "h3imaginative",
      ],
      allowedMessageTypes: ["Chat", "InternalSearchQuery"],
      isStartOfSession: true,
      message: {
        author: "user",
        inputMethod: "Keyboard",
        text: "",
        messageType: "Chat",
      },
      conversationId: "",
      conversationSignature: "",
      participant: {
        id: "",
      },
    },
  ],
  invocationId: "0",
  target: "chat",
  type: 4,
};

bingサーバーリクエスト

リクエストはインターフェースであり、インターフェースは外部に公開されます。

import { Request, catchAwait, MessageCenter } from "utils-lib-js"
import { config } from "../config.js"
// 请求对话信息接口的响应信息
export type IBingInfo = {
    clientId: string
    conversationId: string
    conversationSignature: string
    result: {
        message: unknown
        value: string
    }
}
// 切换可选项,防止报错
export type IBingInfoPartial = Partial<IBingInfo>
// 静态配置项结构
export type IConfig = {
    cookie: string
    proxyUrl: string
    bingUrl: string
    bingSocketUrl: string
}
// NewBingServer的构造函数配置
export type IOpts = {
    agent?: any
}
export class NewBingServer extends MessageCenter {
    bingInfo: IBingInfo
    readonly bingRequest: Request
    constructor(private opts: IOpts, private _config: IConfig = config) {
        super()
        const { bingUrl } = this._config
        this.bingRequest = new Request(bingUrl)// 初始化请求地址
        this.initServer()// 初始化request: 拦截器等
    }
    // 抛错事件
    throwErr(err: any) {
        this.emit("new-bing:server:error", err)
    }
    // 重置当前请求
    async reset() {
        this.clearBing()
        const bingInfo = await this.createConversation()
        this.init(bingInfo)
    }
    // 清除当前请求的信息
    clearBing() {
        this.bingInfo = null
    }
    // 赋值当前请求的信息
    init(bingInfo) {
        this.bingInfo = bingInfo
    }
    // 初始化request
    initServer() {
        this.bingRequest.use("error", console.error)
        // .use("response", console.log)
    }
    // 发起请求
    private async createConversation() {
        const { _config, opts, bingInfo } = this
        const { agent } = opts
        if (bingInfo) return bingInfo
        const { cookie } = _config
        const [err, res] = await catchAwait(this.bingRequest.GET("/turing/conversation/create", {}, null, {
            headers: { cookie },
            agent
        }))
        if (err) return this.throwErr(err)
        return res
    }
}

bingソケットメッセージ

ソケットの内容は多数あり、主にさまざまなメッセージ タイプを区別するために使用されます。

import WebSocket, { MessageEvent, Event, ErrorEvent, CloseEvent } from "ws";
import { getType, IObject, jsonToString, MessageCenter, stringToJson } from "utils-lib-js"
import { ClientRequestArgs } from "http"
import { config } from "../config.js"
import { IConfig, IBingInfoPartial } from "../server/index.js"
import { setConversationTemplate, Conversation } from '../helpers/index.js'
const fixStr = ''// 每段对话的标识符,发送接收都有
// websocket配置
export type IWsConfig = {
    address: string | URL
    options: WebSocket.ClientOptions | ClientRequestArgs
    protocols: string | string[]
}
// 发送socket消息的类型
export type IMessageOpts = {
    message: string | IObject<any>
}
// 发送对话的结构
export type IConversationMessage = {
    message: string
    invocationId: string | number
}
export class NewBingSocket extends MessageCenter {
    private ws: WebSocket // ws实例
    private bingInfo: IBingInfoPartial // 请求拿到的conversation信息
    private convTemp: Conversation.IConversationTemplate // 对话发送的消息模板
    private pingInterval: NodeJS.Timeout | string | number // ping计时器
    constructor(public wsConfig: Partial<IWsConfig>, private _config: IConfig = config) {
        super()
        const { bingSocketUrl } = this._config
        const { address } = wsConfig
        wsConfig.address = bingSocketUrl + address
    }
    // 将conversation信息赋值到消息模板中
    mixBingInfo(bingInfo: IBingInfoPartial) {
        const { conversationId, conversationSignature, clientId } = bingInfo
        this.bingInfo = bingInfo
        this.convTemp = setConversationTemplate({
            conversationId, conversationSignature, clientId
        })
        return this
    }
    // 创建ws
    createWs() {
        const { wsConfig, ws } = this
        if (ws) return this
        const { address, options, protocols } = wsConfig
        this.ws = new WebSocket(address, protocols, options)
        return this
    }
    // 重置ws
    clearWs() {
        const { ws } = this
        if (ws) {
            ws.close(4999, 'clearWs')
        }
        this.clearInterval()
        return this
    }
    // 抛错事件
    private throwErr(err: any) {
        this.emit("new-bing:socket:error", err)
    }
    // 开启ws后初始化事件
    initEvent() {
        const { ws, error, close, open, message } = this
        if (!ws) this.throwErr("ws未定义,不能初始化事件")
        ws.onerror = error
        ws.onclose = close
        ws.onopen = open
        ws.onmessage = message
        return this
    }
    // 发消息,兼容Object和string
    sendMessage = (opts: IMessageOpts) => {
        const { bingInfo, convTemp, ws } = this
        const { message } = opts
        if (!bingInfo || !convTemp) this.throwErr("对话信息未获取,或模板信息未配置,请重新获取信息")
        const __type = getType(message)
        let str = ""
        if (__type === "string") {
            str = message as string
        } else if (__type === "object") {
            str = jsonToString(message as IObject<unknown>)
        }
        this.emit("send-message", str)
        ws.send(str + fixStr)
    }
    // 收到消息
    private message = (e: MessageEvent) => {
        this.emit("message", e)
        onMessage.call(this, e)
    }
    // ws连接成功
    private open = (e: Event) => {
        this.emit("open", e)
        const { sendMessage } = this
        sendMessage({ message: { "protocol": "json", "version": 1 } })// 初始化
    }
    // ws关闭
    private close = (e: CloseEvent) => {
        const { ws } = this
        ws.removeAllListeners()
        this.ws = null
        this.emit("close", e)
    }
    // ws出错
    private error = (e: ErrorEvent) => {
        this.emit("error", e)
        console.log("error");
    }
    // 断线检测
    sendPingMsg() {
        const { ws } = this
        if (!ws) this.throwErr("ws未定义,无法发送Ping")
        this.startInterval()
        this.emit("init:finish", {})
    }
    // 开启断线定时器
    private startInterval() {
        this.clearInterval()
        this.pingInterval = setInterval(() => {
            this.sendMessage({ message: { "type": 6 } })
        }, 20 * 1000)
    }
    // 清空断线定时器
    private clearInterval() {
        const { pingInterval } = this
        if (pingInterval) {
            clearInterval(pingInterval)
            this.pingInterval = null
        }
    }
}

// 接收到消息
export function onMessage(e: MessageEvent) {
    const dataSource = e.data.toString().split(fixStr)[0]
    const data = stringToJson(dataSource)
    const { type } = data ?? {}
    switch (type) {
        case 1://对话中
            this.emit("message:ing", data.arguments?.[0]?.messages?.[0]?.text)
            break;
        case 2://对话完成
            this.emit("message:finish", data.item?.messages?.[1]?.text)
            break;
        case 6://断线检测
            // console.log(data);
            break;
        case 7://Connection closed with an error
            console.log(data);
            break;
        default:// 初始化响应
            this.sendPingMsg()
            break;
    }
}
// 发送聊天消息
export function sendConversationMessage(params?: IConversationMessage) {
    const { message, invocationId } = params
    const arg = this.convTemp.arguments[0]
    arg.message.text = message
    arg.isStartOfSession = invocationId === 0// 是否是新对话
    this.convTemp.invocationId = invocationId.toString()// 第几段对话
    this.sendMessage({ message: this.convTemp })
}

サブスレッド入力部

次に、startBingConversation をエントリ関数として使用して、上記の 2 つのモジュールを呼び出します

import { NewBingServer, IBingInfoPartial } from "./server/index.js"
import { NewBingSocket, sendConversationMessage } from "./socket/index.js"
import { config } from "./config.js"
import ProxyAgent from "proxy-agent"
import { parentPort } from "worker_threads";

const { proxyUrl } = config// 代理地址
const agent = ProxyAgent(proxyUrl)// 访问vpn代理地址
// 初始化bing请求
const bingServer = new NewBingServer({
    agent
})
// 初始化bing的websocket消息
const bingSocket = new NewBingSocket({
    address: "/sydney/ChatHub",
    options: {
        agent
    }
})
let invocationId = -1// 同一段对话的id
let bingInfo: IBingInfoPartial// bing的conversation信息,BingServer请求的结果
const startBingConversation = async () => {
    initEvent()
    await initBingServer()
    initBingSocket()
}

const initEvent = () => {
    bingServer.on("new-bing:server:error", (...args) => { throw new Error(...args) })// 请求抛错
    bingSocket.on("new-bing:socket:error", (...args) => { throw new Error(...args) })// 消息抛错
    // 接收主线程的消息
    parentPort.on("message", (res) => {
        const { type } = res
        if (type === "sendMessage") {
            // 发送消息
            sendConversationMessage.call(bingSocket, { message: res.message, invocationId: ++invocationId })
        }
    })
}
const initBingServer = async () => {
    await bingServer.reset()// 重置请求
    bingInfo = bingServer.bingInfo
}
const initBingSocket = () => {
    bingSocket.mixBingInfo(bingInfo).createWs().initEvent().on("init:finish", () => {// socket初始化完成
        parentPort.postMessage({
            type: "init:finish"
        })
    }).on("message:finish", (data = "") => {
        // 一段对话完成
        parentPort.postMessage({
            type: "message:finish",
            data
        })
    }).on("message:ing", (data = "") => {
        // 对话时,触发主线程loading操作
        parentPort.postMessage({
            type: "message:ing",
            data
        })
    })
}

startBingConversation()

メインスレッド部分

メインスレッドは、以前のパッケージ化ツールを参照し、システム コマンドとして登録し、bing を使用して起動し、readline を通じて通信できます。

#!/usr/bin/env node
import { Worker } from "worker_threads";
import readline from "readline";
import { defer, logLoop, logOneLine } from "utils-lib-js";
const NewBing = new Worker("./src/index.js");
// 工厂模式
const readlineFactory = () => {
  return readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
};
let rl, loading;
// 解决node低版本无readline/promises模块,将异步函数换成promise
const readlinePromise = (...args) => {
  const { promise, resolve } = defer();
  rl.question(...args, resolve);
  return promise;
};
// 启动命令输入
const start = () => {
  readlinePromise("请输入:").then((res) => {
    console.log(`你:${res}`);
    NewBing.postMessage({ type: "sendMessage", message: res });
    loading = logLoop(); // 加载中动画
  });
};
// 关闭命令输入
const clear = () => {
  rl.close();
  rl = null;
};
// 重置
const reset = () => {
  if (rl) {
    clear();
  }
  rl = readlineFactory();
};
// 初始化当前命令窗口
const initBing = () => {
  reset();
  NewBing.on("message", (res) => {
    switch (res.type) {
      case "message:finish": // 收到消息,重置输入框,换行
        loading.isStop = true;
        logOneLine(`Bing:${res.data}`, true, true);
      case "init:finish": // 初始化完成
        start();
        break;
      case "message:ing": // 对话中
        // loading = logLoop(loadList);
        break;
    }
  });
};
initBing();

ツール機能


import { conversationTemplate } from "../config.js"
import { readFileSync, writeFileSync } from "fs"
let conTemp: Conversation.IConversationTemplate = conversationTemplate
export namespace Conversation {
    // 对话模型类型
    // Creative:创造力的,Precise:精确的,Balanced:平衡的
    type ConversationStyle = 'Creative' | 'Precise' | 'Balanced'
    // 对话方式
    type ConversationType = 'SearchQuery' | 'Chat' // bing搜索,聊天
    // 模型映射
    export enum ConversationStr {
        Creative = 'h3imaginative',
        Precise = 'h3precise',
        Balanced = 'galileo'
    }
    // 发起对话时传入的参数
    export type IConversationOpts = {
        convStyle: ConversationStyle
        messageType: ConversationType
        conversationId: string
        conversationSignature: string
        clientId: string
    }
    type IMessage = {
        author: string,
        text: string,
        messageType: ConversationType,
    }
    type IArguments = {
        source: string
        optionsSets: string[]
        allowedMessageTypes: string[]
        isStartOfSession: boolean
        message: IMessage
        conversationId: string
        conversationSignature: string
        participant: {
            id: string
        }
    }
    // 发起对话的模板
    export type IConversationTemplate = {
        arguments: IArguments[]
        invocationId: string
        target: string
        type: number
    }
}
// 默认使用平衡类型
const { Balanced } = Conversation.ConversationStr
// 数据文件缓存(暂时没用上,调试的时候用的)
export function ctrlTemp(path?: string): any
export function ctrlTemp(path?: string, file?: any): void
export function ctrlTemp(path: string = "./temp", file?: string) {
    try {
        if (file) {
            return writeFileSync(path, file, "utf8")
        }
        return readFileSync(path, "utf8")
    } catch (error) { }
}

// 配置socket鉴权及消息模板
export function setConversationTemplate(params: Partial<Conversation.IConversationOpts> = {}): Conversation.IConversationTemplate {
    const { convStyle = Balanced, messageType = "Chat", conversationId,
        conversationSignature, clientId } = params
    if (!conversationId || !conversationSignature || !clientId) return null
    const args = conTemp.arguments[0]
    conTemp.arguments[0] = {
        ...args,
        conversationId,
        conversationSignature,
        participant: { id: clientId }
    }
    args.optionsSets.push(convStyle)// 这里传入对话风格
    args.message.messageType = messageType// 这里传入对话类型
    return conTemp
}

結果を示す

npmリンクを使用してグローバルコマンドをバインドします

次に、bing を使用してコマンドを実行し、ダイアログに入ります。

最後に書きます

以上が記事の全内容です。主にnodeにnewbingとの対話を実装する場合について説明しています。参考になれば幸いです。記事についてのご質問は、コメントまたはプライベートメッセージにてお問い合わせください。

読んでいただきありがとうございます、この記事が良いと思っていただけましたらサポートをお願いいたします、ありがとうございました!

ソースコード:Node-NewBing:node+NewBingが提供するAIモデルをベースにした事例

おすすめ

転載: blog.csdn.net/time_____/article/details/130027484