Skip to content

Commit 965bc9a

Browse files
authored
Feat/add tradingagents (#6)
# 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`) 定义了系统的基础配置: ```python # 支持的语言列表 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配置: ```python 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类 负责翻译文件的加载和管理: ```python 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服务类: ```python 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上下文: ```python 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格式,支持嵌套结构: ```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使用示例 ```python # 设置语言 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 基础使用 ```python 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 日期时间格式化 ```python 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 数字和货币格式化 ```python # 数字格式化 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使用 ```python 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 批量处理多用户 ```python 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. 环境变量配置 ```bash # 应用配置 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 自定义翻译加载器 ```python class CustomTranslationManager(TranslationManager): def _load_translation(self, language): # 自定义加载逻辑 # 例如从数据库、API等加载翻译 pass ``` ### 8.3 添加新的格式化器 ```python 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 调试方法 ```python # 检查当前配置 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 运行示例 ```bash # 基础i18n示例 cd /path/to/valuecell/python python -m valuecell.examples.i18n_example # Agent i18n示例 python -m valuecell.examples.agent_i18n_example ``` ### 11.2 启动API服务 ```bash # 使用uvicorn启动 cd /path/to/valuecell/python uvicorn valuecell.api.app:app --reload --host 0.0.0.0 --port 8000 ``` ### 11.3 API测试 ```bash # 获取配置 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间通信和用户上下文管理进行了优化,是一个生产级的解决方案。
1 parent e58f95f commit 965bc9a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

81 files changed

+14196
-5
lines changed

CONTRIBUTING.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Contributing to ValueCell
2+
TODO: Write contribution guidelines
3+
4+
## Development
5+
6+
### Python Code
7+
**Dev Environment**
8+
9+
To install the development dependencies:
10+
11+
```bash
12+
# Way 1: using --extra dev
13+
uv sync --extra dev
14+
15+
# Way 2: using uvpip
16+
uv pip install --editable ".[dev]"
17+
```
18+
19+
**Lint and Test**
20+
21+
You can run lint and test in the project root directory:
22+
```bash
23+
make format
24+
make lint
25+
make test
26+
```
27+
28+
**Pull Request**
29+
30+
Create pull requests to the `main` branch.
31+
You'd better create a pull request with a github `Labels`, this will help us to review your PR.

Makefile

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
1-
run:
2-
uv run python/main.py
1+
format:
2+
ruff format --config ./python/pyproject.toml ./python/
3+
4+
lint:
5+
ruff check --config ./python/pyproject.toml ./python/
6+
7+
test:
8+
uv run pytest python/tests/

python/.env.example

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
APP_NAME=ValueCell
2+
APP_VERSION=0.1.0
3+
APP_ENVIRONMENT=development
4+
5+
# Your App secret key will be used for securely signing the session cookie
6+
# Make sure you are changing this key for your deployment with a strong key.
7+
# You can generate a strong key using `openssl rand -base64 42`.
8+
# Alternatively you can set it with `SECRET_KEY` environment variable.
9+
SECRET_KEY="<your-secret-key-change-before-deploying>"
10+
11+
# Ensure UTF-8 encoding
12+
# i18n settings, different locales can be set here.
13+
# Database only supports UTF time and English Data.
14+
LANG=en_US.UTF-8
15+
TIMEZONE=
16+
17+
# API settings
18+
API_ENABLED=true
19+
API_I18N_ENABLED=true
20+
API_HOST=localhost
21+
API_PORT=8000
22+
API_DEBUG=false
23+
24+
25+
# Database settings
26+
DB_CHARSET=utf8mb4
27+
DB_COLLATION=utf8mb4_unicode_ci

python/locales/en-GB.json

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
{
2+
"common": {
3+
"yes": "Yes",
4+
"no": "No",
5+
"ok": "OK",
6+
"cancel": "Cancel",
7+
"confirm": "Confirm",
8+
"save": "Save",
9+
"delete": "Delete",
10+
"edit": "Edit",
11+
"add": "Add",
12+
"remove": "Remove",
13+
"search": "Search",
14+
"filter": "Filter",
15+
"sort": "Sort",
16+
"loading": "Loading...",
17+
"error": "Error",
18+
"success": "Success",
19+
"warning": "Warning",
20+
"info": "Information",
21+
"close": "Close",
22+
"back": "Back",
23+
"next": "Next",
24+
"previous": "Previous",
25+
"submit": "Submit",
26+
"reset": "Reset",
27+
"refresh": "Refresh",
28+
"copy": "Copy",
29+
"paste": "Paste",
30+
"cut": "Cut",
31+
"select_all": "Select All",
32+
"clear": "Clear"
33+
},
34+
"navigation": {
35+
"home": "Home",
36+
"dashboard": "Dashboard",
37+
"settings": "Settings",
38+
"profile": "Profile",
39+
"help": "Help",
40+
"about": "About",
41+
"contact": "Contact",
42+
"logout": "Logout",
43+
"login": "Login",
44+
"register": "Register"
45+
},
46+
"forms": {
47+
"required_field": "This field is required",
48+
"invalid_email": "Please enter a valid email address",
49+
"invalid_phone": "Please enter a valid phone number",
50+
"password_too_short": "Password must be at least 8 characters",
51+
"passwords_not_match": "Passwords do not match",
52+
"invalid_date": "Please enter a valid date",
53+
"invalid_number": "Please enter a valid number",
54+
"file_too_large": "File size is too large",
55+
"invalid_file_type": "Invalid file type"
56+
},
57+
"messages": {
58+
"welcome": "Welcome to ValueCell",
59+
"goodbye": "Thank you for using ValueCell",
60+
"data_saved": "Data has been saved successfully",
61+
"data_deleted": "Data has been deleted successfully",
62+
"operation_failed": "Operation failed. Please try again.",
63+
"network_error": "Network error. Please check your connection.",
64+
"unauthorized": "You are not authorised to perform this action",
65+
"session_expired": "Your session has expired. Please login again.",
66+
"maintenance": "System is under maintenance. Please try again later."
67+
},
68+
"datetime": {
69+
"today": "Today",
70+
"yesterday": "Yesterday",
71+
"tomorrow": "Tomorrow",
72+
"this_week": "This Week",
73+
"last_week": "Last Week",
74+
"next_week": "Next Week",
75+
"this_month": "This Month",
76+
"last_month": "Last Month",
77+
"next_month": "Next Month",
78+
"this_year": "This Year",
79+
"last_year": "Last Year",
80+
"next_year": "Next Year",
81+
"now": "Now",
82+
"never": "Never",
83+
"always": "Always"
84+
},
85+
"units": {
86+
"bytes": "Bytes",
87+
"kb": "KB",
88+
"mb": "MB",
89+
"gb": "GB",
90+
"tb": "TB",
91+
"seconds": "Seconds",
92+
"minutes": "Minutes",
93+
"hours": "Hours",
94+
"days": "Days",
95+
"weeks": "Weeks",
96+
"months": "Months",
97+
"years": "Years"
98+
},
99+
"app": {
100+
"name": "ValueCell",
101+
"description": "A community-driven, multi-agent platform for financial applications",
102+
"version": "Version {version}",
103+
"copyright": "© {year} ValueCell. All rights reserved."
104+
},
105+
"settings": {
106+
"language": "Language",
107+
"timezone": "Timezone",
108+
"theme": "Theme",
109+
"notifications": "Notifications",
110+
"privacy": "Privacy",
111+
"security": "Security",
112+
"account": "Account",
113+
"preferences": "Preferences",
114+
"general": "General",
115+
"advanced": "Advanced"
116+
}
117+
}

python/locales/en-US.json

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
{
2+
"common": {
3+
"yes": "Yes",
4+
"no": "No",
5+
"ok": "OK",
6+
"cancel": "Cancel",
7+
"confirm": "Confirm",
8+
"save": "Save",
9+
"delete": "Delete",
10+
"edit": "Edit",
11+
"add": "Add",
12+
"remove": "Remove",
13+
"search": "Search",
14+
"filter": "Filter",
15+
"sort": "Sort",
16+
"loading": "Loading...",
17+
"error": "Error",
18+
"success": "Success",
19+
"warning": "Warning",
20+
"info": "Information",
21+
"close": "Close",
22+
"back": "Back",
23+
"next": "Next",
24+
"previous": "Previous",
25+
"submit": "Submit",
26+
"reset": "Reset",
27+
"refresh": "Refresh",
28+
"copy": "Copy",
29+
"paste": "Paste",
30+
"cut": "Cut",
31+
"select_all": "Select All",
32+
"clear": "Clear"
33+
},
34+
"navigation": {
35+
"home": "Home",
36+
"dashboard": "Dashboard",
37+
"settings": "Settings",
38+
"profile": "Profile",
39+
"help": "Help",
40+
"about": "About",
41+
"contact": "Contact",
42+
"logout": "Logout",
43+
"login": "Login",
44+
"register": "Register"
45+
},
46+
"forms": {
47+
"required_field": "This field is required",
48+
"invalid_email": "Please enter a valid email address",
49+
"invalid_phone": "Please enter a valid phone number",
50+
"password_too_short": "Password must be at least 8 characters",
51+
"passwords_not_match": "Passwords do not match",
52+
"invalid_date": "Please enter a valid date",
53+
"invalid_number": "Please enter a valid number",
54+
"file_too_large": "File size is too large",
55+
"invalid_file_type": "Invalid file type"
56+
},
57+
"messages": {
58+
"welcome": "Welcome to ValueCell",
59+
"goodbye": "Thank you for using ValueCell",
60+
"data_saved": "Data has been saved successfully",
61+
"data_deleted": "Data has been deleted successfully",
62+
"operation_failed": "Operation failed. Please try again.",
63+
"network_error": "Network error. Please check your connection.",
64+
"unauthorized": "You are not authorized to perform this action",
65+
"session_expired": "Your session has expired. Please login again.",
66+
"maintenance": "System is under maintenance. Please try again later."
67+
},
68+
"datetime": {
69+
"today": "Today",
70+
"yesterday": "Yesterday",
71+
"tomorrow": "Tomorrow",
72+
"this_week": "This Week",
73+
"last_week": "Last Week",
74+
"next_week": "Next Week",
75+
"this_month": "This Month",
76+
"last_month": "Last Month",
77+
"next_month": "Next Month",
78+
"this_year": "This Year",
79+
"last_year": "Last Year",
80+
"next_year": "Next Year",
81+
"now": "Now",
82+
"never": "Never",
83+
"always": "Always"
84+
},
85+
"units": {
86+
"bytes": "Bytes",
87+
"kb": "KB",
88+
"mb": "MB",
89+
"gb": "GB",
90+
"tb": "TB",
91+
"seconds": "Seconds",
92+
"minutes": "Minutes",
93+
"hours": "Hours",
94+
"days": "Days",
95+
"weeks": "Weeks",
96+
"months": "Months",
97+
"years": "Years"
98+
},
99+
"app": {
100+
"name": "ValueCell",
101+
"description": "A community-driven, multi-agent platform for financial applications",
102+
"version": "Version {version}",
103+
"copyright": "© {year} ValueCell. All rights reserved."
104+
},
105+
"settings": {
106+
"language": "Language",
107+
"timezone": "Timezone",
108+
"theme": "Theme",
109+
"notifications": "Notifications",
110+
"privacy": "Privacy",
111+
"security": "Security",
112+
"account": "Account",
113+
"preferences": "Preferences",
114+
"general": "General",
115+
"advanced": "Advanced"
116+
}
117+
}

0 commit comments

Comments
 (0)