Skip to content

Commit 29f3072

Browse files
committed
♻️ 使用local_store获取插件目录
1 parent f9703f0 commit 29f3072

File tree

5 files changed

+31
-24
lines changed

5 files changed

+31
-24
lines changed

src/nonebot_plugin_nyaturingtest/__init__.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
import anyio
1111
import httpx
12-
from nonebot import logger, on_command, on_message
12+
from nonebot import logger, on_command, on_message, require
1313
from nonebot.adapters import Message
1414
from nonebot.adapters.onebot.v11 import (
1515
Bot,
@@ -29,6 +29,8 @@
2929
from .mem import Message as MMessage
3030
from .session import Session
3131

32+
require("nonebot_plugin_localstore")
33+
3234
__plugin_meta__ = PluginMetadata(
3335
name="NYATuringTest",
3436
description="群聊特化llm聊天机器人,具有长期记忆和情绪模拟能力",
@@ -564,7 +566,9 @@ async def message2BotMessage(bot_name: str, group_id: int, message: Message, bot
564566

565567
is_sticker = seg.data.get("sub_type") == 1
566568
image_base64 = base64.b64encode(image_bytes).decode("utf-8")
567-
description = image_manager.get_image_description(image_base64=image_base64, is_sticker=is_sticker)
569+
description = await image_manager.get_image_description(
570+
image_base64=image_base64, is_sticker=is_sticker
571+
)
568572
if description:
569573
if is_sticker:
570574
message_content += f"\n[表情包] [情感:{description.emotion}] [内容:{description.description}]\n"

src/nonebot_plugin_nyaturingtest/image_manager.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,16 @@
55
import json
66
from pathlib import Path
77

8+
import anyio
89
from nonebot import logger
10+
import nonebot_plugin_localstore as store
911
import numpy as np
1012
from PIL import Image
1113

12-
from nonebot_plugin_nyaturingtest.vlm import SiliconFlowVLM
13-
1414
from .config import plugin_config
15+
from .vlm import SiliconFlowVLM
1516

16-
IMAGE_CACHE_DIR = Path("image_cache")
17+
IMAGE_CACHE_DIR = Path(f"{store.get_plugin_cache_dir()}/image_cache")
1718

1819

1920
@dataclass
@@ -80,7 +81,7 @@ def __init__(self):
8081
IMAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)
8182
self._initialized = True
8283

83-
def get_image_description(self, image_base64: str, is_sticker: bool) -> ImageWithDescription | None:
84+
async def get_image_description(self, image_base64: str, is_sticker: bool) -> ImageWithDescription | None:
8485
"""
8586
获取图片描述
8687
"""
@@ -90,20 +91,21 @@ def get_image_description(self, image_base64: str, is_sticker: bool) -> ImageWit
9091
# 检查缓存
9192
cache = IMAGE_CACHE_DIR.joinpath(f"{image_hash}.json")
9293
if cache.exists():
93-
with open(cache, encoding="utf-8") as f:
94-
image_with_desc_raw = f.read()
94+
async with await anyio.open_file(cache, encoding="utf-8") as f:
95+
image_with_desc_raw = await f.read()
9596
try:
9697
image_with_desc = ImageWithDescription.from_json(image_with_desc_raw)
9798
if image_with_desc.is_sticker != is_sticker:
9899
image_with_desc.is_sticker = is_sticker
99100
# 修改缓存文件
100-
with open(cache, "w", encoding="utf-8") as f:
101-
f.write(image_with_desc.to_json())
101+
async with await anyio.open_file(cache, "w", encoding="utf-8") as f:
102+
await f.write(image_with_desc.to_json())
102103
return image_with_desc
103104
except ValueError as e:
104105
logger.error(f"缓存文件({cache})格式错误,重新生成")
105106
logger.error(e)
106107
cache.unlink() # 删除缓存文件
108+
cache.unlink() # 删除缓存文件
107109

108110
# 获取图片描述
109111
# 获取图片类型
@@ -120,30 +122,30 @@ def get_image_description(self, image_base64: str, is_sticker: bool) -> ImageWit
120122
return None
121123
prompt = """这是一个动态图,每一张图代表了动态图的某一帧,黑色背景代表透明。"请用中文描述这张图片的内容。如
122124
果有文字,请把文字都描述出来。并尝试猜测这个图片的含义。最多100个字"""
123-
description = self._vlm.request(
125+
description = await self._vlm.request(
124126
prompt=prompt,
125127
image_base64=gif_transfromed,
126128
image_format="jpeg",
127129
)
128130
# 分析表达的情感
129131
prompt = """这是一个动态图,每一张图代表了动态图的某一帧,黑色背景代表透明。请分析这个表情包表达的情感,
130132
用中文给出'情感,类型,含义'的三元式描述,要求每个描述都是一个简单的词语"""
131-
description_emotion = self._vlm.request(
133+
description_emotion = await self._vlm.request(
132134
prompt=prompt,
133135
image_base64=gif_transfromed,
134136
image_format="jpeg",
135137
)
136138
else:
137139
prompt = "请用中文描述这张图片的内容。如果有文字,请把文字都描述出来。并尝试猜测这个图片的含义。最多100个字"
138-
description = self._vlm.request(
140+
description = await self._vlm.request(
139141
prompt=prompt,
140142
image_base64=image_base64,
141143
image_format=image_format,
142144
)
143145
# 分析表达的情感
144146
prompt = """请分析这个表情包表达的情感,用中文给出'情感,类型,含义'的三元式描述,要求每个描述都是一个简单的
145147
词语"""
146-
description_emotion = self._vlm.request(
148+
description_emotion = await self._vlm.request(
147149
prompt=prompt,
148150
image_base64=image_base64,
149151
image_format="jpeg",
@@ -158,10 +160,9 @@ def get_image_description(self, image_base64: str, is_sticker: bool) -> ImageWit
158160
emotion=description_emotion,
159161
is_sticker=is_sticker,
160162
)
161-
162163
# 缓存结果
163-
with open(cache, "w", encoding="utf-8") as f:
164-
f.write(result.to_json())
164+
async with await anyio.open_file(cache, "w", encoding="utf-8") as f:
165+
await f.write(result.to_json())
165166

166167
return result
167168

src/nonebot_plugin_nyaturingtest/mem.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ def related_users(self) -> list[str]:
105105
"""
106106
return list({message.user_name for message in self.__messages})
107107

108-
def compress_message(self):
108+
async def compress_message(self):
109109
"""
110110
压缩历史消息
111111
"""
@@ -129,7 +129,7 @@ def compress_message(self):
129129
{history_messages}
130130
"""
131131
try:
132-
response = self.__llm_client.generate_response(prompt, model="Qwen/Qwen3-8B")
132+
response = await self.__llm_client.generate_response(prompt, model="Qwen/Qwen3-8B")
133133
if response:
134134
self.__compressed_message = response
135135
logger.info(f"压缩消息成功: {response}")

src/nonebot_plugin_nyaturingtest/presets.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import os
44

55
from nonebot import logger
6+
import nonebot_plugin_localstore as store
67

78

89
@dataclass
@@ -59,7 +60,7 @@ class RolePreset:
5960
PRESETS: dict[str, RolePreset] = {}
6061

6162

62-
def _load_presets_from_directory(directory: str = "./nya_presets"):
63+
def _load_presets_from_directory(directory: str = f"{store.get_plugin_config_dir()}/nya_presets"):
6364
# 如果文件夹不存在就创建并且写入例子(_猫娘预设)
6465
if not os.path.exists(directory):
6566
os.makedirs(directory)

src/nonebot_plugin_nyaturingtest/session.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import traceback
1212

1313
from nonebot import logger
14+
import nonebot_plugin_localstore as store
1415
from openai import AsyncOpenAI
1516

1617
from .client import LLMClient
@@ -85,7 +86,7 @@ def __init__(self, siliconflow_api_key: str, id: str = "global", name: str = "te
8586
llm_api_key=plugin_config.nyaturingtest_chat_openai_api_key,
8687
llm_base_url=plugin_config.nyaturingtest_chat_openai_base_url,
8788
embedding_api_key=siliconflow_api_key,
88-
persist_directory=f"./hippo_index_{id}",
89+
persist_directory=f"{store.get_plugin_data_dir()}/hippo_index_{id}",
8990
)
9091
"""
9192
对聊天记录的长期记忆 (基于HippoRAG)
@@ -176,8 +177,8 @@ def get_session_file_path(self) -> str:
176177
获取会话文件路径
177178
"""
178179
# 确保会话目录存在
179-
os.makedirs("yaturningtest_sessions", exist_ok=True)
180-
return f"yaturningtest_sessions/session_{self.id}.json"
180+
os.makedirs(f"{store.get_plugin_data_dir()}/yaturningtest_sessions", exist_ok=True)
181+
return f"{store.get_plugin_data_dir()}/yaturningtest_sessions/session_{self.id}.json"
181182

182183
def save_session(self):
183184
"""
@@ -925,7 +926,7 @@ async def update(self, messages_chunk: list[Message], llm: Callable[[str], Await
925926
texts=[f"'{self.__name}':'{msg}'" for msg in reply_messages],
926927
)
927928
# 压缩,索引记忆
928-
self.global_memory.compress_message()
929+
await self.global_memory.compress_message()
929930
self.long_term_memory.index()
930931

931932
# 保存会话状态

0 commit comments

Comments
 (0)