Transcript · English → Spanish

Building Your First AI Agent

En este video, aprenderás qué son los agentes de IA,

no solo en

teoría, sino en la práctica. Veremos las ideas detrás de los agentes

modernos, y luego construiremos tu primer agente de IA

paso a

paso usando ADK de Google. Al final, entenderás cómo

los agentes razonan, actúan y se adaptan, y tendrás código que podrás

ejecutar tú mismo. Entonces, ¿qué son los agentes de IA?

En el nivel más básico, un agente es un software que no solo responde,

puede decidir y actuar. En lugar de generar una sola respuesta

como un chatbot tradicional, analiza tu solicitud y determina

qué pasos debe seguir, quizá llama a una API, ejecuta

código, analiza los resultados y luego decide qué hacer después.

Una de las explicaciones más claras proviene del artículo de investigación

ReAct, que integra de forma sinérgica el razonamiento y la acción en los modelos de lenguaje.

La idea de ese artículo era sencilla pero poderosa.

Los modelos de lenguaje no deberían generar texto de una sola vez.

En realidad pueden razonar paso a paso, realizar una acción, como llamar a una herramienta

o una API, observar los resultados, y luego decidir qué hacer después.

Ese ciclo de razonar, actuar, observar y

ajustarse es la base de cómo funcionan los agentes modernos de IA,

y concuerda con cómo se definen.

Sistemas con razonamiento y planificación, y memoria, con suficiente

autonomía para adaptarse y tomar decisiones en nombre del usuario.

Ahora bien, no todos los agentes se comportan igual.

Una forma útil de concebirlos es en tres patrones generales.

Primero, tenemos agentes secuenciales.

Funcionan paso a paso, como una cadena de montaje.

Paso uno, luego paso dos, luego paso tres. Son predecibles, pero rígidos.

Segundo, tenemos agentes reactivos. Deciden en el momento.

Observan el estado actual y preguntan: «¿Qué debo hacer ahora?» Quizá la herramienta A una

vez, la B la siguiente. Son flexibles, pero no planifican con antelación.

Por último, tenemos agentes deliberativos o de planificación.

Se detienen para esbozar un plan y luego lo ejecutan.

Piensa en reservar un viaje. No compras un vuelo al azar.

Eliges fechas, hoteles, y luego ese es el orden de los pasos

que sigues hasta completarlos.

Entonces, ¿cuál de estos es el adecuado para ti? Depende del problema.

Para flujos simples y predecibles, los secuenciales están bien.

Para situaciones dinámicas, los reactivos funcionan mejor.

Y para objetivos de varios pasos con dependencias, convienen los agentes de planificación.

Bien, esa es la visión general.

Ahora construyamos un agente, para que veas estas ideas en acción.

Crearemos un agente para redactar blogs. Le das un tema y este

generará un esquema estructurado, convertirá ese esquema en una entrada completa de blog y

luego sugerirá títulos y ganchos alternativos.

Aquí es donde entran en juego las categorías de ADK.

Mientras revisamos el código, observa cómo el planificador y el redactor

son agentes de LLM, que funcionan con un modelo.

Están integrados en agentes de bucle, que son agentes de flujo de trabajo en ADK.

Estos gestionan los reintentos automáticamente si falla la validación.

Y si alguna vez quisiéramos algo más allá de eso, ADK también nos permitiría

ampliar un agente personalizado creando una subclase de la clase base

de agente. Así que preparemos el entorno y luego revisemos el código línea por línea.

Para empezar, necesitas instalar UV.

Puedes hacerlo ejecutando el comando justo aquí.

En segundo lugar, tienes que instalar Google ADK porque

obviamente tenemos que usar

ADK en esto. Y luego creemos un archivo llamado

agent.py en tu IDE. Tenemos que

importar estas bibliotecas clave, y después podemos empezar a desarrollar nuestro

primer

agente. Así que el primer agente que estamos desarrollando se llama el

planificador de blogs. Su única tarea es tomar un tema y convertirlo

en un esquema estructurado. Le damos el nombre de planificador de blogs para que

sea fácil de identificar, y le indicamos qué modelo usar, que

proviene de nuestro archivo de entorno. La descripción es simplemente una nota legible

para humanos. La parte importante de la introducción

está aquí, donde en realidad le decimos

qué debe producir, que es un esquema en Markdown con un título, una

una breve introducción, de cuatro a seis secciones con viñetas,

y una

conclusión. Al especificarlo, hacemos que el resultado sea mucho

más fiable. Por último, observa la clave de salida.

La configuramos como esquema de blog. Esto significa que todo lo que este

agente escriba se almacenará en el estado compartido con ese nombre,

para que el siguiente agente que pueda retomarlo pueda hacerlo

automáticamente.

A continuación, añadimos un segundo agente, el comprobador de validación del esquema.

Este no escribe nada nuevo, solo verifica el esquema.

Su instrucción es estricta. Si el esquema en el estado tiene un

título, una introducción, de cuatro a seis secciones y una conclusión,

debe responder con la palabra «okay». Si falta algo, debe

responder con la palabra «retry» y explicar qué está mal.

Así podemos decidir automáticamente si aceptar el esquema o intentar

de nuevo. Para conectar el planificador y el verificador, los agrupamos dentro de un

agente de bucle llamado planificador robusto de blogs.

El bucle primero ejecuta el planificador y luego el verificador.

Si el verificador dice que está bien, terminamos.

Si el verificador dice que se reintente, el bucle ejecuta el planificador de nuevo

con las mismas instrucciones. Puede hacerlo hasta tres veces.

Esto nos da una red de seguridad, así que si el modelo olvida algo,

tiene otra

oportunidad de hacerlo bien. Ahora creamos otro agente llamado redactor

de blogs. Este toma el esquema que acabamos de guardar

en

blog_outline y lo convierte en una publicación completa de blog en Markdown

. La instrucción le dice cómo escribir.

Debe asumir que la audiencia son ingenieros de software, omitir lo

básico y centrarse en conocimientos prácticos.

Explique tanto el cómo como el porqué e incluya breves

fragmentos de código cuando sean útiles. También debe seguir la estructura del

esquema

con encabezados adecuados. El borrador final se guarda en

blog_post en el estado compartido, listo para el siguiente paso.

A continuación, añadiremos otro verificador, esta vez para la publicación.

Se llama verificador de validación de publicaciones de blog.

Examina blog_post y verifica si el artículo tiene una

introducción, secciones que coinciden con el esquema, una conclusión y explicaciones claras.

Si lo supera, el verificador dice que está bien.

Si no, dice que lo intentes de nuevo y enumera las correcciones necesarias.

Al igual que con la planificación, combinamos el escritor y su verificador

en un agente de bucle llamado redactor robusto de blogs.

Esto hace que el sistema vuelva a intentar automáticamente el paso de redacción hasta que la

validación se supere, hasta tres veces.

Ahora envolvemos cada bucle, el planificador robusto de blogs,

y el sólido redactor de blogs como herramientas.

Esto permite que el agente raíz las llame directamente sin preocuparse

por lo que sucede dentro. Por último, lo reunimos todo con el agente raíz

llamado blogger. Las instrucciones para blogger son sencillas.

Cuando un usuario le da un tema, primero llama a la herramienta de planificación para

hacer un esquema. Luego llama a la herramienta de redacción para crear el

artículo

completo y, por último, añade tres títulos alternativos

y dos ganchos del largo de un tuit.

El agente raíz solo tiene acceso a las dos herramientas que

expusimos, la de planificación y la de redacción, por lo que su flujo de trabajo

es claro y controlado. Le das un tema, lo planifica,

lo escribe, lo revisa y luego te entrega un artículo de blog

pulido. Ahora has escrito con éxito tu primer

script de agente.

El siguiente paso es ejecutarlo de verdad.

Ve a tu terminal e inícialo con este comando de

ADK Web para que puedas verlo todo en una interfaz sencilla.

Cuando esté en ejecución, abre el enlace web local de ADK en tu

navegador

y empieza a interactuar con el agente directamente.

Para empezar, voy a pedirle que genere un blog sobre

los diez

principales casos de uso de agentes de IA. Veamos cómo planifica,

escribe y entrega los resultados.

Tus subagentes trabajarán juntos para crear una entrada de blog.

Y eso es todo. Has creado y ejecutado tu primer agente de IA

con el ADK de Google. Partimos de la idea de qué son los agentes

y luego revisamos el código paso a paso,

y, por último, lo vimos

cobrar vida en la terminal. Gracias por vernos.

Consulta el cuadro de descripción para ver todos los recursos y el código mencionados en este

video. Mira este siguiente video para aprender a

conectar tu agente de IA

a un MC-

End of transcript · 1,434 words · machine translated

Original transcript (English)

In this video, you're going to learn what AI agents are, not just in theory, but in practice. We'll look at the ideas behind modern agents, and then we'll build your very first AI agent step by

step using Google's ADK. By the end, you'll understand how agents reason, act, and adapt, and you'll have code that you can actually run yourself. So what are AI agents? At the simplest level, an agent is software that doesn't just answer, it can decide and take action. Instead of generating a single response

like a traditional chatbot, it looks at your request, figures out what steps need to be taken, maybe calls an API, runs code, looks at the results, and then decides what to do next. One of the clearest explanations comes from the research paper ReAct, synergizing, reasoning, and acting in language models.

The idea in that paper was simple but powerful. Language models shouldn't just generate text in one go. They can actually reason step by step, take an action like calling a tool or API, observe the results, and then decide what to do next. That cycle of reasoning, acting, observing, and

adjusting is the foundation of how modern AI agents work, and it lines up with how it's defined. Systems with reasoning, planning, and memory, with enough autonomy to adapt and make decisions on behalf of the user. Now, not all agents behave the same way.

A useful way to think about them is in three broad patterns. First, we have sequential agents. These run step by step like an assembly line. Step one, then step two, then step three. They're predictable but rigid. Second, we have reactive agents. These decide in the moment.

They look at the current state and ask, "What should I do next?" Maybe tool A one time, tool B the next. They're flexible, but they don't plan ahead. Lastly, we have deliberate or planning agents. These pause to sketch a plan, then execute. Think about booking travel. You don't just buy a flight randomly.

You pick dates, hotels, and then that's the order of steps that you follow through. So which of these is the right one for you? It depends on the problem. For simple, predictable flows, sequential is fine. For dynamic, reactive works better.

And for multi-step goals with dependencies, you want planning agents. Okay, that's the high level view. Now let's actually build an agent, so you can see these ideas in action. We'll build a blog writing agent. You give it a topic, it will generate a structured outline, turn that outline into a full blog post, and

then suggest alternative titles and hooks. This is where ADK's categories comes in. As we walk through the code, notice how the planner and writer agent are LLM agents, which are powered by a model. They're wrapped in loop agents, which are workflow agents in ADK.

These handle retries automatically if validation fails. And if we ever wanted something beyond that, ADK would also let us extend a custom agent by subclassing the base agent. So let's set up the environment and then go line by line through the code. First off, you need to install UV.

You can do that by running the command right here. Secondly, you need to install Google ADK because we need to obviously use ADK in this. And then let's create a file called agent.py in your IDE. We need to

import these key libraries, and then we can start building out our very first agent. So the first agent that we're building out is called the blog planner. Its only job is to take a topic and turn it into a structured outline. We give it the name blog planner, so

it's easy to identify, and we tell it which model to use, which comes from our environment file. The description is just a human readable note. The important part of the introduction is here we actually tell it what to produce, which is a markdown outline with a title, a

short introduction, four to six sections with bullet points, and a conclusion. By spelling that out, we make the output much more reliable. Finally, look at the output key. We set it to blog outline. This means whatever this

agent writes will be stored in shared state under that name, so that the next agent that can pick it up can do it automatically. Next, we add a second agent, the outline validation checker. This one doesn't write anything new, it just checks the outline.

Its instruction is strict. If the outline in state has a title, an intro, four to six sections, and a conclusion, it must answer with the word okay. If something is missing, it must answer with the word retry and explain what's wrong. That way we can automatically decide whether to accept the outline or try

again. To connect the planner and the checker, we wrap them inside a loop agent called robust blog planner. The loop first runs the planner, then the checker. If the checker says okay, we're done. If the checker says retry, the loop runs the planner again

with the same instructions. It can do this up to three times. This gives us a safety net, so if the model forgets something, it has another chance to get it right. Now we create another agent called blog writer. This one takes the outline we just saved

in blog_outline and turns it into a full markdown blog post. The instruction tells it how to write. It should assume the audience is software engineers, skip the basics, and focus on practical insights.

Explain both the how and the why and include short code snippets where helpful. It should also follow the structure of the outline with proper headings. The finished draft is saved under blog_post in shared state, ready for the next step.

Next up, we're gonna add another checker, this time for the post. It's called blog post validation checker. It looks at blog_post and checks if the article has an introduction, a, sections that match the outline, a conclusion, and clear explanations. If it passes, the checker says okay.

If not, it says retry and lists the fixes which are needed. Just like with planning, we combine the writer and its checker into a loop agent called robust blog writer. This makes the system automatically retry the writing step until the validation passes, up to three times.

Now, we wrap each loop, the robust blog planner, and the robust blog writer as tools. This is what lets the root agent call them directly without worrying about what's happening inside. Finally, we put it all together with the root agent called blogger. The instructions for blogger are simple.

When a user gives it a topic, first it calls the planner tool to make an outline. Then it calls the writer tool to draft the full post, and finally, it adds three alternative titles and two tweet-length hooks.

The root agent only has access to the two tools we exposed, the planner and the writer, so its workflow is clear and controlled. You give it a topic, it plans, it writes, it checks, and then it gives you a polished blog post. You've now successfully written your first

agent script. The next step is to actually run it. Head into your terminal and launch it using this command with ADK Web so you can view everything inside a simple UI. Once that's running, open the local ADK web link in your

browser and start interacting with the agent directly. To kick things off, I'm going to ask it to generate a blog on the top 10 use cases for AI agents. Let's see how it plans,

writes, and delivers the results. Your subagents will then work together to create a blog post. And that's it. You've built and run your first AI agent with Google's ADK. We started from the idea of what agents are, then walked through the code step by step,

and finally saw it come to life in terminal. Thank you for watching. Check out the description box for all the resources and code mentioned in this video. Check out this next video to learn how to connect your AI

agent to an MC-

iPhone app Translate videos on your iPhone Paste a TikTok, Instagram or X link, add subtitles in your language and save the video to Photos.

Read any video in your language

Paste a link from X, TikTok, YouTube or Instagram. You get a page like this one.