-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.py
More file actions
executable file
·161 lines (133 loc) · 5.63 KB
/
client.py
File metadata and controls
executable file
·161 lines (133 loc) · 5.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!/usr/bin/env python3
import requests
import json
import sys
from typing import Dict, Any
class AnswerBotClient:
def __init__(self, router_url: str = "http://localhost:8000"):
self.router_url = router_url
self.session = requests.Session()
def ask_question(self, question: str) -> Dict[str, Any]:
try:
response = self.session.post(
f"{self.router_url}/ask",
json={"question": question},
timeout=30
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"error": f"Failed to connect to AnswerBot: {str(e)}"}
def get_health(self) -> Dict[str, Any]:
try:
response = self.session.get(f"{self.router_url}/health", timeout=10)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"error": f"Health check failed: {str(e)}"}
def get_agents(self) -> Dict[str, Any]:
try:
response = self.session.get(f"{self.router_url}/agents", timeout=10)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"error": f"Failed to get agents info: {str(e)}"}
def print_response(response: Dict[str, Any]) -> None:
if "error" in response:
print(f"❌ Error: {response['error']}")
return
print("\n" + "="*50)
if "agent" in response:
agent_name = response["agent"]
print(f"🤖 Agent: {agent_name}")
if "question" in response:
print(f"❓ Question: {response['question']}")
# Handle response types
if agent_name == "MathAgent" and "result" in response:
print(f"🔢 Expression: {response.get('expression', 'N/A')}")
print(f"✅ Result: {response['result']}")
elif agent_name == "WeatherAgent" and "weather" in response:
weather = response["weather"]
city = response.get("city", "Unknown")
print(f"🌍 City: {city}")
print(f"🌡️ Temperature: {weather.get('temperature', 'N/A')}")
print(f"☁️ Condition: {weather.get('condition', 'N/A')}")
print(f"💧 Humidity: {weather.get('humidity', 'N/A')}")
if "response" in response:
print(f"📝 Summary: {response['response']}")
elif agent_name == "QnAAgent" and "response" in response:
print(f"💬 Answer: {response['response']}")
# Routing info
if "router_info" in response:
router_info = response["router_info"]
print(f"\n🔀 Routing Info:")
print(f" Selected Agent: {router_info.get('selected_agent', 'N/A')}")
print(f" Reason: {router_info.get('routing_reason', 'N/A')}")
print("="*50)
def interactive_mode(client: AnswerBotClient) -> None:
print("🤖 AI AnswerBot Interactive Client")
print("Type 'help' for commands, 'quit' to exit")
print("-" * 40)
while True:
try:
try:
question = input("\n💭 Ask me anything: ").strip()
except EOFError:
print("\n👋 Session ended (EOF detected)")
break
if not question:
continue
if question.lower() in ['quit', 'exit', 'q']:
print("👋 Goodbye!")
break
if question.lower() == 'help':
print_help()
continue
if question.lower() == 'health':
health = client.get_health()
print(f"🏥 Health Status: {json.dumps(health, indent=2)}")
continue
if question.lower() == 'agents':
agents = client.get_agents()
print(f"🔍 Available Agents: {json.dumps(agents, indent=2)}")
continue
print("🔄 Processing your question...")
response = client.ask_question(question)
print_response(response)
except KeyboardInterrupt:
print("\n👋 Goodbye!")
break
except Exception as e:
print(f"❌ Unexpected error: {str(e)}")
def print_help() -> None:
print("\n📚 Available Commands:")
print(" help - Show this help message")
print(" health - Check router health")
print(" agents - List available agents")
print(" quit - Exit the client")
print("\n🎯 Example Questions:")
print(" Math: 'What is 25 + 17?', 'Calculate 100 / 4'")
print(" Weather: 'Weather in London?', 'Temperature in Tokyo?'")
print(" General: 'What is AI?', 'Hello, how are you?'")
def main():
if len(sys.argv) > 1:
# Non-interactive mode
router_url = sys.argv[2] if len(sys.argv) > 2 else "http://localhost:8000"
client = AnswerBotClient(router_url)
question = sys.argv[1]
print(f"🤖 AI AnswerBot - Single Query Mode")
print(f"Question: {question}")
response = client.ask_question(question)
print_response(response)
else:
# Interactive mode
client = AnswerBotClient()
# Check service availability
health = client.get_health()
if "error" in health:
print(f"❌ Cannot connect to AnswerBot service: {health['error']}")
print("💡 Make sure the service is running on http://localhost:8000")
sys.exit(1)
interactive_mode(client)
if __name__ == "__main__":
main()