新增16个AI技能:包含图像生成、视频剪辑、数据分析、智能查询等功能模块
This commit is contained in:
282
.opencode/skills/uni-agent/scripts/test_adapters.py
Normal file
282
.opencode/skills/uni-agent/scripts/test_adapters.py
Normal file
@@ -0,0 +1,282 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
UniAgent 适配器测试脚本
|
||||
测试所有协议适配器的基本功能
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from adapters import get_adapter, ADAPTERS, list_protocols
|
||||
|
||||
|
||||
class TestResult:
|
||||
def __init__(self, protocol: str):
|
||||
self.protocol = protocol
|
||||
self.passed = 0
|
||||
self.failed = 0
|
||||
self.skipped = 0
|
||||
self.errors = []
|
||||
|
||||
def pass_(self, msg: str):
|
||||
self.passed += 1
|
||||
print(f" ✅ {msg}")
|
||||
|
||||
def fail(self, msg: str, error: str = ""):
|
||||
self.failed += 1
|
||||
self.errors.append(f"{msg}: {error}")
|
||||
print(f" ❌ {msg}: {error[:100]}")
|
||||
|
||||
def skip(self, msg: str):
|
||||
self.skipped += 1
|
||||
print(f" ⏭️ {msg} (跳过)")
|
||||
|
||||
def summary(self) -> str:
|
||||
status = "✅" if self.failed == 0 else "❌"
|
||||
return f"{status} {self.protocol}: {self.passed} passed, {self.failed} failed, {self.skipped} skipped"
|
||||
|
||||
|
||||
async def test_anp() -> TestResult:
|
||||
"""测试 ANP 适配器"""
|
||||
result = TestResult("ANP")
|
||||
print("\n[ANP] 测试 Agent Network Protocol...\n")
|
||||
|
||||
try:
|
||||
adapter = get_adapter("anp")
|
||||
result.pass_("获取适配器")
|
||||
except Exception as e:
|
||||
result.fail("获取适配器", str(e))
|
||||
return result
|
||||
|
||||
agent_config = {
|
||||
"id": "amap",
|
||||
"protocol": "anp",
|
||||
"ad_url": "https://agent-connect.ai/mcp/agents/amap/ad.json"
|
||||
}
|
||||
|
||||
try:
|
||||
connection = await adapter.connect(agent_config)
|
||||
result.pass_(f"建立连接: {connection.endpoint[:50]}...")
|
||||
except Exception as e:
|
||||
result.fail("建立连接", str(e))
|
||||
return result
|
||||
|
||||
try:
|
||||
methods = await adapter.get_methods(connection)
|
||||
result.pass_(f"获取方法列表: {len(methods)} 个方法")
|
||||
except Exception as e:
|
||||
result.fail("获取方法列表", str(e))
|
||||
|
||||
try:
|
||||
res = await adapter.call(connection, "maps_weather", {"city": "北京"})
|
||||
if res.get("success") or res.get("result"):
|
||||
city = res.get("result", {}).get("city", "")
|
||||
result.pass_(f"调用 maps_weather: {city}")
|
||||
else:
|
||||
result.fail("调用 maps_weather", str(res))
|
||||
except Exception as e:
|
||||
result.fail("调用 maps_weather", str(e))
|
||||
|
||||
try:
|
||||
res = await adapter.call(connection, "maps_text_search", {"keywords": "咖啡厅", "city": "上海"})
|
||||
if res.get("success") or res.get("result"):
|
||||
pois = res.get("result", {}).get("pois", [])
|
||||
result.pass_(f"调用 maps_text_search: 找到 {len(pois)} 个结果")
|
||||
else:
|
||||
result.fail("调用 maps_text_search", str(res))
|
||||
except Exception as e:
|
||||
result.fail("调用 maps_text_search", str(e))
|
||||
|
||||
try:
|
||||
agents = await adapter.discover()
|
||||
result.pass_(f"发现 Agent: {len(agents)} 个")
|
||||
except Exception as e:
|
||||
result.fail("发现 Agent", str(e))
|
||||
|
||||
try:
|
||||
await adapter.close(connection)
|
||||
result.pass_("关闭连接")
|
||||
except Exception as e:
|
||||
result.fail("关闭连接", str(e))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def test_mcp() -> TestResult:
|
||||
"""测试 MCP 适配器"""
|
||||
result = TestResult("MCP")
|
||||
print("\n[MCP] 测试 Model Context Protocol...\n")
|
||||
|
||||
try:
|
||||
adapter = get_adapter("mcp")
|
||||
result.pass_("获取适配器")
|
||||
except Exception as e:
|
||||
result.fail("获取适配器", str(e))
|
||||
return result
|
||||
|
||||
result.skip("MCP 需要本地 npx 环境,跳过实际连接测试")
|
||||
result.skip("如需测试,请配置 config/agents.yaml 中的 MCP Server")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def test_a2a() -> TestResult:
|
||||
"""测试 A2A 适配器"""
|
||||
result = TestResult("A2A")
|
||||
print("\n[A2A] 测试 Agent-to-Agent Protocol...\n")
|
||||
|
||||
try:
|
||||
adapter = get_adapter("a2a")
|
||||
result.pass_("获取适配器")
|
||||
except Exception as e:
|
||||
result.fail("获取适配器", str(e))
|
||||
return result
|
||||
|
||||
result.skip("A2A 需要配置 Agent endpoint,跳过实际连接测试")
|
||||
result.skip("如需测试,请配置 config/agents.yaml 中的 A2A Agent")
|
||||
|
||||
try:
|
||||
agents = await adapter.discover()
|
||||
result.pass_(f"发现 Agent: {len(agents)} 个 (本地配置)")
|
||||
except Exception as e:
|
||||
result.fail("发现 Agent", str(e))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def test_aitp() -> TestResult:
|
||||
"""测试 AITP 适配器"""
|
||||
result = TestResult("AITP")
|
||||
print("\n[AITP] 测试 Agent Interaction & Transaction Protocol...\n")
|
||||
|
||||
try:
|
||||
adapter = get_adapter("aitp")
|
||||
result.pass_("获取适配器")
|
||||
except Exception as e:
|
||||
result.fail("获取适配器", str(e))
|
||||
return result
|
||||
|
||||
result.skip("AITP 需要配置 NEAR 钱包和 endpoint,跳过实际连接测试")
|
||||
result.skip("如需测试,请配置 config/agents.yaml 中的 AITP Agent")
|
||||
|
||||
try:
|
||||
agents = await adapter.discover()
|
||||
result.pass_(f"发现 Agent: {len(agents)} 个 (本地配置)")
|
||||
except Exception as e:
|
||||
result.fail("发现 Agent", str(e))
|
||||
|
||||
try:
|
||||
methods = [
|
||||
{"name": "message", "desc": "发送消息"},
|
||||
{"name": "payment", "desc": "发起支付"},
|
||||
{"name": "decision", "desc": "请求决策"},
|
||||
]
|
||||
result.pass_(f"支持方法: {', '.join([m['name'] for m in methods])}")
|
||||
except Exception as e:
|
||||
result.fail("检查方法", str(e))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def test_agent_protocol() -> TestResult:
|
||||
"""测试 Agent Protocol 适配器"""
|
||||
result = TestResult("Agent Protocol")
|
||||
print("\n[AP] 测试 Agent Protocol...\n")
|
||||
|
||||
try:
|
||||
adapter = get_adapter("agent_protocol")
|
||||
result.pass_("获取适配器 (agent_protocol)")
|
||||
except Exception as e:
|
||||
result.fail("获取适配器", str(e))
|
||||
return result
|
||||
|
||||
try:
|
||||
adapter2 = get_adapter("ap")
|
||||
result.pass_("获取适配器 (别名 ap)")
|
||||
except Exception as e:
|
||||
result.fail("获取适配器别名", str(e))
|
||||
|
||||
result.skip("Agent Protocol 需要运行中的 Agent 服务,跳过实际连接测试")
|
||||
result.skip("如需测试,请启动 AutoGPT 或其他兼容服务")
|
||||
|
||||
try:
|
||||
agents = await adapter.discover()
|
||||
result.pass_(f"发现 Agent: {len(agents)} 个 (本地配置)")
|
||||
except Exception as e:
|
||||
result.fail("发现 Agent", str(e))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def test_lmos() -> TestResult:
|
||||
"""测试 LMOS 适配器"""
|
||||
result = TestResult("LMOS")
|
||||
print("\n[LMOS] 测试 Language Model Operating System...\n")
|
||||
|
||||
try:
|
||||
adapter = get_adapter("lmos")
|
||||
result.pass_("获取适配器")
|
||||
except Exception as e:
|
||||
result.fail("获取适配器", str(e))
|
||||
return result
|
||||
|
||||
result.skip("LMOS 需要配置注册中心或 Agent endpoint,跳过实际连接测试")
|
||||
result.skip("如需测试,请配置 config/agents.yaml 中的 LMOS Agent")
|
||||
|
||||
try:
|
||||
agents = await adapter.discover()
|
||||
result.pass_(f"发现 Agent: {len(agents)} 个 (本地配置)")
|
||||
except Exception as e:
|
||||
result.fail("发现 Agent", str(e))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def main():
|
||||
print("=" * 60)
|
||||
print(" UniAgent 适配器测试")
|
||||
print("=" * 60)
|
||||
|
||||
print(f"\n支持的协议: {list_protocols()}\n")
|
||||
|
||||
results = []
|
||||
|
||||
results.append(await test_anp())
|
||||
results.append(await test_mcp())
|
||||
results.append(await test_a2a())
|
||||
results.append(await test_aitp())
|
||||
results.append(await test_agent_protocol())
|
||||
results.append(await test_lmos())
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print(" 测试汇总")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
total_passed = 0
|
||||
total_failed = 0
|
||||
total_skipped = 0
|
||||
|
||||
for r in results:
|
||||
print(r.summary())
|
||||
total_passed += r.passed
|
||||
total_failed += r.failed
|
||||
total_skipped += r.skipped
|
||||
|
||||
print(f"\n总计: {total_passed} passed, {total_failed} failed, {total_skipped} skipped")
|
||||
|
||||
if total_failed > 0:
|
||||
print("\n失败详情:")
|
||||
for r in results:
|
||||
for err in r.errors:
|
||||
print(f" - [{r.protocol}] {err}")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("\n🎉 所有测试通过!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
368
.opencode/skills/uni-agent/scripts/test_all.py
Normal file
368
.opencode/skills/uni-agent/scripts/test_all.py
Normal file
@@ -0,0 +1,368 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
UniAgent 完整测试脚本
|
||||
启动测试服务器,测试所有协议的真实交互
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import signal
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
from adapters import get_adapter
|
||||
|
||||
|
||||
SERVERS = {}
|
||||
|
||||
|
||||
def start_server(name: str, script: str, port: int) -> subprocess.Popen:
|
||||
"""启动测试服务器"""
|
||||
script_path = Path(__file__).parent.parent / "test_servers" / script
|
||||
proc = subprocess.Popen(
|
||||
[sys.executable, str(script_path)],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
time.sleep(0.5)
|
||||
if proc.poll() is not None:
|
||||
stderr = proc.stderr.read().decode()
|
||||
print(f" ❌ {name} 启动失败: {stderr}")
|
||||
return None
|
||||
print(f" ✅ {name} 启动成功 (port {port})")
|
||||
return proc
|
||||
|
||||
|
||||
def stop_servers():
|
||||
"""停止所有服务器"""
|
||||
for name, proc in SERVERS.items():
|
||||
if proc and proc.poll() is None:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=2)
|
||||
|
||||
|
||||
async def test_anp():
|
||||
"""测试 ANP 适配器"""
|
||||
print("\n" + "=" * 50)
|
||||
print("[ANP] Agent Network Protocol")
|
||||
print("=" * 50)
|
||||
|
||||
adapter = get_adapter("anp")
|
||||
config = {
|
||||
"id": "amap",
|
||||
"protocol": "anp",
|
||||
"ad_url": "https://agent-connect.ai/mcp/agents/amap/ad.json"
|
||||
}
|
||||
|
||||
try:
|
||||
conn = await adapter.connect(config)
|
||||
print(f"✅ 连接成功: {conn.endpoint[:50]}...")
|
||||
|
||||
result = await adapter.call(conn, "maps_weather", {"city": "北京"})
|
||||
city = result.get("result", {}).get("city", "")
|
||||
print(f"✅ maps_weather: {city}")
|
||||
|
||||
result = await adapter.call(conn, "maps_text_search", {"keywords": "咖啡厅", "city": "上海"})
|
||||
pois = result.get("result", {}).get("pois", [])
|
||||
print(f"✅ maps_text_search: 找到 {len(pois)} 个结果")
|
||||
|
||||
await adapter.close(conn)
|
||||
print(f"✅ 关闭连接")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"❌ 测试失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def test_a2a():
|
||||
"""测试 A2A 适配器"""
|
||||
print("\n" + "=" * 50)
|
||||
print("[A2A] Agent-to-Agent Protocol")
|
||||
print("=" * 50)
|
||||
|
||||
adapter = get_adapter("a2a")
|
||||
config = {
|
||||
"id": "test_agent",
|
||||
"protocol": "a2a",
|
||||
"endpoint": "http://localhost:8100"
|
||||
}
|
||||
|
||||
try:
|
||||
conn = await adapter.connect(config)
|
||||
print(f"✅ 连接成功")
|
||||
|
||||
methods = await adapter.get_methods(conn)
|
||||
print(f"✅ 获取方法: {len(methods)} 个 (包含 skills)")
|
||||
|
||||
result = await adapter.call(conn, "tasks/send", {
|
||||
"message": {
|
||||
"role": "user",
|
||||
"parts": [{"type": "text", "text": "Hello A2A!"}]
|
||||
}
|
||||
})
|
||||
if result.get("success"):
|
||||
task = result.get("result", {})
|
||||
history = task.get("history", [])
|
||||
if len(history) >= 2:
|
||||
response = history[-1].get("parts", [{}])[0].get("text", "")
|
||||
print(f"✅ tasks/send: {response}")
|
||||
else:
|
||||
print(f"✅ tasks/send: 任务已创建")
|
||||
else:
|
||||
print(f"❌ tasks/send 失败: {result}")
|
||||
return False
|
||||
|
||||
await adapter.close(conn)
|
||||
print(f"✅ 关闭连接")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"❌ 测试失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def test_aitp():
|
||||
"""测试 AITP 适配器"""
|
||||
print("\n" + "=" * 50)
|
||||
print("[AITP] Agent Interaction & Transaction Protocol")
|
||||
print("=" * 50)
|
||||
|
||||
adapter = get_adapter("aitp")
|
||||
config = {
|
||||
"id": "test_shop",
|
||||
"protocol": "aitp",
|
||||
"endpoint": "http://localhost:8101"
|
||||
}
|
||||
|
||||
try:
|
||||
conn = await adapter.connect(config)
|
||||
print(f"✅ 连接成功 (Thread: {conn.session[:8]}...)")
|
||||
|
||||
result = await adapter.call(conn, "message", {"content": "Hello AITP!"})
|
||||
if result.get("success"):
|
||||
response = result.get("result", {}).get("content", "")
|
||||
print(f"✅ message: {response}")
|
||||
else:
|
||||
print(f"❌ message 失败")
|
||||
return False
|
||||
|
||||
result = await adapter.call(conn, "payment", {
|
||||
"amount": 10,
|
||||
"currency": "NEAR",
|
||||
"recipient": "shop.near"
|
||||
})
|
||||
if result.get("success"):
|
||||
payment = result.get("result", {}).get("payment_response", {})
|
||||
status = payment.get("status", "")
|
||||
tx_id = payment.get("transaction_id", "")[:8]
|
||||
print(f"✅ payment: {status} (tx: {tx_id}...)")
|
||||
else:
|
||||
print(f"❌ payment 失败")
|
||||
return False
|
||||
|
||||
result = await adapter.call(conn, "decision", {
|
||||
"question": "选择颜色",
|
||||
"options": ["红色", "蓝色", "绿色"]
|
||||
})
|
||||
if result.get("success"):
|
||||
decision = result.get("result", {}).get("decision_response", {})
|
||||
selected = decision.get("selected", "")
|
||||
print(f"✅ decision: 选择了 {selected}")
|
||||
else:
|
||||
print(f"❌ decision 失败")
|
||||
return False
|
||||
|
||||
await adapter.close(conn)
|
||||
print(f"✅ 关闭连接")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"❌ 测试失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def test_agent_protocol():
|
||||
"""测试 Agent Protocol 适配器"""
|
||||
print("\n" + "=" * 50)
|
||||
print("[AP] Agent Protocol")
|
||||
print("=" * 50)
|
||||
|
||||
adapter = get_adapter("agent_protocol")
|
||||
config = {
|
||||
"id": "test_agent",
|
||||
"protocol": "agent_protocol",
|
||||
"endpoint": "http://localhost:8102"
|
||||
}
|
||||
|
||||
try:
|
||||
conn = await adapter.connect(config)
|
||||
print(f"✅ 连接成功")
|
||||
|
||||
result = await adapter.call(conn, "create_task", {"input": "Hello Agent Protocol!"})
|
||||
if result.get("success"):
|
||||
task_id = result.get("task_id", "")
|
||||
print(f"✅ create_task: {task_id[:8]}...")
|
||||
else:
|
||||
print(f"❌ create_task 失败")
|
||||
return False
|
||||
|
||||
result = await adapter.call(conn, "execute_step", {
|
||||
"task_id": task_id,
|
||||
"input": "Process this"
|
||||
})
|
||||
if result.get("success"):
|
||||
step = result.get("result", {})
|
||||
output = step.get("output", "")
|
||||
print(f"✅ execute_step: {output}")
|
||||
else:
|
||||
print(f"❌ execute_step 失败")
|
||||
return False
|
||||
|
||||
result = await adapter.call(conn, "get_task", {"task_id": task_id})
|
||||
if result.get("success"):
|
||||
task = result.get("result", {})
|
||||
status = task.get("status", "")
|
||||
print(f"✅ get_task: status={status}")
|
||||
else:
|
||||
print(f"❌ get_task 失败")
|
||||
return False
|
||||
|
||||
result = await adapter.call(conn, "get_artifacts", {"task_id": task_id})
|
||||
if result.get("success"):
|
||||
artifacts = result.get("result", {}).get("artifacts", [])
|
||||
print(f"✅ get_artifacts: {len(artifacts)} 个产物")
|
||||
else:
|
||||
print(f"❌ get_artifacts 失败")
|
||||
return False
|
||||
|
||||
await adapter.close(conn)
|
||||
print(f"✅ 关闭连接")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"❌ 测试失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def test_lmos():
|
||||
"""测试 LMOS 适配器"""
|
||||
print("\n" + "=" * 50)
|
||||
print("[LMOS] Language Model Operating System")
|
||||
print("=" * 50)
|
||||
|
||||
adapter = get_adapter("lmos")
|
||||
config = {
|
||||
"id": "calculator",
|
||||
"protocol": "lmos",
|
||||
"endpoint": "http://localhost:8103/agents/calculator"
|
||||
}
|
||||
|
||||
try:
|
||||
conn = await adapter.connect(config)
|
||||
print(f"✅ 连接成功")
|
||||
|
||||
result = await adapter.call(conn, "invoke", {
|
||||
"capability": "add",
|
||||
"input": {"a": 10, "b": 20}
|
||||
})
|
||||
if result.get("success"):
|
||||
output = result.get("result", {}).get("output", {})
|
||||
calc_result = output.get("result", "")
|
||||
print(f"✅ invoke add(10, 20): {calc_result}")
|
||||
else:
|
||||
print(f"❌ invoke add 失败")
|
||||
return False
|
||||
|
||||
result = await adapter.call(conn, "invoke", {
|
||||
"capability": "multiply",
|
||||
"input": {"a": 6, "b": 7}
|
||||
})
|
||||
if result.get("success"):
|
||||
output = result.get("result", {}).get("output", {})
|
||||
calc_result = output.get("result", "")
|
||||
print(f"✅ invoke multiply(6, 7): {calc_result}")
|
||||
else:
|
||||
print(f"❌ invoke multiply 失败")
|
||||
return False
|
||||
|
||||
greeter_config = {
|
||||
"id": "greeter",
|
||||
"protocol": "lmos",
|
||||
"endpoint": "http://localhost:8103/agents/greeter"
|
||||
}
|
||||
conn2 = await adapter.connect(greeter_config)
|
||||
result = await adapter.call(conn2, "invoke", {
|
||||
"capability": "greet",
|
||||
"input": {"name": "test_user"}
|
||||
})
|
||||
if result.get("success"):
|
||||
output = result.get("result", {}).get("output", {})
|
||||
greeting = output.get("greeting", "")
|
||||
print(f"✅ invoke greet: {greeting}")
|
||||
else:
|
||||
print(f"❌ invoke greet 失败")
|
||||
return False
|
||||
|
||||
await adapter.close(conn)
|
||||
await adapter.close(conn2)
|
||||
print(f"✅ 关闭连接")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"❌ 测试失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def main():
|
||||
print("=" * 60)
|
||||
print(" UniAgent 完整交互测试")
|
||||
print("=" * 60)
|
||||
|
||||
print("\n[1] 启动测试服务器...")
|
||||
SERVERS["A2A"] = start_server("A2A Server", "a2a_server.py", 8100)
|
||||
SERVERS["AITP"] = start_server("AITP Server", "aitp_server.py", 8101)
|
||||
SERVERS["AP"] = start_server("Agent Protocol Server", "agent_protocol_server.py", 8102)
|
||||
SERVERS["LMOS"] = start_server("LMOS Server", "lmos_server.py", 8103)
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
print("\n[2] 开始测试...")
|
||||
|
||||
results = {}
|
||||
|
||||
try:
|
||||
results["ANP"] = await test_anp()
|
||||
results["A2A"] = await test_a2a()
|
||||
results["AITP"] = await test_aitp()
|
||||
results["Agent Protocol"] = await test_agent_protocol()
|
||||
results["LMOS"] = await test_lmos()
|
||||
finally:
|
||||
print("\n[3] 停止测试服务器...")
|
||||
stop_servers()
|
||||
print(" ✅ 所有服务器已停止")
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print(" 测试汇总")
|
||||
print("=" * 60)
|
||||
|
||||
all_passed = True
|
||||
for name, passed in results.items():
|
||||
status = "✅" if passed else "❌"
|
||||
print(f" {status} {name}")
|
||||
if not passed:
|
||||
all_passed = False
|
||||
|
||||
print()
|
||||
if all_passed:
|
||||
print("🎉 所有协议测试通过!")
|
||||
else:
|
||||
print("⚠️ 部分测试失败")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
except KeyboardInterrupt:
|
||||
stop_servers()
|
||||
print("\n测试中断")
|
||||
257
.opencode/skills/uni-agent/scripts/uni_cli.py
Normal file
257
.opencode/skills/uni-agent/scripts/uni_cli.py
Normal file
@@ -0,0 +1,257 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
UniAgent CLI - 统一智能体协议调用工具
|
||||
|
||||
用法:
|
||||
# 调用 Agent
|
||||
python uni_cli.py call amap@anp maps_weather '{"city":"北京"}'
|
||||
python uni_cli.py call filesystem@mcp read_file '{"path":"/tmp/a.txt"}'
|
||||
|
||||
# 发现 Agent
|
||||
python uni_cli.py discover weather
|
||||
|
||||
# 列出已注册 Agent
|
||||
python uni_cli.py list
|
||||
|
||||
# 查看 Agent 方法
|
||||
python uni_cli.py methods amap@anp
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent))
|
||||
|
||||
import yaml
|
||||
from adapters import get_adapter, ADAPTERS
|
||||
|
||||
|
||||
CONFIG_DIR = Path(__file__).parent.parent / "config"
|
||||
|
||||
|
||||
def load_agents_config():
|
||||
"""加载 Agent 配置"""
|
||||
agents_file = CONFIG_DIR / "agents.yaml"
|
||||
if not agents_file.exists():
|
||||
return {"agents": []}
|
||||
|
||||
with open(agents_file) as f:
|
||||
return yaml.safe_load(f) or {"agents": []}
|
||||
|
||||
|
||||
def parse_agent_id(agent_id: str) -> tuple:
|
||||
"""解析 Agent ID,返回 (name, protocol)"""
|
||||
if "@" not in agent_id:
|
||||
return agent_id, "anp"
|
||||
|
||||
parts = agent_id.rsplit("@", 1)
|
||||
return parts[0], parts[1]
|
||||
|
||||
|
||||
def get_agent_config(agent_name: str, protocol: str) -> dict:
|
||||
"""获取 Agent 配置"""
|
||||
config = load_agents_config()
|
||||
|
||||
for agent in config.get("agents", []):
|
||||
if agent.get("id") == agent_name and agent.get("protocol") == protocol:
|
||||
return agent
|
||||
|
||||
raise ValueError(f"未找到 Agent: {agent_name}@{protocol}")
|
||||
|
||||
|
||||
async def call_agent(agent_id: str, method: str, params: dict):
|
||||
"""调用 Agent"""
|
||||
agent_name, protocol = parse_agent_id(agent_id)
|
||||
|
||||
print(f"协议: {protocol}")
|
||||
print(f"Agent: {agent_name}")
|
||||
print(f"方法: {method}")
|
||||
print(f"参数: {json.dumps(params, ensure_ascii=False)}")
|
||||
print()
|
||||
|
||||
agent_config = get_agent_config(agent_name, protocol)
|
||||
adapter = get_adapter(protocol)
|
||||
|
||||
connection = await adapter.connect(agent_config)
|
||||
|
||||
try:
|
||||
result = await adapter.call(connection, method, params)
|
||||
print("=== 结果 ===")
|
||||
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
finally:
|
||||
await adapter.close(connection)
|
||||
|
||||
|
||||
async def discover_agents(capability: str = ""):
|
||||
"""发现 Agent"""
|
||||
print(f"搜索能力: {capability or '全部'}\n")
|
||||
|
||||
all_agents = []
|
||||
|
||||
for protocol, adapter_class in ADAPTERS.items():
|
||||
adapter = adapter_class()
|
||||
agents = await adapter.discover(capability)
|
||||
all_agents.extend(agents)
|
||||
|
||||
if not all_agents:
|
||||
print("未找到匹配的 Agent")
|
||||
return
|
||||
|
||||
print(f"找到 {len(all_agents)} 个 Agent:\n")
|
||||
for agent in all_agents:
|
||||
print(f" {agent.id}")
|
||||
print(f" 名称: {agent.name}")
|
||||
print(f" 协议: {agent.protocol}")
|
||||
if agent.endpoint:
|
||||
print(f" 端点: {agent.endpoint[:60]}...")
|
||||
print()
|
||||
|
||||
|
||||
async def list_agents():
|
||||
"""列出所有已注册 Agent"""
|
||||
config = load_agents_config()
|
||||
agents = config.get("agents", [])
|
||||
|
||||
if not agents:
|
||||
print("暂无已注册的 Agent")
|
||||
print("请编辑 config/agents.yaml 添加 Agent")
|
||||
return
|
||||
|
||||
print(f"\n已注册的 Agent ({len(agents)} 个):\n")
|
||||
|
||||
by_protocol = {}
|
||||
for agent in agents:
|
||||
protocol = agent.get("protocol", "unknown")
|
||||
if protocol not in by_protocol:
|
||||
by_protocol[protocol] = []
|
||||
by_protocol[protocol].append(agent)
|
||||
|
||||
for protocol, protocol_agents in by_protocol.items():
|
||||
print(f"[{protocol.upper()}]")
|
||||
for agent in protocol_agents:
|
||||
agent_id = f"{agent['id']}@{protocol}"
|
||||
name = agent.get("name", agent["id"])
|
||||
print(f" {agent_id}: {name}")
|
||||
print()
|
||||
|
||||
|
||||
async def show_methods(agent_id: str):
|
||||
"""显示 Agent 支持的方法"""
|
||||
agent_name, protocol = parse_agent_id(agent_id)
|
||||
|
||||
print(f"获取 {agent_name}@{protocol} 的方法列表...\n")
|
||||
|
||||
agent_config = get_agent_config(agent_name, protocol)
|
||||
adapter = get_adapter(protocol)
|
||||
|
||||
connection = await adapter.connect(agent_config)
|
||||
|
||||
try:
|
||||
methods = await adapter.get_methods(connection)
|
||||
|
||||
if not methods:
|
||||
print("未获取到方法列表")
|
||||
return
|
||||
|
||||
print(f"可用方法 ({len(methods)} 个):\n")
|
||||
for m in methods[:30]:
|
||||
name = m.get("name", "unknown")
|
||||
desc = m.get("description", "")[:50]
|
||||
print(f" - {name}: {desc}")
|
||||
|
||||
if len(methods) > 30:
|
||||
print(f" ... 还有 {len(methods) - 30} 个方法")
|
||||
finally:
|
||||
await adapter.close(connection)
|
||||
|
||||
|
||||
def show_help():
|
||||
print("""
|
||||
UniAgent - 统一智能体协议调用工具
|
||||
|
||||
用法:
|
||||
python uni_cli.py <命令> [参数...]
|
||||
|
||||
命令:
|
||||
call <agent_id> <method> <params> 调用 Agent 方法
|
||||
discover [capability] 发现 Agent
|
||||
list 列出已注册 Agent
|
||||
methods <agent_id> 查看 Agent 方法
|
||||
|
||||
Agent ID 格式:
|
||||
<name>@<protocol>
|
||||
|
||||
示例:
|
||||
- amap@anp ANP 协议的高德地图
|
||||
- filesystem@mcp MCP 协议的文件系统
|
||||
|
||||
支持的协议:
|
||||
- anp ANP (Agent Network Protocol) - 去中心化 Agent 网络
|
||||
- mcp MCP (Model Context Protocol) - LLM 工具调用
|
||||
- a2a A2A (Agent-to-Agent) - Google Agent 协作
|
||||
- aitp AITP (Agent Interaction & Transaction) - 交互交易
|
||||
- agent_protocol Agent Protocol - REST API 标准 (别名: ap)
|
||||
- lmos LMOS (Language Model OS) - 企业级 Agent 平台
|
||||
|
||||
示例:
|
||||
# ANP - 查天气
|
||||
python uni_cli.py call amap@anp maps_weather '{"city":"北京"}'
|
||||
|
||||
# MCP - 读文件
|
||||
python uni_cli.py call filesystem@mcp read_file '{"path":"/tmp/a.txt"}'
|
||||
|
||||
# A2A - 发送任务
|
||||
python uni_cli.py call assistant@a2a tasks/send '{"message":{"content":"hello"}}'
|
||||
|
||||
# AITP - 对话
|
||||
python uni_cli.py call shop@aitp message '{"content":"我要买咖啡"}'
|
||||
|
||||
# Agent Protocol - 创建任务
|
||||
python uni_cli.py call autogpt@ap create_task '{"input":"写代码"}'
|
||||
|
||||
# 发现 Agent
|
||||
python uni_cli.py discover weather
|
||||
""")
|
||||
|
||||
|
||||
async def main():
|
||||
if len(sys.argv) < 2:
|
||||
show_help()
|
||||
return
|
||||
|
||||
cmd = sys.argv[1]
|
||||
|
||||
if cmd in ["help", "-h", "--help"]:
|
||||
show_help()
|
||||
|
||||
elif cmd == "call":
|
||||
if len(sys.argv) < 5:
|
||||
print("用法: python uni_cli.py call <agent_id> <method> '<params_json>'")
|
||||
return
|
||||
agent_id = sys.argv[2]
|
||||
method = sys.argv[3]
|
||||
params = json.loads(sys.argv[4])
|
||||
await call_agent(agent_id, method, params)
|
||||
|
||||
elif cmd == "discover":
|
||||
capability = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
await discover_agents(capability)
|
||||
|
||||
elif cmd == "list":
|
||||
await list_agents()
|
||||
|
||||
elif cmd == "methods":
|
||||
if len(sys.argv) < 3:
|
||||
print("用法: python uni_cli.py methods <agent_id>")
|
||||
return
|
||||
await show_methods(sys.argv[2])
|
||||
|
||||
else:
|
||||
print(f"未知命令: {cmd}")
|
||||
show_help()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user