#!/usr/bin/env python3
"""
AI Agent for Customer Feedback System
Intelligently handles feedback collection and analysis
"""
import os
import json
import asyncio
from typing import Dict, Any, List
from datetime import datetime
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# For LLM integration
from openai import AsyncOpenAI
# For MCP client
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
class FeedbackAgent:
def __init__(self):
self.name = "Feedback Assistant"
self.llm = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"))
self.mcp_session = None
self.server_params = StdioServerParameters(
command="python",
args=["feedback_server.py"]
)
async def connect_to_server(self):
"""Connect to our MCP server"""
print(f"🔌 Connecting to feedback server...")
async with stdio_client(self.server_params) as (read, write):
async with ClientSession(read, write) as session:
self.mcp_session = session
# Initialize connection
await session.initialize()
# Get available tools and resources
tools = await session.list_tools()
resources = await session.list_resources()
print(f"✅ Connected! Found {len(tools)} tools and {len(resources)} resources")
# Keep the session active
await self.run_agent_loop()
async def think(self, task: str) -> str:
"""Use LLM to understand and plan actions"""
response = await self.llm.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "system",
"content": f"""You are {self.name}, an AI assistant for a café.
You help collect and analyze customer feedback.
Be friendly, professional, and insightful."""
},
{
"role": "user",
"content": task
}
],
temperature=0.7
)
return response.choices[0].message.content
async def collect_customer_feedback(self, conversation: str) -> Dict[str, Any]:
"""Intelligently extract feedback from conversation"""
# Use LLM to extract information
extraction_prompt = f"""
Extract the following from this customer conversation:
1. Customer name (if mentioned)
2. The main feedback points
3. Overall rating (1-5)
4. Key topics mentioned
Conversation:
{conversation}
Return as JSON format.
"""
response = await self.llm.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "Extract information and return valid JSON only."},
{"role": "user", "content": extraction_prompt}
],
temperature=0.3,
response_format={"type": "json_object"}
)
extracted = json.loads(response.choices[0].message.content)
# Use MCP tool to collect feedback
result = await self.mcp_session.call_tool(
"collect_feedback",
arguments={
"customer_name": extracted.get("customer_name", "Anonymous"),
"feedback": extracted.get("feedback", conversation),
"rating": extracted.get("rating", 3)
}
)
return {
"status": "collected",
"details": extracted,
"server_response": result
}
async def analyze_feedback_trends(self) -> str:
"""Analyze all feedback and generate insights"""
# Get recent feedback from MCP server
recent_feedback = await self.mcp_session.read_resource("feedback://recent")
summary_data = await self.mcp_session.read_resource("feedback://summary")
# Use LLM to generate insights
analysis_prompt = f"""
Analyze this customer feedback data and provide:
1. Key themes and patterns
2. Areas needing immediate attention
3. Positive aspects to maintain
4. Specific recommendations for improvement
Recent Feedback:
{recent_feedback}
Summary Statistics:
{summary_data}
"""
response = await self.llm.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "system",
"content": "You are a business analyst. Provide actionable insights."
},
{"role": "user", "content": analysis_prompt}
],
temperature=0.5
)
return response.choices[0].message.content
async def handle_customer_interaction(self, message: str) -> str:
"""Main interaction handler"""
# Determine intent
intent_prompt = f"""
Classify this message intent:
- 'give_feedback': Customer wants to share feedback
- 'check_status': Customer asking about their previous feedback
- 'general_question': Other questions
Message: {message}
Return only the intent classification.
"""
intent_response = await self.llm.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "Classify intent. Return only the classification."},
{"role": "user", "content": intent_prompt}
],
temperature=0.1
)
intent = intent_response.choices[0].message.content.strip().lower()
if "give_feedback" in intent:
# Collect feedback
feedback_result = await self.collect_customer_feedback(message)
# Generate friendly response
response = await self.think(
f"Customer gave feedback. Details: {feedback_result}. "
"Thank them and mention any immediate actions we'll take."
)
return response
elif "check_status" in intent:
# Get feedback summary
summary = await self.mcp_session.read_resource("feedback://summary")
response = await self.think(
f"Customer asking about feedback status. Our summary: {summary}. "
"Provide a helpful update."
)
return response
else:
# General response
return await self.think(f"Respond helpfully to: {message}")
async def run_agent_loop(self):
"""Main agent interaction loop"""
print(f"\n🤖 {self.name} is ready! Type 'quit' to exit.")
print("Try: 'Hi, I'm Sarah. I loved the new latte recipe! 5 stars!'")
while True:
try:
# Get user input
user_input = input("\n👤 You: ").strip()
if user_input.lower() in ['quit', 'exit', 'bye']:
print(f"👋 {self.name}: Goodbye! Have a great day!")
break
if user_input.lower() == 'analyze':
# Run analysis
print(f"\n📊 {self.name}: Analyzing feedback trends...")
analysis = await self.analyze_feedback_trends()
print(f"📈 Analysis:\n{analysis}")
continue
# Handle regular interaction
print(f"\n🤖 {self.name}: Processing...")
response = await self.handle_customer_interaction(user_input)
print(f"🤖 {self.name}: {response}")
except KeyboardInterrupt:
print(f"\n👋 {self.name}: Goodbye!")
break
except Exception as e:
print(f"❌ Error: {e}")
# Main entry point
async def main():
agent = FeedbackAgent()
await agent.connect_to_server()
if __name__ == "__main__":
asyncio.run(main())