Skip to content

Latest commit

 

History

History
252 lines (207 loc) · 9.95 KB

File metadata and controls

252 lines (207 loc) · 9.95 KB

Arquitectura del Framework LIN OpenAI

?? Diagrama de Componentes

???????????????????????????????????????????????????????????????????
?                         USER CODE                               ?
?  ??????????????????  ??????????????????  ??????????????????   ?
?  ?  WeatherTools  ?  ?   MathTools    ?  ? DatabaseTools  ?   ?
?  ?                ?  ?                ?  ?                ?   ?
?  ?  [Tool]        ?  ?  [Tool]        ?  ?  [Tool]        ?   ?
?  ?  GetWeather()  ?  ?  Add()         ?  ?  ExecuteQuery()?   ?
?  ?  [ToolParam]   ?  ?  [ToolParam]   ?  ?  [ToolParam]   ?   ?
?  ??????????????????  ??????????????????  ??????????????????   ?
???????????????????????????????????????????????????????????????????
                            ?
                            ?
???????????????????????????????????????????????????????????????????
?                      FRAMEWORK CORE                             ?
?  ????????????????????????????????????????????????????????      ?
?  ?              ToolRegistry                            ?      ?
?  ?  • AddToolsFrom<T>()                                 ?      ?
?  ?  • GetAllTools()                                     ?      ?
?  ?  • InvokeTool()                                      ?      ?
?  ?  • GenerateToolSchemas()                             ?      ?
?  ????????????????????????????????????????????????????????      ?
?                ?                        ?                       ?
?                ?                        ?                       ?
?  ???????????????????????    ???????????????????????          ?
?  ?  Reflection Engine  ?    ? JsonSchemaGenerator ?          ?
?  ?  • Discovery        ?    ?  • Type Mapping     ?          ?
?  ?  • Parameter Read   ?    ?  • Property Scan    ?          ?
?  ?  • Delegate Create  ?    ?  • Schema Build     ?          ?
?  ???????????????????????    ???????????????????????          ?
???????????????????????????????????????????????????????????????????
                            ?
                            ?
???????????????????????????????????????????????????????????????????
?                    DATA STRUCTURES                              ?
?  ??????????????????  ????????????????  ????????????????????   ?
?  ? ToolDefinition ?  ?ToolParameter ?  ?JsonSchemaDefinition?  ?
?  ?  • Name        ?  ?  • Name      ?  ?  • Properties     ?   ?
?  ?  • Description ?  ?  • Type      ?  ?  • Required       ?   ?
?  ?  • Parameters  ?  ?  • Required  ?  ?  • Description    ?   ?
?  ?  • Handler     ?  ?  • Desc.     ?  ????????????????????   ?
?  ??????????????????  ????????????????                          ?
???????????????????????????????????????????????????????????????????

?? Flujo de Ejecución

1. Fase de Registro

User Code                 ToolRegistry              Reflection
    ?                          ?                        ?
    ???AddToolsFrom<T>()????????                       ?
    ?                          ?                        ?
    ?                          ???Scan Methods??????????
    ?                          ?                        ?
    ?                          ?????Tool Methods????????
    ?                          ?                        ?
    ?                          ???Read Attributes???????
    ?                          ?                        ?
    ?                          ?????Metadata????????????
    ?                          ?                        ?
    ?                          ???Create Delegate???????
    ?                          ?                        ?
    ?                          ?????Handler?????????????
    ?                          ?                        ?
    ????Registration OK?????????                        ?

2. Fase de Invocación

User Code            ToolRegistry         Handler          Tool Method
    ?                     ?                  ?                  ?
    ??InvokeTool(...)??????                  ?                  ?
    ?                     ?                  ?                  ?
    ?                     ??Lookup Tool???????                  ?
    ?                     ?                  ?                  ?
    ?                     ??Validate Args?????                  ?
    ?                     ?                  ?                  ?
    ?                     ??DynamicInvoke?????                  ?
    ?                     ?                  ?                  ?
    ?                     ?                  ??Execute???????????
    ?                     ?                  ?                  ?
    ?                     ?                  ????Result??????????
    ?                     ?                  ?                  ?
    ?                     ???Result???????????                  ?
    ?                     ?                  ?                  ?
    ??????Result???????????                  ?                  ?

3. Fase de Schema Generation

User Code          ToolRegistry      JsonSchemaGenerator    Reflection
    ?                   ?                     ?                  ?
    ??GenerateSchemas()??                     ?                  ?
    ?                   ?                     ?                  ?
    ?                   ???For each tool???????                  ?
    ?                   ?                     ?                  ?
    ?                   ?                     ??Get Return Type???
    ?                   ?                     ?                  ?
    ?                   ?                     ???Type Info????????
    ?                   ?                     ?                  ?
    ?                   ?                     ??Scan Properties???
    ?                   ?                     ?                  ?
    ?                   ?                     ???Property Info????
    ?                   ?                     ?                  ?
    ?                   ?                     ??Read Attributes???
    ?                   ?                     ?                  ?
    ?                   ?                     ???Metadata?????????
    ?                   ?                     ?                  ?
    ?                   ????JsonSchema?????????                  ?
    ?                   ?                     ?                  ?
    ????Schemas??????????                     ?                  ?

?? Decisiones de Diseño

1. Uso de Reflexión

Por qué: Permite descubrimiento automático de métodos y metadata sin generación de código.

Trade-offs:

  • ? Flexibilidad y facilidad de uso
  • ? No requiere source generators
  • ?? Overhead de performance mínimo en registro
  • ?? Validación en runtime en lugar de compile-time

2. Atributos vs Interfaces

Decisión: Usar atributos en lugar de interfaces.

Razones:

  • ? Metadata declarativa clara
  • ? No contamina la jerarquía de tipos
  • ? Permite múltiples decoradores
  • ? Más natural para definir schemas JSON

3. Delegates para Invocación

Decisión: Crear delegates en lugar de usar MethodInfo.Invoke().

Razones:

  • ? Mejor performance
  • ? Type-safety donde es posible
  • ? Más cercano a llamadas directas
  • ?? Requiere reflexión para crear el delegate

4. Schema Generator Simplificado

Decisión: Implementar mapeo básico en lugar de usar JSON Schema completo.

Razones:

  • ? Suficiente para demostración
  • ? Código más legible
  • ? Fácil de extender
  • ?? No es spec-compliant

?? Extensibilidad

Puntos de Extensión

  1. Custom Attributes: Agregar nuevos atributos para metadata adicional
  2. Type Mappings: Extender mapeo CLR ? JSON Schema
  3. Validators: Implementar validaciones personalizadas
  4. Serializers: Agregar diferentes formatos de exportación
  5. Middleware: Interceptar invocaciones de tools

Ejemplo de Extensión

// Nuevo atributo para rate limiting
[AttributeUsage(AttributeTargets.Method)]
public class RateLimitAttribute : Attribute
{
    public int MaxCallsPerMinute { get; set; }
}

// Extender ToolRegistry
public class RateLimitedToolRegistry : ToolRegistry
{
    // Implementar rate limiting en InvokeTool
}

??? Patrones Utilizados

1. Registry Pattern

ToolRegistry actúa como registro central de tools.

2. Metadata Programming

Uso extensivo de atributos para metadata declarativa.

3. Delegate Pattern

Uso de delegates para invocación dinámica eficiente.

4. Builder Pattern (Implícito)

JsonSchemaGenerator construye schemas paso a paso.

5. Template Method (Implícito)

ToolRegistry.AddToolsFrom() sigue pasos consistentes.

?? Performance Considerations

Registro

  • Tiempo: O(n) donde n = número de métodos
  • Memoria: O(m) donde m = número de tools
  • Una vez: Solo ocurre en startup

Invocación

  • Tiempo: O(1) lookup + delegate call (casi nativa)
  • Memoria: Mínima (solo parámetros)
  • Frecuente: Optimizado para llamadas repetidas

Schema Generation

  • Tiempo: O(p) donde p = número de propiedades
  • Memoria: O(s) donde s = tamaño del schema
  • Ocasional: Típicamente una vez o bajo demanda

?? Mejoras Futuras

Para Producción

  1. Async Support: Soportar métodos async
  2. Dependency Injection: Integrar con DI container
  3. Caching: Cache de schemas y metadata
  4. Validation: Validación de argumentos en runtime
  5. Error Handling: Manejo robusto de errores
  6. Logging: Integrar ILogger
  7. Metrics: Telemetría y métricas
  8. Security: Validación de permisos

Características Avanzadas

  1. Tool Chaining: Composición de tools
  2. Streaming: Soporte para respuestas streaming
  3. Versioning: Versionado de tools
  4. OpenAPI Export: Exportar a OpenAPI spec
  5. GraphQL: Generar schema GraphQL
  6. gRPC: Generar servicios gRPC

?? Referencias