xiongzhu 2 лет назад
Родитель
Сommit
4965067a32
7 измененных файлов с 49 добавлено и 288 удалено
  1. 0 112
      bili.ts
  2. 0 5
      handlebars.js
  3. 0 49
      llm.mjs
  4. 0 9
      p.mjs
  5. 49 15
      src/game/game.service.ts
  6. 0 13
      testrxjs.mjs
  7. 0 85
      twitch.mjs

+ 0 - 112
bili.ts

@@ -1,112 +0,0 @@
-import * as crypto from 'crypto'
-import axios from 'axios'
-import { getEncodeHeader } from './src/utils/crypto'
-import * as WebSocket from 'ws'
-import { Proto } from './src/danmu/models/proto.model'
-
-// axios 拦截器
-const api = axios.create({
-    baseURL: 'https://live-open.biliapi.com'
-    // baseURL: "http://test-live-open.biliapi.net" //test
-})
-
-// 鉴权加密处理headers,下次请求自动带上
-api.interceptors.request.use((config) => {
-    const headers = getEncodeHeader(config.data, 'Cwgk7TsPkMtKtGO8rY0LndiF', 'bV9HiQ03OQ0Hk00l90N1QWyAFSI8qR')
-    Object.keys(headers).forEach((key) => {
-        config.headers[key] = headers[key]
-    })
-    return config
-})
-
-let gameInfo, websocketInfo, anchorInfo
-async function start() {
-    const { data } = await api.post('/v2/app/start', { app_id: 1700371901242, code: 'CYCPQYCZ0LJ43' })
-    if (data.code === 0) {
-        console.log('开始成功')
-        console.log(data.data)
-        gameInfo = data.data.game_info
-        websocketInfo = data.data.websocket_info
-        anchorInfo = data.data.anchor_info
-    } else {
-        console.log('开始失败')
-        console.log(data)
-    }
-}
-
-async function end(gameId) {
-    const { data } = await api.post('/v2/app/end', {
-        app_id: 1700371901242,
-        game_id: gameId
-    })
-    if (data.code === 0) {
-        console.log('结束成功')
-    } else {
-        console.log('结束失败')
-        console.log(data)
-    }
-}
-
-let heartbeatTimer
-function heartbeat(gameId) {
-    heartbeatTimer = setInterval(async () => {
-        const { data } = await api.post('/v2/app/batchHeartbeat', {
-            game_ids: [gameId]
-        })
-        if (data.code === 0) {
-            console.log('心跳成功')
-        } else {
-            console.log('心跳失败')
-            console.log(data)
-        }
-    }, 1000)
-}
-
-// heartbeat('83dc18da-c141-439e-8421-081a11045f5d')
-// end( '80cb8117-fd90-48d2-a382-e609219879a4')
-let ws = null
-start().then(() => {
-    heartbeat(gameInfo.game_id)
-    try {
-        ws = new WebSocket(websocketInfo.wss_link[1])
-
-        ws.on('error', console.error)
-
-        ws.on('open', function open() {
-            const proto = new Proto()
-            proto.op = 7
-            proto.body = websocketInfo.auth_body
-            ws.send(proto.pack())
-
-            setTimeout(() => {
-                const proto = new Proto()
-                proto.op = 2
-
-                ws.send(proto.pack())
-            }, 1000)
-        })
-
-        ws.on('message', function message(data, isBinary) {
-            console.log('received: %s', data)
-            try {
-                const proto = new Proto()
-                proto.unpack(data)
-                console.log(proto.body)
-            } catch (error) {
-                console.log(error.stack)
-            }
-        })
-    } catch (error) {
-        console.log(error.stack)
-    }
-})
-
-setTimeout(() => {
-    end(gameInfo.game_id)
-    if (heartbeatTimer) {
-        clearInterval(heartbeatTimer)
-    }
-    if (ws) {
-        ws.close()
-    }
-}, 60000)

+ 0 - 5
handlebars.js

@@ -1,5 +0,0 @@
-"use strict";
-exports.__esModule = true;
-var handlebars = require("handlebars");
-var t = handlebars.compile('Hello {{name}}');
-console.log(t({ name: 'world' }));

+ 0 - 49
llm.mjs

@@ -1,49 +0,0 @@
-import { ChatOpenAI } from 'langchain/chat_models/openai'
-import fs from 'fs'
-const llm = new ChatOpenAI({
-    openAIApiKey: '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',
-    modelName: 'gpt-3.5-turbo-0613',
-    // azureOpenAIApiKey: '62dd8a1466524c64967810c692f0197e',
-    // azureOpenAIApiVersion: '2023-03-15-preview',
-    // azureOpenAIApiInstanceName: 'zouma1',
-    // azureOpenAIApiDeploymentName: 'gpt-35-turbo',
-    maxRetries: 3,
-    configuration: {
-        baseURL: 'https://openai.c8c.top/v1'
-    },
-    onFailedAttempt: (error) => {
-        console.log(error.code)
-    }
-})
-
-try {
-    const response = await llm.call(
-        [
-            `您的任务是为我的小说剧情产生一个最终的的摘要
-我们已经提供了一个到某个剧情节点的摘要: "在10月8日晚上,约翰成功逃脱了一个致命的陷阱,并揭示了黑人岛的秘密组织。他发现组织计划在10月9日使用毒药,并决定利用爆炸物摧毁实验室。虽然受到了特工的追捕,但他成功地返回岛上并警告其他宾客。随着他们的团结行动,实验室被摧毁,组织的阴谋被阻止。10月10日下午,艾米丽发现了一辆藏匿在岛上的秘密列车,并决定和其他宾客潜入列车,寻找更多线索。
-
-他们来到了列车尽头的车厢,发现一间隐藏房间,里面摆满了各种神秘设备。伊莎贝拉发现了一本笔记,上面详细记录了组织计划在全球范围内发动一系列恐怖袭击。亚历山大辨别出笔记上的手写字迹中隐藏着一个名字:"亨德里克森"。艾米丽立刻想到之前一名追捕她们的特工,伊莎贝拉勉强钦定了他为卧底。他们决心找到亨德里克森并阻止恐怖袭击的发生。
-
-10月10日晚上,艾米丽和伊莎贝拉融入了恐怖分子的集会,暗中侦查,寻找关键情报。突然,一个小女孩走向她们,递给她们一个笔记本,上面写着:“这个集会是一个陷阱,你们需要离开。”艾米丽和伊莎贝拉急忙转身,却发现集会已被锁住。惊慌失措中,他们注意到聚光灯瞄向他们,突然,枪声响起!一连串的枪击声中,艾米丽和伊莎贝拉奋力回击。在血雨腥风中,她们成功逃脱集会,但却不知道真正的陷阱即将到来。
-
-10月11日上午,亚历山大潜入组织总部的一楼实验室,发现了一批正在研发的新型毒气。他决定找到控制室,关闭实验室门,阻止毒气散播。艾米丽、威廉和伊莎贝拉在外面保护他。亚历山大穿越走廊,躲避巡逻的特工,终于进入控制室。他成功关闭了门,但突然触发了一个警报,组织的特工们开始围攻控制室。亚历山大抵御着攻击,艾米丽、威廉和伊莎贝拉赶到,提供支援。在惊心动魄的枪战中,他们勉力保护亚历山大,最终击退了特工,控制室恢复安静。他们急忙寻找关键文件,却发现亨德里克森已经提前离开。他们决定追踪他的下落,揭开更大的阴谋。
-
-10月11日下午,艾米丽、威廉、伊莎贝拉和亚历山大在厅堂中发现了一扇隐藏的地下室门。进入地下室后,他们发现里面摆满了锁链和刑具,墙壁上涂满了血迹。探索地下室时,他们发现了一个被组织抓来进行实验的男子。男子告诉他们更多组织的恶行,还提及有着一个更大的计划。他们决定帮助男子逃脱,揭露更多的真相。然而,特工们围住了地下室,他们必须想办法逃脱。
-
-经过艰辛调查和惊险行动,他们最终击败了特工并成功逮捕了亨德里克森。在他们彻底揭露组织的真相后,他们"
-现在,我们提供了一些新的剧情信息,可以用来完善原始摘要(如果有用的话)
-------------
-"10月11日晚上
-亚历山大和组织首领的决斗开始了,没人知道他们将如何收场。同时,艾米丽、威廉和伊莎贝拉被迫与亨德里克森激战,以保护他们的生命和揭露真相。战斗中,亚历山大的洞察力让他发现了首领的弱点,并成功将其击败。然而,就在他们以为胜利在望时,一枚定时炸弹被激活。伊莎贝拉紧急分析炸弹结构,却发现解除密码紧缺。三人必须快速决定,是拆除炸弹还是逃跑!"
-------------
-根据新的剧情,完善原始摘要,尽量完整包含所有情节内容,省略与情节无关的内容,最终的摘要不要太长
-如果新的剧情没有用处,返回原始摘要。
-最终的的摘要:`
-        ],
-        { maxRetries: 3 }
-    )
-    console.log(response.content)
-} catch (error) {
-    console.log(JSON.stringify(error, null, 4))
-    console.log(error.code)
-}

+ 0 - 9
p.mjs

@@ -1,9 +0,0 @@
-import * as https from 'https'
-import { HttpsProxyAgent } from 'https-proxy-agent'
-
-const agent = new HttpsProxyAgent('http://localhost:7890')
-
-https.get('https://www.google.com', { agent }, (res) => {
-    console.log('"response" event!', res.headers)
-    res.pipe(process.stdout)
-})

+ 49 - 15
src/game/game.service.ts

@@ -27,7 +27,7 @@ import { StructuredOutputParser } from 'langchain/output_parsers'
 import { z } from 'zod'
 import { UpdateGameDto } from './dto/update-game.dto'
 import { encoding_for_model } from 'tiktoken'
-import { startOfDay, getHours, format, addDays, differenceInSeconds, addMinutes } from 'date-fns'
+import { startOfDay, getHours, format, addDays, differenceInSeconds, addMinutes, differenceInDays } from 'date-fns'
 import { zhCN } from 'date-fns/locale'
 import { GameStatus } from './enums/game-status.enum'
 import dedent from 'dedent'
@@ -452,7 +452,12 @@ export class GameService implements OnModuleInit {
                 : ''
         })
 
-        const response = await this.callLLM([new HumanMessage(input)])
+        const vars = {
+            days: Math.floor(differenceInDays(date, history[0].date)),
+            charactors: charactors
+        }
+
+        const response = await this.callLLM([new HumanMessage(this.evalPrompt(vars, input))])
         plot = response.content
 
         this.send(`${id}`, {
@@ -488,7 +493,7 @@ export class GameService implements OnModuleInit {
 
             options = (
                 await Promise.all([
-                    this.createOptions(game.type, charactors, `${summary}\n\n${formatedDatatime}\n${plot}`),
+                    this.createOptions(game.type, charactors, `${summary}\n\n${formatedDatatime}\n${plot}`, vars),
                     delay
                 ])
             )[0]
@@ -535,7 +540,11 @@ export class GameService implements OnModuleInit {
             const run = game.status === GameStatus.Running
             return await this.end(id).then((res) => {
                 if (game.autoReset) {
-                    this.resetGame(id, run)
+                    this.sysConfig.getNumber('reset_delay', 0).then((resetDelay) => {
+                        setTimeout(resetDelay * 1000).then(() => {
+                            this.resetGame(id, run)
+                        })
+                    })
                 }
                 return res
             })
@@ -634,15 +643,13 @@ export class GameService implements OnModuleInit {
                 lastState: undefined
             })
         )
-        const resetDelay = await this.sysConfig.getNumber('reset_delay', 0)
-        setTimeout(resetDelay * 1000).then(() => {
-            this.send(`${game.id}`, {
-                type: 'reset',
-                data: {
-                    newGameId: newGame.id,
-                    firstState: newState
-                }
-            })
+
+        this.send(`${game.id}`, {
+            type: 'reset',
+            data: {
+                newGameId: newGame.id,
+                firstState: newState
+            }
         })
 
         await this.gameRepository.update(newGame.id, { currentState: newState.id })
@@ -769,7 +776,7 @@ export class GameService implements OnModuleInit {
         }
     }
 
-    async createOptions(type: string, charactors: Charactor[], summary: string) {
+    async createOptions(type: string, charactors: Charactor[], summary: string, vars) {
         for (let i = 0; i < 5; i++) {
             try {
                 if (i > 0) await setTimeout(1000)
@@ -801,7 +808,7 @@ export class GameService implements OnModuleInit {
                         .join('\n'),
                     summary
                 })
-                const response = await this.callLLM([new HumanMessage(input)])
+                const response = await this.callLLM([new HumanMessage(this.evalPrompt(vars, input))])
                 const output = await parser.parse(response.content.replace('+', '').replace("'", '"'))
                 return output.map((i) => {
                     i.modifyHp = i.modifyHp.filter(
@@ -1036,4 +1043,31 @@ export class GameService implements OnModuleInit {
         }
         return rank
     }
+
+    evalPrompt(vars, template) {
+        vars.total = vars.charactors.length
+        vars.alive = vars.charactors.filter((i) => !i.dead).length
+        vars.dead = vars.charactors.filter((i) => i.dead).length
+        const hps = vars.charactors.filter((i) => i.hp > 0).map((i) => i.hp)
+        vars.minHp = hps.length > 0 ? Math.min(...hps) : 0
+        vars.maxHp = hps.length > 0 ? Math.max(...hps) : 0
+        vars.avgHp = hps.length > 0 ? hps.reduce((a, b) => a + b) / hps.length : 0
+        const reg = /<%([^%]*(?:%(?!>)[^%]*)*)%>/
+        while (reg.test(template)) {
+            template = template.replace(reg, function (match, $1) {
+                var func = new Function('days', 'charactors', 'total', 'alive', 'dead', 'minHp', 'maxHp', 'avgHp', $1)
+                return func(
+                    vars.days,
+                    vars.charactors,
+                    vars.total,
+                    vars.alive,
+                    vars.dead,
+                    vars.minHp,
+                    vars.maxHp,
+                    vars.avgHp
+                )
+            })
+        }
+        return template
+    }
 }

+ 0 - 13
testrxjs.mjs

@@ -1,13 +0,0 @@
-import { Subject, defaultIfEmpty, last, lastValueFrom, shareReplay } from 'rxjs'
-
-const s = new Subject()
-s.subscribe((v) => {
-    console.log('A', v)
-})
-s.next(1)
-s.complete()
-console.log(s.closed)
-console.log(s.closed)
-const r = await lastValueFrom(s)
-console.log('aaa')
-console.log(r + '1')

+ 0 - 85
twitch.mjs

@@ -1,85 +0,0 @@
-import tmi from 'tmi.js'
-import axios from 'axios'
-
-/* let u = new URL('https://id.twitch.tv/oauth2/authorize?')
-u.searchParams.append('client_id', '530df6x09eq34be0vjhsezkl2oxap0')
-u.searchParams.append('redirect_uri', 'http://localhost:3000/api/twitch/auth_callback')
-u.searchParams.append('response_type', 'code')
-u.searchParams.append('scope', 'channel:manage:broadcast chat:read chat:edit channel:manage:polls')
-u.href */
-
-// Define configuration options
-const accessToken = 'dhs3mqa4xv5u6fjh6glqq4bpoq8dx2'
-const clientId = '530df6x09eq34be0vjhsezkl2oxap0'
-const clientSecret = 'p7vcii89g50eiln4y8x4g1i0aih3q5'
-axios.defaults.headers.common['Authorization'] = 'Bearer ' + accessToken
-axios.defaults.headers.common['Client-Id'] = clientId
-
-const {
-    data: {
-        data: [user]
-    }
-} = await axios.get('https://api.twitch.tv/helix/users')
-console.log(user)
-
-const {
-    data: {
-        data: [broadcaster]
-    }
-} = await axios.get('https://api.twitch.tv/helix/channels?broadcaster_id=' + user.id)
-console.log(broadcaster)
-
-// Create a client with our options
-const client = new tmi.client({
-    identity: {
-        username: user.display_name,
-        password: 'oauth:' + accessToken
-    },
-    channels: [user.display_name, 'shroud']
-})
-
-// Register our event handlers (defined below)
-client.on('message', onMessageHandler)
-client.on('connected', onConnectedHandler)
-
-// Connect to Twitch:
-client.connect()
-
-// Called every time a message comes in
-function onMessageHandler(target, context, msg, self) {
-    if (self) {
-        return
-    } // Ignore messages from the bot
-
-    // Remove whitespace from chat message
-    const commandName = msg.trim()
-
-    // If the command is known, let's execute it
-    if (commandName === '!dice') {
-        const num = rollDice()
-        client.say(target, `You rolled a ${num}`)
-        console.log(`* Executed ${commandName} command`)
-    } else if (commandName === '!roll') {
-        axios.post('https://api.twitch.tv/helix/polls', {
-            broadcaster_id: broadcaster.broadcaster_id,
-            title: 'Streaming next Tuesday. Which time works best for you?',
-            choices: [{ title: '9AM' }, { title: '10AM' }, { title: '7PM' }, { title: '8PM' }, { title: '9PM' }],
-            duration: 300,
-            channel_points_voting_enabled: true,
-            channel_points_per_vote: 0
-        })
-    } else {
-        console.log(`* Unknown command ${commandName}`)
-    }
-}
-
-// Function called when the "dice" command is issued
-function rollDice() {
-    const sides = 6
-    return Math.floor(Math.random() * sides) + 1
-}
-
-// Called every time the bot connects to Twitch chat
-function onConnectedHandler(addr, port) {
-    console.log(`* Connected to ${addr}:${port}`)
-}