File size: 8,084 Bytes
27caffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Model Manager for Police Bot AI Runtime
Helps manage and switch between different Ollama models
"""

import os
import sys
import requests
import json
from config import config

def print_banner():
    """Print banner"""
    print("=" * 60)
    print("πŸ€– Police Bot AI - Model Manager")
    print("=" * 60)

def check_ollama_status():
    """Check if Ollama is running and get available models"""
    try:
        response = requests.get("http://localhost:11434/api/tags", timeout=5)
        if response.status_code == 200:
            data = response.json()
            models = data.get("models", [])
            return True, models
        else:
            return False, []
    except:
        return False, []

def list_available_models():
    """List all available models in Ollama"""
    print("\nπŸ“‹ Available Models in Ollama:")
    print("-" * 40)
    
    ollama_running, models = check_ollama_status()
    
    if not ollama_running:
        print("❌ Ollama is not running")
        print("Please start Ollama first: ollama serve")
        return []
    
    if not models:
        print("⚠️  No models found in Ollama")
        print("You can pull models using:")
        print("  ollama pull mistral")
        print("  ollama pull llama3")
        print("  ollama pull police-bot")
        return []
    
    available_models = []
    for i, model in enumerate(models, 1):
        model_name = model.get("name", "Unknown")
        model_size = model.get("size", 0)
        size_mb = model_size / (1024 * 1024) if model_size > 0 else 0
        
        print(f"{i:2d}. {model_name:<20} ({size_mb:.0f} MB)")
        available_models.append(model_name)
    
    return available_models

def list_configured_models():
    """List models configured in the system"""
    print("\nβš™οΈ  Configured Models in System:")
    print("-" * 40)
    
    configured_models = config.list_available_models()
    current_model = config.OLLAMA_MODEL
    
    for i, model in enumerate(configured_models, 1):
        status = "βœ“" if model == current_model else " "
        print(f"{i:2d}. [{status}] {model}")
    
    return configured_models

def switch_model():
    """Switch to a different model"""
    print("\nπŸ”„ Switch Model")
    print("-" * 40)
    
    configured_models = config.list_available_models()
    current_model = config.OLLAMA_MODEL
    
    print(f"Current model: {current_model}")
    print("\nAvailable models:")
    
    for i, model in enumerate(configured_models, 1):
        print(f"{i}. {model}")
    
    try:
        choice = input(f"\nEnter choice (1-{len(configured_models)}): ").strip()
        if choice:
            model_index = int(choice) - 1
            if 0 <= model_index < len(configured_models):
                selected_model = configured_models[model_index]
                
                # Check if model is available in Ollama
                ollama_running, models = check_ollama_status()
                if ollama_running:
                    model_names = [m.get("name") for m in models]
                    if selected_model not in model_names:
                        print(f"⚠️  Warning: {selected_model} is not available in Ollama")
                        pull = input("Would you like to pull it? (y/n): ").lower().strip()
                        if pull == 'y':
                            print(f"Pulling {selected_model}...")
                            os.system(f"ollama pull {selected_model}")
                
                # Switch model
                if config.switch_model(selected_model):
                    print(f"βœ… Switched to {selected_model}")
                    
                    # Save to environment file
                    save_model_to_env(selected_model)
                else:
                    print(f"❌ Failed to switch to {selected_model}")
            else:
                print("❌ Invalid choice")
        else:
            print("❌ No choice made")
    except ValueError:
        print("❌ Invalid input")

def save_model_to_env(model_name):
    """Save model selection to .env file"""
    env_file = ".env"
    env_content = f"OLLAMA_MODEL={model_name}\n"
    
    try:
        with open(env_file, 'w') as f:
            f.write(env_content)
        print(f"βœ… Model selection saved to {env_file}")
    except Exception as e:
        print(f"⚠️  Could not save to {env_file}: {e}")

def test_model():
    """Test the current model"""
    print("\nπŸ§ͺ Test Current Model")
    print("-" * 40)
    
    current_model = config.OLLAMA_MODEL
    print(f"Testing model: {current_model}")
    
    # Check if Ollama is running
    ollama_running, models = check_ollama_status()
    if not ollama_running:
        print("❌ Ollama is not running")
        return
    
    # Check if model is available
    model_names = [m.get("name") for m in models]
    if current_model not in model_names:
        print(f"❌ {current_model} is not available in Ollama")
        print(f"Available models: {', '.join(model_names)}")
        return
    
    # Test the model
    try:
        from police_runtime import PoliceBotRuntime
        
        runtime = PoliceBotRuntime()
        test_prompt = "Hello, how are you today?"
        
        print(f"Sending test prompt: '{test_prompt}'")
        response = runtime.get_llama3_response(test_prompt)
        
        if response:
            print(f"βœ… Model responded: {response[:100]}...")
        else:
            print("❌ No response from model")
            
    except Exception as e:
        print(f"❌ Error testing model: {e}")

def show_model_info():
    """Show information about the current model"""
    print("\nℹ️  Current Model Information")
    print("-" * 40)
    
    current_model = config.OLLAMA_MODEL
    model_config = config.get_current_model_config()
    
    print(f"Model: {current_model}")
    print(f"Temperature: {model_config['temperature']}")
    print(f"Top P: {model_config['top_p']}")
    print(f"Max Tokens: {model_config['max_tokens']}")
    
    print(f"\nSystem Prompt Preview:")
    print("-" * 20)
    prompt_preview = model_config['system_prompt'][:200] + "..." if len(model_config['system_prompt']) > 200 else model_config['system_prompt']
    print(prompt_preview)

def pull_model():
    """Pull a model from Ollama"""
    print("\nπŸ“₯ Pull Model from Ollama")
    print("-" * 40)
    
    model_name = input("Enter model name to pull (e.g., mistral, llama3): ").strip()
    if model_name:
        print(f"Pulling {model_name}...")
        result = os.system(f"ollama pull {model_name}")
        
        if result == 0:
            print(f"βœ… Successfully pulled {model_name}")
        else:
            print(f"❌ Failed to pull {model_name}")
    else:
        print("❌ No model name provided")

def main():
    """Main function"""
    print_banner()
    
    while True:
        print("\nOptions:")
        print("1. List available models in Ollama")
        print("2. List configured models")
        print("3. Switch model")
        print("4. Test current model")
        print("5. Show model information")
        print("6. Pull model from Ollama")
        print("7. Exit")
        
        try:
            choice = input("\nEnter choice (1-7): ").strip()
            
            if choice == '1':
                list_available_models()
            elif choice == '2':
                list_configured_models()
            elif choice == '3':
                switch_model()
            elif choice == '4':
                test_model()
            elif choice == '5':
                show_model_info()
            elif choice == '6':
                pull_model()
            elif choice == '7':
                print("Goodbye! πŸ‘‹")
                break
            else:
                print("❌ Invalid choice")
                
        except KeyboardInterrupt:
            print("\nGoodbye! πŸ‘‹")
            break
        except Exception as e:
            print(f"❌ Error: {e}")

if __name__ == "__main__":
    main()