-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_ai_framework.py
More file actions
257 lines (207 loc) · 9.26 KB
/
demo_ai_framework.py
File metadata and controls
257 lines (207 loc) · 9.26 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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#!/usr/bin/env python3
"""
AI Framework Demonstration Script
This script demonstrates the complete AI integration framework for 3D agents,
including Tasks 8-10 that were completed:
Task 8: AI Integration Framework (Core Components)
Task 9: LangChain Adapter Integration
Task 10: AI Provider Interface
Features demonstrated:
- Multiple AI providers with fallback mechanisms
- Conversation handling and context management
- Decision making engine
- World state integration
- Action system integration
- LangChain tools integration
"""
import time
import sys
from pathlib import Path
# Add src to path
sys.path.insert(0, str(Path(__file__).parent / "src"))
def main():
print("🤖 AI Framework Demonstration")
print("=" * 50)
# Import core components
from core import WorldState, ActionSystem, Player, WorldObject
from ai import (
AI_AVAILABLE, AIManager, ConversationHandler, DecisionEngine,
ProviderManager, MockProvider, LangChainAdapter, create_world_state_tools,
create_action_tools
)
if not AI_AVAILABLE:
print("❌ AI components not available")
return
print("✅ AI Framework Available")
print()
# 1. Setup World State
print("🌍 Setting up World State...")
world_state = WorldState()
world_state.set_world_info("demo_world", "AI Framework Demo World")
# Add some players and objects
alice = Player("alice", "Alice", [0, 0, 0])
bob = Player("bob", "Bob", [5, 0, 5])
world_state.add_player(alice)
world_state.add_player(bob)
tree = WorldObject("tree1", "tree", [10, 0, 10])
rock = WorldObject("rock1", "rock", [3, 0, 3])
world_state.add_object(tree)
world_state.add_object(rock)
print(f" Added {len(world_state.get_all_players())} players")
print(f" Added {len([obj for obj in world_state.objects.values() if not isinstance(obj, Player)])} objects")
print()
# 2. Setup Action System
print("⚡ Setting up Action System...")
action_system = ActionSystem()
print(" Action system initialized")
print()
# 3. Setup AI Provider Manager
print("🧠 Setting up AI Provider Manager...")
provider_manager = ProviderManager()
# Register multiple providers with different priorities
primary_provider = MockProvider({
"model": "mock-gpt-4",
"available": True,
"response_delay": 0.1
})
backup_provider = MockProvider({
"model": "mock-gpt-3.5",
"available": True,
"response_delay": 0.2,
"failure_rate": 0.3 # 30% failure rate
})
# Register providers (higher priority number = higher priority)
provider_manager.register_provider("primary", primary_provider, priority=2)
provider_manager.register_provider("backup", backup_provider, priority=1)
print(f" Registered {len(provider_manager.providers)} providers")
print(f" Available providers: {provider_manager.get_available_providers()}")
print()
# 4. Setup AI Manager
print("🎯 Setting up AI Manager...")
ai_manager = AIManager({"ai_provider": "mock"})
print(f" AI Manager using provider: {ai_manager.name}")
print()
# 5. Setup Conversation Handler
print("💬 Setting up Conversation Handler...")
conversation = ConversationHandler("demo_agent", max_history=20)
print(" Conversation handler initialized")
print()
# 6. Setup Decision Engine
print("🎲 Setting up Decision Engine...")
decision_engine = DecisionEngine("demo_agent", ai_manager)
print(" Decision engine initialized")
print()
# 7. Setup LangChain Adapter (if available)
print("🔗 Setting up LangChain Integration...")
langchain_adapter = LangChainAdapter("demo_agent")
if langchain_adapter.is_available:
# Integrate with world state and action system
langchain_adapter.integrate_world_state(world_state)
langchain_adapter.integrate_action_system(action_system, alice)
langchain_adapter.integrate_conversation_handler(conversation)
print(" LangChain adapter configured")
print(f" Available tools: {langchain_adapter.get_available_tools()}")
else:
print(" LangChain not available - using mock mode")
print()
# 8. Demonstrate Provider Manager Fallback
print("🔄 Testing Provider Fallback Mechanism...")
# Test normal operation
response1 = provider_manager.generate_response("Hello, how are you?")
if response1:
print(f" Response 1: {response1.content[:50]}...")
print(f" Provider used: {response1.provider}")
# Test with provider failure
response2 = provider_manager.generate_response("Tell me about the weather")
if response2:
print(f" Response 2: {response2.content[:50]}...")
print(f" Provider used: {response2.provider}")
# Show provider stats
stats = provider_manager.get_provider_stats()
print(" Provider Statistics:")
for provider_name, stat in stats.items():
print(f" {provider_name}: {stat['successes']} successes, {stat['failures']} failures")
print()
# 9. Demonstrate Conversation Flow
print("💭 Demonstrating Conversation Flow...")
# Simulate user messages
conversation.add_user_message("alice", "Hello agent! What can you see around here?")
conversation.add_user_message("bob", "Hey, I'm new here. Can you help me?")
# Create decision context
context = decision_engine.create_context(
world_state=world_state,
conversation_context=conversation.get_conversation_context("alice"),
agent_state={"position": [0, 0, 0]}
)
# Make decision
decision = decision_engine.make_decision(context)
if decision:
print(f" Decision made: {decision.action}")
print(f" Confidence: {decision.confidence:.2f}")
print(f" Reasoning: {decision.reasoning}")
# Generate AI response based on decision
if decision.decision_type == "conversation_response":
ai_response = ai_manager.generate_response(
f"User asked: {conversation.messages[-2].content}. "
f"Respond helpfully about the world around us. "
f"I can see {len([obj for obj in world_state.objects.values() if not isinstance(obj, Player)])} objects and "
f"{len(world_state.get_all_players())} players."
)
conversation.add_agent_message(ai_response)
print(f" AI Response: {ai_response}")
else:
print(" No decision made (cooldown or no applicable rules)")
print()
# 10. Demonstrate World State Integration
print("🌐 Demonstrating World State Integration...")
# Get world stats
stats = world_state.get_stats()
print(" World Statistics:")
for key, value in stats.items():
print(f" {key}: {value}")
# Test spatial queries
nearby_objects = world_state.get_objects_in_radius([0, 0, 0], 5.0)
print(f" Objects within 5 units of origin: {len(nearby_objects)}")
for obj in nearby_objects:
print(f" - {obj.object_id} ({obj.object_type}) at {obj.position.to_list()}")
print()
# 11. Demonstrate Action System Integration
print("⚙️ Demonstrating Action System Integration...")
# Queue some actions using DelayAction for demonstration
from core.action_system import DelayAction
action1 = DelayAction(duration=0.1, priority=1)
action2 = DelayAction(duration=0.2, priority=2)
action_system.queue_action(action1)
action_system.queue_action(action2)
print(f" Queued {action_system.get_stats()['queue_size']} actions")
# Process actions briefly
start_time = time.time()
while action_system.get_stats()['queue_size'] > 0 and time.time() - start_time < 1.0:
action_system.update(0.1) # 0.1 second delta time
time.sleep(0.1)
action_stats = action_system.get_stats()
print(f" Completed {action_stats['total_completed']} actions")
print()
# 12. Final Summary
print("📊 Final Summary:")
print(f" World Objects: {len([obj for obj in world_state.objects.values() if not isinstance(obj, Player)])}")
print(f" Players: {len(world_state.get_all_players())}")
print(f" Conversation Messages: {len(conversation.messages)}")
print(f" Decisions Made: {len(decision_engine.get_decision_history())}")
print(f" Actions Completed: {action_system.get_stats()['total_completed']}")
print(f" AI Provider: {ai_manager.name}")
print(f" Provider Manager Strategy: {provider_manager.fallback_strategy.name}")
if langchain_adapter.is_available:
print(f" LangChain Tools: {len(langchain_adapter.tools)}")
print()
print("✨ AI Framework Demonstration Complete!")
print("\nKey Features Demonstrated:")
print("• Multiple AI provider management with fallback")
print("• Conversation flow and context tracking")
print("• AI decision making based on world state")
print("• World state management and spatial queries")
print("• Action system integration")
print("• LangChain tools integration")
print("• Provider statistics and monitoring")
if __name__ == "__main__":
main()