Transcript · English → Spanish
Building AI Agents with Google's ADK
En este video, vas a aprender 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ísimo agente de IA
paso a paso usando el ADK de Google.
Al final, entenderás cómo razonan los agentes,
actúan y se adaptan.
Y tendrás código que realmente podrás ejecutar tú mismo.
Entonces, ¿qué son los agentes de IA?
En el nivel más simple, un agente es un software
que no solo responde, sino que puede decidir y actuar.
En lugar de generar una sola respuesta
como un chatbot tradicional,
analiza tu solicitud,
determina qué pasos se deben seguir,
tal vez llama a una API, ejecuta código,
observa los resultados y luego decide qué hacer a continuación.
Una de las explicaciones más claras
proviene del artículo de investigación REACT,
Sinergizar, razonar y actuar en modelos de lenguaje.
La idea de ese artículo era simple pero poderosa.
Los modelos de lenguaje no deberían limitarse a generar texto de una sola vez.
De hecho, pueden razonar paso a paso,
realizar una acción como llamar a una herramienta o API,
observar los resultados y luego decidir qué hacer a continuación.
Ese ciclo de razonamiento, acción, observación y ajuste
es la base de cómo funcionan los agentes de IA modernos.
Y coincide con cómo se define.
Sistemas con razonamiento, 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 de la misma manera.
Una forma útil de pensar en ellos es en tres grandes patrones.
Primero, tenemos los agentes secuenciales.
Estos se ejecutan paso a paso, como una línea de montaje.
Paso uno, luego paso dos, luego paso tres.
Son predecibles pero rígidos.
En segundo lugar, tenemos agentes reactivos.
Estos deciden en el momento.
Miran el estado actual y se preguntan:
¿qué debería hacer a continuación?
Tal vez la herramienta A una vez, la herramienta B la siguiente.
Son flexibles, pero no planifican con antelación.
Por último, tenemos agentes deliberativos o de planificación.
Estos se detienen a esbozar un plan y luego lo ejecutan.
Piense en reservar un viaje.
No se compra un vuelo al azar.
Se eligen fechas, hoteles,
y ese es el orden de pasos que se debe seguir.
Entonces, ¿cuál de estos es el adecuado para usted?
Depende del problema.
Para flujos sencillos y predecibles, el secuencial está bien.
Para los dinámicos, el reactivo funciona mejor.
Y para objetivos de varios pasos con dependencias,
querrá agentes de planificación.
Bien, esa es la visión general.
Ahora, construyamos un agente.
para que puedas ver estas ideas en acción.
Crearemos un agente de redacción de blogs.
Le das un tema, generará un esquema estructurado,
convertirá ese esquema en una publicación de blog completa,
y luego sugerirá títulos alternativos y ganchos.
Aquí es donde entran las categorías de ADK.
A medida que repasamos el código,
observa cómo el agente planificador y el redactor son agentes LLM,
que funcionan con un modelo.
Están envueltos en agentes de bucle,
que son agentes de flujo de trabajo en ADK.
Estos manejan 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 extender un agente personalizado
creando una subclase del agente base.
Así que configuremos el entorno
y luego vayamos línea por línea a través del código.
En primer lugar, debes instalar UV.
Puedes hacerlo ejecutando el comando que aparece aquí.
En segundo lugar, necesitas instalar el ADK de Google
porque obviamente necesitamos usar el ADK en esto.
Y luego, creemos un archivo llamado agent.py en tu IDE.
Necesitamos importar estas librerías clave,
y luego podemos empezar a construir nuestro primer agente.
Así que el primer agente que estamos construyendo
se llama planificador de blogs.
Su único trabajo 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 decimos qué modelo usar,
el cual proviene de nuestro archivo de entorno.
La descripción es solo una nota legible para humanos.
La parte importante de la introducción
es que aquí realmente le decimos qué producir,
que es un esquema en markdown con un título,
una breve introducción, de cuatro a seis secciones
con viñetas y una conclusión.
Al detallar eso, hacemos que el resultado sea mucho más confiable.
Finalmente, mira la clave de salida.
La configuramos como esquema del blog.
Esto significa que lo que sea que escriba este agente
se guardará en el estado compartido bajo ese nombre
para que el siguiente agente que lo reciba
pueda hacerlo automáticamente.
A continuación, agregamos un segundo agente,
el verificador 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.
De esa manera podemos decidir automáticamente
si aceptamos el esquema o lo intentamos de nuevo.
Para conectar el planificador y el verificador,
los hemos envuelto dentro de un agente de bucle
llamado planificador de blog robusto.
El bucle primero ejecuta el planificador,
luego el verificador.
Si el verificador dice que está bien, terminamos.
Si el verificador dice reintentar,
el bucle ejecuta el planificador de nuevo
con las mismas instrucciones.
Puede hacer esto hasta tres veces.
Esto nos da una red de seguridad
por si el modelo olvida algo,
tenga otra oportunidad de hacerlo bien.
Ahora creamos otro agente llamado redactor de blog.
Este toma el esquema que acabamos de guardar
en blog guion bajo outline
y lo convierte en una publicación de blog completa en markdown.
La instrucción le indica cómo escribir.
Debe asumir que la audiencia son ingenieros de software,
omitir lo básico y centrarse en ideas prácticas,
explicar tanto el cómo como el porqué
e incluir fragmentos cortos de código donde sea útil.
También debe seguir la estructura del esquema
con los encabezados adecuados.
El borrador terminado se guarda bajo blog_post
en el estado compartido, listo para el siguiente paso.
A continuación, vamos a añadir otro verificador,
esta vez para la publicación.
Se llama blog post validation checker.
Examina blog_post
y comprueba si el artículo tiene una introducción,
secciones que coincidan con el esquema,
una conclusión y explicaciones claras.
Si la supera, el verificador dice: de acuerdo.
Si no, dice reintentar y enumera las correcciones necesarias.
Al igual que con la planificación,
combinamos al redactor y su verificador
en un agente de bucle llamado robust blog writer.
Esto hace que el sistema reintente automáticamente el paso de escritura
hasta que se supere la validación, hasta un máximo de tres veces.
Ahora envolvemos cada bucle, el robust blog planner
y el robust blog writer como herramientas.
Esto es lo que permite al agente raíz llamarlos directamente
sin preocuparse por lo que ocurre dentro.
Finalmente, lo juntamos 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 redactar la publicación completa
y finalmente añade tres títulos alternativos
y dos ganchos de la longitud de un tuit.
El agente raíz solo tiene acceso a las dos herramientas que expusimos,
el planificador y el redactor.
Así que su flujo de trabajo es claro y controlado.
Le das un tema, planifica, escribe, comprueba,
y luego te da una publicación de blog pulida.
Ya has escrito con éxito tu primer script de agente.
El siguiente paso es ejecutarlo realmente.
Ve a tu terminal y ejecútalo
usando este comando con ADK web.
Así podrás ver todo dentro de una interfaz de usuario sencilla.
Una vez que esté funcionando, abre el enlace local de ADK web
en tu navegador y empieza a interactuar
directamente con el agente.
Para empezar, le voy a pedir que genere un blog
sobre los diez principales casos de uso de los agentes de IA.
Veamos cómo planifica, escribe y entrega los resultados.
Luego, tus subagentes trabajarán juntos
para crear una publicación de blog.
Y eso es todo.
Has creado y ejecutado tu primer agente de IA con ADK de Google.
Comenzamos con la idea de qué son los agentes,
luego repasamos el código paso a paso
y finalmente lo vimos cobrar vida en la Terminal.
Gracias por ver.
Echa un vistazo a la descripción.
End of transcript · 1,417 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've wrapped 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 underscore 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 underscore 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 underscore post and checks if the article has an introduction,
sections that match the outline, a conclusion and clear explanations. If it passes, the checker says, okay. If not, it says retry and list 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 sub-agents 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.