Skip to content

Commit 147ac67

Browse files
committed
update docstrings to Spanish
1 parent 87417de commit 147ac67

11 files changed

Lines changed: 72 additions & 72 deletions

examples/spanish/agent_mcp_local.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444

4545

4646
async def main() -> None:
47-
"""Run an agent connected to a local MCP server to log expenses."""
47+
"""Ejecuta un agente conectado a un servidor MCP local para registrar gastos."""
4848
async with (
4949
MCPStreamableHTTPTool(name="Expenses MCP Server", url=MCP_SERVER_URL) as mcp_server,
5050
ChatAgent(

examples/spanish/agent_mcp_remote.py

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

4343

4444
async def main() -> None:
45-
"""Run an agent that uses a remote MCP server (Microsoft Learn) to answer documentation questions."""
45+
"""Ejecuta un agente que usa un servidor MCP remoto (Microsoft Learn) para responder preguntas de documentación."""
4646
async with (
4747
MCPStreamableHTTPTool(
4848
name="Microsoft Learn MCP",

examples/spanish/agent_middleware.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,39 @@
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

3939
import asyncio
@@ -100,7 +100,7 @@
100100
def 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

111111
def 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

163163
class 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

194194
class 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

212212
class 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

264264
async 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")

examples/spanish/agent_supervisor.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def get_weather(
5454
city: Annotated[str, Field(description="City to fetch the weather for.")],
5555
date: Annotated[str, Field(description="Date (YYYY-MM-DD) to fetch the weather for.")],
5656
) -> dict:
57-
"""Return weather data for a given city and date."""
57+
"""Devuelve datos meteorológicos para una ciudad y fecha dadas."""
5858
logger.info(f"Obteniendo el clima para {city} en {date}")
5959
if random.random() < 0.05:
6060
return {"temperature": 72, "description": "Soleado"}
@@ -66,7 +66,7 @@ def get_activities(
6666
city: Annotated[str, Field(description="City to fetch activities for.")],
6767
date: Annotated[str, Field(description="Date (YYYY-MM-DD) to fetch activities for.")],
6868
) -> list[dict]:
69-
"""Return a list of activities for the given city and date."""
69+
"""Devuelve una lista de actividades para la ciudad y la fecha indicadas."""
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-
"""Get the current system date (YYYY-MM-DD)."""
79+
"""Obtiene la fecha actual del sistema (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-
"""Plan a weekend from the user query and return the final response."""
96+
"""Planifica un fin de semana según la consulta del usuario y devuelve la respuesta final."""
9797
logger.info("Herramienta: plan_weekend invocada")
9898
response = await weekend_agent.run(query)
9999
return response.text
@@ -107,7 +107,7 @@ async def plan_weekend(query: str) -> str:
107107
def find_recipes(
108108
query: Annotated[str, Field(description="User query or desired meal/ingredient")],
109109
) -> list[dict]:
110-
"""Return recipes (JSON) based on a query."""
110+
"""Devuelve recetas (JSON) basadas en una consulta."""
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-
"""Return a JSON list of ingredients currently in the fridge."""
144+
"""Devuelve una lista JSON de ingredientes actualmente en el refrigerador."""
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-
"""Plan a meal from the user query and return the final response."""
165+
"""Planifica una comida según la consulta del usuario y devuelve la respuesta final."""
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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
def get_weather(
4747
city: Annotated[str, Field(description="City name")],
4848
) -> dict:
49-
"""Return weather data for a city: temperature and description."""
49+
"""Devuelve datos meteorológicos para una ciudad: temperatura y descripción."""
5050
logger.info(f"Obteniendo el clima para {city}")
5151
if random.random() < 0.05:
5252
return {

examples/spanish/agent_tools.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
def get_weather(
4949
city: Annotated[str, Field(description="City to fetch the weather for.")],
5050
) -> dict:
51-
"""Return weather data for a city: temperature and description."""
51+
"""Devuelve datos meteorológicos para una ciudad: temperatura y descripción."""
5252
logger.info(f"Obteniendo el clima para {city}")
5353
if random.random() < 0.05:
5454
return {
@@ -66,7 +66,7 @@ def get_activities(
6666
city: Annotated[str, Field(description="City to fetch activities for.")],
6767
date: Annotated[str, Field(description="Date (YYYY-MM-DD) to fetch activities for.")],
6868
) -> list[dict]:
69-
"""Return a list of activities for a given city and date."""
69+
"""Devuelve una lista de actividades para una ciudad y fecha dadas."""
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-
"""Get the current system date in YYYY-MM-DD format."""
79+
"""Obtiene la fecha actual del sistema en formato YYYY-MM-DD."""
8080
logger.info("Obteniendo la fecha actual")
8181
return datetime.now().strftime("%Y-%m-%d")
8282

examples/spanish/mcp_server.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""
2-
Example MCP server for expense tracking.
2+
Servidor MCP de ejemplo para seguimiento de gastos.
33
4-
Run this server first and then use agent_mcp_local.py to connect:
4+
Ejecuta este servidor primero y luego usa agent_mcp_local.py para conectarte:
55
python examples/spanish/mcp_server.py
66
python examples/spanish/agent_mcp_local.py
77
"""
@@ -26,15 +26,15 @@
2626

2727

2828
class PaymentMethod(Enum):
29-
"""Accepted payment methods for expenses."""
29+
"""Métodos de pago aceptados para gastos."""
3030

3131
AMEX = "amex"
3232
VISA = "visa"
3333
CASH = "cash"
3434

3535

3636
class Category(Enum):
37-
"""Expense categories for classification."""
37+
"""Categorías de gastos para clasificación."""
3838

3939
FOOD = "comida"
4040
TRANSPORT = "transporte"
@@ -52,7 +52,7 @@ async def add_expense(
5252
description: Annotated[str, "Human-readable expense description"],
5353
payment_method: Annotated[PaymentMethod, "Payment method used"],
5454
) -> str:
55-
"""Add a new expense to the expenses.csv file."""
55+
"""Agrega un nuevo gasto al archivo expenses.csv."""
5656
if amount <= 0:
5757
return "Error: El monto debe ser positivo"
5858

@@ -77,7 +77,7 @@ async def add_expense(
7777

7878
@mcp.resource("resource://expenses")
7979
async def get_expenses_data() -> str:
80-
"""Get expense data from the CSV file."""
80+
"""Obtiene los datos de gastos desde el archivo CSV."""
8181
logger.info("Datos de gastos consultados")
8282

8383
try:

examples/spanish/openai_tool_calling.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828

2929

3030
def lookup_weather(city_name: str | None = None, zip_code: str | None = None) -> dict:
31-
"""Look up weather for a given city name or zip code."""
31+
"""Consulta el clima para un nombre de ciudad o código postal dado."""
3232
return {
3333
"city_name": city_name,
3434
"zip_code": zip_code,

examples/spanish/workflow_basic.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333

3434
# Define la salida estructurada para los resultados de revisión
3535
class ReviewResult(BaseModel):
36-
"""Review evaluation with scores and feedback."""
36+
"""Evaluación de revisión con puntajes y retroalimentación."""
3737

3838
score: int # Puntaje general de calidad (0-100)
3939
feedback: str # Retroalimentación concisa y accionable
@@ -45,7 +45,7 @@ class ReviewResult(BaseModel):
4545

4646
# Función de condición: envía al editor si puntaje < 80
4747
def needs_editing(message: Any) -> bool:
48-
"""Check if the content needs editing based on the review score."""
48+
"""Verifica si el contenido necesita edición según el puntaje de revisión."""
4949
if not isinstance(message, AgentExecutorResponse):
5050
return False
5151
try:
@@ -57,7 +57,7 @@ def needs_editing(message: Any) -> bool:
5757

5858
# Función de condición: el contenido está aprobado (puntaje >= 80)
5959
def is_approved(message: Any) -> bool:
60-
"""Check if the content is approved (high quality)."""
60+
"""Verifica si el contenido está aprobado (alta calidad)."""
6161
if not isinstance(message, AgentExecutorResponse):
6262
return True
6363
try:

0 commit comments

Comments
 (0)