Guía LiteLLM Proxy para macOS con UV (Principiantes)

Guía rápida para montar LiteLLM Proxy en macOS con UV: instalación, PostgreSQL, configuración de modelos OpenAI y Groq, y API unificada para múltiples proveedores

4 sept 2025 • 7 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Guía rápida LiteLLM Proxy en macOS con UV para principiantes

Objetivo Configurar un proxy de LiteLLM en Mac en 15 a 20 minutos usando el gestor de paquetes moderno UV sin crear una estructura formal de proyecto.

Qué necesitas

- Mac con macOS 10.15 o superior. - Conexión a internet. - 20 minutos. - Una clave de API de tu proveedor preferido OpenAI Anthropic Groq u otro.

Paso 1 Instalar herramientas necesarias

1.1 Homebrew si no lo tienes

Comando para comprobar brew --version

Si falla instala Homebrew con este comando en Terminal bin bash -c $(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)

1.2 Instalar UV gestor de paquetes Python moderno

brew install uv

Verifica uv --version

1.3 Instalar PostgreSQL

brew install postgresql@14

Inicia el servicio brew services start postgresql

Comprueba que está activo brew services list grep postgresql

Paso 2 Crear la base de datos

createdb litellm_db

Verifica psql -l grep litellm_db

Obtén tu usuario del sistema con whoami y guárdalo porque será tu usuario de la base de datos.

Paso 3 Crear el entorno virtual con UV

Ve a tu carpeta preferida por ejemplo Documentos cd ~/Documents

Crea y entra en la carpeta de trabajo mkdir litellm-setup y luego cd litellm-setup

Crea el entorno virtual uv venv

Actívalo source .venv/bin/activate

Importante a partir de aquí ejecuta todo dentro del entorno activo.

Paso 4 Instalar LiteLLM y dependencias

uv pip install litellm[proxy] prisma psycopg2-binary

Verifica la instalación litellm --version

Paso 5 Generar el cliente de Prisma

Localiza el archivo schema.prisma dentro del paquete instalado de litellm con find .venv -name schema.prisma -path */litellm/*

Genera el cliente usando la ruta encontrada python -m prisma generate --schema RUTA_ENCONTRADA_A_SCHEMA.PRISMA

Nota la ruta puede variar según tu versión de Python por eso es clave usar find para localizarla correctamente.

Paso 6 Crear la configuración

6.1 Archivo config.yaml crea un archivo llamado config.yaml con el siguiente contenido

litellm_settings

drop_params true

general_settings

Las opciones principales se cargarán desde variables de entorno

model_list

- model_name groq-llama3-fast

litellm_params

model groq/llama3-8b-8192

api_key os.environ/GROQ_API_KEY

- model_name gpt-3.5-turbo

litellm_params

model gpt-3.5-turbo

api_key os.environ/OPENAI_API_KEY

Guarda el archivo con tu editor preferido.

6.2 Archivo de variables de entorno .env crea un archivo llamado .env con líneas como estas reemplaza admin por el resultado de whoami si es distinto

LITELLM_MASTER_KEY=sk-1234

LITELLM_SALT_KEY=sk-1234

LITELLM_DROP_PARAMS=True

PORT=4000

STORE_MODEL_IN_DB=True

DATABASE_URL=postgresql://admin@localhost:5432/litellm_db

GROQ_API_KEY=tu-clave-groq

OPENAI_API_KEY=tu-clave-openai

ANTHROPIC_API_KEY=tu-clave-anthropic

Paso 7 Iniciar LiteLLM

Ejecuta litellm --config config.yaml --port 4000

En el primer arranque LiteLLM creará automáticamente las tablas en la base de datos. Verás mensajes indicando que el proxy está en marcha y que Uvicorn corre en https://0.0.0.0:4000.

Paso 8 Verificar que todo funciona

8.1 Abre la interfaz web en tu navegador visita https://localhost:4000

8.2 Prueba un modelo desde la UI en la sección Test Key selecciona el modelo groq-llama3-fast escribe un mensaje como Hola que tal y envía. Deberías recibir la respuesta del modelo.

8.3 Probar la API de manera opcional puedes realizar una solicitud al endpoint compatible con OpenAI chat completions con un cliente HTTP de tu preferencia asegurándote de enviar un cuerpo JSON con el modelo groq-llama3-fast y tu mensaje junto con el encabezado Authorization Bearer con tu LITELLM_MASTER_KEY.

Gestión de base de datos de LiteLLM

Con LiteLLM Proxy en marcha se almacenarán datos en PostgreSQL. Así puedes explorarlos y administrarlos.

Conectarte a la base psql -U admin -h localhost -p 5432 litellm_db y escribe tu contraseña si se solicita.

Listar tablas dentro de psql usa el comando meta dt y verás tablas como LiteLLM_AuditLog LiteLLM_BudgetTable LiteLLM_Config LiteLLM_CredentialsTable LiteLLM_CronJob LiteLLM_DailyTagSpend LiteLLM_DailyTeamSpend LiteLLM_DailyUserSpend LiteLLM_EndUserTable LiteLLM_ErrorLogs LiteLLM_GuardrailsTable LiteLLM_HealthCheckTable LiteLLM_InvitationLink LiteLLM_MCPServerTable LiteLLM_ManagedFileTable LiteLLM_ManagedObjectTable LiteLLM_ManagedVectorStoresTable LiteLLM_ModelTable LiteLLM_ObjectPermissionTable LiteLLM_OrganizationMembership LiteLLM_OrganizationTable LiteLLM_PromptTable LiteLLM_ProxyModelTable LiteLLM_SpendLogs LiteLLM_TeamMembership LiteLLM_TeamTable LiteLLM_UserNotifications LiteLLM_UserTable LiteLLM_VerificationToken _prisma_migrations.

Ver el esquema de una tabla por ejemplo d LiteLLM_SpendLogs si el nombre tiene mayúsculas usa comillas dobles al ejecutar el comando en tu terminal.

Ver algunos registros por ejemplo SELECT * FROM LiteLLM_SpendLogs LIMIT 5;

Salir de psql con q

Eliminar la base de datos Aviso esta operación es irreversible y perderás todos los datos. Conéctate a la base postgres psql -U admin -h localhost -p 5432 postgres y ejecuta DROP DATABASE litellm_db; Luego q. La próxima vez que inicies LiteLLM recreará la base y aplicará migraciones.

Limpiar datos concretos sin borrar la base Asegúrate de que el proxy no esté ejecutándose. Conéctate a litellm_db y ejecuta según tu necesidad

- Limpiar logs de solicitudes y errores TRUNCATE TABLE LiteLLM_AuditLog RESTART IDENTITY; y TRUNCATE TABLE LiteLLM_ErrorLogs RESTART IDENTITY;

- Limpiar registros de gasto detallados TRUNCATE TABLE LiteLLM_SpendLogs RESTART IDENTITY;

- Limpiar agregados diarios TRUNCATE TABLE LiteLLM_DailyUserSpend RESTART IDENTITY; TRUNCATE TABLE LiteLLM_DailyTeamSpend RESTART IDENTITY; TRUNCATE TABLE LiteLLM_DailyTagSpend RESTART IDENTITY;

- Otras tablas opcionales según tu caso LiteLLM_HealthCheckTable LiteLLM_CronJob LiteLLM_UserNotifications

Paso 9 Atajo opcional para iniciar más rápido

En lugar de un alias con comillas crea una función de shell

Abre tu configuración de shell zsh nano ~/.zshrc o bash nano ~/.bash_profile

Agrega al final una función como esta ajustando la ruta a tu carpeta de proyecto

function litellm_start() { cd /Users/admin/Documents/litellm-setup; source .venv/bin/activate; litellm --config config.yaml --port 4000; }

Recarga la configuración con source ~/.zshrc o con source ~/.bash_profile según tu shell

Ahora podrás iniciar desde cualquier carpeta ejecutando litellm_start

Solución de problemas

Problema comando no encontrado litellm Solución activa el entorno virtual con source .venv/bin/activate y vuelve a intentar.

Problema ModuleNotFoundError No module named prisma Solución instala prisma dentro del entorno activo uv pip install prisma y repite la generación del cliente de Prisma.

Problema The Client hasnt been generated yet Solución ejecuta de nuevo python -m prisma generate asegurándote de pasar la ruta correcta a schema.prisma.

Problema Error de conexión a la base de datos Solución verifica el servicio con brew services list grep postgresql si no está activo inicia con brew services start postgresql comprueba que exista la base con psql -l grep litellm_db y revisa que tu DATABASE_URL en .env tenga el usuario correcto y el nombre de base.

Problema No se encuentra config.yaml Solución ejecuta el comando litellm desde la misma carpeta donde está el archivo o pasa la ruta correcta con la opción --config.

Problema Clave de API inválida Solución revisa y actualiza las claves en tu archivo .env.

Problema El puerto 4000 ya está en uso Solución inicia con otro puerto por ejemplo litellm --config config.yaml --port 4001

Qué has conseguido

- Proxy de LiteLLM operativo en localhost 4000. - Interfaz web para gestión de modelos y llaves. - API unificada compatible con OpenAI para múltiples proveedores. - Entorno reproducible con UV. - Integración con base de datos para auditoría control de gasto y más. - Flujo listo para compartir y extender.

Por qué este setup es potente

- Interfaz unificada para OpenAI Anthropic Groq y más de 100 modelos. - Seguimiento de costes con presupuestos y reportes. - Limitación de tasa para evitar abusos. - Tooling moderno con UV más rápido y reproducible. - Base en PostgreSQL lista para escalar. - Amigable para desarrollo y equipos.

Próximos pasos

- Añade más modelos a tu config.yaml. - Crea llaves de API con permisos y límites. - Configura monitorización y alertas. - Integra tus aplicaciones usando la API compatible con OpenAI. - Escala desplegando en nubes públicas y Kubernetes.

Cómo puede ayudarte Q2BSTUDIO

En Q2BSTUDIO somos expertos en aplicaciones a medida y software a medida, inteligencia artificial, agentes IA, ciberseguridad, automatización de procesos, servicios cloud AWS y Azure, servicios inteligencia de negocio y analítica avanzada con power bi. Si quieres integrar un proxy de LLM en tus flujos de trabajo crear chatbots privados seguros o desplegarlo en producción con observabilidad alta disponibilidad y CI CD nuestro equipo puede acompañarte de principio a fin. Descubre cómo potenciamos la ia para empresas en nuestra página de inteligencia artificial y consulta nuestras opciones de despliegue y mantenimiento gestionado en servicios cloud aws y azure.

Consejos extra

- Seguridad almacena tus claves en un gestor de secretos y aplica rotación periódica. - Observabilidad activa los registros de gasto y usa paneles con power bi para visualizar uso coste por equipo y tendencias. - Buenas prácticas separa entornos dev preproducción y producción con diferentes claves y budgets. - Rendimiento usa modelos y proveedores adecuados para cada caso comparando coste latencia y calidad.

Con esto ya puedes usar cualquier LLM a través de una sola interfaz de manera eficiente segura y escalable.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat