File size: 8,729 Bytes
78f67d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Advanced finance tests including streaming and complex scenarios.
"""

import httpx
import json
import time

BASE_URL = "https://jeanbaptdzd-open-finance-llm-8b.hf.space"

def test_streaming_response():
    """Test streaming chat completion."""
    print("\n" + "="*80)
    print("TESTING STREAMING RESPONSE")
    print("="*80)
    
    payload = {
        "model": "DragonLLM/qwen3-8b-fin-v1.0",
        "messages": [
            {
                "role": "user",
                "content": "Explain the Black-Scholes option pricing model in simple terms."
            }
        ],
        "stream": True,
        "max_tokens": 150,
        "temperature": 0.4
    }
    
    print(f"\nQuestion: {payload['messages'][0]['content']}")
    print(f"\nStreaming response:")
    print("─" * 80)
    
    start_time = time.time()
    chunks_received = 0
    full_response = ""
    
    try:
        with httpx.stream(
            "POST",
            f"{BASE_URL}/v1/chat/completions",
            json=payload,
            timeout=60.0
        ) as response:
            for line in response.iter_lines():
                if line.startswith("data: "):
                    data_str = line[6:]  # Remove "data: " prefix
                    
                    if data_str == "[DONE]":
                        break
                    
                    try:
                        chunk_data = json.loads(data_str)
                        delta = chunk_data.get("choices", [{}])[0].get("delta", {})
                        content = delta.get("content", "")
                        
                        if content:
                            print(content, end="", flush=True)
                            full_response += content
                            chunks_received += 1
                    except json.JSONDecodeError:
                        pass
        
        elapsed = time.time() - start_time
        
        print("\n" + "─" * 80)
        print(f"\nβœ… Streaming test successful!")
        print(f"   ⏱️  Time: {elapsed:.2f}s")
        print(f"   πŸ“¦ Chunks received: {chunks_received}")
        print(f"   πŸ“ Total characters: {len(full_response)}")
        
        return True
        
    except Exception as e:
        print(f"\n❌ Error: {e}")
        return False

def test_complex_finance_scenario():
    """Test complex multi-step finance reasoning."""
    print("\n" + "="*80)
    print("TESTING COMPLEX FINANCE SCENARIO")
    print("="*80)
    
    question = """A company has the following financials:
- Revenue: $10 million
- Cost of Goods Sold: $4 million
- Operating Expenses: $3 million
- Interest Expense: $500,000
- Tax Rate: 25%

Calculate the company's:
1. Gross Profit Margin
2. Operating Income
3. Net Income
4. EBITDA (assuming $200k depreciation)"""

    payload = {
        "model": "DragonLLM/qwen3-8b-fin-v1.0",
        "messages": [
            {"role": "user", "content": question}
        ],
        "temperature": 0.1,
        "max_tokens": 300
    }
    
    print(f"\nQuestion:\n{question}")
    print("\n" + "─" * 80)
    
    start_time = time.time()
    
    try:
        response = httpx.post(
            f"{BASE_URL}/v1/chat/completions",
            json=payload,
            timeout=60.0
        )
        
        elapsed = time.time() - start_time
        
        if response.status_code == 200:
            data = response.json()
            answer = data['choices'][0]['message']['content']
            usage = data.get('usage', {})
            
            print(f"\nπŸ’¬ Answer:\n{answer}")
            print("\n" + "─" * 80)
            print(f"\nβœ… Complex scenario test successful!")
            print(f"   ⏱️  Time: {elapsed:.2f}s")
            print(f"   πŸ“ Tokens: {usage.get('total_tokens', 'N/A')}")
            
            # Check for key calculations in response
            calculations = ["gross profit", "operating income", "net income", "ebitda"]
            found = [calc for calc in calculations if calc in answer.lower()]
            print(f"   🎯 Calculations mentioned: {len(found)}/{len(calculations)}")
            
            return True
        else:
            print(f"❌ Error: HTTP {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ Error: {e}")
        return False

def test_financial_advice():
    """Test investment advice generation."""
    print("\n" + "="*80)
    print("TESTING FINANCIAL ADVICE")
    print("="*80)
    
    question = """I'm 30 years old with $50,000 to invest. My risk tolerance is moderate, 
and I'm investing for retirement in 35 years. What asset allocation would you recommend?"""

    payload = {
        "model": "DragonLLM/qwen3-8b-fin-v1.0",
        "messages": [
            {"role": "user", "content": question}
        ],
        "temperature": 0.5,
        "max_tokens": 250
    }
    
    print(f"\nQuestion: {question}")
    print("\n" + "─" * 80)
    
    try:
        response = httpx.post(
            f"{BASE_URL}/v1/chat/completions",
            json=payload,
            timeout=60.0
        )
        
        if response.status_code == 200:
            data = response.json()
            answer = data['choices'][0]['message']['content']
            
            print(f"\nπŸ’¬ Answer:\n{answer}")
            print("\n" + "─" * 80)
            print(f"\nβœ… Financial advice test successful!")
            
            # Check for relevant concepts
            concepts = ["stocks", "bonds", "diversification", "allocation", "risk"]
            found = [c for c in concepts if c in answer.lower()]
            print(f"   🎯 Relevant concepts: {', '.join(found)}")
            
            return True
        else:
            print(f"❌ Error: HTTP {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ Error: {e}")
        return False

def test_market_interpretation():
    """Test market data interpretation."""
    print("\n" + "="*80)
    print("TESTING MARKET DATA INTERPRETATION")
    print("="*80)
    
    question = """A stock has the following characteristics:
- Current Price: $100
- 52-week High: $120
- 52-week Low: $75
- P/E Ratio: 25
- Beta: 1.5
- Dividend Yield: 2%

What does this data tell you about the stock's risk and valuation?"""

    payload = {
        "model": "DragonLLM/qwen3-8b-fin-v1.0",
        "messages": [
            {"role": "user", "content": question}
        ],
        "temperature": 0.3,
        "max_tokens": 250
    }
    
    print(f"\nQuestion:\n{question}")
    print("\n" + "─" * 80)
    
    try:
        response = httpx.post(
            f"{BASE_URL}/v1/chat/completions",
            json=payload,
            timeout=60.0
        )
        
        if response.status_code == 200:
            data = response.json()
            answer = data['choices'][0]['message']['content']
            
            print(f"\nπŸ’¬ Answer:\n{answer}")
            print("\n" + "─" * 80)
            print(f"\nβœ… Market interpretation test successful!")
            
            # Check for key concepts
            concepts = ["beta", "p/e", "volatility", "risk", "valuation"]
            found = [c for c in concepts if c in answer.lower()]
            print(f"   🎯 Key concepts addressed: {', '.join(found)}")
            
            return True
        else:
            print(f"❌ Error: HTTP {response.status_code}")
            return False
            
    except Exception as e:
        print(f"❌ Error: {e}")
        return False

def main():
    """Run all advanced tests."""
    print("="*80)
    print("ADVANCED FINANCE LLM TESTING")
    print("="*80)
    print(f"Target: {BASE_URL}")
    
    results = []
    
    # Test 1: Streaming
    results.append(("Streaming Response", test_streaming_response()))
    time.sleep(2)
    
    # Test 2: Complex scenario
    results.append(("Complex Finance Calculations", test_complex_finance_scenario()))
    time.sleep(2)
    
    # Test 3: Financial advice
    results.append(("Investment Advice", test_financial_advice()))
    time.sleep(2)
    
    # Test 4: Market interpretation
    results.append(("Market Data Interpretation", test_market_interpretation()))
    
    # Summary
    print("\n" + "="*80)
    print("ADVANCED TESTS SUMMARY")
    print("="*80)
    
    passed = sum(1 for _, success in results if success)
    total = len(results)
    
    print(f"\nβœ… Passed: {passed}/{total}")
    
    for test_name, success in results:
        status = "βœ…" if success else "❌"
        print(f"   {status} {test_name}")
    
    print("\n" + "="*80)

if __name__ == "__main__":
    main()