refactor(settings): 统一语言设置,合并 interface_language 和 ai_language
- 后端 Schema 将 interface_language 和 ai_language 合并为 language - 前端设置界面只保留一个语言选项 - AI 回复语言统一使用 language 设置 - 更新协议文档 - 新增数据库迁移脚本
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
"""update profile settings schema in trigger
|
||||
|
||||
Revision ID: 20260428_0002
|
||||
Revises: 20260428_0001
|
||||
Create Date: 2026-04-28
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "20260428_0002"
|
||||
down_revision = "20260428_0001"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION public.initialize_profile_and_invite_code_on_signup()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
v_username text;
|
||||
v_invite_code text;
|
||||
v_referrer_id uuid;
|
||||
v_attempts int := 0;
|
||||
invite_code_value text;
|
||||
BEGIN
|
||||
v_username := 'user_' || substring(md5(new.id::text || clock_timestamp()::text || random()::text) from 1 for 6);
|
||||
|
||||
INSERT INTO public.profiles (id, username, avatar_url, bio, settings)
|
||||
VALUES (
|
||||
new.id,
|
||||
v_username,
|
||||
null,
|
||||
null,
|
||||
jsonb_build_object(
|
||||
'version', 1,
|
||||
'preferences', jsonb_build_object(
|
||||
'language', 'zh-CN',
|
||||
'timezone', 'Asia/Shanghai',
|
||||
'country', 'US'
|
||||
),
|
||||
'privacy', jsonb_build_object(
|
||||
'can_sell', false,
|
||||
'profile_visibility', 'public'
|
||||
),
|
||||
'notification', jsonb_build_object(
|
||||
'allow_notifications', true,
|
||||
'allow_vibration', true
|
||||
),
|
||||
'divination_tutorial', jsonb_build_object(
|
||||
'divination_entry_shown', false,
|
||||
'auto_divination_shown', false,
|
||||
'manual_divination_shown', false
|
||||
)
|
||||
)
|
||||
)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
LOOP
|
||||
BEGIN
|
||||
v_invite_code := public.generate_invite_code();
|
||||
INSERT INTO public.invite_codes (code, owner_id, status, used_count, max_uses, expires_at, reward_config)
|
||||
VALUES (
|
||||
v_invite_code,
|
||||
new.id,
|
||||
'active',
|
||||
0,
|
||||
NULL,
|
||||
NULL,
|
||||
'{}'::jsonb
|
||||
);
|
||||
EXIT;
|
||||
EXCEPTION WHEN unique_violation THEN
|
||||
v_attempts := v_attempts + 1;
|
||||
IF v_attempts >= 100 THEN
|
||||
RAISE EXCEPTION 'Failed to generate unique invite code after 100 attempts';
|
||||
END IF;
|
||||
END;
|
||||
END LOOP;
|
||||
|
||||
invite_code_value := new.raw_user_meta_data ->> 'invite_code';
|
||||
IF invite_code_value IS NOT NULL AND length(invite_code_value) = 6 THEN
|
||||
invite_code_value := upper(invite_code_value);
|
||||
IF invite_code_value ~ '^[ABCDEFGHJKMNPQRSTUVWXYZ23456789]{6}$' THEN
|
||||
UPDATE public.invite_codes
|
||||
SET used_count = used_count + 1
|
||||
WHERE code = invite_code_value
|
||||
AND status = 'active'
|
||||
AND (max_uses IS NULL OR used_count < max_uses)
|
||||
AND (expires_at IS NULL OR expires_at > NOW())
|
||||
RETURNING owner_id INTO v_referrer_id;
|
||||
|
||||
IF v_referrer_id IS NOT NULL THEN
|
||||
UPDATE public.profiles
|
||||
SET referred_by = v_referrer_id
|
||||
WHERE id = new.id;
|
||||
END IF;
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION public.initialize_profile_and_invite_code_on_signup()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
SECURITY DEFINER
|
||||
SET search_path = public
|
||||
AS $$
|
||||
DECLARE
|
||||
v_username text;
|
||||
v_invite_code text;
|
||||
v_referrer_id uuid;
|
||||
v_attempts int := 0;
|
||||
invite_code_value text;
|
||||
BEGIN
|
||||
v_username := 'user_' || substring(md5(new.id::text || clock_timestamp()::text || random()::text) from 1 for 6);
|
||||
|
||||
INSERT INTO public.profiles (id, username, avatar_url, bio, settings)
|
||||
VALUES (
|
||||
new.id,
|
||||
v_username,
|
||||
null,
|
||||
null,
|
||||
jsonb_build_object(
|
||||
'version', 1,
|
||||
'preferences', jsonb_build_object(
|
||||
'interface_language', 'zh-CN',
|
||||
'ai_language', 'zh-CN',
|
||||
'timezone', 'Asia/Shanghai',
|
||||
'country', 'CN'
|
||||
),
|
||||
'privacy', jsonb_build_object('profile_visibility', 'public'),
|
||||
'notification', jsonb_build_object(
|
||||
'allow_notifications', true,
|
||||
'allow_vibration', true
|
||||
)
|
||||
)
|
||||
)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
LOOP
|
||||
BEGIN
|
||||
v_invite_code := public.generate_invite_code();
|
||||
INSERT INTO public.invite_codes (code, owner_id, status, used_count, max_uses, expires_at, reward_config)
|
||||
VALUES (
|
||||
v_invite_code,
|
||||
new.id,
|
||||
'active',
|
||||
0,
|
||||
NULL,
|
||||
NULL,
|
||||
'{}'::jsonb
|
||||
);
|
||||
EXIT;
|
||||
EXCEPTION WHEN unique_violation THEN
|
||||
v_attempts := v_attempts + 1;
|
||||
IF v_attempts >= 100 THEN
|
||||
RAISE EXCEPTION 'Failed to generate unique invite code after 100 attempts';
|
||||
END IF;
|
||||
END;
|
||||
END LOOP;
|
||||
|
||||
invite_code_value := new.raw_user_meta_data ->> 'invite_code';
|
||||
IF invite_code_value IS NOT NULL AND length(invite_code_value) = 6 THEN
|
||||
invite_code_value := upper(invite_code_value);
|
||||
IF invite_code_value ~ '^[ABCDEFGHJKMNPQRSTUVWXYZ23456789]{6}$' THEN
|
||||
UPDATE public.invite_codes
|
||||
SET used_count = used_count + 1
|
||||
WHERE code = invite_code_value
|
||||
AND status = 'active'
|
||||
AND (max_uses IS NULL OR used_count < max_uses)
|
||||
AND (expires_at IS NULL OR expires_at > NOW())
|
||||
RETURNING owner_id INTO v_referrer_id;
|
||||
|
||||
IF v_referrer_id IS NOT NULL THEN
|
||||
UPDATE public.profiles
|
||||
SET referred_by = v_referrer_id
|
||||
WHERE id = new.id;
|
||||
END IF;
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
"""
|
||||
)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""migrate existing profile settings to new schema
|
||||
|
||||
Revision ID: 20260428_0003
|
||||
Revises: 20260428_0002
|
||||
Create Date: 2026-04-28
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "20260428_0003"
|
||||
down_revision = "20260428_0002"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute(
|
||||
"""
|
||||
UPDATE profiles
|
||||
SET settings = jsonb_build_object(
|
||||
'version', 1,
|
||||
'preferences', jsonb_build_object(
|
||||
'language', COALESCE(settings->'preferences'->>'language', 'zh-CN'),
|
||||
'timezone', COALESCE(settings->'preferences'->>'timezone', 'Asia/Shanghai'),
|
||||
'country', COALESCE(settings->'preferences'->>'country', 'US')
|
||||
),
|
||||
'privacy', jsonb_build_object(
|
||||
'can_sell', COALESCE((settings->'privacy'->>'can_sell')::boolean, false),
|
||||
'profile_visibility', COALESCE(settings->'privacy'->>'profile_visibility', 'public')
|
||||
),
|
||||
'notification', jsonb_build_object(
|
||||
'allow_notifications', COALESCE((settings->'notification'->>'allow_notifications')::boolean, true),
|
||||
'allow_vibration', COALESCE((settings->'notification'->>'allow_vibration')::boolean, true)
|
||||
),
|
||||
'divination_tutorial', jsonb_build_object(
|
||||
'divination_entry_shown', COALESCE((settings->'divination_tutorial'->>'divination_entry_shown')::boolean, false),
|
||||
'auto_divination_shown', COALESCE((settings->'divination_tutorial'->>'auto_divination_shown')::boolean, false),
|
||||
'manual_divination_shown', COALESCE((settings->'divination_tutorial'->>'manual_divination_shown')::boolean, false)
|
||||
)
|
||||
)
|
||||
WHERE settings IS NOT NULL;
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
raise RuntimeError(
|
||||
"20260428_0003 is a destructive JSON data-shape migration and cannot be "
|
||||
"downgraded automatically. Restore profile settings from backup if rollback "
|
||||
"to the previous schema is required."
|
||||
)
|
||||
@@ -12,10 +12,10 @@ def build_agent_prompt(
|
||||
*,
|
||||
agent_type: AgentType,
|
||||
llm_config: SystemAgentLLMConfig | None = None,
|
||||
ai_language: str = "zh-CN",
|
||||
language: str = "zh-CN",
|
||||
) -> str:
|
||||
_ = agent_type, llm_config
|
||||
role_playing = get_worker_role_playing(ai_language)
|
||||
output_rules = get_worker_output_rules(ai_language)
|
||||
role_playing = get_worker_role_playing(language)
|
||||
output_rules = get_worker_output_rules(language)
|
||||
content = f"[role_playing]\n{role_playing}\n\n[output_json_rules]\n{output_rules}"
|
||||
return wrap_section("agent", content)
|
||||
|
||||
@@ -39,8 +39,8 @@ def _build_safety_section() -> str:
|
||||
)
|
||||
|
||||
|
||||
def _build_output_rules(*, ai_language: str) -> str:
|
||||
lang_label = _get_language_label(ai_language)
|
||||
def _build_output_rules(*, language: str) -> str:
|
||||
lang_label = _get_language_label(language)
|
||||
rules = [
|
||||
"[Language Requirement]",
|
||||
f"- You MUST respond in {lang_label}.",
|
||||
@@ -68,7 +68,7 @@ def _build_time_context(*, now_utc: datetime | None) -> str:
|
||||
def build_system_prompt(
|
||||
*,
|
||||
agent_type: AgentType,
|
||||
ai_language: str,
|
||||
language: str,
|
||||
llm_config: SystemAgentLLMConfig | None = None,
|
||||
tools: Sequence[Tool | dict[str, Any]] | None = None,
|
||||
now_utc: datetime | None = None,
|
||||
@@ -79,9 +79,9 @@ def build_system_prompt(
|
||||
build_agent_prompt(
|
||||
agent_type=agent_type,
|
||||
llm_config=llm_config,
|
||||
ai_language=ai_language,
|
||||
language=language,
|
||||
),
|
||||
build_tools_prompt(tools=tools) if tools else None,
|
||||
_build_output_rules(ai_language=ai_language),
|
||||
_build_output_rules(language=language),
|
||||
]
|
||||
return "\n\n".join(item for item in sections if item).strip()
|
||||
|
||||
@@ -101,14 +101,14 @@ answer: A complete reading covering overall judgment, current situation, final t
|
||||
sign_level: Must be exactly one of: 上上签 / 中上签 / 中下签 / 下下签. Always use the Chinese enum value regardless of language."""
|
||||
|
||||
|
||||
def get_worker_role_playing(ai_language: str) -> str:
|
||||
_ = ai_language
|
||||
def get_worker_role_playing(language: str) -> str:
|
||||
_ = language
|
||||
return _WORKER_ROLE_PLAYING
|
||||
|
||||
|
||||
def get_worker_output_rules(ai_language: str) -> str:
|
||||
if ai_language.startswith("en"):
|
||||
def get_worker_output_rules(language: str) -> str:
|
||||
if language.startswith("en"):
|
||||
return _WORKER_OUTPUT_RULES_EN
|
||||
if ai_language.startswith("zh-Hant") or ai_language.startswith("zh_Hant"):
|
||||
if language.startswith("zh-Hant") or language.startswith("zh_Hant"):
|
||||
return _WORKER_OUTPUT_RULES_ZH_HANT
|
||||
return _WORKER_OUTPUT_RULES_ZH_CN
|
||||
|
||||
@@ -265,15 +265,15 @@ class AgentScopeRunner:
|
||||
emit_text_events=True,
|
||||
emit_tool_events=False,
|
||||
)
|
||||
ai_language = "zh-CN"
|
||||
language = "zh-CN"
|
||||
if user_context.settings is not None:
|
||||
prefs = getattr(user_context.settings, "preferences", None)
|
||||
if prefs is not None:
|
||||
ai_language = getattr(prefs, "ai_language", "zh-CN") or "zh-CN"
|
||||
language = getattr(prefs, "language", "zh-CN") or "zh-CN"
|
||||
|
||||
system_prompt = build_system_prompt(
|
||||
agent_type=stage_config.agent_type,
|
||||
ai_language=ai_language,
|
||||
language=language,
|
||||
llm_config=stage_config.llm_config,
|
||||
tools=None,
|
||||
now_utc=datetime.now(timezone.utc),
|
||||
|
||||
@@ -11,12 +11,10 @@ _COUNTRY_PATTERN = re.compile(r"^[A-Z]{2}$")
|
||||
|
||||
|
||||
class PreferenceSettings(BaseModel):
|
||||
interface_language: str = "zh-CN"
|
||||
ai_language: str = "zh-CN"
|
||||
language: str = "zh-CN"
|
||||
timezone: str = "Asia/Shanghai"
|
||||
country: str = "US"
|
||||
|
||||
@field_validator("interface_language", "ai_language")
|
||||
@field_validator("language")
|
||||
@classmethod
|
||||
def validate_language(cls, value: str) -> str:
|
||||
if not _BCP47_PATTERN.fullmatch(value):
|
||||
@@ -32,14 +30,6 @@ class PreferenceSettings(BaseModel):
|
||||
raise ValueError("timezone must be a valid IANA timezone") from exc
|
||||
return value
|
||||
|
||||
@field_validator("country")
|
||||
@classmethod
|
||||
def validate_country(cls, value: str) -> str:
|
||||
normalized = value.upper()
|
||||
if not _COUNTRY_PATTERN.fullmatch(normalized):
|
||||
raise ValueError("country must be an ISO 3166-1 alpha-2 code")
|
||||
return normalized
|
||||
|
||||
|
||||
class NotificationSettings(BaseModel):
|
||||
allow_notifications: bool = True
|
||||
|
||||
@@ -5,10 +5,10 @@ from core.agentscope.prompts.system_prompt import build_system_prompt
|
||||
from schemas.agent.system_agent import AgentType, SystemAgentLLMConfig
|
||||
|
||||
|
||||
def test_system_prompt_enforces_ai_language_en() -> None:
|
||||
def test_system_prompt_enforces_language_en() -> None:
|
||||
prompt = build_system_prompt(
|
||||
agent_type=AgentType.WORKER,
|
||||
ai_language="en-US",
|
||||
language="en-US",
|
||||
llm_config=SystemAgentLLMConfig(),
|
||||
)
|
||||
|
||||
@@ -17,10 +17,10 @@ def test_system_prompt_enforces_ai_language_en() -> None:
|
||||
assert "<!-- OUTPUT_START -->" in prompt
|
||||
|
||||
|
||||
def test_system_prompt_enforces_ai_language_zh_cn() -> None:
|
||||
def test_system_prompt_enforces_language_zh_cn() -> None:
|
||||
prompt = build_system_prompt(
|
||||
agent_type=AgentType.WORKER,
|
||||
ai_language="zh-CN",
|
||||
language="zh-CN",
|
||||
llm_config=SystemAgentLLMConfig(),
|
||||
)
|
||||
|
||||
@@ -31,7 +31,7 @@ def test_system_prompt_enforces_ai_language_zh_cn() -> None:
|
||||
def test_system_prompt_safety_restricts_to_divination() -> None:
|
||||
prompt = build_system_prompt(
|
||||
agent_type=AgentType.WORKER,
|
||||
ai_language="zh-CN",
|
||||
language="zh-CN",
|
||||
llm_config=SystemAgentLLMConfig(),
|
||||
)
|
||||
|
||||
@@ -41,7 +41,7 @@ def test_system_prompt_safety_restricts_to_divination() -> None:
|
||||
def test_system_prompt_does_not_contain_env_section() -> None:
|
||||
prompt = build_system_prompt(
|
||||
agent_type=AgentType.WORKER,
|
||||
ai_language="zh-CN",
|
||||
language="zh-CN",
|
||||
llm_config=SystemAgentLLMConfig(),
|
||||
)
|
||||
|
||||
@@ -65,7 +65,7 @@ def test_agent_prompt_keeps_only_identity_and_domain_flow() -> None:
|
||||
def test_system_prompt_sections_are_not_duplicated() -> None:
|
||||
prompt = build_system_prompt(
|
||||
agent_type=AgentType.WORKER,
|
||||
ai_language="zh-CN",
|
||||
language="zh-CN",
|
||||
llm_config=SystemAgentLLMConfig(),
|
||||
)
|
||||
|
||||
|
||||
@@ -15,8 +15,7 @@ class TestParseProfileSettings:
|
||||
raw = {
|
||||
"version": 1,
|
||||
"preferences": {
|
||||
"interface_language": "en-US",
|
||||
"ai_language": "en-US",
|
||||
"language": "en-US",
|
||||
"timezone": "America/New_York",
|
||||
"country": "US",
|
||||
},
|
||||
@@ -31,8 +30,7 @@ class TestParseProfileSettings:
|
||||
assert isinstance(result, ProfileSettingsV1)
|
||||
assert result.version == 1
|
||||
assert isinstance(result.preferences, PreferenceSettings)
|
||||
assert result.preferences.interface_language == "en-US"
|
||||
assert result.preferences.ai_language == "en-US"
|
||||
assert result.preferences.language == "en-US"
|
||||
assert result.preferences.timezone == "America/New_York"
|
||||
assert result.preferences.country == "US"
|
||||
assert isinstance(result.notification, NotificationSettings)
|
||||
@@ -45,8 +43,7 @@ class TestParseProfileSettings:
|
||||
assert isinstance(result, ProfileSettingsV1)
|
||||
assert result.version == 1
|
||||
assert isinstance(result.preferences, PreferenceSettings)
|
||||
assert result.preferences.interface_language == "zh-CN"
|
||||
assert result.preferences.ai_language == "zh-CN"
|
||||
assert result.preferences.language == "zh-CN"
|
||||
assert result.preferences.timezone == "Asia/Shanghai"
|
||||
assert result.preferences.country == "US"
|
||||
assert isinstance(result.notification, NotificationSettings)
|
||||
@@ -56,13 +53,12 @@ class TestParseProfileSettings:
|
||||
def test_parse_profile_settings_with_partial_preferences(self) -> None:
|
||||
raw = {
|
||||
"preferences": {
|
||||
"interface_language": "en-US",
|
||||
"language": "en-US",
|
||||
},
|
||||
}
|
||||
result = parse_profile_settings(raw)
|
||||
|
||||
assert result.preferences.interface_language == "en-US"
|
||||
assert result.preferences.ai_language == "zh-CN"
|
||||
assert result.preferences.language == "en-US"
|
||||
assert result.preferences.timezone == "Asia/Shanghai"
|
||||
assert result.preferences.country == "US"
|
||||
|
||||
@@ -93,7 +89,7 @@ class TestParseProfileSettings:
|
||||
def test_parse_profile_settings_invalid_language_uses_default(self) -> None:
|
||||
raw = {
|
||||
"preferences": {
|
||||
"interface_language": "invalid-language",
|
||||
"language": "invalid-language",
|
||||
},
|
||||
}
|
||||
with pytest.raises(ValueError, match="language must be a valid BCP-47 tag"):
|
||||
@@ -120,8 +116,7 @@ class TestParseProfileSettings:
|
||||
def test_profile_settings_v1_model_dump(self) -> None:
|
||||
settings = ProfileSettingsV1(
|
||||
preferences=PreferenceSettings(
|
||||
interface_language="en-US",
|
||||
ai_language="en-US",
|
||||
language="en-US",
|
||||
timezone="UTC",
|
||||
country="US",
|
||||
),
|
||||
@@ -132,6 +127,6 @@ class TestParseProfileSettings:
|
||||
)
|
||||
dumped = settings.model_dump(mode="json")
|
||||
|
||||
assert dumped["preferences"]["interface_language"] == "en-US"
|
||||
assert dumped["preferences"]["language"] == "en-US"
|
||||
assert dumped["notification"]["allow_notifications"] is True
|
||||
assert dumped["notification"]["allow_vibration"] is False
|
||||
|
||||
Reference in New Issue
Block a user