Skip to content

Commit 87417de

Browse files
committed
Spanish updates
1 parent a23e190 commit 87417de

12 files changed

Lines changed: 997 additions & 330 deletions

examples/spanish/agent_mcp_local.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,14 @@
4444

4545

4646
async def main() -> None:
47-
"""Ejecuta un agente conectado a un servidor MCP local para registrar gastos."""
47+
"""Run an agent connected to a local MCP server to log expenses."""
4848
async with (
49-
MCPStreamableHTTPTool(name="Servidor MCP de Gastos", url=MCP_SERVER_URL) as mcp_server,
49+
MCPStreamableHTTPTool(name="Expenses MCP Server", url=MCP_SERVER_URL) as mcp_server,
5050
ChatAgent(
5151
chat_client=client,
5252
instructions=(
5353
"Ayudas a la gente con tareas usando las herramientas disponibles. "
5454
f"La fecha de hoy es {datetime.now().strftime('%Y-%m-%d')}. "
55-
"Responde en español."
5655
),
5756
tools=[mcp_server],
5857
) as agent,

examples/spanish/agent_mcp_remote.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242

4343

4444
async def main() -> None:
45-
"""Ejecuta un agente que usa un servidor MCP remoto (Microsoft Learn) para responder preguntas de documentación."""
45+
"""Run an agent that uses a remote MCP server (Microsoft Learn) to answer documentation questions."""
4646
async with (
4747
MCPStreamableHTTPTool(
4848
name="Microsoft Learn MCP",
@@ -53,7 +53,6 @@ async def main() -> None:
5353
instructions=(
5454
"Ayudas con preguntas sobre la documentación de Microsoft. "
5555
"Usa las herramientas disponibles para buscar documentación relevante. "
56-
"Responde en español."
5756
),
5857
tools=[mcp_server],
5958
) as agent,

examples/spanish/agent_middleware.py

Lines changed: 45 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,39 @@
11
"""
2-
Diagrama de flujo del middleware:
2+
Middleware flow diagram:
33
4-
agent.run("mensaje del usuario")
4+
agent.run("user message")
55
66
77
┌─────────────────────────────────────────────┐
8-
│ Middleware de Agente
9-
│ (temporización, bloqueo, registro)
8+
Agent Middleware
9+
│ (timing, blocking, logging)
1010
│ │
1111
│ ┌───────────────────────────────────────┐ │
12-
│ │ Middleware de Chat │ │
13-
│ │ (registro, conteo de mensajes) │ │
12+
│ │ Chat Middleware │ │
13+
│ │ (logging, message counting) │ │
1414
│ │ │ │
1515
│ │ ┌──────────────┐ │ │
16-
│ │ │ Modelo IA │ │ │
16+
│ │ │ AI Model │ │ │
1717
│ │ └──────┬───────┘ │ │
18-
│ │ │ llamadas a funciones │ │
18+
│ │ │ function calls │ │
1919
│ │ ▼ │ │
2020
│ │ ┌──────────────────────────────────┐ │ │
21-
│ │ │ Middleware de Funciones │ │ │
22-
│ │ │ (registro, temporización) │ │ │
21+
│ │ │ Function Middleware │ │ │
22+
│ │ │ (logging, timing) │ │ │
2323
│ │ │ │ │ │
2424
│ │ │ get_weather(), get_date(), ... │ │ │
2525
│ │ └──────────────────────────────────┘ │ │
2626
│ │ │ │ │
2727
│ │ ▼ │ │
2828
│ │ ┌──────────────┐ │ │
29-
│ │ │ Modelo IA │ │ │
30-
│ │ │ (resp final) │ │ │
29+
│ │ │ AI Model │ │ │
30+
│ │ │ (final resp) │ │ │
3131
│ │ └──────────────┘ │ │
3232
│ └───────────────────────────────────────┘ │
3333
└─────────────────────────────────────────────┘
3434
3535
36-
respuesta
36+
response
3737
"""
3838

3939
import asyncio
@@ -49,7 +49,7 @@
4949
from agent_framework import (
5050
AgentMiddleware,
5151
AgentRunContext,
52-
AgentRunResponse,
52+
AgentResponse,
5353
ChatAgent,
5454
ChatContext,
5555
ChatMessage,
@@ -98,9 +98,9 @@
9898

9999

100100
def get_weather(
101-
city: Annotated[str, Field(description="La ciudad para consultar el clima.")],
101+
city: Annotated[str, Field(description="The city to get the weather for.")],
102102
) -> dict:
103-
"""Devuelve datos del clima para una ciudad dada, un diccionario con temperatura y descripción."""
103+
"""Return weather data for a given city, with temperature and description."""
104104
logger.info(f"Obteniendo clima para {city}")
105105
if random.random() < 0.05:
106106
return {"temperature": 22, "description": "Soleado"}
@@ -109,77 +109,77 @@ def get_weather(
109109

110110

111111
def get_current_date() -> str:
112-
"""Obtiene la fecha actual del sistema y la devuelve como texto en formato AAAA-MM-DD."""
112+
"""Get the current system date as text in YYYY-MM-DD format."""
113113
logger.info("Obteniendo fecha actual")
114114
return datetime.now().strftime("%Y-%m-%d")
115115

116116

117-
# ---- Middleware basado en funciones ----
117+
# ---- Function-based middleware ----
118118

119119

120120
async def timing_agent_middleware(
121121
context: AgentRunContext,
122122
next: Callable[[AgentRunContext], Awaitable[None]],
123123
) -> None:
124-
"""Middleware de agente que registra el tiempo de ejecución."""
124+
"""Agent middleware that logs execution time."""
125125
start = time.perf_counter()
126-
logger.info("[⏲️ Temporización][ Middleware de Agente] Iniciando ejecución del agente")
126+
logger.info("[⏲️ Temporización][ Agent Middleware] Iniciando ejecución del agente")
127127

128128
await next(context)
129129

130130
elapsed = time.perf_counter() - start
131-
logger.info(f"[⏲️ Temporización][ Middleware de Agente] Ejecución completada en {elapsed:.2f}s")
131+
logger.info(f"[⏲️ Temporización][ Agent Middleware] Ejecución completada en {elapsed:.2f}s")
132132

133133

134134
async def logging_function_middleware(
135135
context: FunctionInvocationContext,
136136
next: Callable[[FunctionInvocationContext], Awaitable[None]],
137137
) -> None:
138-
"""Middleware de función que registra las llamadas y resultados de funciones."""
138+
"""Function middleware that logs function calls and results."""
139139
logger.info(
140-
f"[🪵 Registro][ Middleware de Función] Llamando a {context.function.name} con args: {context.arguments}"
140+
f"[🪵 Registro][ Function Middleware] Llamando a {context.function.name} con args: {context.arguments}"
141141
)
142142

143143
await next(context)
144144

145-
logger.info(f"[🪵 Registro][ Middleware de Función] {context.function.name} devolvió: {context.result}")
145+
logger.info(f"[🪵 Registro][ Function Middleware] {context.function.name} devolvió: {context.result}")
146146

147147

148148
async def logging_chat_middleware(
149149
context: ChatContext,
150150
next: Callable[[ChatContext], Awaitable[None]],
151151
) -> None:
152-
"""Middleware de chat que registra las interacciones con la IA."""
153-
logger.info(f"[💬 Registro][ Middleware de Chat] Enviando {len(context.messages)} mensajes a la IA")
152+
"""Chat middleware that logs interactions with the AI."""
153+
logger.info(f"[💬 Registro][ Chat Middleware] Enviando {len(context.messages)} mensajes a la IA")
154154

155155
await next(context)
156156

157-
logger.info("[💬 Registro][ Middleware de Chat] Respuesta de la IA recibida")
157+
logger.info("[💬 Registro][ Chat Middleware] Respuesta de la IA recibida")
158158

159159

160160
# ---- Middleware basado en clases ----
161161

162162

163163
class BlockingAgentMiddleware(AgentMiddleware):
164-
"""Middleware de agente que bloquea solicitudes con palabras prohibidas."""
164+
"""Agent middleware that blocks requests with forbidden words."""
165165

166166
def __init__(self, blocked_words: list[str]) -> None:
167-
"""Inicializa con una lista de palabras que deben ser bloqueadas."""
167+
"""Initialize with a list of words that should be blocked."""
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-
"""Verifica los mensajes en busca de contenido bloqueado y termina si lo encuentra."""
175+
"""Check messages for blocked content and terminate if found."""
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:
179179
if word.lower() in last_message.text.lower():
180-
logger.warning(f"[❌ Bloqueo][ Middleware de Agente] Solicitud bloqueada: contiene '{word}'")
180+
logger.warning(f"[❌ Bloqueo][ Agent Middleware] Solicitud bloqueada: contiene '{word}'")
181181
context.terminate = True
182-
context.result = AgentRunResponse(
182+
context.result = AgentResponse(
183183
messages=[
184184
ChatMessage(
185185
role=Role.ASSISTANT, text=f"Lo siento, no puedo procesar solicitudes sobre '{word}'."
@@ -192,46 +192,46 @@ async def process(
192192

193193

194194
class TimingFunctionMiddleware(FunctionMiddleware):
195-
"""Middleware de función que mide el tiempo de ejecución de cada llamada a función."""
195+
"""Function middleware that measures each function call execution time."""
196196

197197
async def process(
198198
self,
199199
context: FunctionInvocationContext,
200200
next: Callable[[FunctionInvocationContext], Awaitable[None]],
201201
) -> None:
202-
"""Mide el tiempo de ejecución de la función y registra la duración."""
202+
"""Measure function execution time and log the duration."""
203203
start = time.perf_counter()
204-
logger.info(f"[⌚️ Temporización][ Middleware de Función] Iniciando {context.function.name}")
204+
logger.info(f"[⌚️ Temporización][ Function Middleware] Iniciando {context.function.name}")
205205

206206
await next(context)
207207

208208
elapsed = time.perf_counter() - start
209-
logger.info(f"[⌚️ Temporización][ Middleware de Función] {context.function.name} tardó {elapsed:.4f}s")
209+
logger.info(f"[⌚️ Temporización][ Function Middleware] {context.function.name} tardó {elapsed:.4f}s")
210210

211211

212212
class MessageCountChatMiddleware(ChatMiddleware):
213-
"""Middleware de chat que cuenta el número total de mensajes enviados a la IA."""
213+
"""Chat middleware that counts total messages sent to the AI."""
214214

215215
def __init__(self) -> None:
216-
"""Inicializa el contador de mensajes."""
216+
"""Initialize the message counter."""
217217
self.total_messages = 0
218218

219219
async def process(
220220
self,
221221
context: ChatContext,
222222
next: Callable[[ChatContext], Awaitable[None]],
223223
) -> None:
224-
"""Cuenta los mensajes y registra el total acumulado."""
224+
"""Count messages and log the running total."""
225225
self.total_messages += len(context.messages)
226226
logger.info(
227-
"[🔢 Conteo][ Middleware de Chat] Mensajes en esta solicitud: %s, total hasta ahora: %s",
227+
"[🔢 Conteo][ Chat Middleware] Mensajes en esta solicitud: %s, total hasta ahora: %s",
228228
len(context.messages),
229229
self.total_messages,
230230
)
231231

232232
await next(context)
233233

234-
logger.info("[🔢 Conteo][ Middleware de Chat] Respuesta de chat recibida")
234+
logger.info("[🔢 Conteo][ Chat Middleware] Respuesta de chat recibida")
235235

236236

237237
# ---- Configuración del agente ----
@@ -247,7 +247,6 @@ async def process(
247247
instructions=(
248248
"Ayudas a la gente a planificar su fin de semana. "
249249
"Usa las herramientas disponibles para consultar el clima y la fecha. "
250-
"Responde en español."
251250
),
252251
tools=[get_weather, get_current_date],
253252
middleware=[
@@ -263,7 +262,7 @@ async def process(
263262

264263

265264
async def main() -> None:
266-
"""Ejecuta el agente con diferentes entradas para demostrar el comportamiento del middleware."""
265+
"""Run the agent with different inputs to demonstrate middleware behavior."""
267266
# Solicitud normal - todo el middleware se ejecuta
268267
logger.info("=== Solicitud Normal ===")
269268
response = await agent.run("¿Cómo estará el clima este fin de semana en Madrid?")
@@ -281,10 +280,10 @@ async def extra_agent_middleware(
281280
context: AgentRunContext,
282281
next: Callable[[AgentRunContext], Awaitable[None]],
283282
) -> None:
284-
"""Middleware a nivel de ejecución que solo aplica a esta ejecución específica."""
285-
logger.info("[🏃🏽‍♀️ Middleware de Ejecución] Este middleware solo aplica a esta ejecución")
283+
"""Execution middleware that only applies to this specific run."""
284+
logger.info("[🏃🏽‍♀️ Execution Middleware] Este middleware solo aplica a esta ejecución")
286285
await next(context)
287-
logger.info("[🏃🏽‍♀️ Middleware de Ejecución] Ejecución completada")
286+
logger.info("[🏃🏽‍♀️ Execution Middleware] Ejecución completada")
288287

289288
response = await agent.run(
290289
"¿Cómo estará el clima en Barcelona?",

examples/spanish/agent_supervisor.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,10 @@
5151

5252

5353
def get_weather(
54-
city: Annotated[str, Field(description="Ciudad para consultar el clima.")],
55-
date: Annotated[str, Field(description="Fecha (YYYY-MM-DD) para la que se quiere el clima.")],
54+
city: Annotated[str, Field(description="City to fetch the weather for.")],
55+
date: Annotated[str, Field(description="Date (YYYY-MM-DD) to fetch the weather for.")],
5656
) -> dict:
57-
"""Devuelve datos meteorológicos para una ciudad y fecha dadas."""
57+
"""Return weather data for a given city and date."""
5858
logger.info(f"Obteniendo el clima para {city} en {date}")
5959
if random.random() < 0.05:
6060
return {"temperature": 72, "description": "Soleado"}
@@ -63,10 +63,10 @@ def get_weather(
6363

6464

6565
def get_activities(
66-
city: Annotated[str, Field(description="Ciudad para consultar actividades.")],
67-
date: Annotated[str, Field(description="Fecha (YYYY-MM-DD) para consultar actividades.")],
66+
city: Annotated[str, Field(description="City to fetch activities for.")],
67+
date: Annotated[str, Field(description="Date (YYYY-MM-DD) to fetch activities for.")],
6868
) -> list[dict]:
69-
"""Devuelve una lista de actividades para la ciudad y la fecha indicadas."""
69+
"""Return a list of activities for the given city and date."""
7070
logger.info(f"Obteniendo actividades para {city} en {date}")
7171
return [
7272
{"name": "Senderismo", "location": city},
@@ -76,7 +76,7 @@ def get_activities(
7676

7777

7878
def get_current_date() -> str:
79-
"""Obtiene la fecha actual del sistema (YYYY-MM-DD)."""
79+
"""Get the current system date (YYYY-MM-DD)."""
8080
logger.info("Obteniendo la fecha actual")
8181
return datetime.now().strftime("%Y-%m-%d")
8282

@@ -93,7 +93,7 @@ def get_current_date() -> str:
9393

9494

9595
async def plan_weekend(query: str) -> str:
96-
"""Planifica un fin de semana según la consulta del usuario y devuelve la respuesta final."""
96+
"""Plan a weekend from the user query and return the final response."""
9797
logger.info("Herramienta: plan_weekend invocada")
9898
response = await weekend_agent.run(query)
9999
return response.text
@@ -105,9 +105,9 @@ async def plan_weekend(query: str) -> str:
105105

106106

107107
def find_recipes(
108-
query: Annotated[str, Field(description="Consulta del usuario o comida/ingrediente deseado")],
108+
query: Annotated[str, Field(description="User query or desired meal/ingredient")],
109109
) -> list[dict]:
110-
"""Devuelve recetas (JSON) basadas en una consulta."""
110+
"""Return recipes (JSON) based on a query."""
111111
logger.info(f"Buscando recetas para '{query}'")
112112
if "pasta" in query.lower():
113113
recipes = [
@@ -141,7 +141,7 @@ def find_recipes(
141141

142142

143143
def check_fridge() -> list[str]:
144-
"""Devuelve una lista JSON de ingredientes actualmente en el refrigerador."""
144+
"""Return a JSON list of ingredients currently in the fridge."""
145145
logger.info("Revisando los ingredientes del refrigerador")
146146
if random.random() < 0.5:
147147
items = ["pasta", "salsa de tomate", "pimientos", "aceite de oliva"]
@@ -162,7 +162,7 @@ def check_fridge() -> list[str]:
162162

163163

164164
async def plan_meal(query: str) -> str:
165-
"""Planifica una comida según la consulta del usuario y devuelve la respuesta final."""
165+
"""Plan a meal from the user query and return the final response."""
166166
logger.info("Herramienta: plan_meal invocada")
167167
response = await meal_agent.run(query)
168168
return response.text

examples/spanish/agent_tool.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,9 @@
4444

4545

4646
def get_weather(
47-
city: Annotated[str, Field(description="Nombre de la ciudad")],
47+
city: Annotated[str, Field(description="City name")],
4848
) -> dict:
49-
"""Devuelve datos meteorológicos para una ciudad: temperatura y descripción."""
49+
"""Return weather data for a city: temperature and description."""
5050
logger.info(f"Obteniendo el clima para {city}")
5151
if random.random() < 0.05:
5252
return {

0 commit comments

Comments
 (0)