Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
8835c67
Merge main branch into opencode/curious-garden
yhjun1026 Mar 26, 2026
ceaa42a
feat: default init agent optimze
yhjun1026 Mar 28, 2026
8b49df7
feat: default init agent optimze
yhjun1026 Mar 28, 2026
0179d2b
feat: default init agent optimze
yhjun1026 Mar 28, 2026
a19e877
feat: default init agent optimze
yhjun1026 Mar 28, 2026
9b1f7a8
feat: 优化文件上传组件,支持多文件上传和图片预览
yhjun1026 Mar 29, 2026
b859d91
feat: 上传失败时保留文件卡片并支持重试
yhjun1026 Mar 29, 2026
83a5e77
fix: 修复图片预览URL读取错误
yhjun1026 Mar 29, 2026
00306b1
fix: 修复LLM错误未正确推送到前端的问题
yhjun1026 Mar 29, 2026
862be64
feat: default init agent optimze
yhjun1026 Mar 29, 2026
ebcd7e9
feat: default init agent optimze
yhjun1026 Mar 29, 2026
f84a2b8
feat: default init agent optimze
yhjun1026 Mar 29, 2026
5b23cae
feat: default init agent optimze
yhjun1026 Mar 29, 2026
31ed8fc
feat: default init agent optimze
yhjun1026 Mar 29, 2026
3eb05bc
feat: default init agent optimze
yhjun1026 Mar 29, 2026
4d581e8
feat: default init agent optimze
yhjun1026 Mar 29, 2026
325a67e
feat: default init agent optimze
yhjun1026 Mar 30, 2026
2191cbb
feat: default init agent optimze
yhjun1026 Mar 30, 2026
5d8739e
feat: default init agent optimze
yhjun1026 Mar 30, 2026
2ea18e0
feat: default init agent optimze
yhjun1026 Mar 30, 2026
8d47118
feat: default init agent optimze
yhjun1026 Mar 30, 2026
8ed5aad
feat: default init agent optimze
yhjun1026 Mar 30, 2026
2aa067a
Merge main branch into feature/optimze-032801
yhjun1026 Mar 30, 2026
2fcf469
feat: default init agent optimze
yhjun1026 Mar 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
204 changes: 204 additions & 0 deletions AGENT_ALIAS_IMPLEMENTATION_COMPLETE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
# Agent别名系统 - 实现完成总结

## ✅ 验证结果

所有核心功能验证通过:

```
✅ ProfileConfig.aliases字段存在
✅ 别名注册和解析功能正常
✅ AgentManager集成代码正确
✅ 别名系统架构完整
```

## 核心实现

### 1. ProfileConfig添加aliases字段

**文件**: `packages/derisk-core/src/derisk/agent/core/profile/base.py`

```python
class ProfileConfig(BaseModel):
# ... 其他字段 ...

# Agent别名配置:用于历史数据兼容性
aliases: List[str] | ConfigInfo | None = DynConfig(
None,
is_list=True,
description="Agent别名列表,用于历史数据兼容。例如:['ReActMasterV2', 'ReActMaster']",
)
```

### 2. Agent类中定义别名

**文件**: `packages/derisk-core/src/derisk/agent/expand/react_master_agent/react_master_agent.py`

```python
class ReActMasterAgent(ConversableAgent):
profile: ProfileConfig = Field(
default_factory=lambda: ProfileConfig(
name="BAIZE",
role="BAIZE",
goal="白泽Agent...",
# 别名配置:用于历史数据兼容
aliases=["ReActMasterV2", "ReActMaster"],
)
)
```

### 3. AgentManager自动注册别名

**文件**: `packages/derisk-core/src/derisk/agent/core/agent_manage.py`

```python
def register_agent(self, cls: Type[ConversableAgent], ...) -> str:
inst = cls()
profile = inst.role
# ... 注册逻辑 ...

# 自动注册Agent别名
aliases = []
if hasattr(inst, 'profile'):
profile_obj = inst.profile
if hasattr(profile_obj, 'aliases') and profile_obj.aliases:
aliases = profile_obj.aliases

if aliases and isinstance(aliases, list):
AgentAliasManager.register_agent_aliases(profile, aliases)
logger.info(f"[AgentManager] Auto-registered aliases for {profile}: {aliases}")

return profile
```

### 4. 所有检索方法支持别名解析

```python
def get_by_name(self, name: str) -> Type[ConversableAgent]:
resolved_name = AgentAliasManager.resolve_alias(name)
if resolved_name != name:
logger.info(f"[AgentManager.get_by_name] Resolved alias: {name} -> {resolved_name}")
return self._agents[resolved_name][0]
```

## 测试验证

### 单元测试结果

```bash
.venv/bin/python test_agent_alias_complete.py
```

**输出**:
```
✅ ProfileConfig.aliases字段存在
✅ ProfileConfig创建成功
name: BAIZE
aliases: ['ReActMasterV2', 'ReActMaster']

✅ 别名注册成功
所有别名: {'ReActMasterV2': 'BAIZE', 'ReActMaster': 'BAIZE'}

✅ 别名解析测试:
✓ ReActMasterV2 -> BAIZE
✓ ReActMaster -> BAIZE
✓ BAIZE -> BAIZE
✓ Unknown -> Unknown
```

## 工作流程

### 启动阶段

```
Application启动
AgentManager.after_start()
扫描所有Agent (scan_agents)
对每个Agent执行register_agent()
创建Agent实例
读取profile.aliases
AgentAliasManager.register_agent_aliases()
别名注册完成
```

### 运行阶段

```
用户使用"ReActMasterV2"
AgentManager.get_by_name("ReActMasterV2")
AgentAliasManager.resolve_alias("ReActMasterV2")
返回"BAIZE"
从_agents字典获取BAIZE Agent
成功返回Agent
```

## 使用方式

### 为其他Agent添加别名

```python
class YourAgent(ConversableAgent):
profile: ProfileConfig = Field(
default_factory=lambda: ProfileConfig(
name="YourAgent",
role="YourAgent",
aliases=["OldName1", "OldName2"], # 添加历史别名
)
)
```

就这么简单!无需其他代码。

## 优势

| 特性 | 说明 |
|------|------|
| ✅ 配置内聚 | 别名和Agent定义在一起,更加清晰 |
| ✅ 自动注册 | AgentManager自动收集,无需手动维护 |
| ✅ 零侵入 | 对现有代码无影响,完全向后兼容 |
| ✅ 日志追踪 | 详细的注册和解析日志,便于调试 |
| ✅ 类型安全 | 使用Pydantic验证,类型安全 |

## 文件清单

| 文件 | 修改内容 | 状态 |
|------|----------|------|
| `profile/base.py` | 添加aliases字段 | ✅ |
| `react_master_agent.py` | 配置aliases | ✅ |
| `agent_alias.py` | AgentAliasManager | ✅ |
| `agent_manage.py` | 自动注册别名 | ✅ |
| `agent_chat.py` | 使用resolve_agent_name() | ✅ |
| `agent_info.py` | AgentRegistry支持 | ✅ |

## 验证脚本

- `test_agent_alias_complete.py` - 完整功能验证
- `final_verification.py` - 最终验证脚本
- `test_simplified_alias.py` - 简化版测试

## 总结

✅ **Agent别名系统实现完成并验证通过!**

**核心改进**:
- 别名定义在Agent类中,配置跟着类走
- AgentManager自动收集注册,无需手动维护
- 所有检索点支持别名解析,完全向后兼容

**使用效果**:
- 历史配置中的`"agent": "ReActMasterV2"`自动解析为BAIZE
- 历史数据中的`gpts_name="ReActMasterV2"`自动匹配到BAIZE
- 无需修改任何历史配置或数据

感谢你的建议,这个方案比最初的设计更加简洁优雅!🎉
2 changes: 1 addition & 1 deletion assets/schema/derisk.sql
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use derisk;
-- MySQL DDL Script for Derisk
-- Version: 0.3.0
-- Generated from SQLAlchemy ORM Models
-- Generated: 2026-03-29 23:19:58
-- Generated: 2026-03-30 19:52:29
-- ============================================================

SET NAMES utf8mb4;
Expand Down
9 changes: 5 additions & 4 deletions configs/derisk-proxy-aliyun.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,11 @@ agent_name="derisk"
repo_url=""
work_dir="/home/ubuntu"
skill_dir="/mnt/derisk/skills"
oss_ak="${env:OSS_ACCESS_KEY_ID:-xxx}"
oss_sk="${env:OSS_ACCESS_KEY_SECRET:-xxx}"
oss_endpoint="https://oss-cn-beijing.aliyuncs.com"
oss_bucket_name="openderisk"
# OSS configuration deprecated - using unified FileStorageClient from serves.backends
# oss_ak="${env:OSS_ACCESS_KEY_ID:-xxx}"
# oss_sk="${env:OSS_ACCESS_KEY_SECRET:-xxx}"
# oss_endpoint="https://oss-cn-beijing.aliyuncs.com"
# oss_bucket_name="openderisk"

# Disable default skill sync from GitHub (network can be slow)
[derisk.serve.skill]
Expand Down
9 changes: 5 additions & 4 deletions configs/derisk-proxy-openai.toml
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ agent_name="derisk"
repo_url=""
work_dir="/home/ubuntu"
skill_dir="/mnt/derisk/skills"
oss_ak="${env:OSS_ACCESS_KEY_ID:-xxx}"
oss_sk="${env:OSS_ACCESS_KEY_SECRET:-xxx}"
oss_endpoint="https://oss-cn-beijing.aliyuncs.com"
oss_bucket_name="openderisk"
# OSS configuration deprecated - using unified FileStorageClient from serves.backends
# oss_ak="${env:OSS_ACCESS_KEY_ID:-xxx}"
# oss_sk="${env:OSS_ACCESS_KEY_SECRET:-xxx}"
# oss_endpoint="https://oss-cn-beijing.aliyuncs.com"
# oss_bucket_name="openderisk"
128 changes: 128 additions & 0 deletions debug_alias_registration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""
调试Agent别名注册流程
"""

print("=" * 70)
print("调试Agent别名注册")
print("=" * 70)


# 模拟简化版的ProfileConfig
class SimpleProfileConfig:
def __init__(self, name, aliases=None):
self.name = name
self.aliases = aliases or []


# 模拟AgentAliasManager
class DebugAgentAliasManager:
_alias_map = {}
_reverse_map = {}

@classmethod
def register_agent_aliases(cls, current_name, aliases):
print(f" [DEBUG] 尝试注册别名: current_name={current_name}, aliases={aliases}")
if not aliases:
print(f" [DEBUG] aliases为空,跳过注册")
return

for alias in aliases:
if alias and alias != current_name:
cls._alias_map[alias] = current_name
print(f" [DEBUG] ✓ 成功注册: {alias} -> {current_name}")

if current_name not in cls._reverse_map:
cls._reverse_map[current_name] = []

for alias in aliases:
if (
alias
and alias != current_name
and alias not in cls._reverse_map[current_name]
):
cls._reverse_map[current_name].append(alias)


# 模拟Agent类
class MockBAIZEAgent:
def __init__(self):
self.role = "BAIZE"
# 关键:这里模拟ProfileConfig
self.profile = SimpleProfileConfig(
name="BAIZE", aliases=["ReActMasterV2", "ReActMaster"]
)

def __class__(self):
return type("BAIZE", (), {})


print("\n1. 模拟register_agent流程:")
print("-" * 70)

agent_cls = MockBAIZEAgent
print(f"注册Agent类: {agent_cls.__name__}")

# 模拟AgentManager.register_agent的逻辑
inst = agent_cls()
profile = inst.role
print(f" profile名称: {profile}")

# 关键步骤:检查是否有profile.aliases
if hasattr(inst, "profile"):
print(f" ✓ 有profile属性")
if hasattr(inst.profile, "aliases"):
aliases = inst.profile.aliases
print(f" ✓ profile.aliases存在: {aliases}")
DebugAgentAliasManager.register_agent_aliases(profile, aliases)
else:
print(f" ✗ profile.aliases不存在")
else:
print(f" ✗ 没有profile属性")

print("\n2. 检查别名注册结果:")
print("-" * 70)
print(f"所有别名映射: {DebugAgentAliasManager.get_all_aliases()}")
print(f"ReActMasterV2解析: {DebugAgentAliasManager.resolve_alias('ReActMasterV2')}")

print("\n" + "=" * 70)

# 现在检查真实的ProfileConfig定义
print("\n3. 检查真实ProfileConfig定义:")
print("-" * 70)

try:
import sys

sys.path.insert(0, "/Users/tuyang/GitHub/OpenDerisk/packages/derisk-core/src")

# 只导入ProfileConfig,不导入整个agent模块
import importlib.util

spec = importlib.util.spec_from_file_location(
"profile_base",
"/Users/tuyang/GitHub/OpenDerisk/packages/derisk-core/src/derisk/agent/core/profile/base.py",
)
profile_module = importlib.util.module_from_spec(spec)

# 先导入必要的依赖
print("尝试导入ProfileConfig...")
from derisk._private.pydantic import BaseModel, Field

print(" ✓ pydantic导入成功")

# 手动定义简化版ProfileConfig
class TestProfileConfig(BaseModel):
name: str = Field(default="TestAgent")
aliases: list = Field(default_factory=list)

test_profile = TestProfileConfig(
name="BAIZE", aliases=["ReActMasterV2", "ReActMaster"]
)
print(f" ✓ ProfileConfig创建成功")
print(f" - name: {test_profile.name}")
print(f" - aliases: {test_profile.aliases}")

except Exception as e:
print(f" ✗ 导入失败: {e}")

print("\n" + "=" * 70)
25 changes: 0 additions & 25 deletions derisk/context/__init__.py

This file was deleted.

Loading
Loading