mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-06-27 07:54:19 +00:00
chore: switch some comments to en
This commit is contained in:
@@ -7,11 +7,11 @@ from . import app
|
|||||||
|
|
||||||
|
|
||||||
preregistered_migrations: list[typing.Type[Migration]] = []
|
preregistered_migrations: list[typing.Type[Migration]] = []
|
||||||
"""当前阶段暂不支持扩展"""
|
"""Currently not supported for extension"""
|
||||||
|
|
||||||
|
|
||||||
def migration_class(name: str, number: int):
|
def migration_class(name: str, number: int):
|
||||||
"""注册一个迁移"""
|
"""Register a migration"""
|
||||||
|
|
||||||
def decorator(cls: typing.Type[Migration]) -> typing.Type[Migration]:
|
def decorator(cls: typing.Type[Migration]) -> typing.Type[Migration]:
|
||||||
cls.name = name
|
cls.name = name
|
||||||
@@ -23,7 +23,7 @@ def migration_class(name: str, number: int):
|
|||||||
|
|
||||||
|
|
||||||
class Migration(abc.ABC):
|
class Migration(abc.ABC):
|
||||||
"""一个版本的迁移"""
|
"""A version migration"""
|
||||||
|
|
||||||
name: str
|
name: str
|
||||||
|
|
||||||
@@ -36,10 +36,10 @@ class Migration(abc.ABC):
|
|||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
async def need_migrate(self) -> bool:
|
async def need_migrate(self) -> bool:
|
||||||
"""判断当前环境是否需要运行此迁移"""
|
"""Determine if the current environment needs to run this migration"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
async def run(self):
|
async def run(self):
|
||||||
"""执行迁移"""
|
"""Run migration"""
|
||||||
pass
|
pass
|
||||||
|
|||||||
+4
-4
@@ -9,7 +9,7 @@ preregistered_notes: list[typing.Type[LaunchNote]] = []
|
|||||||
|
|
||||||
|
|
||||||
def note_class(name: str, number: int):
|
def note_class(name: str, number: int):
|
||||||
"""注册一个启动信息"""
|
"""Register a launch information"""
|
||||||
|
|
||||||
def decorator(cls: typing.Type[LaunchNote]) -> typing.Type[LaunchNote]:
|
def decorator(cls: typing.Type[LaunchNote]) -> typing.Type[LaunchNote]:
|
||||||
cls.name = name
|
cls.name = name
|
||||||
@@ -21,7 +21,7 @@ def note_class(name: str, number: int):
|
|||||||
|
|
||||||
|
|
||||||
class LaunchNote(abc.ABC):
|
class LaunchNote(abc.ABC):
|
||||||
"""启动信息"""
|
"""Launch information"""
|
||||||
|
|
||||||
name: str
|
name: str
|
||||||
|
|
||||||
@@ -34,10 +34,10 @@ class LaunchNote(abc.ABC):
|
|||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
async def need_show(self) -> bool:
|
async def need_show(self) -> bool:
|
||||||
"""判断当前环境是否需要显示此启动信息"""
|
"""Determine if the current environment needs to display this launch information"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
async def yield_note(self) -> typing.AsyncGenerator[typing.Tuple[str, int], None]:
|
async def yield_note(self) -> typing.AsyncGenerator[typing.Tuple[str, int], None]:
|
||||||
"""生成启动信息"""
|
"""Generate launch information"""
|
||||||
pass
|
pass
|
||||||
|
|||||||
+4
-4
@@ -7,9 +7,9 @@ from . import app
|
|||||||
|
|
||||||
|
|
||||||
preregistered_stages: dict[str, typing.Type[BootingStage]] = {}
|
preregistered_stages: dict[str, typing.Type[BootingStage]] = {}
|
||||||
"""预注册的请求处理阶段。在初始化时,所有请求处理阶段类会被注册到此字典中。
|
"""Pre-registered request processing stages. All request processing stage classes are registered in this dictionary during initialization.
|
||||||
|
|
||||||
当前阶段暂不支持扩展
|
Currently not supported for extension
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@@ -22,11 +22,11 @@ def stage_class(name: str):
|
|||||||
|
|
||||||
|
|
||||||
class BootingStage(abc.ABC):
|
class BootingStage(abc.ABC):
|
||||||
"""启动阶段"""
|
"""Booting stage"""
|
||||||
|
|
||||||
name: str = None
|
name: str = None
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
async def run(self, ap: app.Application):
|
async def run(self, ap: app.Application):
|
||||||
"""启动"""
|
"""Run"""
|
||||||
pass
|
pass
|
||||||
|
|||||||
+20
-20
@@ -9,13 +9,13 @@ from . import entities as core_entities
|
|||||||
|
|
||||||
|
|
||||||
class TaskContext:
|
class TaskContext:
|
||||||
"""任务跟踪上下文"""
|
"""Task tracking context"""
|
||||||
|
|
||||||
current_action: str
|
current_action: str
|
||||||
"""当前正在执行的动作"""
|
"""Current action being executed"""
|
||||||
|
|
||||||
log: str
|
log: str
|
||||||
"""记录日志"""
|
"""Log"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.current_action = 'default'
|
self.current_action = 'default'
|
||||||
@@ -58,40 +58,40 @@ placeholder_context: TaskContext | None = None
|
|||||||
|
|
||||||
|
|
||||||
class TaskWrapper:
|
class TaskWrapper:
|
||||||
"""任务包装器"""
|
"""Task wrapper"""
|
||||||
|
|
||||||
_id_index: int = 0
|
_id_index: int = 0
|
||||||
"""任务ID索引"""
|
"""Task ID index"""
|
||||||
|
|
||||||
id: int
|
id: int
|
||||||
"""任务ID"""
|
"""Task ID"""
|
||||||
|
|
||||||
task_type: str = 'system' # 任务类型: system 或 user
|
task_type: str = 'system' # Task type: system or user
|
||||||
"""任务类型"""
|
"""Task type"""
|
||||||
|
|
||||||
kind: str = 'system_task' # 由发起者确定任务种类,通常同质化的任务种类相同
|
kind: str = 'system_task' # Task type determined by the initiator, usually the same task type
|
||||||
"""任务种类"""
|
"""Task type"""
|
||||||
|
|
||||||
name: str = ''
|
name: str = ''
|
||||||
"""任务唯一名称"""
|
"""Task unique name"""
|
||||||
|
|
||||||
label: str = ''
|
label: str = ''
|
||||||
"""任务显示名称"""
|
"""Task display name"""
|
||||||
|
|
||||||
task_context: TaskContext
|
task_context: TaskContext
|
||||||
"""任务上下文"""
|
"""Task context"""
|
||||||
|
|
||||||
task: asyncio.Task
|
task: asyncio.Task
|
||||||
"""任务"""
|
"""Task"""
|
||||||
|
|
||||||
task_stack: list = None
|
task_stack: list = None
|
||||||
"""任务堆栈"""
|
"""Task stack"""
|
||||||
|
|
||||||
ap: app.Application
|
ap: app.Application
|
||||||
"""应用实例"""
|
"""Application instance"""
|
||||||
|
|
||||||
scopes: list[core_entities.LifecycleControlScope]
|
scopes: list[core_entities.LifecycleControlScope]
|
||||||
"""任务所属生命周期控制范围"""
|
"""Task scope"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -165,13 +165,13 @@ class TaskWrapper:
|
|||||||
|
|
||||||
|
|
||||||
class AsyncTaskManager:
|
class AsyncTaskManager:
|
||||||
"""保存app中的所有异步任务
|
"""Save all asynchronous tasks in the app
|
||||||
包含系统级的和用户级(插件安装、更新等由用户直接发起的)的"""
|
Include system-level and user-level (plugin installation, update, etc. initiated by users directly)"""
|
||||||
|
|
||||||
ap: app.Application
|
ap: app.Application
|
||||||
|
|
||||||
tasks: list[TaskWrapper]
|
tasks: list[TaskWrapper]
|
||||||
"""所有任务"""
|
"""All tasks"""
|
||||||
|
|
||||||
def __init__(self, ap: app.Application):
|
def __init__(self, ap: app.Application):
|
||||||
self.ap = ap
|
self.ap = ap
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from .base import Base
|
|||||||
|
|
||||||
|
|
||||||
class Bot(Base):
|
class Bot(Base):
|
||||||
"""机器人"""
|
"""Bot"""
|
||||||
|
|
||||||
__tablename__ = 'bots'
|
__tablename__ = 'bots'
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ initial_metadata = [
|
|||||||
|
|
||||||
|
|
||||||
class Metadata(Base):
|
class Metadata(Base):
|
||||||
"""数据库元数据"""
|
"""Database metadata"""
|
||||||
|
|
||||||
__tablename__ = 'metadata'
|
__tablename__ = 'metadata'
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from .base import Base
|
|||||||
|
|
||||||
|
|
||||||
class LLMModel(Base):
|
class LLMModel(Base):
|
||||||
"""LLM 模型"""
|
"""LLM model"""
|
||||||
|
|
||||||
__tablename__ = 'llm_models'
|
__tablename__ = 'llm_models'
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from .base import Base
|
|||||||
|
|
||||||
|
|
||||||
class LegacyPipeline(Base):
|
class LegacyPipeline(Base):
|
||||||
"""旧版流水线"""
|
"""Legacy pipeline"""
|
||||||
|
|
||||||
__tablename__ = 'legacy_pipelines'
|
__tablename__ = 'legacy_pipelines'
|
||||||
|
|
||||||
@@ -26,7 +26,7 @@ class LegacyPipeline(Base):
|
|||||||
|
|
||||||
|
|
||||||
class PipelineRunRecord(Base):
|
class PipelineRunRecord(Base):
|
||||||
"""流水线运行记录"""
|
"""Pipeline run record"""
|
||||||
|
|
||||||
__tablename__ = 'pipeline_run_records'
|
__tablename__ = 'pipeline_run_records'
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from .base import Base
|
|||||||
|
|
||||||
|
|
||||||
class PluginSetting(Base):
|
class PluginSetting(Base):
|
||||||
"""插件配置"""
|
"""Plugin setting"""
|
||||||
|
|
||||||
__tablename__ = 'plugin_settings'
|
__tablename__ = 'plugin_settings'
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ preregistered_managers: list[type[BaseDatabaseManager]] = []
|
|||||||
|
|
||||||
|
|
||||||
def manager_class(name: str) -> None:
|
def manager_class(name: str) -> None:
|
||||||
"""注册一个数据库管理类"""
|
"""Register a database manager class"""
|
||||||
|
|
||||||
def decorator(cls: type[BaseDatabaseManager]) -> type[BaseDatabaseManager]:
|
def decorator(cls: type[BaseDatabaseManager]) -> type[BaseDatabaseManager]:
|
||||||
cls.name = name
|
cls.name = name
|
||||||
@@ -22,7 +22,7 @@ def manager_class(name: str) -> None:
|
|||||||
|
|
||||||
|
|
||||||
class BaseDatabaseManager(abc.ABC):
|
class BaseDatabaseManager(abc.ABC):
|
||||||
"""基础数据库管理类"""
|
"""Base database manager class"""
|
||||||
|
|
||||||
name: str
|
name: str
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from .. import database
|
|||||||
|
|
||||||
@database.manager_class('sqlite')
|
@database.manager_class('sqlite')
|
||||||
class SQLiteDatabaseManager(database.BaseDatabaseManager):
|
class SQLiteDatabaseManager(database.BaseDatabaseManager):
|
||||||
"""SQLite 数据库管理类"""
|
"""SQLite database manager"""
|
||||||
|
|
||||||
async def initialize(self) -> None:
|
async def initialize(self) -> None:
|
||||||
sqlite_path = 'data/langbot.db'
|
sqlite_path = 'data/langbot.db'
|
||||||
|
|||||||
@@ -22,12 +22,12 @@ importutil.import_modules_in_pkg(persistence)
|
|||||||
|
|
||||||
|
|
||||||
class PersistenceManager:
|
class PersistenceManager:
|
||||||
"""持久化模块管理器"""
|
"""Persistence module manager"""
|
||||||
|
|
||||||
ap: app.Application
|
ap: app.Application
|
||||||
|
|
||||||
db: database.BaseDatabaseManager
|
db: database.BaseDatabaseManager
|
||||||
"""数据库管理器"""
|
"""Database manager"""
|
||||||
|
|
||||||
meta: sqlalchemy.MetaData
|
meta: sqlalchemy.MetaData
|
||||||
|
|
||||||
@@ -79,7 +79,7 @@ class PersistenceManager:
|
|||||||
'stages': pipeline_service.default_stage_order,
|
'stages': pipeline_service.default_stage_order,
|
||||||
'is_default': True,
|
'is_default': True,
|
||||||
'name': 'ChatPipeline',
|
'name': 'ChatPipeline',
|
||||||
'description': '默认提供的流水线,您配置的机器人、第一个模型将自动绑定到此流水线',
|
'description': 'Default pipeline provided, your new bots will be automatically bound to this pipeline | 默认提供的流水线,您配置的机器人将自动绑定到此流水线',
|
||||||
'config': pipeline_config,
|
'config': pipeline_config,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ preregistered_db_migrations: list[typing.Type[DBMigration]] = []
|
|||||||
|
|
||||||
|
|
||||||
def migration_class(number: int):
|
def migration_class(number: int):
|
||||||
"""迁移类装饰器"""
|
"""Migration class decorator"""
|
||||||
|
|
||||||
def wrapper(cls: typing.Type[DBMigration]) -> typing.Type[DBMigration]:
|
def wrapper(cls: typing.Type[DBMigration]) -> typing.Type[DBMigration]:
|
||||||
cls.number = number
|
cls.number = number
|
||||||
@@ -21,20 +21,20 @@ def migration_class(number: int):
|
|||||||
|
|
||||||
|
|
||||||
class DBMigration(abc.ABC):
|
class DBMigration(abc.ABC):
|
||||||
"""数据库迁移"""
|
"""Database migration"""
|
||||||
|
|
||||||
number: int
|
number: int
|
||||||
"""迁移号"""
|
"""Migration number"""
|
||||||
|
|
||||||
def __init__(self, ap: app.Application):
|
def __init__(self, ap: app.Application):
|
||||||
self.ap = ap
|
self.ap = ap
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
async def upgrade(self):
|
async def upgrade(self):
|
||||||
"""升级"""
|
"""Upgrade"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
async def downgrade(self):
|
async def downgrade(self):
|
||||||
"""降级"""
|
"""Downgrade"""
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -15,21 +15,21 @@ from ...entity.persistence import (
|
|||||||
|
|
||||||
@migration.migration_class(1)
|
@migration.migration_class(1)
|
||||||
class DBMigrateV3Config(migration.DBMigration):
|
class DBMigrateV3Config(migration.DBMigration):
|
||||||
"""从 v3 的配置迁移到 v4 的数据库"""
|
"""Migrate v3 config to v4 database"""
|
||||||
|
|
||||||
async def upgrade(self):
|
async def upgrade(self):
|
||||||
"""升级"""
|
"""Upgrade"""
|
||||||
"""
|
"""
|
||||||
将 data/config 下的所有配置文件进行迁移。
|
Migrate all config files under data/config.
|
||||||
迁移后,之前的配置文件都保存到 data/legacy/config 下。
|
After migration, all previous config files are saved under data/legacy/config.
|
||||||
迁移后,data/metadata/ 下的所有配置文件都保存到 data/legacy/metadata 下。
|
After migration, all config files under data/metadata/ are saved under data/legacy/metadata.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if self.ap.provider_cfg is None:
|
if self.ap.provider_cfg is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
# ======= 迁移模型 =======
|
# ======= Migrate model =======
|
||||||
# 只迁移当前选中的模型
|
# Only migrate the currently selected model
|
||||||
model_name = self.ap.provider_cfg.data.get('model', 'gpt-4o')
|
model_name = self.ap.provider_cfg.data.get('model', 'gpt-4o')
|
||||||
|
|
||||||
model_requester = 'openai-chat-completions'
|
model_requester = 'openai-chat-completions'
|
||||||
@@ -91,8 +91,8 @@ class DBMigrateV3Config(migration.DBMigration):
|
|||||||
sqlalchemy.insert(persistence_model.LLMModel).values(**llm_model_data)
|
sqlalchemy.insert(persistence_model.LLMModel).values(**llm_model_data)
|
||||||
)
|
)
|
||||||
|
|
||||||
# ======= 迁移流水线配置 =======
|
# ======= Migrate pipeline config =======
|
||||||
# 修改到默认流水线
|
# Modify to default pipeline
|
||||||
default_pipeline = [
|
default_pipeline = [
|
||||||
self.ap.persistence_mgr.serialize_model(persistence_pipeline.LegacyPipeline, pipeline)
|
self.ap.persistence_mgr.serialize_model(persistence_pipeline.LegacyPipeline, pipeline)
|
||||||
for pipeline in (
|
for pipeline in (
|
||||||
@@ -184,8 +184,8 @@ class DBMigrateV3Config(migration.DBMigration):
|
|||||||
.where(persistence_pipeline.LegacyPipeline.uuid == default_pipeline['uuid'])
|
.where(persistence_pipeline.LegacyPipeline.uuid == default_pipeline['uuid'])
|
||||||
)
|
)
|
||||||
|
|
||||||
# ======= 迁移机器人 =======
|
# ======= Migrate bot =======
|
||||||
# 只迁移启用的机器人
|
# Only migrate enabled bots
|
||||||
for adapter in self.ap.platform_cfg.data.get('platform-adapters', []):
|
for adapter in self.ap.platform_cfg.data.get('platform-adapters', []):
|
||||||
if not adapter.get('enable'):
|
if not adapter.get('enable'):
|
||||||
continue
|
continue
|
||||||
@@ -207,7 +207,7 @@ class DBMigrateV3Config(migration.DBMigration):
|
|||||||
|
|
||||||
await self.ap.persistence_mgr.execute_async(sqlalchemy.insert(persistence_bot.Bot).values(**bot_data))
|
await self.ap.persistence_mgr.execute_async(sqlalchemy.insert(persistence_bot.Bot).values(**bot_data))
|
||||||
|
|
||||||
# ======= 迁移系统设置 =======
|
# ======= Migrate system settings =======
|
||||||
self.ap.instance_config.data['admins'] = self.ap.system_cfg.data['admin-sessions']
|
self.ap.instance_config.data['admins'] = self.ap.system_cfg.data['admin-sessions']
|
||||||
self.ap.instance_config.data['api']['port'] = self.ap.system_cfg.data['http-api']['port']
|
self.ap.instance_config.data['api']['port'] = self.ap.system_cfg.data['http-api']['port']
|
||||||
self.ap.instance_config.data['command'] = {
|
self.ap.instance_config.data['command'] = {
|
||||||
@@ -223,7 +223,7 @@ class DBMigrateV3Config(migration.DBMigration):
|
|||||||
await self.ap.instance_config.dump_config()
|
await self.ap.instance_config.dump_config()
|
||||||
|
|
||||||
# ======= move files =======
|
# ======= move files =======
|
||||||
# 迁移 data/config 下的所有配置文件
|
# Migrate all config files under data/config
|
||||||
all_legacy_dir_name = [
|
all_legacy_dir_name = [
|
||||||
'config',
|
'config',
|
||||||
# 'metadata',
|
# 'metadata',
|
||||||
@@ -246,4 +246,4 @@ class DBMigrateV3Config(migration.DBMigration):
|
|||||||
move_legacy_files(dir_name)
|
move_legacy_files(dir_name)
|
||||||
|
|
||||||
async def downgrade(self):
|
async def downgrade(self):
|
||||||
"""降级"""
|
"""Downgrade"""
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ from ...entity.persistence import pipeline as persistence_pipeline
|
|||||||
|
|
||||||
@migration.migration_class(2)
|
@migration.migration_class(2)
|
||||||
class DBMigrateCombineQuoteMsgConfig(migration.DBMigration):
|
class DBMigrateCombineQuoteMsgConfig(migration.DBMigration):
|
||||||
"""引用消息合并配置"""
|
"""Combine quote message config"""
|
||||||
|
|
||||||
async def upgrade(self):
|
async def upgrade(self):
|
||||||
"""升级"""
|
"""Upgrade"""
|
||||||
# read all pipelines
|
# read all pipelines
|
||||||
pipelines = await self.ap.persistence_mgr.execute_async(sqlalchemy.select(persistence_pipeline.LegacyPipeline))
|
pipelines = await self.ap.persistence_mgr.execute_async(sqlalchemy.select(persistence_pipeline.LegacyPipeline))
|
||||||
|
|
||||||
@@ -37,5 +37,5 @@ class DBMigrateCombineQuoteMsgConfig(migration.DBMigration):
|
|||||||
)
|
)
|
||||||
|
|
||||||
async def downgrade(self):
|
async def downgrade(self):
|
||||||
"""降级"""
|
"""Downgrade"""
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ from ...entity.persistence import pipeline as persistence_pipeline
|
|||||||
|
|
||||||
@migration.migration_class(3)
|
@migration.migration_class(3)
|
||||||
class DBMigrateN8nConfig(migration.DBMigration):
|
class DBMigrateN8nConfig(migration.DBMigration):
|
||||||
"""N8n配置"""
|
"""N8n config"""
|
||||||
|
|
||||||
async def upgrade(self):
|
async def upgrade(self):
|
||||||
"""升级"""
|
"""Upgrade"""
|
||||||
# read all pipelines
|
# read all pipelines
|
||||||
pipelines = await self.ap.persistence_mgr.execute_async(sqlalchemy.select(persistence_pipeline.LegacyPipeline))
|
pipelines = await self.ap.persistence_mgr.execute_async(sqlalchemy.select(persistence_pipeline.LegacyPipeline))
|
||||||
|
|
||||||
@@ -45,5 +45,5 @@ class DBMigrateN8nConfig(migration.DBMigration):
|
|||||||
)
|
)
|
||||||
|
|
||||||
async def downgrade(self):
|
async def downgrade(self):
|
||||||
"""降级"""
|
"""Downgrade"""
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ from ...core import entities as core_entities
|
|||||||
|
|
||||||
@stage.stage_class('BanSessionCheckStage')
|
@stage.stage_class('BanSessionCheckStage')
|
||||||
class BanSessionCheckStage(stage.PipelineStage):
|
class BanSessionCheckStage(stage.PipelineStage):
|
||||||
"""访问控制处理阶段
|
"""Access control processing stage
|
||||||
|
|
||||||
仅检查query中群号或个人号是否在访问控制列表中。
|
Only check if the group or personal number in the query is in the access control list.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
async def initialize(self, pipeline_config: dict):
|
async def initialize(self, pipeline_config: dict):
|
||||||
@@ -41,5 +41,7 @@ class BanSessionCheckStage(stage.PipelineStage):
|
|||||||
return entities.StageProcessResult(
|
return entities.StageProcessResult(
|
||||||
result_type=entities.ResultType.CONTINUE if ctn else entities.ResultType.INTERRUPT,
|
result_type=entities.ResultType.CONTINUE if ctn else entities.ResultType.INTERRUPT,
|
||||||
new_query=query,
|
new_query=query,
|
||||||
console_notice=f'根据访问控制忽略消息: {query.launcher_type.value}_{query.launcher_id}' if not ctn else '',
|
console_notice=f'Ignore message according to access control: {query.launcher_type.value}_{query.launcher_id}'
|
||||||
|
if not ctn
|
||||||
|
else '',
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -13,13 +13,13 @@ preregistered_filters: list[typing.Type[ContentFilter]] = []
|
|||||||
def filter_class(
|
def filter_class(
|
||||||
name: str,
|
name: str,
|
||||||
) -> typing.Callable[[typing.Type[ContentFilter]], typing.Type[ContentFilter]]:
|
) -> typing.Callable[[typing.Type[ContentFilter]], typing.Type[ContentFilter]]:
|
||||||
"""内容过滤器类装饰器
|
"""Content filter class decorator
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
name (str): 过滤器名称
|
name (str): Filter name
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
typing.Callable[[typing.Type[ContentFilter]], typing.Type[ContentFilter]]: 装饰器
|
typing.Callable[[typing.Type[ContentFilter]], typing.Type[ContentFilter]]: Decorator
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def decorator(cls: typing.Type[ContentFilter]) -> typing.Type[ContentFilter]:
|
def decorator(cls: typing.Type[ContentFilter]) -> typing.Type[ContentFilter]:
|
||||||
@@ -35,7 +35,7 @@ def filter_class(
|
|||||||
|
|
||||||
|
|
||||||
class ContentFilter(metaclass=abc.ABCMeta):
|
class ContentFilter(metaclass=abc.ABCMeta):
|
||||||
"""内容过滤器抽象类"""
|
"""Content filter abstract class"""
|
||||||
|
|
||||||
name: str
|
name: str
|
||||||
|
|
||||||
@@ -46,31 +46,31 @@ class ContentFilter(metaclass=abc.ABCMeta):
|
|||||||
|
|
||||||
@property
|
@property
|
||||||
def enable_stages(self):
|
def enable_stages(self):
|
||||||
"""启用的阶段
|
"""Enabled stages
|
||||||
|
|
||||||
默认为消息请求AI前后的两个阶段。
|
Default is the two stages before and after the message request to AI.
|
||||||
|
|
||||||
entity.EnableStage.PRE: 消息请求AI前,此时需要检查的内容是用户的输入消息。
|
entity.EnableStage.PRE: Before message request to AI, the content to check is the user's input message.
|
||||||
entity.EnableStage.POST: 消息请求AI后,此时需要检查的内容是AI的回复消息。
|
entity.EnableStage.POST: After message request to AI, the content to check is the AI's reply message.
|
||||||
"""
|
"""
|
||||||
return [entities.EnableStage.PRE, entities.EnableStage.POST]
|
return [entities.EnableStage.PRE, entities.EnableStage.POST]
|
||||||
|
|
||||||
async def initialize(self):
|
async def initialize(self):
|
||||||
"""初始化过滤器"""
|
"""Initialize filter"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
async def process(self, query: core_entities.Query, message: str = None, image_url=None) -> entities.FilterResult:
|
async def process(self, query: core_entities.Query, message: str = None, image_url=None) -> entities.FilterResult:
|
||||||
"""处理消息
|
"""Process message
|
||||||
|
|
||||||
分为前后阶段,具体取决于 enable_stages 的值。
|
It is divided into two stages, depending on the value of enable_stages.
|
||||||
对于内容过滤器来说,不需要考虑消息所处的阶段,只需要检查消息内容即可。
|
For content filters, you do not need to consider the stage of the message, you only need to check the message content.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
message (str): 需要检查的内容
|
message (str): Content to check
|
||||||
image_url (str): 要检查的图片的 URL
|
image_url (str): URL of the image to check
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
entities.FilterResult: 过滤结果,具体内容请查看 entities.FilterResult 类的文档
|
entities.FilterResult: Filter result, please refer to the documentation of entities.FilterResult class
|
||||||
"""
|
"""
|
||||||
raise NotImplementedError
|
raise NotImplementedError
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from ....core import entities as core_entities
|
|||||||
|
|
||||||
@filter_model.filter_class('ban-word-filter')
|
@filter_model.filter_class('ban-word-filter')
|
||||||
class BanWordFilter(filter_model.ContentFilter):
|
class BanWordFilter(filter_model.ContentFilter):
|
||||||
"""根据内容过滤"""
|
"""Filter content"""
|
||||||
|
|
||||||
async def initialize(self):
|
async def initialize(self):
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from ....core import entities as core_entities
|
|||||||
|
|
||||||
@filter_model.filter_class('content-ignore')
|
@filter_model.filter_class('content-ignore')
|
||||||
class ContentIgnore(filter_model.ContentFilter):
|
class ContentIgnore(filter_model.ContentFilter):
|
||||||
"""根据内容忽略消息"""
|
"""Ignore message according to content"""
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def enable_stages(self):
|
def enable_stages(self):
|
||||||
@@ -24,7 +24,7 @@ class ContentIgnore(filter_model.ContentFilter):
|
|||||||
level=entities.ResultLevel.BLOCK,
|
level=entities.ResultLevel.BLOCK,
|
||||||
replacement='',
|
replacement='',
|
||||||
user_notice='',
|
user_notice='',
|
||||||
console_notice='根据 ignore_rules 中的 prefix 规则,忽略消息',
|
console_notice='Ignore message according to prefix rule in ignore_rules',
|
||||||
)
|
)
|
||||||
|
|
||||||
if 'regexp' in query.pipeline_config['trigger']['ignore-rules']:
|
if 'regexp' in query.pipeline_config['trigger']['ignore-rules']:
|
||||||
@@ -34,7 +34,7 @@ class ContentIgnore(filter_model.ContentFilter):
|
|||||||
level=entities.ResultLevel.BLOCK,
|
level=entities.ResultLevel.BLOCK,
|
||||||
replacement='',
|
replacement='',
|
||||||
user_notice='',
|
user_notice='',
|
||||||
console_notice='根据 ignore_rules 中的 regexp 规则,忽略消息',
|
console_notice='Ignore message according to regexp rule in ignore_rules',
|
||||||
)
|
)
|
||||||
|
|
||||||
return entities.FilterResult(
|
return entities.FilterResult(
|
||||||
|
|||||||
@@ -16,9 +16,9 @@ importutil.import_modules_in_pkg(strategies)
|
|||||||
|
|
||||||
@stage.stage_class('LongTextProcessStage')
|
@stage.stage_class('LongTextProcessStage')
|
||||||
class LongTextProcessStage(stage.PipelineStage):
|
class LongTextProcessStage(stage.PipelineStage):
|
||||||
"""长消息处理阶段
|
"""Long message processing stage
|
||||||
|
|
||||||
改写:
|
Rewrite:
|
||||||
- resp_message_chain
|
- resp_message_chain
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -36,22 +36,22 @@ class LongTextProcessStage(stage.PipelineStage):
|
|||||||
use_font = 'C:/Windows/Fonts/msyh.ttc'
|
use_font = 'C:/Windows/Fonts/msyh.ttc'
|
||||||
if not os.path.exists(use_font):
|
if not os.path.exists(use_font):
|
||||||
self.ap.logger.warn(
|
self.ap.logger.warn(
|
||||||
'未找到字体文件,且无法使用Windows自带字体,更换为转发消息组件以发送长消息,您可以在配置文件中调整相关设置。'
|
'Font file not found, and Windows system font cannot be used, switch to forward message component to send long messages, you can adjust the related settings in the configuration file.'
|
||||||
)
|
)
|
||||||
config['blob_message_strategy'] = 'forward'
|
config['blob_message_strategy'] = 'forward'
|
||||||
else:
|
else:
|
||||||
self.ap.logger.info('使用Windows自带字体:' + use_font)
|
self.ap.logger.info('Using Windows system font: ' + use_font)
|
||||||
config['font-path'] = use_font
|
config['font-path'] = use_font
|
||||||
else:
|
else:
|
||||||
self.ap.logger.warn(
|
self.ap.logger.warn(
|
||||||
'未找到字体文件,且无法使用系统自带字体,更换为转发消息组件以发送长消息,您可以在配置文件中调整相关设置。'
|
'Font file not found, and system font cannot be used, switch to forward message component to send long messages, you can adjust the related settings in the configuration file.'
|
||||||
)
|
)
|
||||||
|
|
||||||
pipeline_config['output']['long-text-processing']['strategy'] = 'forward'
|
pipeline_config['output']['long-text-processing']['strategy'] = 'forward'
|
||||||
except Exception:
|
except Exception:
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
self.ap.logger.error(
|
self.ap.logger.error(
|
||||||
'加载字体文件失败({}),更换为转发消息组件以发送长消息,您可以在配置文件中调整相关设置。'.format(
|
'Failed to load font file ({}), switch to forward message component to send long messages, you can adjust the related settings in the configuration file.'.format(
|
||||||
use_font
|
use_font
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -63,12 +63,12 @@ class LongTextProcessStage(stage.PipelineStage):
|
|||||||
self.strategy_impl = strategy_cls(self.ap)
|
self.strategy_impl = strategy_cls(self.ap)
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
raise ValueError(f'未找到名为 {config["strategy"]} 的长消息处理策略')
|
raise ValueError(f'Long message processing strategy not found: {config["strategy"]}')
|
||||||
|
|
||||||
await self.strategy_impl.initialize()
|
await self.strategy_impl.initialize()
|
||||||
|
|
||||||
async def process(self, query: core_entities.Query, stage_inst_name: str) -> entities.StageProcessResult:
|
async def process(self, query: core_entities.Query, stage_inst_name: str) -> entities.StageProcessResult:
|
||||||
# 检查是否包含非 Plain 组件
|
# Check if it contains non-Plain components
|
||||||
contains_non_plain = False
|
contains_non_plain = False
|
||||||
|
|
||||||
for msg in query.resp_message_chain[-1]:
|
for msg in query.resp_message_chain[-1]:
|
||||||
@@ -77,7 +77,7 @@ class LongTextProcessStage(stage.PipelineStage):
|
|||||||
break
|
break
|
||||||
|
|
||||||
if contains_non_plain:
|
if contains_non_plain:
|
||||||
self.ap.logger.debug('消息中包含非 Plain 组件,跳过长消息处理。')
|
self.ap.logger.debug('Message contains non-Plain components, skip long message processing.')
|
||||||
elif (
|
elif (
|
||||||
len(str(query.resp_message_chain[-1]))
|
len(str(query.resp_message_chain[-1]))
|
||||||
> query.pipeline_config['output']['long-text-processing']['threshold']
|
> query.pipeline_config['output']['long-text-processing']['threshold']
|
||||||
|
|||||||
@@ -15,17 +15,17 @@ Forward = platform_message.Forward
|
|||||||
class ForwardComponentStrategy(strategy_model.LongTextStrategy):
|
class ForwardComponentStrategy(strategy_model.LongTextStrategy):
|
||||||
async def process(self, message: str, query: core_entities.Query) -> list[platform_message.MessageComponent]:
|
async def process(self, message: str, query: core_entities.Query) -> list[platform_message.MessageComponent]:
|
||||||
display = ForwardMessageDiaplay(
|
display = ForwardMessageDiaplay(
|
||||||
title='群聊的聊天记录',
|
title='Group chat history',
|
||||||
brief='[聊天记录]',
|
brief='[Chat history]',
|
||||||
source='聊天记录',
|
source='Chat history',
|
||||||
preview=['QQ用户: ' + message],
|
preview=['User: ' + message],
|
||||||
summary='查看1条转发消息',
|
summary='View 1 forwarded message',
|
||||||
)
|
)
|
||||||
|
|
||||||
node_list = [
|
node_list = [
|
||||||
platform_message.ForwardMessageNode(
|
platform_message.ForwardMessageNode(
|
||||||
sender_id=query.adapter.bot_account_id,
|
sender_id=query.adapter.bot_account_id,
|
||||||
sender_name='QQ用户',
|
sender_name='User',
|
||||||
message_chain=platform_message.MessageChain([message]),
|
message_chain=platform_message.MessageChain([message]),
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -14,13 +14,13 @@ preregistered_strategies: list[typing.Type[LongTextStrategy]] = []
|
|||||||
def strategy_class(
|
def strategy_class(
|
||||||
name: str,
|
name: str,
|
||||||
) -> typing.Callable[[typing.Type[LongTextStrategy]], typing.Type[LongTextStrategy]]:
|
) -> typing.Callable[[typing.Type[LongTextStrategy]], typing.Type[LongTextStrategy]]:
|
||||||
"""长文本处理策略类装饰器
|
"""Long text processing strategy class decorator
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
name (str): 策略名称
|
name (str): Strategy name
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
typing.Callable[[typing.Type[LongTextStrategy]], typing.Type[LongTextStrategy]]: 装饰器
|
typing.Callable[[typing.Type[LongTextStrategy]], typing.Type[LongTextStrategy]]: Decorator
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def decorator(cls: typing.Type[LongTextStrategy]) -> typing.Type[LongTextStrategy]:
|
def decorator(cls: typing.Type[LongTextStrategy]) -> typing.Type[LongTextStrategy]:
|
||||||
@@ -36,7 +36,7 @@ def strategy_class(
|
|||||||
|
|
||||||
|
|
||||||
class LongTextStrategy(metaclass=abc.ABCMeta):
|
class LongTextStrategy(metaclass=abc.ABCMeta):
|
||||||
"""长文本处理策略抽象类"""
|
"""Long text processing strategy abstract class"""
|
||||||
|
|
||||||
name: str
|
name: str
|
||||||
|
|
||||||
@@ -50,15 +50,15 @@ class LongTextStrategy(metaclass=abc.ABCMeta):
|
|||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
async def process(self, message: str, query: core_entities.Query) -> list[platform_message.MessageComponent]:
|
async def process(self, message: str, query: core_entities.Query) -> list[platform_message.MessageComponent]:
|
||||||
"""处理长文本
|
"""Process long text
|
||||||
|
|
||||||
在 platform.json 中配置 long-text-process 字段,只要 文本长度超过了 threshold 就会调用此方法
|
If the text length exceeds the threshold, this method will be called.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
message (str): 消息
|
message (str): Message
|
||||||
query (core_entities.Query): 此次请求的上下文对象
|
query (core_entities.Query): Query object
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
list[platform_message.MessageComponent]: 转换后的 平台 消息组件列表
|
list[platform_message.MessageComponent]: Converted platform message components
|
||||||
"""
|
"""
|
||||||
return []
|
return []
|
||||||
|
|||||||
@@ -12,9 +12,9 @@ importutil.import_modules_in_pkg(truncators)
|
|||||||
|
|
||||||
@stage.stage_class('ConversationMessageTruncator')
|
@stage.stage_class('ConversationMessageTruncator')
|
||||||
class ConversationMessageTruncator(stage.PipelineStage):
|
class ConversationMessageTruncator(stage.PipelineStage):
|
||||||
"""会话消息截断器
|
"""Conversation message truncator
|
||||||
|
|
||||||
用于截断会话消息链,以适应平台消息长度限制。
|
Used to truncate the conversation message chain to adapt to the LLM message length limit.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
trun: truncator.Truncator
|
trun: truncator.Truncator
|
||||||
@@ -27,10 +27,10 @@ class ConversationMessageTruncator(stage.PipelineStage):
|
|||||||
self.trun = trun(self.ap)
|
self.trun = trun(self.ap)
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
raise ValueError(f'未知的截断器: {use_method}')
|
raise ValueError(f'Unknown truncator: {use_method}')
|
||||||
|
|
||||||
async def process(self, query: core_entities.Query, stage_inst_name: str) -> entities.StageProcessResult:
|
async def process(self, query: core_entities.Query, stage_inst_name: str) -> entities.StageProcessResult:
|
||||||
"""处理"""
|
"""Process"""
|
||||||
query = await self.trun.truncate(query)
|
query = await self.trun.truncate(query)
|
||||||
|
|
||||||
return entities.StageProcessResult(result_type=entities.ResultType.CONTINUE, new_query=query)
|
return entities.StageProcessResult(result_type=entities.ResultType.CONTINUE, new_query=query)
|
||||||
|
|||||||
@@ -6,17 +6,17 @@ from ....core import entities as core_entities
|
|||||||
|
|
||||||
@truncator.truncator_class('round')
|
@truncator.truncator_class('round')
|
||||||
class RoundTruncator(truncator.Truncator):
|
class RoundTruncator(truncator.Truncator):
|
||||||
"""前文回合数阶段器"""
|
"""Truncate the conversation message chain to adapt to the LLM message length limit."""
|
||||||
|
|
||||||
async def truncate(self, query: core_entities.Query) -> core_entities.Query:
|
async def truncate(self, query: core_entities.Query) -> core_entities.Query:
|
||||||
"""截断"""
|
"""Truncate"""
|
||||||
max_round = query.pipeline_config['ai']['local-agent']['max-round']
|
max_round = query.pipeline_config['ai']['local-agent']['max-round']
|
||||||
|
|
||||||
temp_messages = []
|
temp_messages = []
|
||||||
|
|
||||||
current_round = 0
|
current_round = 0
|
||||||
|
|
||||||
# 从后往前遍历
|
# Traverse from back to front
|
||||||
for msg in query.messages[::-1]:
|
for msg in query.messages[::-1]:
|
||||||
if current_round < max_round:
|
if current_round < max_round:
|
||||||
temp_messages.append(msg)
|
temp_messages.append(msg)
|
||||||
|
|||||||
@@ -11,11 +11,11 @@ from ...platform.types import message as platform_message
|
|||||||
|
|
||||||
@stage.stage_class('PreProcessor')
|
@stage.stage_class('PreProcessor')
|
||||||
class PreProcessor(stage.PipelineStage):
|
class PreProcessor(stage.PipelineStage):
|
||||||
"""请求预处理阶段
|
"""Request pre-processing stage
|
||||||
|
|
||||||
签出会话、prompt、上文、模型、内容函数。
|
Check out session, prompt, context, model, and content functions.
|
||||||
|
|
||||||
改写:
|
Rewrite:
|
||||||
- session
|
- session
|
||||||
- prompt
|
- prompt
|
||||||
- messages
|
- messages
|
||||||
@@ -29,12 +29,12 @@ class PreProcessor(stage.PipelineStage):
|
|||||||
query: core_entities.Query,
|
query: core_entities.Query,
|
||||||
stage_inst_name: str,
|
stage_inst_name: str,
|
||||||
) -> entities.StageProcessResult:
|
) -> entities.StageProcessResult:
|
||||||
"""处理"""
|
"""Process"""
|
||||||
selected_runner = query.pipeline_config['ai']['runner']['runner']
|
selected_runner = query.pipeline_config['ai']['runner']['runner']
|
||||||
|
|
||||||
session = await self.ap.sess_mgr.get_session(query)
|
session = await self.ap.sess_mgr.get_session(query)
|
||||||
|
|
||||||
# 非 local-agent 时,llm_model 为 None
|
# When not local-agent, llm_model is None
|
||||||
llm_model = (
|
llm_model = (
|
||||||
await self.ap.model_mgr.get_model_by_uuid(query.pipeline_config['ai']['local-agent']['model'])
|
await self.ap.model_mgr.get_model_by_uuid(query.pipeline_config['ai']['local-agent']['model'])
|
||||||
if selected_runner == 'local-agent'
|
if selected_runner == 'local-agent'
|
||||||
@@ -51,7 +51,7 @@ class PreProcessor(stage.PipelineStage):
|
|||||||
|
|
||||||
conversation.use_llm_model = llm_model
|
conversation.use_llm_model = llm_model
|
||||||
|
|
||||||
# 设置query
|
# Set query
|
||||||
query.session = session
|
query.session = session
|
||||||
query.prompt = conversation.prompt.copy()
|
query.prompt = conversation.prompt.copy()
|
||||||
query.messages = conversation.messages.copy()
|
query.messages = conversation.messages.copy()
|
||||||
@@ -109,7 +109,7 @@ class PreProcessor(stage.PipelineStage):
|
|||||||
query.variables['user_message_text'] = plain_text
|
query.variables['user_message_text'] = plain_text
|
||||||
|
|
||||||
query.user_message = llm_entities.Message(role='user', content=content_list)
|
query.user_message = llm_entities.Message(role='user', content=content_list)
|
||||||
# =========== 触发事件 PromptPreProcessing
|
# =========== Trigger event PromptPreProcessing
|
||||||
|
|
||||||
event_ctx = await self.ap.plugin_mgr.emit_event(
|
event_ctx = await self.ap.plugin_mgr.emit_event(
|
||||||
event=events.PromptPreProcessing(
|
event=events.PromptPreProcessing(
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ class MessageHandler(metaclass=abc.ABCMeta):
|
|||||||
|
|
||||||
def cut_str(self, s: str) -> str:
|
def cut_str(self, s: str) -> str:
|
||||||
"""
|
"""
|
||||||
取字符串第一行,最多20个字符,若有多行,或超过20个字符,则加省略号
|
Take the first line of the string, up to 20 characters, if there are multiple lines, or more than 20 characters, add an ellipsis
|
||||||
"""
|
"""
|
||||||
s0 = s.split('\n')[0]
|
s0 = s.split('\n')[0]
|
||||||
if len(s0) > 20 or '\n' in s:
|
if len(s0) > 20 or '\n' in s:
|
||||||
|
|||||||
@@ -22,11 +22,11 @@ class ChatMessageHandler(handler.MessageHandler):
|
|||||||
self,
|
self,
|
||||||
query: core_entities.Query,
|
query: core_entities.Query,
|
||||||
) -> typing.AsyncGenerator[entities.StageProcessResult, None]:
|
) -> typing.AsyncGenerator[entities.StageProcessResult, None]:
|
||||||
"""处理"""
|
"""Process"""
|
||||||
# 调API
|
# Call API
|
||||||
# 生成器
|
# generator
|
||||||
|
|
||||||
# 触发插件事件
|
# Trigger plugin event
|
||||||
event_class = (
|
event_class = (
|
||||||
events.PersonNormalMessageReceived
|
events.PersonNormalMessageReceived
|
||||||
if query.launcher_type == core_entities.LauncherTypes.PERSON
|
if query.launcher_type == core_entities.LauncherTypes.PERSON
|
||||||
@@ -54,7 +54,7 @@ class ChatMessageHandler(handler.MessageHandler):
|
|||||||
yield entities.StageProcessResult(result_type=entities.ResultType.INTERRUPT, new_query=query)
|
yield entities.StageProcessResult(result_type=entities.ResultType.INTERRUPT, new_query=query)
|
||||||
else:
|
else:
|
||||||
if event_ctx.event.alter is not None:
|
if event_ctx.event.alter is not None:
|
||||||
# if isinstance(event_ctx.event, str): # 现在暂时不考虑多模态alter
|
# if isinstance(event_ctx.event, str): # Currently not considering multi-modal alter
|
||||||
query.user_message.content = event_ctx.event.alter
|
query.user_message.content = event_ctx.event.alter
|
||||||
|
|
||||||
text_length = 0
|
text_length = 0
|
||||||
@@ -65,12 +65,12 @@ class ChatMessageHandler(handler.MessageHandler):
|
|||||||
runner = r(self.ap, query.pipeline_config)
|
runner = r(self.ap, query.pipeline_config)
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
raise ValueError(f'未找到请求运行器: {query.pipeline_config["ai"]["runner"]["runner"]}')
|
raise ValueError(f'Request runner not found: {query.pipeline_config["ai"]["runner"]["runner"]}')
|
||||||
|
|
||||||
async for result in runner.run(query):
|
async for result in runner.run(query):
|
||||||
query.resp_messages.append(result)
|
query.resp_messages.append(result)
|
||||||
|
|
||||||
self.ap.logger.info(f'对话({query.query_id})响应: {self.cut_str(result.readable_str())}')
|
self.ap.logger.info(f'Response({query.query_id}): {self.cut_str(result.readable_str())}')
|
||||||
|
|
||||||
if result.content is not None:
|
if result.content is not None:
|
||||||
text_length += len(result.content)
|
text_length += len(result.content)
|
||||||
@@ -80,7 +80,7 @@ class ChatMessageHandler(handler.MessageHandler):
|
|||||||
query.session.using_conversation.messages.append(query.user_message)
|
query.session.using_conversation.messages.append(query.user_message)
|
||||||
query.session.using_conversation.messages.extend(query.resp_messages)
|
query.session.using_conversation.messages.extend(query.resp_messages)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.ap.logger.error(f'对话({query.query_id})请求失败: {type(e).__name__} {str(e)}')
|
self.ap.logger.error(f'Request failed({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']
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ class CommandHandler(handler.MessageHandler):
|
|||||||
self,
|
self,
|
||||||
query: core_entities.Query,
|
query: core_entities.Query,
|
||||||
) -> typing.AsyncGenerator[entities.StageProcessResult, None]:
|
) -> typing.AsyncGenerator[entities.StageProcessResult, None]:
|
||||||
"""处理"""
|
"""Process"""
|
||||||
|
|
||||||
command_text = str(query.message_chain).strip()[1:]
|
command_text = str(query.message_chain).strip()[1:]
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ class CommandHandler(handler.MessageHandler):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
self.ap.logger.info(f'命令({query.query_id})报错: {self.cut_str(str(ret.error))}')
|
self.ap.logger.info(f'Command({query.query_id}) error: {self.cut_str(str(ret.error))}')
|
||||||
|
|
||||||
yield entities.StageProcessResult(result_type=entities.ResultType.CONTINUE, new_query=query)
|
yield entities.StageProcessResult(result_type=entities.ResultType.CONTINUE, new_query=query)
|
||||||
elif ret.text is not None or ret.image_url is not None:
|
elif ret.text is not None or ret.image_url is not None:
|
||||||
@@ -89,7 +89,7 @@ class CommandHandler(handler.MessageHandler):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
self.ap.logger.info(f'命令返回: {self.cut_str(str(content[0]))}')
|
self.ap.logger.info(f'Command returned: {self.cut_str(str(content[0]))}')
|
||||||
|
|
||||||
yield entities.StageProcessResult(result_type=entities.ResultType.CONTINUE, new_query=query)
|
yield entities.StageProcessResult(result_type=entities.ResultType.CONTINUE, new_query=query)
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -33,11 +33,11 @@ class Processor(stage.PipelineStage):
|
|||||||
query: core_entities.Query,
|
query: core_entities.Query,
|
||||||
stage_inst_name: str,
|
stage_inst_name: str,
|
||||||
) -> entities.StageProcessResult:
|
) -> entities.StageProcessResult:
|
||||||
"""处理"""
|
"""Process"""
|
||||||
message_text = str(query.message_chain).strip()
|
message_text = str(query.message_chain).strip()
|
||||||
|
|
||||||
self.ap.logger.info(
|
self.ap.logger.info(
|
||||||
f'处理 {query.launcher_type.value}_{query.launcher_id} 的请求({query.query_id}): {message_text}'
|
f'Processing request from {query.launcher_type.value}_{query.launcher_id} ({query.query_id}): {message_text}'
|
||||||
)
|
)
|
||||||
|
|
||||||
async def generator():
|
async def generator():
|
||||||
|
|||||||
Reference in New Issue
Block a user