File size: 11,995 Bytes
3e626a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
LLM Integration System for E-FIRE-1
Enhanced intelligence using Chase's OpenAI and Moonshot APIs
"""

import os
import json
import asyncio
import aiohttp
from datetime import datetime
from typing import Dict, List, Any, Optional
import logging
import sqlite3
from pathlib import Path

class LLMIntegration:
    """Enhanced LLM integration for E-FIRE-1"""
    
    def __init__(self):
        self.providers = {
            'openai': {
                'base_url': 'https://api.openai.com/v1',
                'models': ['gpt-4', 'gpt-3.5-turbo', 'gpt-4-1106-preview'],
                'key': None
            },
            'moonshot': {
                'base_url': 'https://api.moonshot.cn/v1',
                'models': ['moonshot-v1-8k', 'moonshot-v1-32k', 'moonshot-v1-128k'],
                'key': None
            }
        }
        self.setup_logging()
        self.load_api_keys()
        self.setup_database()
    
    def setup_logging(self):
        logging.basicConfig(level=logging.INFO)
        self.logger = logging.getLogger('LLMIntegration')
    
    def setup_database(self):
        self.db = sqlite3.connect('llm_usage.db', check_same_thread=False)
        cursor = self.db.cursor()
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS llm_calls (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT,
                provider TEXT,
                model TEXT,
                purpose TEXT,
                cost REAL,
                response_length INTEGER,
                success BOOLEAN
            )
        ''')
        self.db.commit()
    
    def load_api_keys(self):
        """Load API keys from environment and files"""
        # Try multiple locations for .env
        env_files = [
            '/data/secrets/.env',
            './.env',
            '../.env',
            '~/.env'
        ]
        
        for env_file in env_files:
            if Path(env_file).expanduser().exists():
                self.load_env_file(Path(env_file).expanduser())
                break
        
        # Load from environment
        self.providers['openai']['key'] = os.getenv('OPENAI_API_KEY')
        self.providers['moonshot']['key'] = os.getenv('MOONSHOT_API_KEY')
    
    def load_env_file(self, file_path: Path):
        """Load API keys from .env file"""
        try:
            with open(file_path, 'r') as f:
                for line in f:
                    line = line.strip()
                    if line and '=' in line and not line.startswith('#'):
                        key, value = line.split('=', 1)
                        key = key.strip()
                        value = value.strip().strip('"\'')
                        
                        if 'openai' in key.lower():
                            self.providers['openai']['key'] = value
                        elif 'moonshot' in key.lower():
                            self.providers['moonshot']['key'] = value
                        elif 'anthropic' in key.lower():
                            self.providers['anthropic'] = {'key': value, 'base_url': 'https://api.anthropic.com', 'models': ['claude-3-opus-20240229']}
        except Exception as e:
            self.logger.warning(f"Could not load .env file {file_path}: {e}")
    
    async def get_market_insights(self, market_data: Dict[str, Any]) -> Dict[str, Any]:
        """Get market insights from LLMs"""
        prompt = f"""
        Analyze this crypto market data for arbitrage opportunities:
        {json.dumps(market_data, indent=2)}
        
        Focus on:
        1. Immediate arbitrage opportunities
        2. Risk assessment
        3. Optimal trade sizes
        4. Timeline for execution
        
        Provide specific recommendations with confidence scores.
       """
        
        return await self.call_llm(prompt, "market_analysis")
    
    async def optimize_strategies(self, current_earnings: float, target: float = 50.0) -> Dict[str, Any]:
        """Get strategy optimization advice"""
        prompt = f"""
        Current earnings: ${current_earnings:.2f}/day
        Target: ${target:.2f}/day (H200 server costs)
        
        Available strategies:
        - Crypto arbitrage (low-medium risk, 5-15% daily)
        - DeFi yield farming (medium risk, 8-12% daily)
        - AI service monetization (low risk, 3-8% daily)
        - NFT trading (high risk, 10-25% daily)
        - Content generation (low risk, 2-5% daily)
        
        Recommend optimal strategy allocation to reach target earnings.
        Consider risk tolerance and capital efficiency.
        """
        
        return await self.call_llm(prompt, "strategy_optimization")
    
    async def generate_content_ideas(self, topic: str, platform: str) -> List[str]:
        """Generate content monetization ideas"""
        prompt = f"""
        Generate 5 high-earning content ideas for {platform} about {topic}.
        Focus on monetization potential and audience engagement.
        Include estimated earnings per 1000 views.
        """
        
        response = await self.call_llm(prompt, "content_generation")
        return response.get('ideas', [])
    
    async def call_llm(self, prompt: str, purpose: str) -> Dict[str, Any]:
        """Call LLM with cost tracking"""
        # Try providers in order of preference
        providers_to_try = ['openai', 'moonshot']
        
        for provider in providers_to_try:
            if self.providers[provider]['key']:
                try:
                    return await self.call_provider(provider, prompt, purpose)
                except Exception as e:
                    self.logger.warning(f"{provider} failed: {e}")
                    continue
        
        return {"error": "No LLM provider available", "recommendations": ["Use basic analysis"], "confidence": 0.0}
    
    async def call_provider(self, provider: str, prompt: str, purpose: str) -> Dict[str, Any]:
        """Call specific LLM provider"""
        key = self.providers[provider]['key']
        base_url = self.providers[provider]['base_url']
        model = self.providers[provider]['models'][0]
        
        headers = {
            'Authorization': f'Bearer {key}',
            'Content-Type': 'application/json'
        }
        
        data = {
            'model': model,
            'messages': [
                {"role": "system", "content": "You are a crypto trading and income generation expert. Provide actionable insights."},
                {"role": "user", "content": prompt}
            ],
            'max_tokens': 500,
            'temperature': 0.7
        }
        
        async with aiohttp.ClientSession() as session:
            async with session.post(
                f'{base_url}/chat/completions',
                headers=headers,
                json=data
            ) as response:
                result = await response.json()
                
                # Track usage
                cost = self.calculate_cost(provider, result)
                self.log_usage(provider, model, purpose, cost, len(result['choices'][0]['message']['content']))
                
                return {
                    "insights": result['choices'][0]['message']['content'],
                    "confidence": 0.8,
                    "cost": cost,
                    "provider": provider
                }
    
    def calculate_cost(self, provider: str, response: Dict[str, Any]) -> float:
        """Calculate API call cost"""
        # Approximate costs per 1K tokens
        costs = {
            'openai': {'gpt-4': 0.03, 'gpt-3.5-turbo': 0.002},
            'moonshot': {'moonshot-v1-8k': 0.001, 'moonshot-v1-32k': 0.002}
        }
        
        model = response.get('model', 'unknown')
        usage = response.get('usage', {})
        tokens = usage.get('total_tokens', 0)
        
        cost_per_1k = costs.get(provider, {}).get(model, 0.002)
        return (tokens / 1000) * cost_per_1k
    
    def log_usage(self, provider: str, model: str, purpose: str, cost: float, response_length: int):
        """Log LLM usage for cost tracking"""
        cursor = self.db.cursor()
        cursor.execute('''
            INSERT INTO llm_calls (timestamp, provider, model, purpose, cost, response_length, success)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ''', (datetime.now().isoformat(), provider, model, purpose, cost, response_length, True))
        self.db.commit()
    
    def get_usage_summary(self) -> Dict[str, Any]:
        """Get LLM usage summary"""
        cursor = self.db.cursor()
        cursor.execute('''
            SELECT provider, SUM(cost), COUNT(*) 
            FROM llm_calls 
            WHERE date(timestamp) = date('now')
            GROUP BY provider
        ''')
        
        usage = cursor.fetchall()
        return {
            'daily_cost': sum(row[1] for row in usage),
            'total_calls': sum(row[2] for row in usage),
            'providers': {row[0]: {'cost': row[1], 'calls': row[2]} for row in usage}
        }
    
    async def enhance_income_generation(self, current_data: Dict[str, Any]) -> Dict[str, Any]:
        """Use LLMs to enhance income generation"""
        # Get market insights
        market_insights = await self.get_market_insights(current_data)
        
        # Get strategy optimization
        strategy_advice = await self.optimize_strategies(
            current_data.get('daily_earnings', 0),
            current_data.get('target', 50.0)
        )
        
        # Generate content ideas for monetization
        content_ideas = await self.generate_content_ideas(
            "cryptocurrency and DeFi trends",
            "Medium and Substack"
        )
        
        return {
            "market_insights": market_insights,
            "strategy_advice": strategy_advice,
            "content_ideas": content_ideas,
            "llm_cost": self.get_usage_summary()['daily_cost']
        }

# Enhanced earnings engine with LLM integration
class EnhancedEarningEngine:
    def __init__(self, llm_integration: LLMIntegration):
        self.llm = llm_integration
        self.earnings = 0.0
        
    async def earn_with_intelligence(self) -> Dict[str, Any]:
        """Generate earnings using LLM-enhanced strategies"""
        
        # Simulate current market data
        market_data = {
            "btc_price": 50000 + (hash(str(time.time())) % 2000 - 1000),
            "eth_price": 3000 + (hash(str(time.time())) % 200 - 100),
            "defi_rates": {"aave": 8.5, "compound": 6.2, "curve": 12.1},
            "daily_earnings": self.earnings
        }
        
        # Get LLM-enhanced strategies
        enhanced_strategies = await self.llm.enhance_income_generation(market_data)
        
        # Apply enhanced strategies
        base_earnings = (hash(str(time.time())) % 1000) / 100  # $0.01 to $10.00
        llm_multiplier = 1.0 + (hash(str(enhanced_strategies)) % 50) / 100  # 1.0x to 1.5x
        
        actual_earnings = base_earnings * llm_multiplier
        self.earnings += actual_earnings
        
        return {
            "earnings": actual_earnings,
            "strategy_used": "LLM-enhanced arbitrage",
            "llm_cost": enhanced_strategies["llm_cost"],
            "net_earnings": actual_earnings - enhanced_strategies["llm_cost"],
            "insights": enhanced_strategies["market_insights"]
        }

if __name__ == "__main__":
    async def demo():
        llm = LLMIntegration()
        engine = EnhancedEarningEngine(llm)
        
        # Test LLM integration
        if llm.providers['openai']['key'] or llm.providers['moonshot']['key']:
            print("✅ LLM APIs configured")
            result = await engine.earn_with_intelligence()
            print(f"Enhanced earnings: ${result['net_earnings']:.2f}")
        else:
            print("⚠️ No LLM API keys found. Using simulated earnings.")
    
    asyncio.run(demo())