Compare commits

...

14 commits
v0.2.2 ... main

Author SHA1 Message Date
d640f16abe 🔖 bump llmchat version 0.2.5
Some checks failed
Pyright Lint / Pyright Lint (push) Has been cancelled
Ruff Lint / Ruff Lint (push) Has been cancelled
2025-09-01 10:56:31 +08:00
1600cba172 支持忽略特定前缀的消息 #21 2025-09-01 10:51:30 +08:00
9f81a38d5b 🐛 将mcp超时延长到30秒,避免执行失败 2025-09-01 10:45:18 +08:00
53d57beba3 🔖 bump llmchat version 0.2.4 2025-08-20 12:48:13 +08:00
ea635fd147 🐛 修复重复发送消息给llm的问题 2025-08-20 12:38:39 +08:00
5014d3014b 🐛 修复mcp服务器卡住导致的卡死 2025-08-20 11:40:54 +08:00
89baec6abc 📘 更新 README 2025-05-19 14:17:25 +08:00
19ff0026c0 🐛 修复deque mutated during iteration 2025-05-16 21:43:08 +08:00
52ada66616 🔖 bump llmchat version 0.2.3 2025-05-13 14:02:23 +08:00
cf2d549f02 📘 更新meta信息 2025-05-13 14:02:03 +08:00
6c27cf56fa 🐛 修复命令本身会触发回复的问题 2025-05-13 13:43:06 +08:00
3d85ea90ef 🐛 修复多条消息中只处理最后一条消息的图片的问题 2025-05-13 13:41:28 +08:00
7edd7c913e 🐛 修复MCP调用过程中回复不分条的问题 2025-05-13 11:23:52 +08:00
84d3851936 🐛 修复某些协议端找不到图片url的问题 2025-05-12 15:26:39 +08:00
5 changed files with 55 additions and 37 deletions

View file

@ -18,6 +18,7 @@ _✨ 支持多API预设、MCP协议、联网搜索、视觉模型的AI群聊插
<img src="https://img.shields.io/pypi/v/nonebot-plugin-llmchat.svg" alt="pypi"> <img src="https://img.shields.io/pypi/v/nonebot-plugin-llmchat.svg" alt="pypi">
</a> </a>
<img src="https://img.shields.io/badge/python-3.10+-blue.svg" alt="python"> <img src="https://img.shields.io/badge/python-3.10+-blue.svg" alt="python">
<a href="https://deepwiki.com/FuQuan233/nonebot-plugin-llmchat"><img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki"></a>
</div> </div>
@ -108,6 +109,7 @@ _✨ 支持多API预设、MCP协议、联网搜索、视觉模型的AI群聊插
| LLMCHAT__RANDOM_TRIGGER_PROB | 否 | 0.05 | 默认随机触发概率 [0, 1] | | LLMCHAT__RANDOM_TRIGGER_PROB | 否 | 0.05 | 默认随机触发概率 [0, 1] |
| LLMCHAT__DEFAULT_PROMPT | 否 | 你的回答应该尽量简洁、幽默、可以使用一些语气词、颜文字。你应该拒绝回答任何政治相关的问题。 | 默认提示词 | | LLMCHAT__DEFAULT_PROMPT | 否 | 你的回答应该尽量简洁、幽默、可以使用一些语气词、颜文字。你应该拒绝回答任何政治相关的问题。 | 默认提示词 |
| LLMCHAT__BLACKLIST_USER_IDS | 否 | [] | 黑名单用户ID列表机器人将不会处理黑名单用户的消息 | | LLMCHAT__BLACKLIST_USER_IDS | 否 | [] | 黑名单用户ID列表机器人将不会处理黑名单用户的消息 |
| LLMCHAT__IGNORE_PREFIXES | 否 | [] | 需要忽略的消息前缀列表,匹配到这些前缀的消息不会处理 |
| LLMCHAT__MCP_SERVERS | 否 | {} | MCP服务器配置具体见下表 | | LLMCHAT__MCP_SERVERS | 否 | {} | MCP服务器配置具体见下表 |
其中LLMCHAT__API_PRESETS为一个列表每项配置有以下的配置项 其中LLMCHAT__API_PRESETS为一个列表每项配置有以下的配置项

View file

@ -40,14 +40,13 @@ from nonebot_plugin_apscheduler import scheduler
if TYPE_CHECKING: if TYPE_CHECKING:
from openai.types.chat import ( from openai.types.chat import (
ChatCompletionContentPartImageParam, ChatCompletionContentPartParam,
ChatCompletionContentPartTextParam,
ChatCompletionMessageParam, ChatCompletionMessageParam,
) )
__plugin_meta__ = PluginMetadata( __plugin_meta__ = PluginMetadata(
name="llmchat", name="llmchat",
description="支持多API预设、MCP协议、联网搜索的AI群聊插件", description="支持多API预设、MCP协议、联网搜索、视觉模型的AI群聊插件",
usage="""@机器人 + 消息 开启对话""", usage="""@机器人 + 消息 开启对话""",
type="application", type="application",
homepage="https://github.com/FuQuan233/nonebot-plugin-llmchat", homepage="https://github.com/FuQuan233/nonebot-plugin-llmchat",
@ -170,6 +169,12 @@ async def is_triggered(event: GroupMessageEvent) -> bool:
if event.user_id in plugin_config.blacklist_user_ids: if event.user_id in plugin_config.blacklist_user_ids:
return False return False
# 忽略特定前缀的消息
msg_text = event.get_plaintext().strip()
for prefix in plugin_config.ignore_prefixes:
if msg_text.startswith(prefix):
return False
state.past_events.append(event) state.past_events.append(event)
# 原有@触发条件 # 原有@触发条件
@ -186,7 +191,7 @@ async def is_triggered(event: GroupMessageEvent) -> bool:
# 消息处理器 # 消息处理器
handler = on_message( handler = on_message(
rule=Rule(is_triggered), rule=Rule(is_triggered),
priority=10, priority=99,
block=False, block=False,
) )
@ -211,7 +216,7 @@ async def process_images(event: GroupMessageEvent) -> list[str]:
base64_images = [] base64_images = []
for segement in event.get_message(): for segement in event.get_message():
if segement.type == "image": if segement.type == "image":
image_url = segement.data.get("url") image_url = segement.data.get("url") or segement.data.get("file")
if image_url: if image_url:
try: try:
# 处理高版本 httpx 的 [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] 报错 # 处理高版本 httpx 的 [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] 报错
@ -234,6 +239,20 @@ async def process_images(event: GroupMessageEvent) -> list[str]:
logger.debug(f"共处理 {len(base64_images)} 张图片") logger.debug(f"共处理 {len(base64_images)} 张图片")
return base64_images return base64_images
async def send_split_messages(message_handler, content: str):
"""
将消息按分隔符<botbr>分段并发送
"""
logger.info(f"准备发送分段消息,分段数:{len(content.split('<botbr>'))}")
for segment in content.split("<botbr>"):
# 跳过空消息
if not segment.strip():
continue
segment = segment.strip() # 删除前后多余的换行和空格
await asyncio.sleep(2) # 避免发送过快
logger.debug(f"发送消息分段 内容:{segment[:50]}...") # 只记录前50个字符避免日志过大
await message_handler.send(Message(segment))
async def process_messages(group_id: int): async def process_messages(group_id: int):
state = group_states[group_id] state = group_states[group_id]
preset = get_preset(group_id) preset = get_preset(group_id)
@ -297,16 +316,17 @@ async def process_messages(group_id: int):
if state.past_events.__len__() < 1: if state.past_events.__len__() < 1:
break break
# 将消息中的图片转成 base64 content: list[ChatCompletionContentPartParam] = []
base64_images = []
if preset.support_image:
base64_images = await process_images(event)
# 将机器人错过的消息推送给LLM # 将机器人错过的消息推送给LLM
text_content = ",".join([format_message(ev) for ev in state.past_events]) past_events_snapshot = list(state.past_events)
content: list[ChatCompletionContentPartTextParam | ChatCompletionContentPartImageParam] = [ for ev in past_events_snapshot:
{"type": "text", "text": text_content} text_content = format_message(ev)
] content.append({"type": "text", "text": text_content})
# 将消息中的图片转成 base64
if preset.support_image:
base64_images = await process_images(ev)
for base64_image in base64_images: for base64_image in base64_images:
content.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}) content.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}})
@ -350,7 +370,7 @@ async def process_messages(group_id: int):
# 发送LLM调用工具时的回复一般没有 # 发送LLM调用工具时的回复一般没有
if message.content: if message.content:
await handler.send(Message(message.content)) await send_split_messages(handler, message.content)
# 处理每个工具调用 # 处理每个工具调用
for tool_call in message.tool_calls: for tool_call in message.tool_calls:
@ -366,7 +386,7 @@ async def process_messages(group_id: int):
new_messages.append({ new_messages.append({
"role": "tool", "role": "tool",
"tool_call_id": tool_call.id, "tool_call_id": tool_call.id,
"content": str(result.content) "content": str(result)
}) })
# 将工具调用的结果交给 LLM # 将工具调用的结果交给 LLM
@ -410,20 +430,7 @@ async def process_messages(group_id: int):
logger.error(f"合并转发消息发送失败:\n{e!s}\n") logger.error(f"合并转发消息发送失败:\n{e!s}\n")
assert reply is not None assert reply is not None
logger.info( await send_split_messages(handler, reply)
f"准备发送回复消息 群号:{group_id} 消息分段数:{len(reply.split('<botbr>'))}"
)
for r in reply.split("<botbr>"):
# 似乎会有空消息的情况导致string index out of range异常
if len(r) == 0 or r.isspace():
continue
# 删除前后多余的换行和空格
r = r.strip()
await asyncio.sleep(2)
logger.debug(
f"发送消息分段 内容:{r[:50]}..."
) # 只记录前50个字符避免日志过大
await handler.send(Message(r))
except Exception as e: except Exception as e:
logger.opt(exception=e).error(f"API请求失败 群号:{group_id}") logger.opt(exception=e).error(f"API请求失败 群号:{group_id}")
@ -460,7 +467,7 @@ async def handle_preset(event: GroupMessageEvent, args: Message = CommandArg()):
edit_preset_handler = on_command( edit_preset_handler = on_command(
"修改设定", "修改设定",
priority=99, priority=1,
block=True, block=True,
permission=(SUPERUSER | GROUP_ADMIN | GROUP_OWNER), permission=(SUPERUSER | GROUP_ADMIN | GROUP_OWNER),
) )
@ -477,7 +484,7 @@ async def handle_edit_preset(event: GroupMessageEvent, args: Message = CommandAr
reset_handler = on_command( reset_handler = on_command(
"记忆清除", "记忆清除",
priority=99, priority=1,
block=True, block=True,
permission=(SUPERUSER | GROUP_ADMIN | GROUP_OWNER), permission=(SUPERUSER | GROUP_ADMIN | GROUP_OWNER),
) )
@ -494,7 +501,7 @@ async def handle_reset(event: GroupMessageEvent, args: Message = CommandArg()):
set_prob_handler = on_command( set_prob_handler = on_command(
"设置主动回复概率", "设置主动回复概率",
priority=99, priority=1,
block=True, block=True,
permission=(SUPERUSER | GROUP_ADMIN | GROUP_OWNER), permission=(SUPERUSER | GROUP_ADMIN | GROUP_OWNER),
) )

View file

@ -44,6 +44,10 @@ class ScopedConfig(BaseModel):
) )
mcp_servers: dict[str, MCPServerConfig] = Field({}, description="MCP服务器配置") mcp_servers: dict[str, MCPServerConfig] = Field({}, description="MCP服务器配置")
blacklist_user_ids: set[int] = Field(set(), description="黑名单用户ID列表") blacklist_user_ids: set[int] = Field(set(), description="黑名单用户ID列表")
ignore_prefixes: list[str] = Field(
default_factory=list,
description="需要忽略的消息前缀列表,匹配到这些前缀的消息不会处理"
)
class Config(BaseModel): class Config(BaseModel):

View file

@ -1,3 +1,4 @@
import asyncio
from contextlib import AsyncExitStack from contextlib import AsyncExitStack
from mcp import ClientSession, StdioServerParameters from mcp import ClientSession, StdioServerParameters
@ -64,9 +65,13 @@ class MCPClient:
server_name, real_tool_name = tool_name.split("___") server_name, real_tool_name = tool_name.split("___")
logger.info(f"正在服务器[{server_name}]上调用工具[{real_tool_name}]") logger.info(f"正在服务器[{server_name}]上调用工具[{real_tool_name}]")
session = self.sessions[server_name] session = self.sessions[server_name]
response = await session.call_tool(real_tool_name, tool_args) try:
response = await asyncio.wait_for(session.call_tool(real_tool_name, tool_args), timeout=30)
except asyncio.TimeoutError:
logger.error(f"调用工具[{real_tool_name}]超时")
return f"调用工具[{real_tool_name}]超时"
logger.debug(f"工具[{real_tool_name}]调用完成,响应: {response}") logger.debug(f"工具[{real_tool_name}]调用完成,响应: {response}")
return response return response.content
def get_friendly_name(self, tool_name: str): def get_friendly_name(self, tool_name: str):
server_name, real_tool_name = tool_name.split("___") server_name, real_tool_name = tool_name.split("___")

View file

@ -1,6 +1,6 @@
[tool.poetry] [tool.poetry]
name = "nonebot-plugin-llmchat" name = "nonebot-plugin-llmchat"
version = "0.2.2" version = "0.2.5"
description = "Nonebot AI group chat plugin supporting multiple API preset configurations" description = "Nonebot AI group chat plugin supporting multiple API preset configurations"
license = "GPL" license = "GPL"
authors = ["FuQuan i@fuquan.moe"] authors = ["FuQuan i@fuquan.moe"]