11"""
2- Middleware flow diagram :
2+ Diagrama de flujo del middleware :
33
4- agent.run("user message ")
4+ agent.run("mensaje del usuario ")
55 │
66 ▼
77 ┌─────────────────────────────────────────────┐
88 │ Agent Middleware │
9- │ (timing, blocking, logging) │
9+ │ (temporización, bloqueo, registro) │
1010 │ │
1111 │ ┌───────────────────────────────────────┐ │
1212 │ │ Chat Middleware │ │
13- │ │ (logging, message counting) │ │
13+ │ │ (registro, conteo de mensajes) │ │
1414 │ │ │ │
1515 │ │ ┌──────────────┐ │ │
16- │ │ │ AI Model │ │ │
16+ │ │ │ Modelo IA │ │ │
1717 │ │ └──────┬───────┘ │ │
18- │ │ │ function calls │ │
18+ │ │ │ llamadas a funciones │ │
1919 │ │ ▼ │ │
2020 │ │ ┌──────────────────────────────────┐ │ │
2121 │ │ │ Function Middleware │ │ │
22- │ │ │ (logging, timing) │ │ │
22+ │ │ │ (registro, temporización) │ │ │
2323 │ │ │ │ │ │
2424 │ │ │ get_weather(), get_date(), ... │ │ │
2525 │ │ └──────────────────────────────────┘ │ │
2626 │ │ │ │ │
2727 │ │ ▼ │ │
2828 │ │ ┌──────────────┐ │ │
29- │ │ │ AI Model │ │ │
30- │ │ │ (final resp) │ │ │
29+ │ │ │ Modelo IA │ │ │
30+ │ │ │ (resp final ) │ │ │
3131 │ │ └──────────────┘ │ │
3232 │ └───────────────────────────────────────┘ │
3333 └─────────────────────────────────────────────┘
3434 │
3535 ▼
36- response
36+ respuesta
3737"""
3838
3939import asyncio
100100def get_weather (
101101 city : Annotated [str , Field (description = "The city to get the weather for." )],
102102) -> dict :
103- """Return weather data for a given city, with temperature and description ."""
103+ """Devuelve datos del clima para una ciudad dada, con temperatura y descripción ."""
104104 logger .info (f"Obteniendo clima para { city } " )
105105 if random .random () < 0.05 :
106106 return {"temperature" : 22 , "description" : "Soleado" }
@@ -109,7 +109,7 @@ def get_weather(
109109
110110
111111def get_current_date () -> str :
112- """Get the current system date as text in YYYY-MM-DD format ."""
112+ """Obtiene la fecha actual del sistema en texto con formato YYYY-MM-DD."""
113113 logger .info ("Obteniendo fecha actual" )
114114 return datetime .now ().strftime ("%Y-%m-%d" )
115115
@@ -121,7 +121,7 @@ async def timing_agent_middleware(
121121 context : AgentRunContext ,
122122 next : Callable [[AgentRunContext ], Awaitable [None ]],
123123) -> None :
124- """Agent middleware that logs execution time ."""
124+ """Middleware de agente que registra el tiempo de ejecución ."""
125125 start = time .perf_counter ()
126126 logger .info ("[⏲️ Temporización][ Agent Middleware] Iniciando ejecución del agente" )
127127
@@ -135,7 +135,7 @@ async def logging_function_middleware(
135135 context : FunctionInvocationContext ,
136136 next : Callable [[FunctionInvocationContext ], Awaitable [None ]],
137137) -> None :
138- """Function middleware that logs function calls and results ."""
138+ """Middleware de función que registra llamadas y resultados ."""
139139 logger .info (
140140 f"[🪵 Registro][ Function Middleware] Llamando a { context .function .name } con args: { context .arguments } "
141141 )
@@ -149,7 +149,7 @@ async def logging_chat_middleware(
149149 context : ChatContext ,
150150 next : Callable [[ChatContext ], Awaitable [None ]],
151151) -> None :
152- """Chat middleware that logs interactions with the AI ."""
152+ """Middleware de chat que registra interacciones con la IA ."""
153153 logger .info (f"[💬 Registro][ Chat Middleware] Enviando { len (context .messages )} mensajes a la IA" )
154154
155155 await next (context )
@@ -161,18 +161,18 @@ async def logging_chat_middleware(
161161
162162
163163class BlockingAgentMiddleware (AgentMiddleware ):
164- """Agent middleware that blocks requests with forbidden words ."""
164+ """Middleware de agente que bloquea solicitudes con palabras prohibidas ."""
165165
166166 def __init__ (self , blocked_words : list [str ]) -> None :
167- """Initialize with a list of words that should be blocked ."""
167+ """Inicializa con una lista de palabras que deben ser bloqueadas ."""
168168 self .blocked_words = blocked_words
169169
170170 async def process (
171171 self ,
172172 context : AgentRunContext ,
173173 next : Callable [[AgentRunContext ], Awaitable [None ]],
174174 ) -> None :
175- """Check messages for blocked content and terminate if found ."""
175+ """Verifica mensajes con contenido bloqueado y termina si lo encuentra ."""
176176 last_message = context .messages [- 1 ] if context .messages else None
177177 if last_message and last_message .text :
178178 for word in self .blocked_words :
@@ -192,14 +192,14 @@ async def process(
192192
193193
194194class TimingFunctionMiddleware (FunctionMiddleware ):
195- """Function middleware that measures each function call execution time ."""
195+ """Middleware de función que mide el tiempo de ejecución de cada llamada ."""
196196
197197 async def process (
198198 self ,
199199 context : FunctionInvocationContext ,
200200 next : Callable [[FunctionInvocationContext ], Awaitable [None ]],
201201 ) -> None :
202- """Measure function execution time and log the duration ."""
202+ """Mide el tiempo de ejecución de la función y registra la duración ."""
203203 start = time .perf_counter ()
204204 logger .info (f"[⌚️ Temporización][ Function Middleware] Iniciando { context .function .name } " )
205205
@@ -210,18 +210,18 @@ async def process(
210210
211211
212212class MessageCountChatMiddleware (ChatMiddleware ):
213- """Chat middleware that counts total messages sent to the AI ."""
213+ """Middleware de chat que cuenta el total de mensajes enviados a la IA ."""
214214
215215 def __init__ (self ) -> None :
216- """Initialize the message counter ."""
216+ """Inicializa el contador de mensajes ."""
217217 self .total_messages = 0
218218
219219 async def process (
220220 self ,
221221 context : ChatContext ,
222222 next : Callable [[ChatContext ], Awaitable [None ]],
223223 ) -> None :
224- """Count messages and log the running total."""
224+ """Cuenta los mensajes y registra el total acumulado ."""
225225 self .total_messages += len (context .messages )
226226 logger .info (
227227 "[🔢 Conteo][ Chat Middleware] Mensajes en esta solicitud: %s, total hasta ahora: %s" ,
@@ -262,7 +262,7 @@ async def process(
262262
263263
264264async def main () -> None :
265- """Run the agent with different inputs to demonstrate middleware behavior ."""
265+ """Ejecuta el agente con diferentes entradas para demostrar el comportamiento del middleware ."""
266266 # Solicitud normal - todo el middleware se ejecuta
267267 logger .info ("=== Solicitud Normal ===" )
268268 response = await agent .run ("¿Cómo estará el clima este fin de semana en Madrid?" )
@@ -280,7 +280,7 @@ async def extra_agent_middleware(
280280 context : AgentRunContext ,
281281 next : Callable [[AgentRunContext ], Awaitable [None ]],
282282 ) -> None :
283- """Execution middleware that only applies to this specific run ."""
283+ """Middleware de ejecución que solo aplica a esta ejecución específica ."""
284284 logger .info ("[🏃🏽♀️ Execution Middleware] Este middleware solo aplica a esta ejecución" )
285285 await next (context )
286286 logger .info ("[🏃🏽♀️ Execution Middleware] Ejecución completada" )
0 commit comments