Update hf.js
Browse files4 unmodified lines5678910111213145 unmodified lines202122232425262 unmodified lines293031323334353637383940414210 unmodified lines53545556575859129 unmodified lines18919019119219319419540 unmodified lines2362372382392402412422 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254261 unmodified line4284294304314324334344354364374384391 unmodified line4414424434444454464473 unmodified lines4514524534544554564574584594604614 unmodified linesconst url = require('url');const app = express();// 启用日志app.use(morgan('dev'));// 环境变量配置const PORT = process.env.HF_PORT || 7860;const TARGET_URL = process.env.TARGET_URL || 'http://localhost:3010';const API_PATH = process.env.API_PATH || '/v1';5 unmodified lines- API Path: ${API_PATH}- Timeout: ${TIMEOUT}ms`);// 解析代理设置let proxyPool = [];if (process.env.PROXY) {proxyPool = process.env.PROXY.split(',').map(p => p.trim()).filter(p => p);2 unmodified linesif (proxyPool.length > 0) {console.log('Proxy pool initialized:');proxyPool.forEach((proxy, index) => {// 隐藏敏感信息的日志const maskedProxy = proxy.replace(/(https?:\/\/)([^:]+):([^@]+)@/, '$1$2:****@');console.log(` [${index + 1}] ${maskedProxy}`);});}}// 从代理池中随机选择一个代理function getRandomProxy() {if (proxyPool.length === 0) return null;const randomIndex = Math.floor(Math.random() * proxyPool.length);10 unmodified lines};}// 模型列表 APIapp.get('/hf/v1/models', (req, res) => {const models = {"object": "list",129 unmodified linesres.json(models);});// 代理转发,使用动态代理池app.use('/hf/v1/chat/completions', (req, res, next) => {const proxy = getRandomProxy();const targetEndpoint = `${TARGET_URL}${API_PATH}/chat/completions`;40 unmodified linesmiddleware(req, res, next);});// 首页app.get('/', (req, res) => {const htmlContent = `<!DOCTYPE html>2 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Cursor To OpenAI</title><style>:root {--primary-color: #2563eb;--bg-color: #f8fafc;--card-bg: #ffffff;}body {padding: 20px;font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;max-width: 1000px;margin: 0 auto;line-height: 1.6;background: var(--bg-color);color: #1a1a1a;}.container {padding: 20px;}.header {text-align: center;margin-bottom: 40px;}.header h1 {color: var(--primary-color);font-size: 2.5em;margin-bottom: 10px;}.info {background: #fff;padding: 25px;border-radius: 12px;box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);margin-bottom: 30px;border: 1px solid #e5e7eb;}.info-item {margin: 15px 0;padding: 10px;background: #f8fafc;border-radius: 8px;border: 1px solid #e5e7eb;}.info-label {color: #4b5563;font-size: 0.9em;margin-bottom: 5px;}.info-value {color: var(--primary-color);font-weight: 500;}.service-status {background: #dcfce7;border: 1px solid #86efac;color: #166534;padding: 8px 12px;border-radius: 6px;font-size: 0.95em;display: inline-block;margin: 15px 0;}.models {background: var(--card-bg);padding: 25px;border-radius: 12px;box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);border: 1px solid #e5e7eb;}.models h3 {color: #1a1a1a;margin-bottom: 20px;font-size: 1.5em;border-bottom: 2px solid #e5e7eb;padding-bottom: 10px;}.model-item {margin: 12px 0;padding: 15px;background: #f8fafc;border-radius: 8px;border: 1px solid #e5e7eb;transition: all 0.3s ease;display: flex;justify-content: space-between;align-items: center;}.model-item:hover {transform: translateY(-2px);box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);}.model-name {font-weight: 500;color: #1a1a1a;}.model-provider {color: #6b7280;font-size: 0.9em;padding: 4px 8px;background: #f1f5f9;border-radius: 4px;}.details {margin-top: 20px;background: #f8fafc;padding: 15px;border-radius: 8px;border: 1px solid #e5e7eb;}.details pre {background: #f1f5f9;padding: 10px;border-radius: 6px;overflow-x: auto;}@media (max-width: 768px) {body {padding: 10px;}.container {padding: 10px;}}</style></head><body><div class="container"><div class="header"><h1>Cursor To OpenAI Server</h1><p>高性能 AI 模型代理服务</p><div class="service-status">服务正在运行</div></div><div class="info"><h2>配置信息</h2><div class="info-item"><div class="info-label">服务环境</div><div class="info-value">环境变量配置模式</div></div><div class="info-item"><div class="info-label">自定义端点(基本URL)</div><div class="info-value" id="endpoint-url"></div></div><div class="info-item"><div class="info-label">目标服务</div><div class="info-value">${TARGET_URL}${API_PATH}</div></div><div class="info-item"><div class="info-label">代理状态</div><div class="info-value">${proxyPool.length > 0 ? `使用中 (${proxyPool.length}个代理)` : '未启用'}</div></div></div><div class="models"><h3>支持的模型列表</h3><div id="model-list"></div></div><div class="details"><h3>使用说明</h3><p>在客户端配置以下信息:</p><pre>API URL: http://{服务器地址}:${PORT}/hf/v1API Key: 您的API密钥</pre><p>支持兼容OpenAI格式的请求,已预配置转发到${TARGET_URL}${API_PATH}</p></div></div><script>const url = new URL(window.location.href);const link = url.protocol + '//' + url.host + '/hf/v1';document.getElementById('endpoint-url').textContent = link;fetch(link + '/models').then(response => response.json()).then(data => {const modelList = document.getElementById('model-list');data.data.forEach(model => {const div = document.createElement('div');div.className = 'model-item';div.innerHTML = \`1 unmodified line<span class="model-provider">\${model.owned_by}</span>\`;modelList.appendChild(div);});}).catch(error => {console.error('Error fetching models:', error);document.getElementById('model-list').textContent = '获取模型列表失败';});</script></body></html>1 unmodified lineres.send(htmlContent);});// 健康检查端点app.get('/health', (req, res) => {res.status(200).json({status: 'ok',3 unmodified lines});});// 启动服务app.listen(PORT, () => {console.log(`HF Proxy server is running at PORT: ${PORT}`);console.log(`Target service: ${TARGET_URL}${API_PATH}`);console.log(`Proxy status: ${proxyPool.length > 0 ? 'Enabled' : 'Disabled'}`);});4 unmodified lines5678910111213145 unmodified lines202122232425262 unmodified lines293031323334353637383940414210 unmodified lines53545556575859129 unmodified lines18919019119219319419540 unmodified lines2362372382392402412422 unmodified lines2452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126131 unmodified line6156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117121 unmodified line7147157167177187197203 unmodified lines7247257267277287297307317324 unmodified linesconst url = require('url');const app = express();// Enable loggingapp.use(morgan('dev'));// Environment variables configurationconst PORT = process.env.HF_PORT || 7860;const TARGET_URL = process.env.TARGET_URL || 'http://localhost:3010';const API_PATH = process.env.API_PATH || '/v1';5 unmodified lines- API Path: ${API_PATH}- Timeout: ${TIMEOUT}ms`);// Parse proxy settingslet proxyPool = [];if (process.env.PROXY) {proxyPool = process.env.PROXY.split(',').map(p => p.trim()).filter(p => p);2 unmodified linesif (proxyPool.length > 0) {console.log('Proxy pool initialized:');proxyPool.forEach((proxy, index) => {// Log with sensitive information maskedconst maskedProxy = proxy.replace(/(https?:\/\/)([^:]+):([^@]+)@/, '$1$2:****@');console.log(` [${index + 1}] ${maskedProxy}`);});}}// Randomly select a proxy from the poolfunction getRandomProxy() {if (proxyPool.length === 0) return null;const randomIndex = Math.floor(Math.random() * proxyPool.length);10 unmodified lines};}// Models list APIapp.get('/hf/v1/models', (req, res) => {const models = {"object": "list",129 unmodified linesres.json(models);});// Proxy forwarding using dynamic proxy poolapp.use('/hf/v1/chat/completions', (req, res, next) => {const proxy = getRandomProxy();const targetEndpoint = `${TARGET_URL}${API_PATH}/chat/completions`;40 unmodified linesmiddleware(req, res, next);});// Homepage with dark themed dashboardapp.get('/', (req, res) => {const htmlContent = `<!DOCTYPE html>2 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Cursor To OpenAI</title><link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet"><style>:root {--primary-color: #5D5CDE;--secondary-color: #4f46e5;--accent-color: #818cf8;--bg-color: #181818;--card-bg: #242424;--text-primary: #e2e8f0;--text-secondary: #94a3b8;--border-color: #374151;--success-bg: #065f46;--success-text: #a7f3d0;--input-bg: #1e1e1e;--hover-bg: #2d2d2d;}body {background-color: var(--bg-color);color: var(--text-primary);font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;transition: all 0.3s ease;}.container {max-width: 1200px;margin: 0 auto;padding: 1.5rem;}.card {background-color: var(--card-bg);border-radius: 0.75rem;border: 1px solid var(--border-color);box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);margin-bottom: 1.5rem;padding: 1.5rem;transition: transform 0.3s ease, box-shadow 0.3s ease;}.card:hover {transform: translateY(-2px);box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);}.info-item {background-color: var(--bg-color);border-radius: 0.5rem;border: 1px solid var(--border-color);margin: 0.75rem 0;padding: 0.75rem;}.service-status {background-color: var(--success-bg);color: var(--success-text);border-radius: 0.5rem;padding: 0.5rem 0.75rem;display: inline-block;font-weight: 500;margin: 1rem 0;}.model-item {background-color: var(--bg-color);border-radius: 0.5rem;border: 1px solid var(--border-color);padding: 0.75rem 1rem;margin: 0.5rem 0;display: flex;justify-content: space-between;align-items: center;transition: all 0.2s ease;}.model-item:hover {background-color: var(--hover-bg);transform: translateY(-2px);}.model-provider {background-color: var(--primary-color);color: white;border-radius: 0.25rem;padding: 0.25rem 0.5rem;font-size: 0.875rem;}.tab-button {background-color: var(--card-bg);color: var(--text-secondary);border: 1px solid var(--border-color);border-bottom: none;border-radius: 0.5rem 0.5rem 0 0;padding: 0.75rem 1.5rem;font-weight: 500;cursor: pointer;transition: all 0.2s ease;}.tab-button.active {background-color: var(--primary-color);color: white;}.tab-content {display: none;}.tab-content.active {display: block;}pre {background-color: var(--input-bg);border-radius: 0.5rem;padding: 1rem;overflow-x: auto;color: var(--text-primary);border: 1px solid var(--border-color);}input, textarea, select {background-color: var(--input-bg);border: 1px solid var(--border-color);color: var(--text-primary);padding: 0.75rem;border-radius: 0.5rem;width: 100%;font-size: 1rem;}input:focus, textarea:focus, select:focus {outline: 2px solid var(--primary-color);border-color: var(--primary-color);}button {background-color: var(--primary-color);color: white;border: none;border-radius: 0.5rem;padding: 0.75rem 1.5rem;font-weight: 500;cursor: pointer;transition: all 0.2s ease;}button:hover {background-color: var(--secondary-color);}button:disabled {opacity: 0.6;cursor: not-allowed;}.response-area {background-color: var(--input-bg);border-radius: 0.5rem;border: 1px solid var(--border-color);padding: 1rem;min-height: 200px;max-height: 500px;overflow-y: auto;white-space: pre-wrap;font-family: monospace;}.loading {display: inline-block;width: 20px;height: 20px;border: 3px solid rgba(255,255,255,.3);border-radius: 50%;border-top-color: white;animation: spin 1s ease-in-out infinite;}@keyframes spin {to { transform: rotate(360deg); }}.form-group {margin-bottom: 1.5rem;}.form-label {display: block;margin-bottom: 0.5rem;color: var(--text-secondary);}/* Light/Dark mode toggle support */@media (prefers-color-scheme: light) {:root {--bg-color: #f8fafc;--card-bg: #ffffff;--text-primary: #1a1a1a;--text-secondary: #4b5563;--border-color: #e5e7eb;--success-bg: #dcfce7;--success-text: #166534;--input-bg: #f8fafc;--hover-bg: #f1f5f9;}}</style></head><body><div class="container"><div class="text-center mt-4 mb-8"><h1 class="text-4xl font-bold mb-2" style="color: var(--primary-color);">Cursor To OpenAI Server</h1><p class="text-xl">High-performance AI Model Proxy Service</p><div class="service-status">Service is running</div></div><div class="mb-6"><div class="flex"><button id="tab-dashboard" class="tab-button active mr-2">Dashboard</button><button id="tab-interact" class="tab-button">API Interaction</button></div></div><div id="content-dashboard" class="tab-content active"><div class="card"><h2 class="text-2xl font-bold mb-4">Configuration Information</h2><div class="info-item"><div class="text-sm text-gray-400 mb-1">Service Environment</div><div class="font-medium" style="color: var(--primary-color);">Environment Variable Configuration Mode</div></div><div class="info-item"><div class="text-sm text-gray-400 mb-1">Custom Endpoint (Base URL)</div><div class="font-medium" id="endpoint-url" style="color: var(--primary-color);"></div></div><div class="info-item"><div class="text-sm text-gray-400 mb-1">Target Service</div><div class="font-medium" id="target-service" style="color: var(--primary-color);">${TARGET_URL}${API_PATH}</div></div><div class="info-item"><div class="text-sm text-gray-400 mb-1">Proxy Status</div><div class="font-medium" id="proxy-status" style="color: var(--primary-color);">${proxyPool.length > 0 ? `Enabled (${proxyPool.length} proxies)` : 'Disabled'}</div></div></div><div class="card"><h2 class="text-2xl font-bold mb-4">Supported Models</h2><div id="model-list" class="mt-4"><div class="flex justify-center"><div class="loading"></div><span class="ml-2">Loading models...</span></div></div></div><div class="card"><h2 class="text-2xl font-bold mb-4">Usage Instructions</h2><p class="mb-3">Configure the following in your client:</p><pre id="usage-instructions">API URL: http://{server-address}:${PORT}/hf/v1API Key: Your API Key</pre><p class="mt-3">Supports requests compatible with OpenAI format, pre-configured for forwarding to the target service.</p></div></div><div id="content-interact" class="tab-content"><div class="card"><h2 class="text-2xl font-bold mb-4">Test API Interaction</h2><div class="form-group"><label class="form-label">Model</label><select id="model-select" class="text-base"><option value="">Loading models...</option></select></div><div class="form-group"><label class="form-label">System Message (optional)</label><input id="system-message" type="text" placeholder="You are a helpful AI assistant" class="text-base" /></div><div class="form-group"><label class="form-label">User Message</label><textarea id="user-message" rows="4" placeholder="Enter your message here" class="text-base"></textarea></div><div class="form-group"><label class="form-label">Temperature (0-2)</label><input id="temperature" type="range" min="0" max="2" step="0.1" value="0.7" /><div class="flex justify-between"><span>0 (More deterministic)</span><span id="temp-value">0.7</span><span>2 (More random)</span></div></div><div class="form-group"><button id="send-button" class="w-full">Send Request</button></div><div class="mt-6"><h3 class="text-xl font-bold mb-3">Response</h3><div id="response-container" class="response-area">No response yet.</div></div></div></div></div><script>// Set up UI elements with server configdocument.addEventListener('DOMContentLoaded', function() {// Handle tabsconst tabButtons = document.querySelectorAll('.tab-button');const tabContents = document.querySelectorAll('.tab-content');tabButtons.forEach(button => {button.addEventListener('click', () => {const target = button.id.replace('tab-', 'content-');// Update active tab buttontabButtons.forEach(btn => btn.classList.remove('active'));button.classList.add('active');// Update visible contenttabContents.forEach(content => content.classList.remove('active'));document.getElementById(target).classList.add('active');});});// Set up configuration infoconst url = new URL(window.location.href);const link = url.protocol + '//' + url.host + '/hf/v1';document.getElementById('endpoint-url').textContent = link;// Update usage instructionsdocument.getElementById('usage-instructions').textContent = \`API URL: \${link}API Key: Your API Key\`;// Fetch and display modelsfetchModels();// Set up temperature sliderconst tempSlider = document.getElementById('temperature');const tempValue = document.getElementById('temp-value');tempSlider.addEventListener('input', () => {tempValue.textContent = tempSlider.value;});// Set up API interactiondocument.getElementById('send-button').addEventListener('click', sendAPIRequest);});// Fetch models from the APIasync function fetchModels() {try {const url = new URL(window.location.href);const link = url.protocol + '//' + url.host + '/hf/v1/models';const response = await fetch(link);const data = await response.json();// Populate model list in dashboardconst modelList = document.getElementById('model-list');modelList.innerHTML = '';// Populate model select dropdownconst modelSelect = document.getElementById('model-select');modelSelect.innerHTML = '';data.data.forEach(model => {// Add to dashboard listconst div = document.createElement('div');div.className = 'model-item';div.innerHTML = \`1 unmodified line<span class="model-provider">\${model.owned_by}</span>\`;modelList.appendChild(div);// Add to select dropdownconst option = document.createElement('option');option.value = model.id;option.textContent = model.id;modelSelect.appendChild(option);});} catch (error) {console.error('Error fetching models:', error);document.getElementById('model-list').innerHTML = '<div class="text-red-500">Failed to load models</div>';document.getElementById('model-select').innerHTML = '<option value="">Failed to load models</option>';}}// Send API request for interaction tabasync function sendAPIRequest() {const modelSelect = document.getElementById('model-select');const systemMessage = document.getElementById('system-message');const userMessage = document.getElementById('user-message');const temperature = document.getElementById('temperature');const responseContainer = document.getElementById('response-container');const sendButton = document.getElementById('send-button');// Validate inputsif (!modelSelect.value) {responseContainer.textContent = 'Error: Please select a model';return;}if (!userMessage.value.trim()) {responseContainer.textContent = 'Error: Please enter a user message';return;}// Prepare requestconst url = new URL(window.location.href);const endpoint = url.protocol + '//' + url.host + '/hf/v1/chat/completions';const payload = {model: modelSelect.value,messages: [...(systemMessage.value.trim() ? [{ role: 'system', content: systemMessage.value }] : []),{ role: 'user', content: userMessage.value }],temperature: parseFloat(temperature.value),stream: false};// Show loading statesendButton.disabled = true;responseContainer.innerHTML = '<div class="flex justify-center"><div class="loading"></div><span class="ml-2">Waiting for response...</span></div>';try {const response = await fetch(endpoint, {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify(payload)});const data = await response.json();if (response.ok) {if (data.choices && data.choices.length > 0) {const messageContent = data.choices[0].message.content;responseContainer.textContent = messageContent;} else {responseContainer.textContent = 'Received an empty response from the API.';}} else {responseContainer.textContent = \`Error: \${data.error?.message || 'Unknown error'}\`;}} catch (error) {responseContainer.textContent = \`Error: \${error.message || 'Failed to send request'}\`;} finally {sendButton.disabled = false;}}// Light/Dark mode supportif (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {document.documentElement.classList.add('dark');}window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {if (event.matches) {document.documentElement.classList.add('dark');} else {document.documentElement.classList.remove('dark');}});</script></body></html>1 unmodified lineres.send(htmlContent);});// Health check endpointapp.get('/health', (req, res) => {res.status(200).json({status: 'ok',3 unmodified lines});});// Start serverapp.listen(PORT, () => {console.log(`HF Proxy server is running at PORT: ${PORT}`);console.log(`Target service: ${TARGET_URL}${API_PATH}`);console.log(`Proxy status: ${proxyPool.length > 0 ? 'Enabled' : 'Disabled'}`);});
hf.js+416-145