From e3973baa37fe2af00abe2d76edddc2dffe630762 Mon Sep 17 00:00:00 2001 From: FuQuan233 Date: Sun, 27 Apr 2025 11:56:38 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20=E4=BF=AE=E5=A4=8Dassistant?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E6=B2=A1=E6=9C=89=E6=AD=A3=E7=A1=AE=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E5=88=B0=E5=8E=86=E5=8F=B2=E8=AE=B0=E5=BD=95=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- nonebot_plugin_llmchat/__init__.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/nonebot_plugin_llmchat/__init__.py b/nonebot_plugin_llmchat/__init__.py index 3435f28..879953a 100644 --- a/nonebot_plugin_llmchat/__init__.py +++ b/nonebot_plugin_llmchat/__init__.py @@ -268,10 +268,6 @@ async def process_messages(group_id: int): logger.debug( f"发送API请求 模型:{preset.model_name} 历史消息数:{len(messages)}" ) - mcp_client = MCPClient(plugin_config.mcp_servers) - await mcp_client.connect_to_servers() - - available_tools = await mcp_client.get_available_tools() client_config = { "model": preset.model_name, @@ -280,7 +276,10 @@ async def process_messages(group_id: int): "timeout": 60, } + mcp_client = MCPClient(plugin_config.mcp_servers) if preset.support_mcp: + await mcp_client.connect_to_servers() + available_tools = await mcp_client.get_available_tools() client_config["tools"] = available_tools response = await client.chat.completions.create( @@ -291,10 +290,7 @@ async def process_messages(group_id: int): if response.usage is not None: logger.debug(f"收到API响应 使用token数:{response.usage.total_tokens}") - final_message = [] message = response.choices[0].message - if message.content: - final_message.append(message.content) # 处理响应并处理工具调用 while preset.support_mcp and message.tool_calls: @@ -302,6 +298,11 @@ async def process_messages(group_id: int): "role": "assistant", "tool_calls": [tool_call.model_dump() for tool_call in message.tool_calls] }) + + # 发送LLM调用工具时的回复,一般没有 + if message.content: + await handler.send(Message(message.content)) + # 处理每个工具调用 for tool_call in message.tool_calls: tool_name = tool_call.function.name @@ -326,8 +327,6 @@ async def process_messages(group_id: int): ) message = response.choices[0].message - if message.content: - final_message.append(message.content) await mcp_client.cleanup() @@ -339,6 +338,11 @@ async def process_messages(group_id: int): or matched_reasoning_content ) + new_messages.append({ + "role": "assistant", + "content": reply, + }) + # 请求成功后再保存历史记录,保证user和assistant穿插,防止R1模型报错 for message in new_messages: state.history.append(message)