File size: 11,633 Bytes
ca7a2c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0140f42
ca7a2c2
 
 
 
 
 
 
 
 
 
 
 
 
0140f42
 
 
 
ca7a2c2
0140f42
 
 
 
 
 
ca7a2c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
"""
LocalMate Agent Test Script - Single vs ReAct Mode Comparison

Tests 10 queries in both modes:
- Single mode: configurable delay between queries
- ReAct mode: configurable delay between queries  
- Configurable delay between modes

Generates detailed report with all step inputs/outputs.
"""

import asyncio
import json
import time
from datetime import datetime
import httpx

# =============================================================================
# CONFIGURATION - Adjust these values as needed
# =============================================================================

# API Settings
API_BASE = "https://cuong2004-localmate.hf.space/api/v1"
USER_ID = "test_comparison"

# Delay Settings (in seconds)
SINGLE_MODE_DELAY = 10       # Delay between queries in single mode
REACT_MODE_DELAY = 60       # Delay between queries in ReAct mode
MODE_SWITCH_DELAY = 60      # Delay between switching modes
REQUEST_TIMEOUT = 120       # Timeout for each API request

# =============================================================================

# Test Cases - 10 queries covering different scenarios
TEST_CASES = [
    # {
    #     "id": 1,
    #     "query": "Quán cafe view đẹp",
    #     "description": "Simple text search - no location",
    #     "expected_tools": ["retrieve_context_text"],
    # },
    {
        "id": 2,
        "query": "Nhà hàng gần bãi biển Mỹ Khê",
        "description": "Location-based search",
        "expected_tools": ["find_nearby_places"],
    },
    # {
    #     "id": 3,
    #     "query": "Quán cafe có không gian xanh mát gần Cầu Rồng",
    #     "description": "Complex: location + feature (should use multiple tools in ReAct)",
    #     "expected_tools": ["find_nearby_places", "retrieve_context_text"],
    # },
    # {
    #     "id": 4,
    #     "query": "Phở ngon giá rẻ",
    #     "description": "Food-specific text search",
    #     "expected_tools": ["retrieve_context_text"],
    # },
    # {
    #     "id": 5,
    #     "query": "Địa điểm checkin đẹp gần Bà Nà",
    #     "description": "Location + activity type",
    #     "expected_tools": ["find_nearby_places"],
    # },
    # {
    #     "id": 6,
    #     "query": "Quán ăn hải sản có view sông gần trung tâm",
    #     "description": "Complex: location + category + feature",
    #     "expected_tools": ["find_nearby_places", "retrieve_context_text"],
    # },
    # {
    #     "id": 7,
    #     "query": "Khách sạn 5 sao gần biển",
    #     "description": "Hotel + location search",
    #     "expected_tools": ["find_nearby_places"],
    # },
    # {
    #     "id": 8,
    #     "query": "Quán bar có view đẹp về đêm",
    #     "description": "Nightlife text search",
    #     "expected_tools": ["retrieve_context_text"],
    # },
    # {
    #     "id": 9,
    #     "query": "Cafe rooftop gần Sơn Trà có coffee ngon",
    #     "description": "Complex: location + feature + quality",
    #     "expected_tools": ["find_nearby_places", "retrieve_context_text"],
    # },
    # {
    #     "id": 10,
    #     "query": "Nhà hàng Việt Nam authentic gần Rex Hotel",
    #     "description": "Specific location + category + style",
    #     "expected_tools": ["find_nearby_places", "retrieve_context_text"],
    # },
]


async def run_test(client: httpx.AsyncClient, test_case: dict, react_mode: bool) -> dict:
    """Run a single test case and return results."""
    start_time = time.time()
    
    try:
        response = await client.post(
            f"{API_BASE}/chat",
            json={
                "message": test_case["query"],
                "user_id": USER_ID,
                "provider": "MegaLLM",
                "react_mode": react_mode,
                "max_steps": 5,
            },
            timeout=float(REQUEST_TIMEOUT),
        )
        
        duration = (time.time() - start_time) * 1000
        
        if response.status_code == 200:
            data = response.json()
            return {
                "success": True,
                "test_id": test_case["id"],
                "query": test_case["query"],
                "description": test_case["description"],
                "react_mode": react_mode,
                "response": data.get("response", "")[:300],
                "workflow": data.get("workflow", {}),
                "tools_used": data.get("tools_used", []),
                "api_duration_ms": data.get("duration_ms", 0),
                "total_duration_ms": duration,
            }
        else:
            return {
                "success": False,
                "test_id": test_case["id"],
                "query": test_case["query"],
                "react_mode": react_mode,
                "error": f"HTTP {response.status_code}: {response.text[:200]}",
                "total_duration_ms": duration,
            }
    
    except Exception as e:
        return {
            "success": False,
            "test_id": test_case["id"],
            "query": test_case["query"],
            "react_mode": react_mode,
            "error": str(e),
            "total_duration_ms": (time.time() - start_time) * 1000,
        }


def format_workflow_steps(workflow: dict) -> str:
    """Format workflow steps for report."""
    steps = workflow.get("steps", [])
    if not steps:
        return "No steps recorded"
    
    lines = []
    for step in steps:
        tool = step.get("tool", "N/A")
        purpose = step.get("purpose", "")
        results = step.get("results", 0)
        lines.append(f"  - {step.get('step', 'Unknown')}")
        lines.append(f"    Tool: `{tool}` | Results: {results}")
    
    return "\n".join(lines)


def generate_report(single_results: list, react_results: list) -> str:
    """Generate detailed markdown report."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    report = f"""# LocalMate Agent Test Report

**Generated:** {timestamp}

## Summary

| Metric | Single Mode | ReAct Mode |
|--------|-------------|------------|
| Total Tests | {len(single_results)} | {len(react_results)} |
| Success | {sum(1 for r in single_results if r.get('success'))} | {sum(1 for r in react_results if r.get('success'))} |
| Avg Duration | {sum(r.get('api_duration_ms', 0) for r in single_results if r.get('success')) / max(1, sum(1 for r in single_results if r.get('success'))):.0f}ms | {sum(r.get('api_duration_ms', 0) for r in react_results if r.get('success')) / max(1, sum(1 for r in react_results if r.get('success'))):.0f}ms |

---

## Detailed Results

"""
    
    for i, (single, react) in enumerate(zip(single_results, react_results)):
        test_id = single.get("test_id", i + 1)
        query = single.get("query", "N/A")
        description = single.get("description", "")
        
        report += f"""### Test Case {test_id}: {description}

**Query:** `{query}`

#### Single Mode

"""
        if single.get("success"):
            report += f"""- **Status:** ✅ Success
- **Duration:** {single.get('api_duration_ms', 0):.0f}ms
- **Tools Used:** {', '.join(single.get('tools_used', [])) or 'None'}

**Workflow:**
{format_workflow_steps(single.get('workflow', {}))}

**Response Preview:**
> {single.get('response', 'N/A')[:200]}...

"""
        else:
            report += f"""- **Status:** ❌ Failed
- **Error:** {single.get('error', 'Unknown')}

"""
        
        report += """#### ReAct Mode

"""
        if react.get("success"):
            workflow = react.get("workflow", {})
            report += f"""- **Status:** ✅ Success
- **Duration:** {react.get('api_duration_ms', 0):.0f}ms
- **Tools Used:** {', '.join(react.get('tools_used', [])) or 'None'}
- **Steps:** {len(workflow.get('steps', []))}
- **Intent Detected:** {workflow.get('intent_detected', 'N/A')}

**Workflow Steps:**
{format_workflow_steps(workflow)}

**Response Preview:**
> {react.get('response', 'N/A')[:200]}...

"""
        else:
            report += f"""- **Status:** ❌ Failed
- **Error:** {react.get('error', 'Unknown')}

"""
        
        report += "---\n\n"
    
    # Comparison analysis
    report += """## Analysis

### Tool Usage Comparison

| Test | Single Mode Tools | ReAct Mode Tools | ReAct Steps |
|------|-------------------|------------------|-------------|
"""
    
    for single, react in zip(single_results, react_results):
        test_id = single.get("test_id", "?")
        single_tools = ", ".join(single.get("tools_used", [])) if single.get("success") else "❌"
        react_tools = ", ".join(react.get("tools_used", [])) if react.get("success") else "❌"
        react_steps = len(react.get("workflow", {}).get("steps", [])) if react.get("success") else 0
        report += f"| {test_id} | {single_tools} | {react_tools} | {react_steps} |\n"
    
    report += """

### Key Observations

1. **Multi-tool queries**: ReAct mode can chain multiple tools for complex queries
2. **Single-tool queries**: Both modes perform similarly for simple queries
3. **Reasoning steps**: ReAct mode shows explicit reasoning before each tool call

"""
    
    return report


async def main():
    """Main test runner."""
    print("=" * 60)
    print("LocalMate Agent Mode Comparison Test")
    print("=" * 60)
    print()
    
    single_results = []
    react_results = []
    
    async with httpx.AsyncClient() as client:
        # Test Single Mode
        print(f"📌 Running Single Mode Tests ({SINGLE_MODE_DELAY}s delay)...")
        print("-" * 40)
        
        for test in TEST_CASES:
            print(f"  Test {test['id']}: {test['query'][:40]}...")
            result = await run_test(client, test, react_mode=False)
            single_results.append(result)
            
            status = "✅" if result.get("success") else "❌"
            tools = ", ".join(result.get("tools_used", [])) or "None"
            print(f"    {status} Tools: {tools} | {result.get('api_duration_ms', 0):.0f}ms")
            
            if test["id"] < len(TEST_CASES):
                await asyncio.sleep(SINGLE_MODE_DELAY)
        
        print()
        print(f"⏸️  Waiting {MODE_SWITCH_DELAY}s before ReAct mode...")
        await asyncio.sleep(MODE_SWITCH_DELAY)
        
        # Test ReAct Mode
        print()
        print(f"🧠 Running ReAct Mode Tests ({REACT_MODE_DELAY}s delay)...")
        print("-" * 40)
        
        for test in TEST_CASES:
            print(f"  Test {test['id']}: {test['query'][:40]}...")
            result = await run_test(client, test, react_mode=True)
            react_results.append(result)
            
            status = "✅" if result.get("success") else "❌"
            tools = ", ".join(result.get("tools_used", [])) or "None"
            steps = len(result.get("workflow", {}).get("steps", []))
            print(f"    {status} Tools: {tools} | Steps: {steps} | {result.get('api_duration_ms', 0):.0f}ms")
            
            if test["id"] < len(TEST_CASES):
                await asyncio.sleep(REACT_MODE_DELAY)
    
    # Generate report
    print()
    print("📝 Generating report...")
    report = generate_report(single_results, react_results)
    
    # Use absolute path based on script location
    import os
    script_dir = os.path.dirname(os.path.abspath(__file__))
    report_path = os.path.join(script_dir, "react_comparison_report.md")
    with open(report_path, "w", encoding="utf-8") as f:
        f.write(report)
    
    print(f"✅ Report saved to: {report_path}")
    print()
    print("=" * 60)
    print("Test Complete!")
    print("=" * 60)


if __name__ == "__main__":
    asyncio.run(main())