|
1 | 1 | import re |
| 2 | +from dataclasses import asdict |
| 3 | +from typing import Any, Union, Literal, Optional |
2 | 4 |
|
| 5 | +import httpx |
| 6 | +from nonebot.adapters import Event |
| 7 | +from nonebot.permission import User, Permission |
| 8 | +from nonebot_plugin_htmlrender import md_to_pic |
| 9 | +from nonebot_plugin_waiter import Waiter, prompt |
| 10 | +from nonebot_plugin_alconna.uniseg import UniMsg, UniMessage |
| 11 | +from nonebot.matcher import Matcher, current_event, current_matcher |
| 12 | + |
| 13 | +from .apis import API |
3 | 14 | from .schemas import Message |
| 15 | +from .config import CustomModel, config |
| 16 | +from .function_call.registry import registry |
| 17 | + |
| 18 | + |
| 19 | +class DeepSeekHandler: |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + model: CustomModel, |
| 23 | + is_to_pic: bool, |
| 24 | + is_contextual: bool, |
| 25 | + ) -> None: |
| 26 | + self.model: CustomModel = model |
| 27 | + self.is_to_pic: bool = is_to_pic |
| 28 | + self.is_contextual: bool = is_contextual |
| 29 | + |
| 30 | + self.event: Event = current_event.get() |
| 31 | + self.matcher: Matcher = current_matcher.get() |
| 32 | + self.waiter: Waiter[Union[str, Literal[False]]] = self._setup_waiter() |
| 33 | + |
| 34 | + self.context: list[dict[str, Any]] = [] |
| 35 | + |
| 36 | + async def handle(self, content: Optional[str]) -> None: |
| 37 | + if content: |
| 38 | + self.context.append({"role": "user", "content": content}) |
| 39 | + |
| 40 | + if not self.is_contextual: |
| 41 | + await self._handle_single_conversion() |
| 42 | + else: |
| 43 | + await self._handle_multi_round_conversion() |
| 44 | + |
| 45 | + async def _handle_single_conversion(self) -> None: |
| 46 | + if message := await self._get_response_message(): |
| 47 | + await self._send_response(message) |
| 48 | + |
| 49 | + async def _handle_multi_round_conversion(self) -> None: |
| 50 | + async for resp in self.waiter(default=False, timeout=config.context_timeout): |
| 51 | + await self._process_waiter_response(resp) |
| 52 | + |
| 53 | + if resp == "rollback": |
| 54 | + continue |
| 55 | + |
| 56 | + message = await self._get_response_message() |
| 57 | + if not message: |
| 58 | + continue |
| 59 | + |
| 60 | + await self._send_response(message) |
| 61 | + self.context.append(asdict(message)) |
| 62 | + |
| 63 | + if await self._handle_tool_calls(message): |
| 64 | + self.waiter.future.set_result("") |
| 65 | + continue |
| 66 | + |
| 67 | + def _setup_waiter(self) -> Waiter[Union[str, Literal[False]]]: |
| 68 | + permission = Permission(User.from_event(self.event, perm=self.matcher.permission)) |
| 69 | + waiter = Waiter(waits=["message"], handler=self._waiter_handler, matcher=self.matcher, permission=permission) |
| 70 | + waiter.future.set_result("") |
| 71 | + return waiter |
| 72 | + |
| 73 | + def _waiter_handler(self, msg: UniMsg) -> Union[str, Literal[False]]: |
| 74 | + text = msg.extract_plain_text() |
| 75 | + if text in ["结束", "取消", "done"]: |
| 76 | + return False |
| 77 | + if text in ["回滚", "rollback"]: |
| 78 | + return "rollback" |
| 79 | + return text |
| 80 | + |
| 81 | + async def _process_waiter_response(self, resp: Union[bool, str]) -> None: |
| 82 | + if resp == "" and not self.context: |
| 83 | + _resp = await prompt("你想对 DeepSeek 说什么呢?", timeout=60) |
| 84 | + if _resp is None: |
| 85 | + await self.matcher.finish("等待超时") |
| 86 | + resp = self._waiter_handler(UniMessage.generate_sync(message=_resp)) |
| 87 | + |
| 88 | + if resp is False: |
| 89 | + await self.matcher.finish("已结束对话") |
| 90 | + elif resp == "rollback": |
| 91 | + await self._handle_rollback() |
| 92 | + elif resp and isinstance(resp, str): |
| 93 | + self.context.append({"role": "user", "content": resp}) |
| 94 | + |
| 95 | + async def _handle_rollback(self, steps: int = 1, by_error: bool = False) -> None: |
| 96 | + rollback_per_step = 1 if by_error else 2 |
| 97 | + required_length = steps * rollback_per_step |
| 98 | + rollback_position = -rollback_per_step * steps |
| 99 | + |
| 100 | + if len(self.context) >= required_length: |
| 101 | + self.context = self.context[:rollback_position] |
| 102 | + action_desc = f"回滚 {steps} 条输入" if by_error else f"回滚 {steps} 轮对话" |
| 103 | + status_msg = f"Oops! 连接异常,已自动{action_desc}。" if by_error else f"已{action_desc}。" |
| 104 | + |
| 105 | + remaining_context = ( |
| 106 | + "空" if not self.context else f'{self.context[-1]["role"]}: {self.context[-1]["content"]}' |
| 107 | + ) |
| 108 | + |
| 109 | + await self.matcher.send(f"{status_msg}当前上下文为:\n{remaining_context}\n" "user:(等待输入)") |
| 110 | + elif by_error and len(self.context) > 0: |
| 111 | + self.context.clear() |
| 112 | + await self.matcher.send("Oops! 连接异常,请重新输入") |
| 113 | + else: |
| 114 | + await self.matcher.send("无法回滚,当前对话记录为空") |
| 115 | + |
| 116 | + async def _handle_tool_calls(self, message: Message) -> bool: |
| 117 | + if not message.tool_calls: |
| 118 | + return False |
| 119 | + |
| 120 | + try: |
| 121 | + result = await registry.execute_tool_call(message.tool_calls[0]) |
| 122 | + except Exception: |
| 123 | + self.context.pop() |
| 124 | + return False |
| 125 | + |
| 126 | + self.context.append({"role": "tool", "tool_call_id": message.tool_calls[0].id, "content": result}) |
| 127 | + return True |
| 128 | + |
| 129 | + async def _get_response_message(self) -> Optional[Message]: |
| 130 | + try: |
| 131 | + completion = await API.chat(self.context, self.model.name) |
| 132 | + return completion.choices[0].message |
| 133 | + except (httpx.ReadTimeout, httpx.RequestError): |
| 134 | + await self._handle_rollback(by_error=True) |
| 135 | + |
| 136 | + def _extract_content_and_think(self, message: Message) -> tuple[str, str]: |
| 137 | + thinking = message.reasoning_content |
| 138 | + |
| 139 | + if not thinking: |
| 140 | + think_blocks = re.findall(r"<think>(.*?)</think>", message.content or "", flags=re.DOTALL) |
| 141 | + thinking = "\n".join([block.strip() for block in think_blocks if block.strip()]) |
4 | 142 |
|
| 143 | + content = re.sub(r"<think>.*?</think>", "", message.content or "", flags=re.DOTALL).strip() |
5 | 144 |
|
6 | | -def extract_content_and_think(message: Message) -> tuple[str, str]: |
7 | | - thinking = message.reasoning_content |
| 145 | + return content, thinking |
8 | 146 |
|
9 | | - if not thinking: |
10 | | - think_blocks = re.findall(r"<think>(.*?)</think>", message.content or "", flags=re.DOTALL) |
11 | | - thinking = "\n".join([block.strip() for block in think_blocks if block.strip()]) |
| 147 | + def _format_output(self, message: Message) -> str: |
| 148 | + content, thinking = self._extract_content_and_think(message) |
12 | 149 |
|
13 | | - content = re.sub(r"<think>.*?</think>", "", message.content or "", flags=re.DOTALL).strip() |
| 150 | + if config.enable_send_thinking and content and thinking: |
| 151 | + return ( |
| 152 | + f"<blockquote><p>{thinking}</p></blockquote>{content}" |
| 153 | + if self.is_to_pic |
| 154 | + else f"{thinking}\n----\n{content}" |
| 155 | + ) |
| 156 | + return content |
14 | 157 |
|
15 | | - return content, thinking |
| 158 | + async def _send_response(self, message: Message) -> None: |
| 159 | + output = self._format_output(message) |
| 160 | + message.reasoning_content = None |
| 161 | + if self.is_to_pic: |
| 162 | + if unimsg := UniMessage.image(raw=await md_to_pic(output)): |
| 163 | + await unimsg.send() |
| 164 | + else: |
| 165 | + await self.matcher.send(output) |
0 commit comments