| 
 | 1 | +"""  | 
 | 2 | +Enhanced response callbacks for employee onboarding agent system.  | 
 | 3 | +Provides detailed monitoring and response handling for different agent types.  | 
 | 4 | +"""  | 
 | 5 | + | 
 | 6 | +import sys  | 
 | 7 | +from semantic_kernel.contents import ChatMessageContent, StreamingChatMessageContent  | 
 | 8 | + | 
 | 9 | +def enhanced_agent_response_callback(message: ChatMessageContent) -> None:  | 
 | 10 | +    """Enhanced callback to monitor agent responses with detailed information."""  | 
 | 11 | +      | 
 | 12 | +    # Get basic message information  | 
 | 13 | +    message_type = type(message).__name__  | 
 | 14 | +    role = getattr(message, 'role', 'unknown')  | 
 | 15 | +    metadata = getattr(message, 'metadata', {})  | 
 | 16 | +    agent_name = message.name or "Unknown Agent"  | 
 | 17 | +      | 
 | 18 | +    # Handle different agent types with specific formatting  | 
 | 19 | +    if "Coder" in agent_name:  | 
 | 20 | +        _handle_coder_response(message, agent_name, message_type)  | 
 | 21 | +    elif "Reasoning" in agent_name:  | 
 | 22 | +        _handle_reasoning_response(message, agent_name, message_type, role)  | 
 | 23 | +    elif "Research" in agent_name or "Enhanced" in agent_name:  | 
 | 24 | +        _handle_research_response(message, agent_name, message_type, role, metadata)  | 
 | 25 | +    else:  | 
 | 26 | +        _handle_default_response(message, agent_name, message_type, role)  | 
 | 27 | + | 
 | 28 | +def _handle_coder_response(message, agent_name, message_type):  | 
 | 29 | +    """Handle coder agent responses with code execution details."""  | 
 | 30 | +    if hasattr(message, 'items') and message.items and len(message.items) > 0:  | 
 | 31 | +        for item in message.items:  | 
 | 32 | +            if hasattr(item, 'text') and item.text:  | 
 | 33 | +                print(item.text, end='', flush=True)  | 
 | 34 | +      | 
 | 35 | +    content = message.content or ""  | 
 | 36 | +    if content.strip():  | 
 | 37 | +        print(content, end='', flush=True)  | 
 | 38 | + | 
 | 39 | +def _handle_reasoning_response(message, agent_name, message_type, role):  | 
 | 40 | +    """Handle reasoning agent responses with logical process details."""  | 
 | 41 | +    print(f"\n🧠 **{agent_name}** [{message_type}] (role: {role})")  | 
 | 42 | +    print("-" * (len(agent_name) + len(message_type) + 15))  | 
 | 43 | +      | 
 | 44 | +    if hasattr(message, 'items') and message.items:  | 
 | 45 | +        for item in message.items:  | 
 | 46 | +            if hasattr(item, 'function_name') and item.function_name:  | 
 | 47 | +                print(f"🔧 Function Call: {item.function_name}")  | 
 | 48 | +            if hasattr(item, 'text') and item.text:  | 
 | 49 | +                print(item.text, end='', flush=True)  | 
 | 50 | +      | 
 | 51 | +    content = message.content or ""  | 
 | 52 | +    if content.strip():  | 
 | 53 | +        print(f"💭 Reasoning: {content}")  | 
 | 54 | +      | 
 | 55 | +    sys.stdout.flush()  | 
 | 56 | +    print()  | 
 | 57 | + | 
 | 58 | +def _handle_research_response(message, agent_name, message_type, role, metadata):  | 
 | 59 | +    """Handle research agent responses with search result details."""  | 
 | 60 | +    print(f"\n🔍 **{agent_name}** [{message_type}] (role: {role})")  | 
 | 61 | +    print("-" * (len(agent_name) + len(message_type) + 15))  | 
 | 62 | +      | 
 | 63 | +    if metadata:  | 
 | 64 | +        print(f"📋 Metadata: {metadata}")  | 
 | 65 | +      | 
 | 66 | +    # Show detailed search results if available  | 
 | 67 | +    if hasattr(message, 'items') and message.items and len(message.items) > 0:  | 
 | 68 | +        print(f"🔧 Found {len(message.items)} items in message")  | 
 | 69 | +          | 
 | 70 | +        for i, item in enumerate(message.items):  | 
 | 71 | +            print(f"   Item {i+1}:")  | 
 | 72 | +              | 
 | 73 | +            if hasattr(item, 'function_name'):  | 
 | 74 | +                print(f"      Function Name: {item.function_name}")  | 
 | 75 | +              | 
 | 76 | +            if hasattr(item, 'arguments'):  | 
 | 77 | +                print(f"      Arguments: {item.arguments}")  | 
 | 78 | +              | 
 | 79 | +            if hasattr(item, 'text') and item.text:  | 
 | 80 | +                print(f"      Text: {item.text[:200]}...")  | 
 | 81 | +              | 
 | 82 | +            # Extract Bing search results  | 
 | 83 | +            if hasattr(item, 'response_metadata'):  | 
 | 84 | +                _parse_search_results(item.response_metadata)  | 
 | 85 | +      | 
 | 86 | +    content = message.content or ""  | 
 | 87 | +    if content.strip():  | 
 | 88 | +        print(f"💬 Content: {content}")  | 
 | 89 | +    else:  | 
 | 90 | +        print("💬 Content: [Empty]")  | 
 | 91 | +      | 
 | 92 | +    sys.stdout.flush()  | 
 | 93 | +    print()  | 
 | 94 | + | 
 | 95 | +def _parse_search_results(response_meta):  | 
 | 96 | +    """Parse and display Bing search results from metadata."""  | 
 | 97 | +    print(f"      Response Metadata: {str(response_meta)[:300]}...")  | 
 | 98 | +      | 
 | 99 | +    if isinstance(response_meta, str):  | 
 | 100 | +        try:  | 
 | 101 | +            import json  | 
 | 102 | +            parsed_meta = json.loads(response_meta)  | 
 | 103 | +            if 'webPages' in parsed_meta:  | 
 | 104 | +                web_pages = parsed_meta.get('webPages', {})  | 
 | 105 | +                total_docs = web_pages.get('totalEstimatedMatches', 0)  | 
 | 106 | +                available_docs = len(web_pages.get('value', []))  | 
 | 107 | +                print(f"      📊 BING SEARCH RESULTS: {available_docs} docs returned, ~{total_docs} total matches")  | 
 | 108 | +                  | 
 | 109 | +                # Show first few results  | 
 | 110 | +                for j, page in enumerate(web_pages.get('value', [])[:3]):  | 
 | 111 | +                    title = page.get('name', 'No title')[:50]  | 
 | 112 | +                    url = page.get('url', 'No URL')[:80]  | 
 | 113 | +                    print(f"         Result {j+1}: {title} - {url}")  | 
 | 114 | +        except Exception as parse_error:  | 
 | 115 | +            print(f"      ⚠️ Could not parse search results: {parse_error}")  | 
 | 116 | + | 
 | 117 | +def _handle_default_response(message, agent_name, message_type, role):  | 
 | 118 | +    """Handle default agent responses."""  | 
 | 119 | +    print(f"\n🤖 **{agent_name}** [{message_type}] (role: {role})")  | 
 | 120 | +    print("-" * (len(agent_name) + len(message_type) + 15))  | 
 | 121 | +      | 
 | 122 | +    content = message.content or ""  | 
 | 123 | +    if content.strip():  | 
 | 124 | +        print(f"💬 Content: {content}")  | 
 | 125 | +    else:  | 
 | 126 | +        print("💬 Content: [Empty]")  | 
 | 127 | +      | 
 | 128 | +    sys.stdout.flush()  | 
 | 129 | +    print()  | 
 | 130 | + | 
 | 131 | +async def streaming_agent_response_callback(streaming_message: StreamingChatMessageContent, is_final: bool) -> None:  | 
 | 132 | +    """Simple streaming callback to show real-time agent responses."""  | 
 | 133 | +      | 
 | 134 | +    # Print streaming content as it arrives  | 
 | 135 | +    if hasattr(streaming_message, 'content') and streaming_message.content:  | 
 | 136 | +        print(streaming_message.content, end='', flush=True)  | 
 | 137 | +      | 
 | 138 | +    # Add a newline when the streaming is complete for this message  | 
 | 139 | +    if is_final:  | 
 | 140 | +        print()  | 
0 commit comments