File size: 15,086 Bytes
4117054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f15ea60
 
 
 
4117054
 
f15ea60
 
 
 
 
 
4117054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f15ea60
 
 
 
4117054
 
f15ea60
 
 
 
 
 
4117054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f15ea60
4117054
f15ea60
 
 
 
 
 
 
 
 
 
 
 
4117054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f15ea60
4117054
f15ea60
 
 
 
 
 
 
 
 
 
 
4117054
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import discord
import pytz
import re
from discord.ext import commands
from utils.func import get_time, now


class ContextPrompter:
    def __init__(self):
        self.tz = pytz.timezone("Asia/Shanghai")
        self.agent_manager = None

    def set_agent_manager(self, agent_manager):
        self.agent_manager = agent_manager

    def set_tz(self, tz: str):
        try:
            self.tz = pytz.timezone(tz)
        except Exception as e:
            print(e)

    def maltose_regex(self, context: str) -> str:
        """
        使用正则表达式预处理上下文内容,删除命令触发词
        例如: .hey, .yo claude, .yoo 等,这些只是触发词对机器人理解没有用处
        """
        # 匹配并删除命令触发词
        # 1. 匹配 .hey, .yo, .yoo 后跟空格和可能的参数
        pattern1 = r'\.hey\s+|\.yo\s+[a-zA-Z]+\s+|\.yoo\s+'
        # 2. 匹配独立的命令 .hey, .yo, .yoo (行首或前面有空格,后面是行尾或空格)
        pattern2 = r'(^|\s)\.hey($|\s)|(^|\s)\.yo($|\s)|(^|\s)\.yoo($|\s)'
        
        # 应用正则替换
        context = re.sub(pattern1, '', context)
        context = re.sub(pattern2, '', context)
        
        return context.strip()

    def get_msg_time(self, msg: discord.Message) -> str:
        time = msg.created_at if msg.edited_at is None else msg.edited_at
        return get_time(time, tz=self.tz)

    async def get_context_for_prompt(
        self,
        ctx: commands.Context,
        context_length: int,
        before_message=None,
        after_message=None,
        after_message_context_length=0,
    ):
        context_msg = []
        if before_message is not None and after_message is not None:
            async for msg in ctx.channel.history(
                limit=context_length + 1, before=before_message
            ):
                context_msg.append(
                    f"{msg.author.display_name} ({msg.author.name}) ({self.get_msg_time(msg)}): {msg.content}"
                )
            context_msg.reverse()
            context_msg.append(
                f"{after_message.author.display_name} ({after_message.author.name}) ({self.get_msg_time(after_message)}): {after_message.content}"
            )
            async for msg in ctx.channel.history(
                limit=after_message_context_length + 1, after=after_message
            ):
                context_msg.append(
                    f"{msg.author.display_name} ({msg.author.name}) ({self.get_msg_time(msg)}): {msg.content}"
                )
        elif before_message is not None:
            async for msg in ctx.channel.history(
                limit=context_length + 1, before=before_message
            ):
                context_msg.append(
                    f"{msg.author.display_name} ({msg.author.name}) ({self.get_msg_time(msg)}): {msg.content}"
                )
            context_msg.reverse()
        elif after_message is not None:
            async for msg in ctx.channel.history(
                limit=context_length + 1, after=after_message
            ):
                context_msg.append(
                    f"{msg.author.display_name} ({msg.author.name}) ({self.get_msg_time(msg)}): {msg.content}"
                )
        else:
            async for msg in ctx.channel.history(
                limit=context_length + 1, before=ctx.message
            ):
                context_msg.append(
                    f"{msg.author.display_name} ({msg.author.name}) ({self.get_msg_time(msg)}): {msg.content}"
                )
            context_msg.reverse()
        return "\n".join(context_msg)

    def _get_template(self, template_name, channel_id=None):
        """获取模板内容"""
        if self.agent_manager:
            return self.agent_manager.get_preset_file(template_name, channel_id)
        else:
            # 如果没有设置agent_manager,返回默认模板
            return None

    async def chat_prompt(
        self,
        ctx: commands.Context,
        context_length: int,
        question: str,
        name: str = None,
    ):
        context = await self.get_context_for_prompt(ctx, context_length)
        # 应用正则预处理
        context = self.maltose_regex(context)
        name = name if name else ctx.me.display_name
        
        # 获取预设模板
        if self.agent_manager:
            # 获取预设JSON
            preset = self.agent_manager.get_preset_json("chat_preset.json", ctx.channel.id, guild_id=str(ctx.guild.id))
            role_preset = self.agent_manager.get_preset_json("role_preset.json", ctx.channel.id, guild_id=str(ctx.guild.id))

            if preset and "main_content" in preset and role_preset:
                # 使用预设中的main_content,并替换其中的模板变量
                main_content = preset["main_content"]

                # 先替换 {bot_role}
                bot_role_text = role_preset.get("bot_role", "")
                main_content = main_content.replace("{bot_role}", bot_role_text)

                # 再替换其他变量
                return main_content.format(
                    context=context,
                    question=question,
                    name=name,
                    bot_name=ctx.me.name,
                    current_time=now(tz=self.tz),
                    user_display_name=ctx.author.display_name,
                    user_name=ctx.author.name
                )
        
        # 回退到原始模板
        prompt = f"""
        <context>
        {context}
        </context>
        <question>
        {question}
        </question>
        You are {name} ({ctx.me.name}), chatting in a discord server.
        Speak naturally like a human who talks, and don't use phrases like 'according to the context' since humans never talk like that. Remember the Language is Chinese unless the user specifies otherwise! Avoid explicitly mentioning someone's name. If you have to mention someone (try to avoid this case), use their display name (the name that appears outside the parentheses).
        Now is {now(tz=self.tz)}.
        {ctx.author.display_name} ({ctx.author.name}) is asking you a question (refer to `<question>`).
        Consider the context in `<context>` and reply now. 
        Avoid using ellipsis!
        Your reply:
        """
        return prompt

    async def chat_prompt_with_reference(
        self,
        ctx: commands.Context,
        context_length: int,
        after_message_context_length: int,
        question: str,
        reference: discord.Message,
        name: str = None,
    ):
        context = await self.get_context_for_prompt(
            ctx, context_length, reference, after_message_context_length=after_message_context_length
        )
        # 应用正则预处理
        context = self.maltose_regex(context)
        name = name if name else ctx.me.display_name
        
        # 获取预设模板
        if self.agent_manager:
            # 获取预设JSON
            preset = self.agent_manager.get_preset_json("reference_preset.json", ctx.channel.id, guild_id=str(ctx.guild.id))
            role_preset = self.agent_manager.get_preset_json("role_preset.json", ctx.channel.id, guild_id=str(ctx.guild.id))

            if preset and "main_content" in preset and role_preset:
                # 使用预设中的main_content,并替换其中的模板变量
                main_content = preset["main_content"]

                # 先替换 {bot_role}
                bot_role_text = role_preset.get("bot_role", "")
                main_content = main_content.replace("{bot_role}", bot_role_text)

                # 再替换其他变量
                return main_content.format(
                    context=context,
                    question=question,
                    name=name,
                    bot_name=ctx.me.name,
                    current_time=now(tz=self.tz),
                    user_display_name=ctx.author.display_name,
                    user_name=ctx.author.name,
                    reference_user_display_name=reference.author.display_name,
                    reference_user_name=reference.author.name,
                    reference_time=self.get_msg_time(reference),
                    reference_content=reference.content
                )
        
        # 回退到原始模板
        prompt = f"""
        <context>
        {context}
        </context>
        <question>
        {question}
        </question>
        <reference>
        {reference.author.display_name} ({reference.author.name}) ({self.get_msg_time(reference)}): {reference.content}
        </reference>
        You are {name} ({ctx.me.name}), chatting in a discord server.
        Speak naturally like a human who talks, and don't use phrases like 'according to the context' since humans never talk like that. Remember the Language is Chinese unless the user specifies otherwise! Avoid explicitly mentioning someone's name. If you have to mention someone (try to avoid this case), use their display name (the name that appears outside the parentheses).
        Now is {now(tz=self.tz)}.
        {ctx.author.display_name} ({ctx.author.name}) is asking you a question (refer to `<question>`) about the message above (refer to `<reference>`).
        Consider the context in `<context>` and reply now.
        Avoid using ellipsis!
        Your reply:
        """
        return prompt

    async def chat_prompt_with_attachment(
        self,
        ctx: commands.Context,
        question: str,
        reference: discord.Message,
    ):
        content = reference.content
        if content == "":
            content = "[No content, only attachments]"
            
        # 使用模板
        template = self._get_template("attachment_preset.json", ctx.channel.id, guild_id=str(ctx.guild.id))
        if template:
            # 加载 role_preset
            bot_role_text = ""
            if self.agent_manager:
                role_preset = self.agent_manager.get_preset_json("role_preset.json", ctx.channel.id, guild_id=str(ctx.guild.id))
                if role_preset:
                    bot_role_text = role_preset.get("bot_role", "")

            # 先替换 {bot_role}
            main_content_template = template.get("main_content", "")
            main_content = main_content_template.replace("{bot_role}", bot_role_text)

            # 再替换其他变量
            return template.format(
                question=question,
                name=ctx.me.display_name,
                bot_name=ctx.me.name,
                current_time=now(tz=self.tz),
                user_display_name=ctx.author.display_name,
                user_name=ctx.author.name,
                reference_user_display_name=reference.author.display_name,
                reference_user_name=reference.author.name,
                reference_time=self.get_msg_time(reference),
                reference_content=content
            )
            
        # 回退到原始模板
        prompt: str = f"""
        <question>
        {question}
        </question>
        <reference>
        {reference.author.display_name} ({reference.author.name}) ({self.get_msg_time(reference)}): {content}
        </reference>
        You are {ctx.me.display_name} ({ctx.me.name}), chatting in a discord server.
        Speak naturally like a human who talks, and don't use phrases like 'according to the context' since humans never talk like that. Remember the Language is Chinese unless the user specifies otherwise! Avoid explicitly mentioning someone's name. If you have to mention someone (try to avoid this case), use their display name (the name that appears outside the parentheses).
        Now is {now(tz=self.tz)}.
        {ctx.author.display_name} ({ctx.author.name}) is asking you a question (refer to `<question>`) about the message (refer to `<reference>`) with the ATTACHMENT FILE.
        Analyze the attachment file and reply now.
        Avoid using ellipsis!
        Your reply:
        """
        return prompt

    async def translate_prompt(
        self,
        ctx: commands.Context,
        context_length: int,
        reference: discord.Message,
        after_message_context_length: int,
        target_language: str,
    ):
        # 获取上下文内容
        context = await self.get_context_for_prompt(
            ctx, context_length, reference, after_message_context_length=after_message_context_length
        )
        # 应用正则预处理
        context = self.maltose_regex(context)
        
        # 使用模板
        template = self._get_template("translate_preset.json", ctx.channel.id, guild_id=str(ctx.guild.id))
        if template:
            # 翻译模板通常不包含 {bot_role},但以防万一,还是处理一下
            bot_role_text = ""
            if self.agent_manager:
                role_preset = self.agent_manager.get_preset_json("role_preset.json", ctx.channel.id, guild_id=str(ctx.guild.id))
                if role_preset:
                    bot_role_text = role_preset.get("bot_role", "")

            main_content_template = template.get("main_content", "")
            main_content = main_content_template.replace("{bot_role}", bot_role_text)

            return main_content.format(
                context=context,
                target_language=target_language,
                reference_content=reference.content,
                bot_name=ctx.me.name,
                current_time=now(tz=self.tz),
                user_display_name=ctx.author.display_name,
                user_name=ctx.author.name,
                reference_user_display_name=reference.author.display_name,
                reference_user_name=reference.author.name,
                reference_time=self.get_msg_time(reference)
            )

        # 回退到原始模板
        prompt = f"""
        <context>
        {context}
        </context>
        `<reference>` is the message you need to translate.
        <reference>
        {reference.content}
        </reference>
        This message is from `<author>`.
        <author>
        {reference.author.display_name} ({reference.author.name}) ({self.get_msg_time(reference)})
        </author>
        You are a skilled muti-lingual translator, currently doing a translation job in a discord server. You'll get a message which you need to translate into {target_language} with context. You only need to supply the translation according to the context without any additional information. Don't act like a machine, translate smoothly like a human without being too informal. 
        Your translation should not include the author's name and the time.
        Now is {now(tz=self.tz)}.
        {ctx.author.display_name} ({ctx.author.name}) is asking you to translate the message in `<reference>` into {target_language} under the context (refer to <context>). The message is from `<author>`, so consider the context and try to understand the message before translating.
        Your translation:
        """
        return prompt