NewDynamicTool creates a DynamicTool with a typed handler. The JSON schema is derived from T using invopop/jsonschema. The handler receives deserialized args and the DynamicToolCall metadata.
( name, description string, handler func(ctx context.Context, args T, call DynamicToolCall) (DynamicToolResponse, error), )
| 1640 | // The JSON schema is derived from T using invopop/jsonschema. |
| 1641 | // The handler receives deserialized args and the DynamicToolCall metadata. |
| 1642 | func NewDynamicTool[T any]( |
| 1643 | name, description string, |
| 1644 | handler func(ctx context.Context, args T, call DynamicToolCall) (DynamicToolResponse, error), |
| 1645 | ) DynamicTool { |
| 1646 | reflector := jsonschema.Reflector{ |
| 1647 | DoNotReference: true, |
| 1648 | Anonymous: true, |
| 1649 | AllowAdditionalProperties: true, |
| 1650 | } |
| 1651 | schema := reflector.Reflect(new(T)) |
| 1652 | schema.Version = "" |
| 1653 | schemaJSON, err := json.Marshal(schema) |
| 1654 | if err != nil { |
| 1655 | panic(fmt.Sprintf("codersdk: failed to marshal schema for %q: %v", name, err)) |
| 1656 | } |
| 1657 | |
| 1658 | return DynamicTool{ |
| 1659 | Name: name, |
| 1660 | Description: description, |
| 1661 | InputSchema: schemaJSON, |
| 1662 | Handler: func(ctx context.Context, call DynamicToolCall) (DynamicToolResponse, error) { |
| 1663 | var parsed T |
| 1664 | if err := json.Unmarshal([]byte(call.Args), &parsed); err != nil { |
| 1665 | return DynamicToolResponse{ |
| 1666 | Content: fmt.Sprintf("invalid parameters: %s", err), |
| 1667 | IsError: true, |
| 1668 | }, nil |
| 1669 | } |
| 1670 | return handler(ctx, parsed, call) |
| 1671 | }, |
| 1672 | } |
| 1673 | } |
| 1674 | |
| 1675 | // ChatWatchEventKind represents the kind of event in the chat watch stream. |
| 1676 | type ChatWatchEventKind string |