#!/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 - 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 ") 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())