Class: SharedTools::Tools::WeatherTool

Inherits:
RubyLLM::Tool
  • Object
show all
Defined in:
lib/shared_tools/tools/weather_tool.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger: nil) ⇒ WeatherTool

Returns a new instance of WeatherTool.

Parameters:

  • logger (Logger) (defaults to: nil)

    optional logger



50
51
52
# File 'lib/shared_tools/tools/weather_tool.rb', line 50

def initialize(logger: nil)
  @logger = logger || RubyLLM.logger
end

Class Method Details

.nameObject



8
# File 'lib/shared_tools/tools/weather_tool.rb', line 8

def self.name = 'weather_tool'

Instance Method Details

#execute(city:, units: "metric", include_forecast: false) ⇒ Hash

Execute weather lookup for specified city

Parameters:

  • city (String)

    City name, optionally with country code

  • units (String) (defaults to: "metric")

    Unit system: metric, imperial, or kelvin

  • include_forecast (Boolean) (defaults to: false)

    Whether to include 3-day forecast

Returns:

  • (Hash)

    Weather data with success status



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/shared_tools/tools/weather_tool.rb', line 61

def execute(city:, units: "metric", include_forecast: false)
  @logger.info("WeatherTool#execute city=#{city.inspect} units=#{units} include_forecast=#{include_forecast}")

  begin
    api_key = ENV['OPENWEATHER_API_KEY']
    unless api_key
      @logger.error("OpenWeather API key not configured in OPENWEATHER_API_KEY environment variable")
      raise "OpenWeather API key not configured"
    end

    # Create API client with units mapping
    api_units = map_units_to_api(units)
    api = OpenWeatherMap::API.new(api_key, 'en', api_units)

    current_weather = fetch_current_weather(api, city)
    result = {
      success:   true,
      city:      city,
      current:   current_weather,
      units:     units,
      timestamp: Time.now.iso8601
    }

    if include_forecast
      @logger.debug("Fetching forecast data for #{city}")
      forecast_data = fetch_forecast(api, city)
      result[:forecast] = forecast_data
    end

    @logger.info("Weather data retrieved successfully for #{city}")
    result
  rescue => e
    @logger.error("Weather lookup failed for #{city}: #{e.message}")
    {
      success:    false,
      error:      e.message,
      city:       city,
      suggestion: "Verify city name and API key configuration"
    }
  end
end