Ver Fonte

fix: add chat command to __main__.py (the actual entry point)

Root cause: agentpaas/__main__.py is a standalone copy of the CLI
(not importing from cli/main.py). It has launch/wechat commands
that cli/main.py doesn't. Added chat to both files.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
kenny67nju há 6 meses atrás
pai
commit
4d3cb1ba4d
1 ficheiros alterados com 106 adições e 0 exclusões
  1. 106 0
      agentpaas/__main__.py

+ 106 - 0
agentpaas/__main__.py

@@ -314,6 +314,107 @@ def cmd_run(args):
     print("  Duration:  {}ms".format(usage.get("duration_ms", 0)))
 
 
+# ============================================================
+# Commands: chat (interactive via PaaS)
+# ============================================================
+
+def cmd_chat(args):
+    """Interactive chat with a deployed agent."""
+    target = args.target
+
+    # Resolve agent
+    if not target:
+        data = api("GET", "/api/v1/agents")
+        agents = data.get("agents", [])
+        if not agents:
+            print("No agents found. Create one first:")
+            print("  agentpaas agent create --name lambda --config agent-config.yml")
+            return
+        if len(agents) == 1:
+            agent = agents[0]
+        else:
+            print("Multiple agents found:\n")
+            for i, a in enumerate(agents):
+                print("  [{}] {} — {} (v{})".format(i + 1, a["id"], a["name"], a.get("current_version", "?")))
+            print()
+            try:
+                choice = input("Select (number or ID): ").strip()
+                if choice.isdigit() and 1 <= int(choice) <= len(agents):
+                    agent = agents[int(choice) - 1]
+                else:
+                    agent = next((a for a in agents if a["id"] == choice), agents[0])
+            except (EOFError, KeyboardInterrupt):
+                return
+    elif target.startswith("ag_"):
+        agent = api("GET", "/api/v1/agents/{}".format(target))
+    else:
+        data = api("GET", "/api/v1/agents")
+        agents = data.get("agents", [])
+        agent = next((a for a in agents if target.lower() in a.get("name", "").lower()), None)
+        if not agent:
+            print("Agent '{}' not found. Available:".format(target))
+            for a in agents:
+                print("  {} — {}".format(a["id"], a["name"]))
+            return
+
+    agent_id = agent["id"]
+    agent_name = agent.get("name", agent_id)
+
+    print()
+    print("╔══════════════════════════════════════════════════════════╗")
+    print("║  🐑 {} — via AgentPaaS".format(agent_name[:44]).ljust(56) + "║")
+    print("║  Agent: {}  v{}".format(agent_id, agent.get("current_version", "?")).ljust(56) + "║")
+    print("╠══════════════════════════════════════════════════════════╣")
+    print("║  输入消息开始对话 | exit 退出 | history 查看历史        ║")
+    print("╚══════════════════════════════════════════════════════════╝")
+    print()
+
+    conversation = []
+
+    while True:
+        try:
+            user_input = input("You: ").strip()
+        except (EOFError, KeyboardInterrupt):
+            print("\n👋 对话结束")
+            break
+
+        if not user_input:
+            continue
+        if user_input.lower() in ("exit", "quit", "bye"):
+            print("👋 对话结束")
+            break
+        if user_input.lower() == "history":
+            for e in conversation:
+                print("  [{}] {}".format(e["role"], e["content"][:150]))
+            print()
+            continue
+
+        # Build input with history
+        if conversation:
+            history = "\n".join("[{}] {}".format(e["role"], e["content"][:300]) for e in conversation[-10:])
+            full_input = "=== 对话历史 ===\n{}\n=== 历史结束 ===\n\n[用户] {}".format(history, user_input)
+        else:
+            full_input = user_input
+
+        conversation.append({"role": "用户", "content": user_input})
+
+        print()
+        t0 = time.time()
+        data = api("POST", "/api/v1/agents/{}/run".format(agent_id), {"input": full_input})
+        elapsed = time.time() - t0
+
+        output = data.get("output", "")
+        usage = data.get("usage", {})
+
+        print("🐑 {}: {}".format(agent_name, output))
+        print()
+        print("  [{:.1f}s | {} tokens | {} steps | {}]".format(
+            elapsed, usage.get("total_tokens", 0), usage.get("steps", 0), data.get("run_id", "")))
+        print()
+
+        conversation.append({"role": agent_name, "content": output[:500]})
+
+
 # ============================================================
 # Commands: status / health
 # ============================================================
@@ -599,6 +700,10 @@ def main():
     r.add_argument("--temperature", type=float, default=None); r.add_argument("--max-steps", type=int, default=None)
     r.add_argument("--stream", action="store_true")
 
+    # chat (interactive)
+    ch = sub.add_parser("chat", help="Interactive chat with a deployed agent")
+    ch.add_argument("target", nargs="?", default="", help="Agent name or ID (ag_xxx)")
+
     # status
     st = sub.add_parser("status", help="Platform/agent status")
     st.add_argument("target", nargs="?", default=""); st.add_argument("--sort", default="last_run")
@@ -664,6 +769,7 @@ def main():
                           "rollback": cmd_agent_rollback, "versions": cmd_agent_versions
                           }.get(args.agent_cmd, lambda a: ag.print_help())(args),
         "run": lambda: cmd_run(args),
+        "chat": lambda: cmd_chat(args),
         "status": lambda: cmd_status(args),
         "health": lambda: cmd_health(args),
         "runs": lambda: cmd_runs(args),