← Why I am learning Python for AI without abandoning TypeScript
Why I am learning Python for AI without abandoning TypeScript
English ↔ Español
Why I added Python to my stack
After years of working primarily in JavaScript and TypeScript, I got very close to a comfortable conclusion: I can build almost everything I need with this ecosystem.
Node/Nest on the backend, React/Next on the frontend, workers, queues, integrations, streaming, and LLM APIs. And I still prefer the syntax for a lot of everyday code.
Give me these two lines:
const activeUsers = users.filter(user => user.active)
active_users = [user for user in users if user.active]
My brain still picks the first one without scheduling a meeting.
Even so, I decided to learn Python properly for AI and use FastAPI at that boundary.
Not because "Python is mandatory." Because I started separating two questions I had been treating as one:
- which language do I prefer?
- which ecosystem removes more work for this specific problem?
JavaScript did not suddenly become worse
This was the first thing I needed to get clear.
Adding Python does not mean admitting that Node.js is inadequate for AI.
For a huge number of products, TypeScript remains excellent for:
- calling OpenAI, Anthropic, Gemini, Kimi, or Groq;
- streaming responses;
- tool calling;
- straightforward RAG;
- SaaS integrations;
- web orchestration;
- queues and workers;
- product APIs;
- authentication and billing;
- AI SDK applications;
- agents whose main job is coordinating web tools.
If the core value of the system is business logic and AI is one dependency among many, I see no reason to abandon the ecosystem that already delivers the rest of the product well.
Where Python started winning for me
The difference appeared when a project moved from simply consuming models to doing more AI engineering.
Examples include:
- notebooks for experimentation;
- embedding evaluation;
- datasets;
- ML pipelines;
- academic libraries;
- computer vision and audio tooling;
- local inference;
- Hugging Face;
- PyTorch;
- experiments that start in papers and land in Python first.
Some of this can be reached from JavaScript. The better question is: why would I add friction in exactly the area where I am trying to learn faster?
The architecture that makes sense to me
Instead of thinking "I am moving to Python," I started thinking in boundaries.
┌───────────────────────────────────────────┐
│ Product │
│ Next.js / TypeScript │
│ auth, UI, billing, workflows, webhooks │
└─────────────────┬─────────────────────────┘
│ HTTP / queue / events
┌─────────────────▼─────────────────────────┐
│ AI service │
│ FastAPI / Python │
│ models, evals, RAG, ML, local inference │
└───────────────────────────────────────────┘
Not every project needs this. An unnecessary extra service is just an operational tax.
But when the boundary is real, it becomes clean: the product remains TypeScript; the component where Python has a meaningful ecosystem advantage becomes Python.
Why FastAPI
I considered a few options, but FastAPI maps well to the way I already think about backend systems.
A simple route is predictable:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class AnalyzeRequest(BaseModel):
text: str
class AnalyzeResponse(BaseModel):
category: str
confidence: float
@app.post('/analyze', response_model=AnalyzeResponse)
async def analyze(payload: AnalyzeRequest) -> AnalyzeResponse:
result = await classifier.classify(payload.text)
return AnalyzeResponse(
category=result.category,
confidence=result.confidence,
)
Anyone coming from NestJS recognizes the concepts immediately:
- input contracts;
- validation;
- output contracts;
- dependency injection when needed;
- OpenAPI;
- separation by layer.
I do not need to become a framework collector to apply good architecture in Python.
The danger: writing Node.js with Python syntax
This is a mistake I am consciously trying to avoid.
Learning a language is not only figuring out how it spells for, class, and async. It also means learning the conventions that make code in that ecosystem readable.
My practical learning path is therefore focused on:
- modern Python and typing;
uvfor environments and dependencies;- Pydantic;
- FastAPI;
pytest;- async/await and concurrency;
- notebooks when they actually help;
- the data/AI ecosystem;
- packaging and deployment.
The goal is not to memorize the entire language. It is to reach the point where I can judge Python code without mentally translating every line into TypeScript.
Typed interfaces reduce friction between stacks
Once two languages coexist, contracts matter even more.
I prefer explicit boundaries:
{
"documentId": "doc_123",
"analysis": {
"category": "quality-complaint",
"confidence": 0.94,
"evidence": ["line 12", "line 48"]
}
}
OpenAPI helps a lot here.
A FastAPI service can publish its schema, while the TypeScript side generates or validates a client. The language changes; the contract does not become implicit.
For asynchronous work, the boundary can also be a queue:
Node publishes job → Python worker processes → result event → Node updates product
The important part is avoiding a tightly coupled hybrid where each side knows internal details of the other.
What stays in TypeScript
My current heuristic is simple.
I start with TypeScript when the problem is mostly:
- web product;
- integrations;
- business rules;
- traditional APIs;
- SaaS automation;
- agents with many web tools;
- realtime systems.
I pull in Python when the problem leans heavily toward:
- ML;
- scientific experimentation;
- local models;
- AI-oriented data pipelines;
- libraries that treat Python as first-class;
- evaluation tied closely to the research ecosystem.
This is not a law. It is a heuristic that prevents language choice from becoming identity.
A realistic example: analyzing quality complaints
Imagine an internal system that receives complex spreadsheets, normalizes complaints, groups likely causes, and feeds a dashboard.
I could organize it like this:
Desktop / Web UI
↓
Application API
↓
parser and normalization
↓
classification / embeddings / clustering
↓
verifiable rules
↓
analytical database
↓
Power BI
The product side can stay in a familiar stack. Clustering, embeddings, experimental parsing, and model evaluation would probably give me more options in Python.
Each ecosystem gets to do what it does best.
The bigger insight was not about Python
The real insight was noticing that I had been optimizing too early for one single stack.
A consistent stack is great. A dogmatic stack is not.
Too many services are bad. Too many languages are bad too. But insisting on a familiar tool can create a different kind of complexity: adapters, bindings, less mature libraries, and time spent fighting the ecosystem.
Today I would rather ask:
what is the smallest number of technologies that gives this product access to the best tools for the job?
Sometimes the answer is still full TypeScript.
For deeper AI systems, I am increasingly comfortable with the answer being TypeScript and Python.
That is fine.
My goal with FastAPI
I do not want to become someone who knows twenty Python frameworks superficially.
I want enough depth to build a production AI service with:
- clear contracts;
- tests;
- observability;
- queues when needed;
- asynchronous processing;
- domain isolation;
- reproducible deployment;
- model evaluation separated from opinion.
In other words, the same engineering concerns I had before Python entered the picture.
The language changes. Engineering is still engineering.
References
Por qué añadí Python a mi stack
Después de años trabajando principalmente con JavaScript y TypeScript, llegué muy cerca de una conclusión cómoda: puedo construir prácticamente todo lo que necesito con este ecosistema.
Node/Nest en backend, React/Next en frontend, workers, colas, integraciones, streaming y APIs de LLM. Y sigo prefiriendo la sintaxis para muchas cosas del día a día.
Si me das estas dos líneas:
const activeUsers = users.filter(user => user.active)
active_users = [user for user in users if user.active]
mi cerebro todavía elige la primera sin convocar una reunión.
Aun así, decidí aprender Python de verdad para IA y usar FastAPI en esa frontera.
No porque "Python sea obligatorio". Sino porque empecé a separar dos preguntas que estaba tratando como si fueran una sola:
- ¿qué lenguaje prefiero?
- ¿qué ecosistema elimina más trabajo en este problema concreto?
JavaScript no se volvió peor de repente
Esto fue lo primero que tuve que aclarar.
Añadir Python a la stack no significa admitir que Node.js sea inadecuado para IA.
Para una enorme cantidad de productos, TypeScript sigue siendo excelente para:
- llamar OpenAI, Anthropic, Gemini, Kimi o Groq;
- streaming de respuestas;
- tool calling;
- RAG sencillo;
- integraciones SaaS;
- orquestación web;
- colas y workers;
- APIs de producto;
- autenticación y billing;
- aplicaciones con AI SDK;
- agentes cuyo trabajo principal es integrar herramientas web.
Si el valor principal del sistema está en las reglas de negocio y la IA es una dependencia más, no veo motivo para abandonar el ecosistema que ya entrega bien el resto del producto.
Dónde Python empezó a ganar para mí
La diferencia apareció cuando el proyecto dejó de limitarse a consumir modelos y empezó a hacer más ingeniería de IA.
Algunos ejemplos:
- notebooks para experimentación;
- evaluación de embeddings;
- datasets;
- pipelines de ML;
- librerías académicas;
- herramientas de visión y audio;
- inferencia local;
- Hugging Face;
- PyTorch;
- experimentos que nacen en papers y llegan primero a Python.
Parte de esto se puede usar desde JavaScript. La mejor pregunta es: ¿por qué añadiría fricción justo en el área donde estoy intentando aprender más rápido?
La arquitectura que tiene más sentido para mí
En lugar de pensar "voy a migrar a Python", empecé a pensar en fronteras.
┌───────────────────────────────────────────┐
│ Producto │
│ Next.js / TypeScript │
│ auth, UI, billing, workflows, webhooks │
└─────────────────┬─────────────────────────┘
│ HTTP / queue / events
┌─────────────────▼─────────────────────────┐
│ Servicio de IA │
│ FastAPI / Python │
│ models, evals, RAG, ML, local inference │
└───────────────────────────────────────────┘
No todo proyecto necesita esto. Un servicio extra sin necesidad es solo un impuesto operativo.
Pero cuando la frontera existe de verdad, queda clara: el producto sigue en TypeScript; el componente donde Python tiene una ventaja real de ecosistema pasa a Python.
Por qué FastAPI
Consideré varias opciones, pero FastAPI encaja bien con la forma en que ya pienso backend.
Una ruta sencilla es predecible:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class AnalyzeRequest(BaseModel):
text: str
class AnalyzeResponse(BaseModel):
category: str
confidence: float
@app.post('/analyze', response_model=AnalyzeResponse)
async def analyze(payload: AnalyzeRequest) -> AnalyzeResponse:
result = await classifier.classify(payload.text)
return AnalyzeResponse(
category=result.category,
confidence=result.confidence,
)
Quien viene de NestJS reconoce los conceptos de inmediato:
- contrato de entrada;
- validación;
- contrato de salida;
- inyección de dependencias cuando hace falta;
- OpenAPI;
- separación por capas.
No necesito convertirme en coleccionista de frameworks para aplicar buena arquitectura en Python.
El peligro: escribir Node.js con sintaxis de Python
Es un error que intento evitar conscientemente.
Aprender un lenguaje no consiste solo en descubrir cómo escribe for, class y async. También significa aprender las convenciones que hacen legible el código de ese ecosistema.
Por eso mi ruta práctica está enfocada en:
- Python moderno y typing;
uvpara entornos y dependencias;- Pydantic;
- FastAPI;
pytest;- async/await y concurrencia;
- notebooks cuando realmente ayudan;
- ecosistema de datos/IA;
- packaging y deploy.
El objetivo no es memorizar todo el lenguaje. Es llegar al punto en que pueda juzgar código Python sin traducir mentalmente cada línea a TypeScript.
Interfaces tipadas reducen fricción entre stacks
Cuando conviven dos lenguajes, los contratos importan aún más.
Prefiero fronteras explícitas:
{
"documentId": "doc_123",
"analysis": {
"category": "quality-complaint",
"confidence": 0.94,
"evidence": ["line 12", "line 48"]
}
}
OpenAPI ayuda bastante aquí.
Un servicio FastAPI puede publicar su schema y el lado TypeScript puede generar o validar el cliente. Cambia el lenguaje; el contrato no se vuelve implícito.
Para trabajo asíncrono, la frontera también puede ser una cola:
Node publica job → worker Python procesa → evento de resultado → Node actualiza producto
Lo importante es evitar un híbrido fuertemente acoplado donde cada lado conozca detalles internos del otro.
Qué se queda en TypeScript
Mi heurística actual es simple.
Empiezo con TypeScript cuando el problema es principalmente:
- producto web;
- integraciones;
- reglas de negocio;
- APIs tradicionales;
- automatización SaaS;
- agentes con muchas herramientas web;
- realtime.
Traigo Python cuando entran con fuerza:
- ML;
- experimentación científica;
- modelos locales;
- pipelines de datos orientados a IA;
- librerías que tratan Python como first-class;
- evaluación muy ligada al ecosistema de investigación.
No es una ley. Es una heurística para que la elección de lenguaje no se convierta en identidad.
Un ejemplo realista: análisis de reclamaciones de calidad
Imagina un sistema interno que recibe hojas de cálculo complejas, normaliza reclamaciones, agrupa causas probables y alimenta un dashboard.
Podría organizarlo así:
Desktop / Web UI
↓
API de aplicación
↓
parser y normalización
↓
clasificación / embeddings / clustering
↓
reglas verificables
↓
base analítica
↓
Power BI
La parte de producto puede quedarse en una stack conocida. Clustering, embeddings, parsing experimental y evaluación de modelos probablemente me den más opciones en Python.
Cada ecosistema hace lo que mejor sabe hacer.
El insight más importante no fue sobre Python
El insight real fue notar que estaba optimizando demasiado pronto para una única stack.
Una stack consistente es excelente. Una stack dogmática no.
Demasiados servicios son malos. Demasiados lenguajes también. Pero insistir en una herramienta solo porque es familiar puede crear otro tipo de complejidad: adapters, bindings, librerías menos maduras y tiempo perdido luchando con el ecosistema.
Hoy prefiero preguntar:
¿cuál es la menor cantidad de tecnologías que le da a este producto acceso a las mejores herramientas para el problema?
A veces la respuesta sigue siendo full TypeScript.
En sistemas de IA más profundos, cada vez me resulta más natural que la respuesta sea TypeScript y Python.
Y está bien.
Mi objetivo con FastAPI
No quiero convertirme en alguien que conoce veinte frameworks Python de forma superficial.
Quiero suficiente profundidad para construir un servicio de IA de producción con:
- contratos claros;
- tests;
- observabilidad;
- colas cuando haga falta;
- procesamiento asíncrono;
- aislamiento de dominio;
- deploy reproducible;
- evaluación de modelos separada de opiniones.
Es decir: las mismas preocupaciones de ingeniería que tenía antes de que Python entrara en la historia.
Cambia el lenguaje. La ingeniería sigue siendo ingeniería.