cli.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. #!/usr/bin/env python3
  2. """
  3. Gateway CLI - 命令行工具
  4. 可以直接在终端运行的 A2A IM 工具。
  5. 使用示例:
  6. # 发送消息
  7. gateway-cli send --to agent-001 --message "Hello"
  8. # 查询在线 Agent
  9. gateway-cli list
  10. # 查询 Agent 状态
  11. gateway-cli status agent-001
  12. """
  13. import asyncio
  14. import json
  15. import sys
  16. from typing import Optional
  17. import click
  18. from gateway.client.python import tools
  19. @click.group()
  20. @click.option('--gateway-url', default='http://localhost:8001',
  21. envvar='GATEWAY_URL',
  22. help='Gateway 地址 (默认: http://localhost:8001)')
  23. @click.pass_context
  24. def cli(ctx, gateway_url):
  25. """Gateway CLI - A2A IM 命令行工具"""
  26. ctx.ensure_object(dict)
  27. ctx.obj['gateway_url'] = gateway_url
  28. @cli.command()
  29. @click.option('--from', 'from_agent', required=True, help='发送方 Agent ID')
  30. @click.option('--to', 'to_agent', required=True, help='接收方 Agent ID')
  31. @click.option('--message', '-m', required=True, help='消息内容')
  32. @click.option('--conversation-id', '-c', help='对话 ID (可选)')
  33. @click.pass_context
  34. def send(ctx, from_agent, to_agent, message, conversation_id):
  35. """发送消息到其他 Agent"""
  36. async def _send():
  37. result = await tools.send_message(
  38. gateway_url=ctx.obj['gateway_url'],
  39. from_agent_id=from_agent,
  40. to_agent_id=to_agent,
  41. message=message,
  42. conversation_id=conversation_id
  43. )
  44. click.echo(json.dumps(result, indent=2, ensure_ascii=False))
  45. asyncio.run(_send())
  46. @cli.command()
  47. @click.option('--type', 'agent_type', help='过滤 Agent 类型')
  48. @click.pass_context
  49. def list(ctx, agent_type):
  50. """查询在线 Agent 列表"""
  51. async def _list():
  52. agents = await tools.list_online_agents(
  53. gateway_url=ctx.obj['gateway_url'],
  54. agent_type=agent_type
  55. )
  56. if not agents:
  57. click.echo("没有找到在线 Agent")
  58. return
  59. click.echo(f"找到 {len(agents)} 个在线 Agent:\n")
  60. for agent in agents:
  61. click.echo(f"🟢 {agent['agent_name']} ({agent['agent_id']})")
  62. if agent.get('capabilities'):
  63. click.echo(f" 能力: {', '.join(agent['capabilities'])}")
  64. if agent.get('description'):
  65. click.echo(f" 描述: {agent['description']}")
  66. click.echo()
  67. asyncio.run(_list())
  68. @cli.command()
  69. @click.argument('agent_id')
  70. @click.pass_context
  71. def status(ctx, agent_id):
  72. """查询 Agent 在线状态"""
  73. async def _status():
  74. result = await tools.get_agent_status(
  75. gateway_url=ctx.obj['gateway_url'],
  76. agent_id=agent_id
  77. )
  78. status = result.get('status', 'unknown')
  79. icon = '🟢' if status == 'online' else '⚪'
  80. click.echo(f"{icon} {agent_id}")
  81. click.echo(f"状态: {status}")
  82. if result.get('last_seen'):
  83. click.echo(f"最后在线: {result['last_seen']}")
  84. asyncio.run(_status())
  85. @cli.command()
  86. @click.option('--id', 'agent_id', required=True, help='Agent ID')
  87. @click.option('--name', 'agent_name', required=True, help='Agent 名称')
  88. @click.option('--type', 'agent_type', help='Agent 类型')
  89. @click.option('--capabilities', '-c', multiple=True, help='Agent 能力 (可多次指定)')
  90. @click.option('--description', '-d', help='Agent 描述')
  91. @click.pass_context
  92. def register(ctx, agent_id, agent_name, agent_type, capabilities, description):
  93. """注册 Agent 到 Gateway (保持连接)"""
  94. async def _register():
  95. click.echo(f"正在注册 Agent: {agent_id}...")
  96. client = await tools.register_agent(
  97. gateway_url=ctx.obj['gateway_url'],
  98. agent_id=agent_id,
  99. agent_name=agent_name,
  100. agent_type=agent_type,
  101. capabilities=list(capabilities) if capabilities else [],
  102. description=description
  103. )
  104. click.echo(f"✅ Agent 已注册: {agent_id}")
  105. click.echo("按 Ctrl+C 断开连接")
  106. try:
  107. # 保持连接
  108. while True:
  109. await asyncio.sleep(1)
  110. except KeyboardInterrupt:
  111. click.echo("\n正在断开连接...")
  112. await client.disconnect()
  113. click.echo("已断开连接")
  114. asyncio.run(_register())
  115. if __name__ == '__main__':
  116. cli()