-
Notifications
You must be signed in to change notification settings - Fork 4
feat(character): 创建角色时用 LLM 从描述补名称 #329
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
xiaocheny214
wants to merge
3
commits into
1024XEngineer:main
Choose a base branch
from
xiaocheny214:feat/character-name-from-description
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 2 additions & 1 deletion
3
backend/packages/ai_engine/src/windup_ai_engine/impl/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| """impl:CharacterGeneratorPort 的装配实现(串联 strategy + 最后一公里)。""" | ||
|
|
||
| from .character_generator import CharacterGenerator | ||
| from .character_namer import LangChainCharacterNamer | ||
|
|
||
| __all__ = ["CharacterGenerator"] | ||
| __all__ = ["CharacterGenerator", "LangChainCharacterNamer"] |
46 changes: 46 additions & 0 deletions
46
backend/packages/ai_engine/src/windup_ai_engine/impl/character_namer.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| """用 LangChain Chat 模型从角色描述抽出短名称。""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any | ||
|
|
||
| from langchain_core.messages import HumanMessage, SystemMessage | ||
|
|
||
| from windup_framework.providers import create_chat_model | ||
|
|
||
| NAME_MAX_LEN = 20 | ||
|
|
||
| _SYSTEM_PROMPT = ( | ||
| "你从角色外观或人设描述中抽出一个适合资产库展示的称呼。" | ||
| "只输出名称本身,不要引号、标点或解释。" | ||
| f"名称不超过 {NAME_MAX_LEN} 个字,优先中文。" | ||
| ) | ||
|
|
||
|
|
||
| def _clean_name(raw: str) -> str: | ||
| return raw.strip().strip("\"'“”‘’").strip()[:NAME_MAX_LEN] | ||
|
|
||
|
|
||
| class LangChainCharacterNamer: | ||
| """``CharacterNamerPort`` 的 LangChain 实现。""" | ||
|
|
||
| def __init__(self, chat_model: Any | None = None) -> None: | ||
| # 装配期不创建 ChatOpenAI:CI / 本地无 AI_API_KEY 时 create_app 仍能起来。 | ||
| self._model = chat_model | ||
|
|
||
| def _chat_model(self) -> Any: | ||
| if self._model is None: | ||
| self._model = create_chat_model() | ||
| return self._model | ||
|
|
||
| def name_from_description(self, description: str) -> str: | ||
| result = self._chat_model().invoke( | ||
| [ | ||
| SystemMessage(content=_SYSTEM_PROMPT), | ||
| HumanMessage(content=description), | ||
| ] | ||
| ) | ||
| content = getattr(result, "content", result) | ||
| if not isinstance(content, str): | ||
| content = str(content or "") | ||
| return _clean_name(content) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
42 changes: 42 additions & 0 deletions
42
backend/packages/app/src/windup_app/server/character/naming.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| """创建角色时解析最终名称:用户输入优先,否则 LLM,再否则描述兜底。""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Protocol | ||
|
|
||
| NAME_MAX_LEN = 20 | ||
| FALLBACK_NAME = "未命名角色" | ||
|
|
||
|
|
||
| class CharacterNamer(Protocol): | ||
| """server 侧起名器契约,避免 web→service 链路碰到 ai_engine。""" | ||
|
|
||
| def name_from_description(self, description: str) -> str: ... | ||
|
|
||
|
|
||
| def _clip(value: str) -> str: | ||
| return value[:NAME_MAX_LEN] | ||
|
|
||
|
|
||
| def resolve_character_name( | ||
| name: str | None, | ||
| description: str | None, | ||
| namer: CharacterNamer | None = None, | ||
| ) -> str: | ||
| """把可空的 name / description 收成入库用的非空短名称。""" | ||
| cleaned_name = (name or "").strip() | ||
| if cleaned_name: | ||
| return _clip(cleaned_name) | ||
|
|
||
| cleaned_description = (description or "").strip() | ||
| if cleaned_description and namer is not None: | ||
| try: | ||
| generated = (namer.name_from_description(cleaned_description) or "").strip() | ||
| except Exception: | ||
| generated = "" | ||
| if generated: | ||
| return _clip(generated) | ||
|
|
||
| if cleaned_description: | ||
| return _clip(cleaned_description) | ||
| return FALLBACK_NAME |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,12 +13,29 @@ | |
|
|
||
| from windup_app.server.character.interface import CharacterService | ||
| from windup_app.server.character.model import Character | ||
| from windup_app.server.character.naming import CharacterNamer, resolve_character_name | ||
|
|
||
|
|
||
| class SqlAlchemyCharacterService(CharacterService): | ||
| """基于 SQLAlchemy session 的角色 CRUD 实现。""" | ||
|
|
||
| def __init__(self, namer: CharacterNamer | None = None) -> None: | ||
| self._namer = namer | ||
|
|
||
| def create_character(self, session: Session, **fields) -> Character: | ||
| fields = dict(fields) | ||
| workflow_run_id = fields.get("workflow_run_id") | ||
| existing = ( | ||
| self.get_character_by_workflow_run(session, workflow_run_id) | ||
| if workflow_run_id is not None | ||
| else None | ||
| ) | ||
| if existing is not None and existing.project_id == fields.get("project_id"): | ||
| return existing | ||
| name = fields.get("name") | ||
| # 已有同 workflow_run(含跨项目冲突)不再打 LLM,插入交给唯一约束。 | ||
| namer = None if (name or "").strip() or existing is not None else self._namer | ||
| fields["name"] = resolve_character_name(name, fields.get("description"), namer) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] 在付费起名前先处理 workflow_run 幂等
|
||
| character = Character(**fields) | ||
| session.add(character) | ||
| session.flush() | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| """LangChain 角色起名器:注入假 chat model,不打真实 LLM。""" | ||
|
|
||
| from types import SimpleNamespace | ||
|
|
||
| from windup_ai_engine.impl.character_namer import LangChainCharacterNamer | ||
|
|
||
|
|
||
| class _FakeChat: | ||
| def __init__(self, content: object, error: Exception | None = None) -> None: | ||
| self.content = content | ||
| self.error = error | ||
| self.messages = None | ||
|
|
||
| def invoke(self, messages): | ||
| self.messages = messages | ||
| if self.error is not None: | ||
| raise self.error | ||
| return SimpleNamespace(content=self.content) | ||
|
|
||
|
|
||
| def test_namer_returns_cleaned_model_text(): | ||
| chat = _FakeChat(' "赤发旅人" ') | ||
| namer = LangChainCharacterNamer(chat_model=chat) | ||
|
|
||
| assert namer.name_from_description("红发少年站在雾港") == "赤发旅人" | ||
| assert chat.messages is not None | ||
|
|
||
|
|
||
| def test_namer_truncates_to_20_chars(): | ||
| chat = _FakeChat("风" * 25) | ||
| namer = LangChainCharacterNamer(chat_model=chat) | ||
| assert namer.name_from_description("一段描述") == "风" * 20 | ||
|
|
||
|
|
||
| def test_namer_construction_does_not_touch_chat_provider(): | ||
| """装配应用时不能因为没有 AI_API_KEY 就炸。""" | ||
| namer = LangChainCharacterNamer() | ||
| assert namer._model is None |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P1] 避免在应用启动时强制创建 ChatOpenAI
create_app()现在无条件构造LangChainCharacterNamer,其构造函数会立即调用ChatOpenAI;当本地、测试或仅使用非聊天 AI 能力的部署没有设置AI_API_KEY时,langchain-openai==1.4.0会在这里直接抛出OpenAIError: Missing credentials。这样应用连健康检查都无法启动,请求内resolve_character_name的异常兜底也没有机会执行。请延迟到实际起名调用时再创建模型(让该异常落入现有兜底),或在 bootstrap 中容忍未配置聊天 provider。