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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Script để chuyển đổi API chatbot giữa các mode:
|
| 4 |
+
- api: Gọi HF Spaces API (mặc định)
|
| 5 |
+
- local: Dùng local model
|
| 6 |
+
- llama_cpp: Dùng llama.cpp model
|
| 7 |
+
- openai: Dùng OpenAI API
|
| 8 |
+
- anthropic: Dùng Anthropic Claude API
|
| 9 |
+
- ollama: Dùng Ollama local
|
| 10 |
+
"""
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
# Colors for terminal output
|
| 16 |
+
class Colors:
|
| 17 |
+
GREEN = '\033[92m'
|
| 18 |
+
YELLOW = '\033[93m'
|
| 19 |
+
RED = '\033[91m'
|
| 20 |
+
BLUE = '\033[94m'
|
| 21 |
+
CYAN = '\033[96m'
|
| 22 |
+
RESET = '\033[0m'
|
| 23 |
+
BOLD = '\033[1m'
|
| 24 |
+
|
| 25 |
+
def print_colored(text: str, color: str = Colors.RESET):
|
| 26 |
+
"""Print colored text."""
|
| 27 |
+
print(f"{color}{text}{Colors.RESET}")
|
| 28 |
+
|
| 29 |
+
def get_env_file():
|
| 30 |
+
"""Get .env file path."""
|
| 31 |
+
backend_dir = Path(__file__).parent
|
| 32 |
+
env_file = backend_dir / ".env"
|
| 33 |
+
return env_file
|
| 34 |
+
|
| 35 |
+
def read_env_file():
|
| 36 |
+
"""Read .env file and return as dict."""
|
| 37 |
+
env_file = get_env_file()
|
| 38 |
+
env_vars = {}
|
| 39 |
+
|
| 40 |
+
if env_file.exists():
|
| 41 |
+
with open(env_file, 'r', encoding='utf-8') as f:
|
| 42 |
+
for line in f:
|
| 43 |
+
line = line.strip()
|
| 44 |
+
if line and not line.startswith('#') and '=' in line:
|
| 45 |
+
key, value = line.split('=', 1)
|
| 46 |
+
env_vars[key.strip()] = value.strip()
|
| 47 |
+
|
| 48 |
+
return env_vars
|
| 49 |
+
|
| 50 |
+
def write_env_file(env_vars: dict):
|
| 51 |
+
"""Write .env file from dict."""
|
| 52 |
+
env_file = get_env_file()
|
| 53 |
+
|
| 54 |
+
# Read existing file to preserve comments and order
|
| 55 |
+
existing_lines = []
|
| 56 |
+
if env_file.exists():
|
| 57 |
+
with open(env_file, 'r', encoding='utf-8') as f:
|
| 58 |
+
existing_lines = f.readlines()
|
| 59 |
+
|
| 60 |
+
# Update or add LLM_PROVIDER and HF_API_BASE_URL
|
| 61 |
+
new_lines = []
|
| 62 |
+
llm_provider_set = False
|
| 63 |
+
hf_api_base_set = False
|
| 64 |
+
|
| 65 |
+
for line in existing_lines:
|
| 66 |
+
stripped = line.strip()
|
| 67 |
+
if stripped.startswith('LLM_PROVIDER='):
|
| 68 |
+
new_lines.append(f"LLM_PROVIDER={env_vars.get('LLM_PROVIDER', 'api')}\n")
|
| 69 |
+
llm_provider_set = True
|
| 70 |
+
elif stripped.startswith('HF_API_BASE_URL='):
|
| 71 |
+
new_lines.append(f"HF_API_BASE_URL={env_vars.get('HF_API_BASE_URL', 'https://davidtran999-hue-portal-backend.hf.space/api')}\n")
|
| 72 |
+
hf_api_base_set = True
|
| 73 |
+
else:
|
| 74 |
+
new_lines.append(line)
|
| 75 |
+
|
| 76 |
+
# Add if not found
|
| 77 |
+
if not llm_provider_set:
|
| 78 |
+
new_lines.append(f"LLM_PROVIDER={env_vars.get('LLM_PROVIDER', 'api')}\n")
|
| 79 |
+
if not hf_api_base_set and env_vars.get('LLM_PROVIDER') == 'api':
|
| 80 |
+
new_lines.append(f"HF_API_BASE_URL={env_vars.get('HF_API_BASE_URL', 'https://davidtran999-hue-portal-backend.hf.space/api')}\n")
|
| 81 |
+
|
| 82 |
+
with open(env_file, 'w', encoding='utf-8') as f:
|
| 83 |
+
f.writelines(new_lines)
|
| 84 |
+
|
| 85 |
+
def show_current():
|
| 86 |
+
"""Show current LLM provider configuration."""
|
| 87 |
+
env_vars = read_env_file()
|
| 88 |
+
provider = env_vars.get('LLM_PROVIDER', 'api')
|
| 89 |
+
api_url = env_vars.get('HF_API_BASE_URL', 'https://davidtran999-hue-portal-backend.hf.space/api')
|
| 90 |
+
|
| 91 |
+
print_colored("\n📊 Cấu hình hiện tại:", Colors.BOLD)
|
| 92 |
+
print_colored(f" Provider: {provider}", Colors.CYAN)
|
| 93 |
+
if provider == 'api':
|
| 94 |
+
print_colored(f" API URL: {api_url}", Colors.CYAN)
|
| 95 |
+
print()
|
| 96 |
+
|
| 97 |
+
def switch_provider(provider: str, api_url: str = None):
|
| 98 |
+
"""Switch LLM provider."""
|
| 99 |
+
env_vars = read_env_file()
|
| 100 |
+
|
| 101 |
+
valid_providers = ['api', 'local', 'llama_cpp', 'openai', 'anthropic', 'ollama', 'huggingface']
|
| 102 |
+
|
| 103 |
+
if provider not in valid_providers:
|
| 104 |
+
print_colored(f"❌ Provider không hợp lệ: {provider}", Colors.RED)
|
| 105 |
+
print_colored(f" Các provider hợp lệ: {', '.join(valid_providers)}", Colors.YELLOW)
|
| 106 |
+
return False
|
| 107 |
+
|
| 108 |
+
env_vars['LLM_PROVIDER'] = provider
|
| 109 |
+
|
| 110 |
+
if provider == 'api':
|
| 111 |
+
if api_url:
|
| 112 |
+
env_vars['HF_API_BASE_URL'] = api_url
|
| 113 |
+
elif 'HF_API_BASE_URL' not in env_vars:
|
| 114 |
+
env_vars['HF_API_BASE_URL'] = 'https://davidtran999-hue-portal-backend.hf.space/api'
|
| 115 |
+
print_colored(f"✅ Đã chuyển sang API mode (HF Spaces)", Colors.GREEN)
|
| 116 |
+
print_colored(f" API URL: {env_vars['HF_API_BASE_URL']}", Colors.CYAN)
|
| 117 |
+
elif provider == 'local':
|
| 118 |
+
print_colored(f"✅ Đã chuyển sang Local model mode", Colors.GREEN)
|
| 119 |
+
elif provider == 'llama_cpp':
|
| 120 |
+
print_colored(f"✅ Đã chuyển sang llama.cpp mode", Colors.GREEN)
|
| 121 |
+
elif provider == 'openai':
|
| 122 |
+
print_colored(f"✅ Đã chuyển sang OpenAI mode", Colors.GREEN)
|
| 123 |
+
elif provider == 'anthropic':
|
| 124 |
+
print_colored(f"✅ Đã chuyển sang Anthropic Claude mode", Colors.GREEN)
|
| 125 |
+
elif provider == 'ollama':
|
| 126 |
+
print_colored(f"✅ Đã chuyển sang Ollama mode", Colors.GREEN)
|
| 127 |
+
elif provider == 'huggingface':
|
| 128 |
+
print_colored(f"✅ Đã chuyển sang Hugging Face Inference API mode", Colors.GREEN)
|
| 129 |
+
|
| 130 |
+
write_env_file(env_vars)
|
| 131 |
+
print_colored("\n⚠️ Cần restart backend server để áp dụng thay đổi!", Colors.YELLOW)
|
| 132 |
+
return True
|
| 133 |
+
|
| 134 |
+
def main():
|
| 135 |
+
"""Main function."""
|
| 136 |
+
if len(sys.argv) < 2:
|
| 137 |
+
print_colored("\n🔧 Script chuyển đổi API Chatbot", Colors.BOLD)
|
| 138 |
+
print_colored("=" * 50, Colors.CYAN)
|
| 139 |
+
print_colored("\nCách sử dụng:", Colors.BOLD)
|
| 140 |
+
print_colored(" python chuyenapichatbot.py <provider> [api_url]", Colors.YELLOW)
|
| 141 |
+
print_colored("\nCác provider:", Colors.BOLD)
|
| 142 |
+
print_colored(" api - Gọi HF Spaces API (mặc định)", Colors.GREEN)
|
| 143 |
+
print_colored(" local - Dùng local model", Colors.CYAN)
|
| 144 |
+
print_colored(" llama_cpp - Dùng llama.cpp model", Colors.CYAN)
|
| 145 |
+
print_colored(" openai - Dùng OpenAI API", Colors.CYAN)
|
| 146 |
+
print_colored(" anthropic - Dùng Anthropic Claude API", Colors.CYAN)
|
| 147 |
+
print_colored(" ollama - Dùng Ollama local", Colors.CYAN)
|
| 148 |
+
print_colored(" huggingface - Dùng Hugging Face Inference API", Colors.CYAN)
|
| 149 |
+
print_colored("\nVí dụ:", Colors.BOLD)
|
| 150 |
+
print_colored(" python chuyenapichatbot.py api", Colors.YELLOW)
|
| 151 |
+
print_colored(" python chuyenapichatbot.py api https://custom-api.hf.space/api", Colors.YELLOW)
|
| 152 |
+
print_colored(" python chuyenapichatbot.py local", Colors.YELLOW)
|
| 153 |
+
print_colored(" python chuyenapichatbot.py current # Xem cấu hình hiện tại", Colors.YELLOW)
|
| 154 |
+
print()
|
| 155 |
+
show_current()
|
| 156 |
+
return
|
| 157 |
+
|
| 158 |
+
command = sys.argv[1].lower()
|
| 159 |
+
|
| 160 |
+
if command == 'current' or command == 'show':
|
| 161 |
+
show_current()
|
| 162 |
+
return
|
| 163 |
+
|
| 164 |
+
provider = command
|
| 165 |
+
api_url = sys.argv[2] if len(sys.argv) > 2 else None
|
| 166 |
+
|
| 167 |
+
switch_provider(provider, api_url)
|
| 168 |
+
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
main()
|
| 171 |
+
|
| 172 |
+
|