mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-06-09 07:16:04 +00:00
style: introduce ruff as linter and formatter (#1356)
* style: remove necessary imports * style: fix F841 * style: fix F401 * style: fix F811 * style: fix E402 * style: fix E721 * style: fix E722 * style: fix E722 * style: fix F541 * style: ruff format * style: all passed * style: add ruff in deps * style: more ignores in ruff.toml * style: add pre-commit
This commit is contained in:
committed by
GitHub
parent
09e70d70e9
commit
209f16af76
@@ -8,7 +8,6 @@ from .. import entities
|
||||
|
||||
|
||||
class MessageHandler(metaclass=abc.ABCMeta):
|
||||
|
||||
ap: app.Application
|
||||
|
||||
def __init__(self, ap: app.Application):
|
||||
|
||||
@@ -3,33 +3,36 @@ from __future__ import annotations
|
||||
import typing
|
||||
import time
|
||||
import traceback
|
||||
import json
|
||||
|
||||
|
||||
from .. import handler
|
||||
from ... import entities
|
||||
from ....core import entities as core_entities
|
||||
from ....provider import entities as llm_entities
|
||||
from ....provider import runner as runner_module
|
||||
from ....provider.runners import localagent, difysvapi, dashscopeapi
|
||||
from ....plugin import events
|
||||
|
||||
from ....platform.types import message as platform_message
|
||||
from ....utils import importutil
|
||||
from ....provider import runners
|
||||
|
||||
importutil.import_modules_in_pkg(runners)
|
||||
|
||||
|
||||
class ChatMessageHandler(handler.MessageHandler):
|
||||
|
||||
async def handle(
|
||||
self,
|
||||
query: core_entities.Query,
|
||||
) -> typing.AsyncGenerator[entities.StageProcessResult, None]:
|
||||
"""处理
|
||||
"""
|
||||
"""处理"""
|
||||
# 调API
|
||||
# 生成器
|
||||
|
||||
# 触发插件事件
|
||||
event_class = events.PersonNormalMessageReceived if query.launcher_type == core_entities.LauncherTypes.PERSON else events.GroupNormalMessageReceived
|
||||
event_class = (
|
||||
events.PersonNormalMessageReceived
|
||||
if query.launcher_type == core_entities.LauncherTypes.PERSON
|
||||
else events.GroupNormalMessageReceived
|
||||
)
|
||||
|
||||
event_ctx = await self.ap.plugin_mgr.emit_event(
|
||||
event=event_class(
|
||||
@@ -37,7 +40,7 @@ class ChatMessageHandler(handler.MessageHandler):
|
||||
launcher_id=query.launcher_id,
|
||||
sender_id=query.sender_id,
|
||||
text_message=str(query.message_chain),
|
||||
query=query
|
||||
query=query,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -48,16 +51,13 @@ class ChatMessageHandler(handler.MessageHandler):
|
||||
query.resp_messages.append(mc)
|
||||
|
||||
yield entities.StageProcessResult(
|
||||
result_type=entities.ResultType.CONTINUE,
|
||||
new_query=query
|
||||
result_type=entities.ResultType.CONTINUE, new_query=query
|
||||
)
|
||||
else:
|
||||
yield entities.StageProcessResult(
|
||||
result_type=entities.ResultType.INTERRUPT,
|
||||
new_query=query
|
||||
result_type=entities.ResultType.INTERRUPT, new_query=query
|
||||
)
|
||||
else:
|
||||
|
||||
if event_ctx.event.alter is not None:
|
||||
# if isinstance(event_ctx.event, str): # 现在暂时不考虑多模态alter
|
||||
query.user_message.content = event_ctx.event.alter
|
||||
@@ -67,48 +67,52 @@ class ChatMessageHandler(handler.MessageHandler):
|
||||
start_time = time.time()
|
||||
|
||||
try:
|
||||
|
||||
for r in runner_module.preregistered_runners:
|
||||
if r.name == query.pipeline_config["ai"]["runner"]["runner"]:
|
||||
if r.name == query.pipeline_config['ai']['runner']['runner']:
|
||||
runner = r(self.ap, query.pipeline_config)
|
||||
break
|
||||
else:
|
||||
raise ValueError(f"未找到请求运行器: {query.pipeline_config['ai']['runner']['runner']}")
|
||||
raise ValueError(
|
||||
f'未找到请求运行器: {query.pipeline_config["ai"]["runner"]["runner"]}'
|
||||
)
|
||||
|
||||
async for result in runner.run(query):
|
||||
query.resp_messages.append(result)
|
||||
|
||||
self.ap.logger.info(f'对话({query.query_id})响应: {self.cut_str(result.readable_str())}')
|
||||
self.ap.logger.info(
|
||||
f'对话({query.query_id})响应: {self.cut_str(result.readable_str())}'
|
||||
)
|
||||
|
||||
if result.content is not None:
|
||||
text_length += len(result.content)
|
||||
|
||||
yield entities.StageProcessResult(
|
||||
result_type=entities.ResultType.CONTINUE,
|
||||
new_query=query
|
||||
result_type=entities.ResultType.CONTINUE, new_query=query
|
||||
)
|
||||
|
||||
query.session.using_conversation.messages.append(query.user_message)
|
||||
query.session.using_conversation.messages.extend(query.resp_messages)
|
||||
except Exception as e:
|
||||
|
||||
self.ap.logger.error(f'对话({query.query_id})请求失败: {type(e).__name__} {str(e)}')
|
||||
self.ap.logger.error(
|
||||
f'对话({query.query_id})请求失败: {type(e).__name__} {str(e)}'
|
||||
)
|
||||
|
||||
hide_exception_info = query.pipeline_config['output']['misc']['hide-exception']
|
||||
hide_exception_info = query.pipeline_config['output']['misc'][
|
||||
'hide-exception'
|
||||
]
|
||||
|
||||
yield entities.StageProcessResult(
|
||||
result_type=entities.ResultType.INTERRUPT,
|
||||
new_query=query,
|
||||
user_notice='请求失败' if hide_exception_info else f'{e}',
|
||||
error_notice=f'{e}',
|
||||
debug_notice=traceback.format_exc()
|
||||
debug_notice=traceback.format_exc(),
|
||||
)
|
||||
finally:
|
||||
|
||||
await self.ap.ctr_mgr.usage.post_query_record(
|
||||
session_type=query.session.launcher_type.value,
|
||||
session_id=str(query.session.launcher_id),
|
||||
query_ability_provider="LangBot.Chat",
|
||||
query_ability_provider='LangBot.Chat',
|
||||
usage=text_length,
|
||||
model_name=query.use_model.name,
|
||||
response_seconds=int(time.time() - start_time),
|
||||
|
||||
@@ -11,24 +11,29 @@ from ....platform.types import message as platform_message
|
||||
|
||||
|
||||
class CommandHandler(handler.MessageHandler):
|
||||
|
||||
async def handle(
|
||||
self,
|
||||
query: core_entities.Query,
|
||||
) -> typing.AsyncGenerator[entities.StageProcessResult, None]:
|
||||
"""处理
|
||||
"""
|
||||
"""处理"""
|
||||
|
||||
command_text = str(query.message_chain).strip()[1:]
|
||||
|
||||
privilege = 1
|
||||
|
||||
if f'{query.launcher_type.value}_{query.launcher_id}' in self.ap.instance_config.data['admins']:
|
||||
|
||||
if (
|
||||
f'{query.launcher_type.value}_{query.launcher_id}'
|
||||
in self.ap.instance_config.data['admins']
|
||||
):
|
||||
privilege = 2
|
||||
|
||||
spt = command_text.split(' ')
|
||||
|
||||
event_class = events.PersonCommandSent if query.launcher_type == core_entities.LauncherTypes.PERSON else events.GroupCommandSent
|
||||
event_class = (
|
||||
events.PersonCommandSent
|
||||
if query.launcher_type == core_entities.LauncherTypes.PERSON
|
||||
else events.GroupCommandSent
|
||||
)
|
||||
|
||||
event_ctx = await self.ap.plugin_mgr.emit_event(
|
||||
event=event_class(
|
||||
@@ -38,41 +43,35 @@ class CommandHandler(handler.MessageHandler):
|
||||
command=spt[0],
|
||||
params=spt[1:] if len(spt) > 1 else [],
|
||||
text_message=str(query.message_chain),
|
||||
is_admin=(privilege==2),
|
||||
query=query
|
||||
is_admin=(privilege == 2),
|
||||
query=query,
|
||||
)
|
||||
)
|
||||
|
||||
if event_ctx.is_prevented_default():
|
||||
|
||||
if event_ctx.event.reply is not None:
|
||||
mc = platform_message.MessageChain(event_ctx.event.reply)
|
||||
|
||||
query.resp_messages.append(mc)
|
||||
|
||||
yield entities.StageProcessResult(
|
||||
result_type=entities.ResultType.CONTINUE,
|
||||
new_query=query
|
||||
result_type=entities.ResultType.CONTINUE, new_query=query
|
||||
)
|
||||
else:
|
||||
yield entities.StageProcessResult(
|
||||
result_type=entities.ResultType.INTERRUPT,
|
||||
new_query=query
|
||||
result_type=entities.ResultType.INTERRUPT, new_query=query
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
if event_ctx.event.alter is not None:
|
||||
query.message_chain = platform_message.MessageChain([
|
||||
platform_message.Plain(event_ctx.event.alter)
|
||||
])
|
||||
query.message_chain = platform_message.MessageChain(
|
||||
[platform_message.Plain(event_ctx.event.alter)]
|
||||
)
|
||||
|
||||
session = await self.ap.sess_mgr.get_session(query)
|
||||
|
||||
async for ret in self.ap.cmd_mgr.execute(
|
||||
command_text=command_text,
|
||||
query=query,
|
||||
session=session
|
||||
command_text=command_text, query=query, session=session
|
||||
):
|
||||
if ret.error is not None:
|
||||
query.resp_messages.append(
|
||||
@@ -82,20 +81,18 @@ class CommandHandler(handler.MessageHandler):
|
||||
)
|
||||
)
|
||||
|
||||
self.ap.logger.info(f'命令({query.query_id})报错: {self.cut_str(str(ret.error))}')
|
||||
self.ap.logger.info(
|
||||
f'命令({query.query_id})报错: {self.cut_str(str(ret.error))}'
|
||||
)
|
||||
|
||||
yield entities.StageProcessResult(
|
||||
result_type=entities.ResultType.CONTINUE,
|
||||
new_query=query
|
||||
result_type=entities.ResultType.CONTINUE, new_query=query
|
||||
)
|
||||
elif ret.text is not None or ret.image_url is not None:
|
||||
|
||||
content: list[llm_entities.ContentElement]= []
|
||||
content: list[llm_entities.ContentElement] = []
|
||||
|
||||
if ret.text is not None:
|
||||
content.append(
|
||||
llm_entities.ContentElement.from_text(ret.text)
|
||||
)
|
||||
content.append(llm_entities.ContentElement.from_text(ret.text))
|
||||
|
||||
if ret.image_url is not None:
|
||||
content.append(
|
||||
@@ -112,11 +109,9 @@ class CommandHandler(handler.MessageHandler):
|
||||
self.ap.logger.info(f'命令返回: {self.cut_str(str(content[0]))}')
|
||||
|
||||
yield entities.StageProcessResult(
|
||||
result_type=entities.ResultType.CONTINUE,
|
||||
new_query=query
|
||||
result_type=entities.ResultType.CONTINUE, new_query=query
|
||||
)
|
||||
else:
|
||||
yield entities.StageProcessResult(
|
||||
result_type=entities.ResultType.INTERRUPT,
|
||||
new_query=query
|
||||
result_type=entities.ResultType.INTERRUPT, new_query=query
|
||||
)
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from ...core import app, entities as core_entities
|
||||
from ...core import entities as core_entities
|
||||
from . import handler
|
||||
from .handlers import chat, command
|
||||
from .. import entities
|
||||
from .. import stage, entities
|
||||
from ...core import entities as core_entities
|
||||
from ...config import manager as cfg_mgr
|
||||
from .. import stage
|
||||
|
||||
|
||||
@stage.stage_class("MessageProcessor")
|
||||
@stage.stage_class('MessageProcessor')
|
||||
class Processor(stage.PipelineStage):
|
||||
"""请求实际处理阶段
|
||||
|
||||
|
||||
通过命令处理器和聊天处理器处理消息。
|
||||
|
||||
改写:
|
||||
@@ -35,11 +33,12 @@ class Processor(stage.PipelineStage):
|
||||
query: core_entities.Query,
|
||||
stage_inst_name: str,
|
||||
) -> entities.StageProcessResult:
|
||||
"""处理
|
||||
"""
|
||||
"""处理"""
|
||||
message_text = str(query.message_chain).strip()
|
||||
|
||||
self.ap.logger.info(f"处理 {query.launcher_type.value}_{query.launcher_id} 的请求({query.query_id}): {message_text}")
|
||||
self.ap.logger.info(
|
||||
f'处理 {query.launcher_type.value}_{query.launcher_id} 的请求({query.query_id}): {message_text}'
|
||||
)
|
||||
|
||||
async def generator():
|
||||
cmd_prefix = self.ap.instance_config.data['command']['prefix']
|
||||
@@ -50,5 +49,5 @@ class Processor(stage.PipelineStage):
|
||||
else:
|
||||
async for result in self.chat_handler.handle(query):
|
||||
yield result
|
||||
|
||||
|
||||
return generator()
|
||||
|
||||
Reference in New Issue
Block a user