feat: Add docs
This commit is contained in:
210
docs/examples/tool_registry_examples.py
Normal file
210
docs/examples/tool_registry_examples.py
Normal file
@@ -0,0 +1,210 @@
|
||||
"""
|
||||
Ejemplos de uso del patrón Registry con el Agent.
|
||||
|
||||
Muestra diferentes formas de usar el ToolRegistry con el agente.
|
||||
"""
|
||||
|
||||
from src.naliiabot.bot.tools.tool_registry import ToolRegistry, ToolRegistryBuilder
|
||||
from src.naliiabot.bot.tools.tools import (
|
||||
CalculatorTool,
|
||||
GreeterTool,
|
||||
WeatherTool,
|
||||
TimeTool
|
||||
)
|
||||
from src.naliiabot.bot.agent.agent import Agent, AgentConfig
|
||||
|
||||
|
||||
def example_1_basic_registry():
|
||||
"""Ejemplo 1: Crear un registry básico y usarlo."""
|
||||
print("\n" + "="*60)
|
||||
print("EJEMPLO 1: Registry Básico")
|
||||
print("="*60)
|
||||
|
||||
# Crear el registro
|
||||
registry = ToolRegistry()
|
||||
|
||||
# Registrar herramientas
|
||||
registry.register(CalculatorTool())
|
||||
registry.register(GreeterTool())
|
||||
|
||||
# Ver herramientas disponibles
|
||||
print(f"\nHerramientas disponibles: {len(registry)}")
|
||||
for name, description in registry.list_tools().items():
|
||||
print(f" - {name}: {description[:50]}...")
|
||||
|
||||
# Obtener una herramienta específica
|
||||
calc = registry.get_tool("calculator")
|
||||
result = calc.invoke(a=10, b=5, operation="add")
|
||||
print(f"\nResultado de cálculo: {result}")
|
||||
|
||||
|
||||
def example_2_builder_pattern():
|
||||
"""Ejemplo 2: Usar el builder para crear un registry."""
|
||||
print("\n" + "="*60)
|
||||
print("EJEMPLO 2: Builder Pattern")
|
||||
print("="*60)
|
||||
|
||||
# Usar el builder fluido
|
||||
registry = (ToolRegistryBuilder()
|
||||
.add(CalculatorTool())
|
||||
.add(GreeterTool())
|
||||
.add(WeatherTool())
|
||||
.add(TimeTool())
|
||||
.build())
|
||||
|
||||
print(f"\nRegistro creado con {len(registry)} herramientas")
|
||||
print(f"Contenido: {registry}")
|
||||
|
||||
|
||||
def example_3_agent_integration():
|
||||
"""Ejemplo 3: Integrar registry con Agent."""
|
||||
print("\n" + "="*60)
|
||||
print("EJEMPLO 3: Integración con Agent")
|
||||
print("="*60)
|
||||
|
||||
# Crear registro de tools
|
||||
registry = (ToolRegistryBuilder()
|
||||
.add(CalculatorTool())
|
||||
.add(GreeterTool())
|
||||
.add(WeatherTool())
|
||||
.build())
|
||||
|
||||
# Crear configuración
|
||||
config = AgentConfig(
|
||||
system_prompt="You are a helpful assistant with access to tools.",
|
||||
max_iterations=5
|
||||
)
|
||||
|
||||
# Aquí iría el modelo real (mock para ejemplo)
|
||||
# agent = Agent(model=your_model, config=config, tools=registry)
|
||||
print(f"Agent configurado con {len(registry.get_all_tools())} herramientas")
|
||||
print("Tools disponibles:")
|
||||
for tool in registry.get_all_tools():
|
||||
print(f" - {tool.name}: {tool.description}")
|
||||
|
||||
|
||||
def example_4_dynamic_tools():
|
||||
"""Ejemplo 4: Registración dinámica de herramientas."""
|
||||
print("\n" + "="*60)
|
||||
print("EJEMPLO 4: Registración Dinámica")
|
||||
print("="*60)
|
||||
|
||||
registry = ToolRegistry()
|
||||
|
||||
# Fase 1: herramientas básicas
|
||||
registry.register(CalculatorTool())
|
||||
print(f"Paso 1 - Herramientas: {len(registry)}")
|
||||
|
||||
# Fase 2: añadir más
|
||||
registry.register(GreeterTool())
|
||||
registry.register(WeatherTool())
|
||||
print(f"Paso 2 - Herramientas: {len(registry)}")
|
||||
|
||||
# Fase 3: remover según necesidad
|
||||
registry.unregister("calculator")
|
||||
print(f"Paso 3 - Herramientas: {len(registry)}")
|
||||
|
||||
# Ver estado final
|
||||
print(f"\nHerramientas finales:")
|
||||
for tool in registry.get_all_tools():
|
||||
print(f" - {tool.name}")
|
||||
|
||||
|
||||
def example_5_error_handling():
|
||||
"""Ejemplo 5: Manejo de errores."""
|
||||
print("\n" + "="*60)
|
||||
print("EJEMPLO 5: Manejo de Errores")
|
||||
print("="*60)
|
||||
|
||||
registry = ToolRegistry()
|
||||
|
||||
# Intentar operación inválida
|
||||
try:
|
||||
registry.register("not a tool")
|
||||
except TypeError as e:
|
||||
print(f"Error esperado: {e}")
|
||||
|
||||
# Registrar herramienta
|
||||
registry.register(CalculatorTool())
|
||||
|
||||
# Intentar registrar duplicada
|
||||
try:
|
||||
registry.register(CalculatorTool())
|
||||
except ValueError as e:
|
||||
print(f"Error esperado: {e}")
|
||||
|
||||
# Intentar desregistrar inexistente
|
||||
try:
|
||||
registry.unregister("nonexistent")
|
||||
except KeyError as e:
|
||||
print(f"Error esperado: {e}")
|
||||
|
||||
|
||||
def example_6_tool_execution():
|
||||
"""Ejemplo 6: Ejecutar herramientas desde el registry."""
|
||||
print("\n" + "="*60)
|
||||
print("EJEMPLO 6: Ejecución de Herramientas")
|
||||
print("="*60)
|
||||
|
||||
registry = (ToolRegistryBuilder()
|
||||
.add(CalculatorTool())
|
||||
.add(GreeterTool())
|
||||
.add(WeatherTool())
|
||||
.add(TimeTool())
|
||||
.build())
|
||||
|
||||
# Ejecutar calculator
|
||||
calc_tool = registry.get_tool("calculator")
|
||||
calc_result = calc_tool.invoke(a=15, b=3, operation="multiply")
|
||||
print(f"\nCalculadora: {calc_result}")
|
||||
|
||||
# Ejecutar greeter
|
||||
greeter = registry.get_tool("greeter")
|
||||
greeting = greeter.invoke(name="Alice", tone="formal")
|
||||
print(f"Saludo: {greeting}")
|
||||
|
||||
# Ejecutar weather
|
||||
weather = registry.get_tool("get_weather")
|
||||
weather_result = weather.invoke(location="Barcelona", units="celsius")
|
||||
print(f"Clima: {weather_result}")
|
||||
|
||||
# Ejecutar time
|
||||
time_tool = registry.get_tool("get_time")
|
||||
time_result = time_tool.invoke(format="24h", timezone="CET")
|
||||
print(f"Hora: {time_result}")
|
||||
|
||||
|
||||
def example_7_langchain_format():
|
||||
"""Ejemplo 7: Convertir a formato LangChain."""
|
||||
print("\n" + "="*60)
|
||||
print("EJEMPLO 7: Formato LangChain")
|
||||
print("="*60)
|
||||
|
||||
registry = (ToolRegistryBuilder()
|
||||
.add(CalculatorTool())
|
||||
.add(GreeterTool())
|
||||
.build())
|
||||
|
||||
# Obtener herramientas en formato LangChain
|
||||
langchain_tools = registry.get_langchain_tools()
|
||||
|
||||
print(f"\nHerramientas en formato LangChain: {len(langchain_tools)}")
|
||||
for tool in langchain_tools:
|
||||
print(f" - Nombre: {tool.name}")
|
||||
print(f" Descripción: {tool.description[:50]}...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("\n🚀 EJEMPLOS DE USO DEL TOOL REGISTRY")
|
||||
|
||||
example_1_basic_registry()
|
||||
example_2_builder_pattern()
|
||||
example_3_agent_integration()
|
||||
example_4_dynamic_tools()
|
||||
example_5_error_handling()
|
||||
example_6_tool_execution()
|
||||
example_7_langchain_format()
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("✅ Ejemplos completados")
|
||||
print("="*60 + "\n")
|
||||
Reference in New Issue
Block a user