Skip to content

Conversation

@hazeone
Copy link
Contributor

@hazeone hazeone commented Sep 4, 2025

ValueCell i18n(国际化)系统详细说明文档

1. 系统概述

ValueCell的i18n系统是一个完整的国际化解决方案,支持多语言、时区、货币格式、日期时间格式等功能。系统采用模块化设计,支持Agent间的上下文管理。

1.1 支持的语言

  • en-US: English (United States)
  • en-GB: English (United Kingdom)
  • zh-Hans: 简体中文 (Simplified Chinese)
  • zh-Hant: 繁體中文 (Traditional Chinese)

1.2 核心特性

  • 🌍 多语言翻译支持
  • ⏰ 时区自动转换
  • 💰 货币格式化
  • 📅 日期时间本地化
  • 🔢 数字格式化
  • 🤖 Agent上下文管理
  • 🌐 HTTP API接口
  • 📱 浏览器语言检测

2. 项目结构

python/valuecell/
├── core/
│   └── constants.py          # 核心常量定义
├── config/
│   ├── settings.py          # 应用程序设置
│   └── i18n.py             # i18n配置类
├── services/
│   ├── i18n_service.py     # 主要i18n服务
│   └── agent_context.py    # Agent上下文管理
├── utils/
│   └── i18n_utils.py       # i18n工具函数
├── api/
│   ├── app.py              # 主API应用
│   ├── i18n_api.py         # i18n API路由
│   └── schemas.py          # API数据模型
├── examples/
│   ├── i18n_example.py     # 基础使用示例
│   └── agent_i18n_example.py # Agent使用示例
├── i18n.py                 # 统一入口模块
└── locales/                # 翻译文件目录
    ├── en-US.json
    ├── en-GB.json
    ├── zh-Hans.json
    └── zh-Hant.json

3. 核心组件详解

3.1 常量配置 (core/constants.py)

定义了系统的基础配置:

# 支持的语言列表
SUPPORTED_LANGUAGES = [
    ("en-US", "English (United States)"),
    ("en-GB", "English (United Kingdom)"),
    ("zh-Hans", "简体中文"),
    ("zh-Hant", "繁體中文"),
]

# 语言与时区映射
LANGUAGE_TIMEZONE_MAPPING = {
    "en-US": "America/New_York",
    "en-GB": "Europe/London", 
    "zh-Hans": "Asia/Shanghai",
    "zh-Hant": "Asia/Hong_Kong",
}

# 日期时间格式
DATE_FORMATS = {
    "en-US": "%m/%d/%Y",
    "en-GB": "%d/%m/%Y",
    "zh-Hans": "%Y年%m月%d日",
    "zh-Hant": "%Y年%m月%d日",
}

# 货币符号
CURRENCY_SYMBOLS = {
    "en-US": "$",
    "en-GB": "£",
    "zh-Hans": "¥", 
    "zh-Hant": "HK$",
}

3.2 配置类 (config/i18n.py)

I18nConfig类管理i18n配置:

class I18nConfig:
    def __init__(self, language=None, timezone=None):
        # 自动从环境变量获取配置
        self._language = self._validate_language(language or self._get_env_language())
        self._timezone = self._validate_timezone(timezone or self._get_env_timezone())
    
    # 核心方法
    def format_datetime(self, dt, format_type="datetime"):
        """格式化日期时间"""
    
    def format_number(self, number, decimal_places=2):
        """格式化数字"""
    
    def format_currency(self, amount, decimal_places=2):
        """格式化货币"""

3.3 翻译管理 (services/i18n_service.py)

TranslationManager类

负责翻译文件的加载和管理:

class TranslationManager:
    def __init__(self, locale_dir=None):
        self._locale_dir = locale_dir or get_settings().LOCALE_DIR
        self._translations = {}
        self._load_all_translations()
    
    def get_translation(self, language, key, **kwargs):
        """获取翻译文本,支持点号分隔的嵌套键"""
        # 支持 "messages.welcome" 这样的嵌套键
        # 支持字符串格式化变量

I18nService类

主要的i18n服务类:

class I18nService:
    def translate(self, key, language=None, **kwargs):
        """翻译指定键"""
    
    def t(self, key, **kwargs):
        """翻译的简短别名"""
    
    def set_language(self, language):
        """设置当前语言"""
    
    def format_datetime(self, dt, format_type="datetime"):
        """格式化日期时间"""

3.4 Agent上下文管理 (services/agent_context.py)

为Agent提供用户特定的i18n上下文:

class AgentContextManager:
    def __init__(self):
        self._local = threading.local()  # 线程本地存储
    
    def set_user_context(self, user_id, session_id=None):
        """设置用户上下文"""
        
    @contextmanager
    def user_context(self, user_id, session_id=None):
        """临时用户上下文管理器"""
        # 保存当前上下文
        # 设置新上下文
        try:
            yield self
        finally:
            # 恢复原上下文

3.5 工具函数 (utils/i18n_utils.py)

提供各种实用功能:

  • detect_browser_language(): 从HTTP头检测语言偏好
  • format_file_size(): 文件大小格式化
  • format_duration(): 时长格式化
  • pluralize(): 复数形式处理
  • validate_translation_file(): 翻译文件验证
  • get_missing_translations(): 查找缺失翻译

4. 翻译文件结构

翻译文件采用JSON格式,支持嵌套结构:

{
    "common": {
        "yes": "",
        "no": "",
        "loading": "加载中..."
    },
    "messages": {
        "welcome": "欢迎使用ValueCell",
        "data_saved": "数据已成功保存"
    },
    "app": {
        "version": "版本 {version}",
        "copyright": "© {year} ValueCell. 保留所有权利。"
    }
}

4.1 支持的功能

  • 嵌套键: 使用点号分隔,如 "messages.welcome"
  • 变量替换: 使用花括号,如 "版本 {version}"
  • 回退机制: 找不到翻译时回退到默认语言

5. API接口

5.1 主要端点

端点 方法 功能
/i18n/config GET 获取当前i18n配置
/i18n/languages GET 获取支持的语言列表
/i18n/language POST 设置当前语言
/i18n/timezones GET 获取可用时区
/i18n/timezone POST 设置时区
/i18n/translate POST 翻译指定键
/i18n/format/datetime POST 格式化日期时间
/i18n/format/number POST 格式化数字
/i18n/format/currency POST 格式化货币
/i18n/user/settings GET/POST 用户i18n设置
/i18n/agent/context GET Agent i18n上下文

5.2 请求头支持

  • X-User-ID: 用户标识
  • X-Session-ID: 会话标识
  • Accept-Language: 浏览器语言偏好

5.3 API使用示例

# 设置语言
POST /i18n/language
{
    "language": "zh-Hans"
}

# 翻译文本
POST /i18n/translate  
{
    "key": "messages.welcome",
    "language": "zh-Hans",
    "variables": {"name": "张三"}
}

# 格式化货币
POST /i18n/format/currency
{
    "amount": 1234.56,
    "decimal_places": 2
}

6. 使用方法

6.1 基础使用

from valuecell.i18n import get_i18n_service, t

# 获取服务实例
i18n = get_i18n_service()

# 基础翻译
welcome_text = t("messages.welcome")
print(welcome_text)  # 输出: "欢迎使用ValueCell"

# 带变量的翻译
version_text = t("app.version", version="1.0.0")
print(version_text)  # 输出: "版本 1.0.0"

# 设置语言
i18n.set_language("en-US")
welcome_text = t("messages.welcome") 
print(welcome_text)  # 输出: "Welcome to ValueCell"

6.2 日期时间格式化

from datetime import datetime

now = datetime.now()

# 格式化为不同类型
date_str = i18n.format_datetime(now, "date")      # "2024/01/15"
time_str = i18n.format_datetime(now, "time")      # "14:30"
datetime_str = i18n.format_datetime(now)          # "2024/01/15 14:30"

6.3 数字和货币格式化

# 数字格式化
number = 1234567.89
formatted = i18n.format_number(number, 2)
print(formatted)  # "1,234,567.89"

# 货币格式化  
amount = 9876.54
formatted = i18n.format_currency(amount)
print(formatted)  # "¥9,876.54"

6.4 Agent使用

from valuecell.services.agent_context import get_agent_context, user_context

agent_ctx = get_agent_context()

# 方式1: 设置用户上下文
agent_ctx.set_user_context("user123")
welcome = agent_ctx.translate("messages.welcome")

# 方式2: 使用上下文管理器
with user_context("user123"):
    welcome = t("messages.welcome")
    formatted_time = agent_ctx.format_datetime(datetime.now())

6.5 批量处理多用户

def process_users(user_requests):
    results = {}
    agent_ctx = get_agent_context()
    
    for user_id, request in user_requests.items():
        with agent_ctx.user_context(user_id):
            # 在此块内的所有操作都使用该用户的i18n设置
            welcome = t("messages.welcome")
            success = t("messages.data_saved") 
            time = agent_ctx.format_datetime(datetime.now())
            
            results[user_id] = {
                "welcome": welcome,
                "status": success,
                "time": time,
                "language": agent_ctx.get_current_language()
            }
    
    return results

7. 环境变量配置

# 应用配置
APP_NAME=ValueCell
APP_VERSION=0.1.0
APP_ENVIRONMENT=development

# i18n配置
LANG=zh-Hans                    # 默认语言
TIMEZONE=Asia/Shanghai          # 默认时区

# API配置
API_HOST=localhost
API_PORT=8000
API_DEBUG=true
API_ENABLED=true
API_I18N_ENABLED=true

8. 扩展和定制

8.1 添加新语言

  1. core/constants.py 中添加语言定义
  2. locales/ 目录创建对应的JSON文件
  3. 添加时区映射和格式配置

8.2 自定义翻译加载器

class CustomTranslationManager(TranslationManager):
    def _load_translation(self, language):
        # 自定义加载逻辑
        # 例如从数据库、API等加载翻译
        pass

8.3 添加新的格式化器

def format_percentage(value, language=None):
    """格式化百分比"""
    i18n = get_i18n_service()
    formatted_number = i18n.format_number(value * 100, 1)
    return f"{formatted_number}%"

9. 最佳实践

9.1 翻译键命名规范

  • 使用点号分隔的层级结构
  • 使用描述性名称而非简写
  • 按功能模块组织
✅ 好的命名:
- "messages.welcome"
- "forms.validation.required_field"  
- "navigation.dashboard"

❌ 避免的命名:
- "msg1"
- "err"
- "btn_ok"

9.2 Agent开发建议

  • 总是使用用户上下文进行翻译
  • 使用上下文管理器处理临时切换
  • 避免在循环中频繁切换上下文

9.3 性能优化

  • 翻译文件在启动时一次性加载
  • 使用线程本地存储避免上下文冲突
  • 合理使用缓存机制

10. 故障排除

10.1 常见问题

Q: 翻译不显示,返回键名
A: 检查翻译文件是否存在,键名是否正确

Q: 时区转换不正确
A: 确认pytz库已安装,时区名称正确

Q: Agent上下文混乱
A: 确保使用上下文管理器或正确清理上下文

10.2 调试方法

# 检查当前配置
i18n = get_i18n_service()
print(i18n.to_dict())

# 检查可用翻译键
keys = i18n.get_translation_keys("zh-Hans")
print(keys)

# 验证翻译文件
from valuecell.utils.i18n_utils import validate_translation_file
result = validate_translation_file(Path("locales/zh-Hans.json"))
print(result)

11. 开发和测试

11.1 运行示例

# 基础i18n示例
cd /path/to/valuecell/python
python -m valuecell.examples.i18n_example

# Agent i18n示例  
python -m valuecell.examples.agent_i18n_example

11.2 启动API服务

# 使用uvicorn启动
cd /path/to/valuecell/python
uvicorn valuecell.api.app:app --reload --host 0.0.0.0 --port 8000

11.3 API测试

# 获取配置
curl http://localhost:8000/i18n/config

# 设置语言
curl -X POST http://localhost:8000/i18n/language \
  -H "Content-Type: application/json" \
  -d '{"language": "zh-Hans"}'

# 翻译文本
curl -X POST http://localhost:8000/i18n/translate \
  -H "Content-Type: application/json" \
  -d '{"key": "messages.welcome"}'

这个i18n系统为ValueCell提供了完整的国际化支持,不仅支持基本的多语言功能,还特别针对Agent间通信和用户上下文管理进行了优化,是一个生产级的解决方案。

@hazeone hazeone requested a review from vcfgv September 4, 2025 06:46
@hazeone hazeone added the enhancement New feature or request label Sep 4, 2025
"fastapi>=0.104.0",
"pydantic>=2.0.0",
"uvicorn>=0.24.0",
"ruff>=0.12.11",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

already defined in optional dependencies below

@hazeone hazeone merged commit 965bc9a into main Sep 4, 2025
1 check passed
@hazeone hazeone deleted the feat/add_tradingagents branch September 4, 2025 07:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants