fix(image): isolate reaction search context
这个提交存在于:
父节点
69800b8b03
当前提交
763d979695
共有 3 个文件被更改,包括 227 次插入 和 6 次删除
|
|
@ -228,7 +228,7 @@ class LlmToolActionsMixin:
|
|||
if reaction_enabled:
|
||||
lines.extend(
|
||||
[
|
||||
"- 用户要“找/发/来一张已有表情包”、要用现成反应图回应当前语境时,优先使用 `pc_find_reaction_image`,把需求和当前语境写进 `query/context`。",
|
||||
"- 用户要“找/发/来一张已有表情包”、要用现成反应图回应当前语境时,优先使用 `pc_find_reaction_image`,把需求和当前语境写进 `query/search_context`。",
|
||||
"- 图库未匹配时可以自然改用文字回应,不要擅自声称已发图。",
|
||||
]
|
||||
)
|
||||
|
|
@ -2112,7 +2112,7 @@ class LlmToolActionsMixin:
|
|||
self,
|
||||
event: AstrMessageEvent,
|
||||
query: str = "",
|
||||
context: str = "",
|
||||
search_context: str = "",
|
||||
meme_only: bool = True,
|
||||
send: bool = True,
|
||||
caption: str = "",
|
||||
|
|
@ -2154,7 +2154,7 @@ class LlmToolActionsMixin:
|
|||
if send_image:
|
||||
self._mark_smart_imagechat_skip_proactive_emoji(event)
|
||||
|
||||
lookup_context = _single_line(context, 1000)
|
||||
lookup_context = _single_line(search_context, 1000)
|
||||
snapshot_builder = getattr(self, "_build_companion_scene_snapshot", None)
|
||||
snapshot_formatter = getattr(self, "_format_companion_scene_snapshot", None)
|
||||
if callable(snapshot_builder) and callable(snapshot_formatter):
|
||||
|
|
@ -2206,6 +2206,40 @@ class LlmToolActionsMixin:
|
|||
context=lookup_context,
|
||||
meme_only=meme_filter,
|
||||
)
|
||||
except TypeError as exc:
|
||||
# Older Smart ImageChat installations may not yet expose the
|
||||
# optional context keyword. Retry the same local lookup without
|
||||
# it; this is an interoperability fallback, never a different
|
||||
# source or a new authorization path.
|
||||
if "context" not in str(exc).lower():
|
||||
logger.warning(
|
||||
"[PrivateCompanion] 智能图片对话图库检索失败: %s",
|
||||
_single_line(exc, 180),
|
||||
exc_info=True,
|
||||
)
|
||||
lookup = {
|
||||
"success": False,
|
||||
"status": "error",
|
||||
"message": f"图库检索失败:{_single_line(exc, 160)}",
|
||||
}
|
||||
else:
|
||||
try:
|
||||
lookup = await api.find_image(
|
||||
event,
|
||||
query_text,
|
||||
meme_only=meme_filter,
|
||||
)
|
||||
except Exception as fallback_exc:
|
||||
logger.warning(
|
||||
"[PrivateCompanion] 智能图片对话图库兼容检索失败: %s",
|
||||
_single_line(fallback_exc, 180),
|
||||
exc_info=True,
|
||||
)
|
||||
lookup = {
|
||||
"success": False,
|
||||
"status": "error",
|
||||
"message": f"图库检索失败:{_single_line(fallback_exc, 160)}",
|
||||
}
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"[PrivateCompanion] 智能图片对话图库检索失败: %s",
|
||||
|
|
|
|||
16
main.py
16
main.py
|
|
@ -5339,16 +5339,17 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
self,
|
||||
event: AstrMessageEvent,
|
||||
query: str = "",
|
||||
context: str = "",
|
||||
search_context: str = "",
|
||||
meme_only: bool = True,
|
||||
send: bool = True,
|
||||
caption: str = "",
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
"""从智能图片对话插件的本地图库检索并发送一张已有图片。
|
||||
|
||||
Args:
|
||||
query(string): 表情或图片需求,例如“震惊又无语的反应图”。
|
||||
context(string): 可选,当前对话语境或希望表达的情绪。
|
||||
search_context(string): 可选,当前对话语境或希望表达的情绪。
|
||||
meme_only(boolean): 是否只检索标记为表情包的图片,默认 true。
|
||||
send(boolean): 是否直接发送到当前会话,默认 true。
|
||||
caption(string): 可选,随图片发送的短文字。
|
||||
|
|
@ -5364,10 +5365,19 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
|
|||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
# AstrBot 4.26.x may inject a host-owned ``context`` keyword. Keep
|
||||
# the public tool schema on ``search_context`` so a model-supplied
|
||||
# legacy ``context`` cannot collide with that injection. A direct,
|
||||
# string-valued legacy call remains a lowest-priority compatibility
|
||||
# path only; host context objects are never used as search text.
|
||||
legacy_context = kwargs.get("context")
|
||||
if not search_context and isinstance(legacy_context, str):
|
||||
search_context = legacy_context
|
||||
|
||||
return await self._pc_find_reaction_image_impl(
|
||||
event,
|
||||
query=query,
|
||||
context=context,
|
||||
search_context=search_context,
|
||||
meme_only=meme_only,
|
||||
send=send,
|
||||
caption=caption,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,177 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import copy
|
||||
import inspect
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def _single_line(value: Any, limit: int = 1000) -> str:
|
||||
return re.sub(r"\s+", " ", str(value or "")).strip()[:limit]
|
||||
|
||||
|
||||
def _load_method(filename: str, class_name: str, name: str) -> Any:
|
||||
source = (ROOT / filename).read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == class_name)
|
||||
method = next(node for node in owner.body if isinstance(node, ast.AsyncFunctionDef) and node.name == name)
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"AstrMessageEvent": Any,
|
||||
"json": json,
|
||||
"filter": SimpleNamespace(llm_tool=lambda **_kwargs: lambda target: target),
|
||||
}
|
||||
module = ast.Module(body=[copy.deepcopy(method)], type_ignores=[])
|
||||
ast.fix_missing_locations(module)
|
||||
exec(compile(module, str(ROOT / filename), "exec"), namespace)
|
||||
return namespace[name]
|
||||
|
||||
|
||||
PUBLIC_TOOL = _load_method("main.py", "PrivateCompanionPlugin", "pc_find_reaction_image")
|
||||
|
||||
|
||||
def _load_reaction_impl() -> Any:
|
||||
source = (ROOT / "llm_tool_actions.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "LlmToolActionsMixin")
|
||||
method = next(
|
||||
node for node in owner.body if isinstance(node, ast.AsyncFunctionDef) and node.name == "_pc_find_reaction_image_impl"
|
||||
)
|
||||
namespace: dict[str, Any] = {
|
||||
"Any": Any,
|
||||
"AstrMessageEvent": Any,
|
||||
"json": json,
|
||||
"logger": logging.getLogger("test_req021"),
|
||||
"os": os,
|
||||
"_single_line": _single_line,
|
||||
}
|
||||
module = ast.Module(body=[copy.deepcopy(method)], type_ignores=[])
|
||||
ast.fix_missing_locations(module)
|
||||
exec(compile(module, str(ROOT / "llm_tool_actions.py"), "exec"), namespace)
|
||||
return namespace["_pc_find_reaction_image_impl"]
|
||||
|
||||
|
||||
REACTION_IMPL = _load_reaction_impl()
|
||||
|
||||
|
||||
class _ToolHost:
|
||||
def _proactive_only_blocks_passive_event(self, _event: object, _scope: str) -> bool:
|
||||
return False
|
||||
|
||||
async def _pc_find_reaction_image_impl(self, event: object, **kwargs: Any) -> str:
|
||||
self.called_event = event
|
||||
self.called_kwargs = kwargs
|
||||
return "ok"
|
||||
|
||||
|
||||
class _ReactionHost:
|
||||
data: dict[str, Any] = {}
|
||||
|
||||
def __init__(self, api: object | None) -> None:
|
||||
self.api = api
|
||||
self.skip_calls = 0
|
||||
|
||||
def _mark_smart_imagechat_skip_proactive_emoji(self, _event: object) -> None:
|
||||
self.skip_calls += 1
|
||||
|
||||
def _smart_imagechat_api(self) -> object | None:
|
||||
return self.api
|
||||
|
||||
|
||||
class _ModernImageApi:
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple[object, str, str, bool]] = []
|
||||
|
||||
async def find_image(self, event: object, query: str, *, context: str, meme_only: bool) -> dict[str, Any]:
|
||||
self.calls.append((event, query, context, meme_only))
|
||||
return {"success": False, "status": "not_found", "message": "no match"}
|
||||
|
||||
|
||||
class _LegacyImageApi:
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple[object, str, bool]] = []
|
||||
|
||||
async def find_image(self, event: object, query: str, *, meme_only: bool) -> dict[str, Any]:
|
||||
self.calls.append((event, query, meme_only))
|
||||
return {"success": False, "status": "not_found_legacy", "message": "no match"}
|
||||
|
||||
|
||||
class ReactionSearchContextCompatibilityTests(unittest.IsolatedAsyncioTestCase):
|
||||
async def test_public_schema_uses_search_context_and_captures_host_context(self) -> None:
|
||||
signature = inspect.signature(PUBLIC_TOOL)
|
||||
self.assertIn("search_context", signature.parameters)
|
||||
self.assertNotIn("context", signature.parameters)
|
||||
self.assertEqual(inspect.Parameter.VAR_KEYWORD, signature.parameters["kwargs"].kind)
|
||||
|
||||
async def test_search_context_wins_over_legacy_context(self) -> None:
|
||||
host = _ToolHost()
|
||||
event = object()
|
||||
|
||||
self.assertEqual("ok", await PUBLIC_TOOL(host, event, query="惊讶", search_context="新字段", context="旧字段"))
|
||||
self.assertIs(event, host.called_event)
|
||||
self.assertEqual("新字段", host.called_kwargs["search_context"])
|
||||
self.assertNotIn("context", host.called_kwargs)
|
||||
|
||||
async def test_legacy_string_context_is_accepted_but_host_object_is_not_search_text(self) -> None:
|
||||
host = _ToolHost()
|
||||
event = object()
|
||||
|
||||
await PUBLIC_TOOL(host, event, context="旧调用")
|
||||
self.assertEqual("旧调用", host.called_kwargs["search_context"])
|
||||
|
||||
await PUBLIC_TOOL(host, event, context=SimpleNamespace(host_owned=True))
|
||||
self.assertEqual("", host.called_kwargs["search_context"])
|
||||
|
||||
def test_internal_name_and_smart_imagechat_keyword_are_separated(self) -> None:
|
||||
main_source = (ROOT / "main.py").read_text(encoding="utf-8")
|
||||
impl_source = (ROOT / "llm_tool_actions.py").read_text(encoding="utf-8")
|
||||
|
||||
self.assertIn("search_context: str = \"\"", main_source)
|
||||
self.assertIn("search_context=search_context", main_source)
|
||||
self.assertIn("query/search_context", impl_source)
|
||||
self.assertIn("search_context: str = \"\"", impl_source)
|
||||
self.assertIn("lookup_context = _single_line(search_context, 1000)", impl_source)
|
||||
self.assertIn("context=lookup_context", impl_source)
|
||||
|
||||
async def test_absent_smart_imagechat_is_a_controlled_unavailable_result(self) -> None:
|
||||
payload = json.loads(await REACTION_IMPL(_ReactionHost(None), object(), query="惊讶", send=False))
|
||||
|
||||
self.assertEqual("unavailable", payload["status"])
|
||||
self.assertFalse(payload["success"])
|
||||
self.assertTrue(payload["must_not_claim_sent"])
|
||||
|
||||
async def test_modern_smart_imagechat_receives_search_context_under_its_own_keyword(self) -> None:
|
||||
api = _ModernImageApi()
|
||||
event = object()
|
||||
|
||||
payload = json.loads(
|
||||
await REACTION_IMPL(_ReactionHost(api), event, query="惊讶", search_context="当前对话", send=False)
|
||||
)
|
||||
|
||||
self.assertEqual("not_found", payload["status"])
|
||||
self.assertEqual([(event, "惊讶", "当前对话", True)], api.calls)
|
||||
|
||||
async def test_legacy_smart_imagechat_retries_without_context_keyword(self) -> None:
|
||||
api = _LegacyImageApi()
|
||||
event = object()
|
||||
|
||||
payload = json.loads(
|
||||
await REACTION_IMPL(_ReactionHost(api), event, query="惊讶", search_context="当前对话", send=False)
|
||||
)
|
||||
|
||||
self.assertEqual("not_found_legacy", payload["status"])
|
||||
self.assertEqual([(event, "惊讶", True)], api.calls)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
正在加载…
添加表格
在新工单中引用