Files
cp1-agents/docs/source-material/agent-shapes/subagent-pattern/tests/test_chatbot.py
Jonathan Boniface 416c66ced4
All checks were successful
check agents / check (push) Successful in 10s
Add CP1 Discovery agents in both patterns
ALZ-F01 Discovery as a sub-agent orchestrator (sub-agents/) and as eight
individual declarative agents (individual-agents/), with their KAB workflow
exports. Shared check, render and import scripts, the alz-discovery-sample
MCP server, the crucible-kab-dev deploy profile, deployment docs, platform
issue reports and the source material. Agent steps time out at 20 minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:25:57 +00:00

253 lines
9.4 KiB
Python

#!/usr/bin/env python3
"""
Interactive chatbot test for this agent, over the A2A protocol.
This script allows you to test the agent like a chatbot with real-time conversation.
"""
import asyncio
import logging
import sys
from pathlib import Path
# Add the current directory to Python path to import the a2a_client
sys.path.insert(0, str(Path(__file__).parent))
from a2a_client import AgentA2AClient
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class ChatbotTester:
"""Interactive chatbot tester. The agent names itself via its card."""
def __init__(self, agent_url: str = "http://localhost:8080"):
"""Initialize the chatbot tester."""
self.agent_url = agent_url
self.client = AgentA2AClient(agent_url)
self.conversation_history = []
async def initialize(self):
"""Initialize the A2A client and perform health check."""
print("🤖 Connecting...")
try:
# Initialize the client
await self.client.initialize()
# Get agent info
agent_info = await self.client.get_agent_info()
print(f"✅ Connected to agent: {agent_info['name']}")
print(f"📝 Description: {agent_info['description']}")
# Perform health check
health = await self.client.health_check()
if health['status'] == 'healthy':
print("💚 Agent is healthy and ready!")
else:
print(f"⚠️ Agent health check: {health['status']}")
if 'error' in health:
print(f" Error: {health['error']}")
return True
except Exception as e:
print(f"❌ Failed to initialize: {str(e)}")
print(f" Make sure your agent is running at {self.agent_url}")
return False
async def send_message(self, message: str, use_streaming: bool = False):
"""Send a message to the agent and get response."""
try:
context = {
"conversation_turn": len(self.conversation_history) + 1,
"instructions": "Please provide a helpful and conversational response."
}
if use_streaming:
print("🔄 Sending message (streaming)...")
response_parts = []
async for chunk in self.client.send_streaming_message(message, context):
if chunk.get('has_content') and chunk.get('content'):
response_parts.append(chunk['content'])
# Print streaming content in real-time
print(chunk['content'], end='', flush=True)
print() # New line after streaming
response_text = ''.join(response_parts)
else:
print("🔄 Sending message...")
result = await self.client.send_message(message, context)
response_text = result['response_data'].get('message_text', 'No response text found')
# Store in conversation history
self.conversation_history.append({
"user": message,
"agent": response_text,
"timestamp": asyncio.get_event_loop().time()
})
return response_text
except Exception as e:
error_msg = f"Error sending message: {str(e)}"
print(f"❌ {error_msg}")
return error_msg
def print_conversation_history(self):
"""Print the conversation history."""
if not self.conversation_history:
print("📝 No conversation history yet.")
return
print("\n📜 Conversation History:")
print("=" * 50)
for i, turn in enumerate(self.conversation_history, 1):
print(f"\n[Turn {i}]")
print(f"👤 You: {turn['user']}")
print(f"🤖 Agent: {turn['agent'][:200]}{'...' if len(turn['agent']) > 200 else ''}")
def print_help(self):
"""Print available commands."""
print("\n📚 Available commands:")
print(" • Type any message to chat with the agent")
print(" • /stream <message> - Send message with streaming response")
print(" • /history - Show conversation history")
print(" • /info - Show agent information")
print(" • /health - Check agent health")
print(" • /clear - Clear conversation history")
print(" • /help - Show this help")
print(" • /quit or /exit - Exit the chatbot")
async def handle_command(self, command: str, args: str = "") -> bool:
"""Handle special commands. Returns True if should continue, False to exit."""
command = command.lower()
if command in ['/quit', '/exit']:
return False
elif command == '/help':
self.print_help()
elif command == '/history':
self.print_conversation_history()
elif command == '/clear':
self.conversation_history = []
print("🗑️ Conversation history cleared.")
elif command == '/info':
try:
agent_info = await self.client.get_agent_info()
print("\n🤖 Agent Information:")
print(f" Name: {agent_info['name']}")
print(f" Description: {agent_info['description']}")
print(f" Version: {agent_info.get('version', 'unknown')}")
print(f" URL: {agent_info['url']}")
if agent_info.get('skills'):
print(f" Skills: {len(agent_info['skills'])} available")
except Exception as e:
print(f"❌ Error getting agent info: {str(e)}")
elif command == '/health':
try:
health = await self.client.health_check()
print(f"\n💚 Health Status: {health['status']}")
if health.get('response_time_ms'):
print(f" Response Time: {health['response_time_ms']:.2f}ms")
if health.get('error'):
print(f" Error: {health['error']}")
except Exception as e:
print(f"❌ Error checking health: {str(e)}")
elif command == '/stream':
if args.strip():
response = await self.send_message(args.strip(), use_streaming=True)
print(f"\n🤖 Agent response: {response[:100]}{'...' if len(response) > 100 else ''}")
else:
print("❌ Usage: /stream <your message>")
else:
print(f"❓ Unknown command: {command}")
print(" Type /help for available commands")
return True
async def run_interactive_chat(self):
"""Run the interactive chat session."""
print("\n" + "=" * 60)
print("🤖 Interactive Chatbot Test")
print("=" * 60)
print("💡 Tip: Type /help for commands or just start chatting!")
print(" Press Ctrl+C to exit anytime")
try:
while True:
print("\n" + "-" * 40)
user_input = input("👤 You: ").strip()
if not user_input:
continue
# Handle commands
if user_input.startswith('/'):
parts = user_input.split(' ', 1)
command = parts[0]
args = parts[1] if len(parts) > 1 else ""
should_continue = await self.handle_command(command, args)
if not should_continue:
break
# Regular chat message
else:
response = await self.send_message(user_input)
print(f"\n🤖 Agent: {response}")
except KeyboardInterrupt:
print("\n\n👋 Goodbye! Thanks for chatting!")
except Exception as e:
print(f"\n❌ Unexpected error: {str(e)}")
async def main():
"""Main function to run the chatbot tester."""
import argparse
parser = argparse.ArgumentParser(description='Interactive A2A chatbot tester for this agent')
# 8080 matches the port the runtime image listens on, so this works
# out of the box when the agent runs locally. Running in a container with a
# published port (podman run -p 10014:8080) means passing --url explicitly —
# point it at the *host* port, not the container's.
parser.add_argument('--url', default='http://localhost:8080',
help='Agent base URL, host-side (default: http://localhost:8080)')
parser.add_argument('--test-message',
help='Send a single test message instead of interactive mode')
parser.add_argument('--streaming', action='store_true',
help='Use streaming mode for test message')
args = parser.parse_args()
# Create and initialize the chatbot tester
tester = ChatbotTester(args.url)
if not await tester.initialize():
sys.exit(1)
# Single message test mode
if args.test_message:
print(f"\n🧪 Test Message: {args.test_message}")
response = await tester.send_message(args.test_message, args.streaming)
print(f"\n🤖 Agent Response:\n{response}")
return
# Interactive chat mode
await tester.run_interactive_chat()
if __name__ == "__main__":
asyncio.run(main())