Skip to content

under0tech/WeatherPlugin

Repository files navigation

Mastering Weather forecasting Chat GPT Plugin via C#

To create 'Weather forecasting' plugin for Chat GPT from scretch you have to:

  1. Open Visual Studio 2022

    click 'Create a new Project' and choose 'ASP.NET Core Web API' and click 'Next' button.

    in the next window put 'WeatherPluginV1' into textbox 'Project name' and click 'Next'

    image

    in the following window that appeared

    image

    you have to uncheck 'Configure for HTTPS' and choose '.NET 7.0' in the field 'Framework' and click the button 'Create'.

    You will see the initially configure project as shown on the picture below.

    image

    Now you can remove default endpoint and supportive code as shown on the picture below.

    image

  2. Create new class 'GetWeatherResponse'

    namespace WeatherPlugin
    {
        public class GetWeatherResponse
        {
            public double temperature { get; set; }
            public double windspeed { get; set; }
            public double winddirection { get; set; }
            public GetWeatherResponse() { }
            public GetWeatherResponse(
                double temperature,
                double windspeed,
                double winddirection)
            {
                this.temperature = temperature;
                this.windspeed = windspeed;
                this.winddirection = winddirection;
            }
        }
    }

    we need this to parse the response from Weather API

  3. Add usings in the begining of 'Program.cs'

    using Microsoft.Extensions.FileProviders;
    using System.Text.Json;
    using WeatherPluginV1;
  4. Add the constant with Weather API URL before the builder initialization

    const string WEATHER_API_URL = "https://api.open-meteo.com/v1/forecast?";
  5. Add Cors to services before 'var app = builder.Build();'

    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", policy =>
        {
            policy.WithOrigins(
                "https://chat.openai.com", 
                "http://localhost:5139")
                .AllowAnyHeader()
                .AllowAnyMethod();
        });
    });
  6. and using them right after the build

    var app = builder.Build();
    app.UseCors("AllowAll");
  7. Also we have to add support for Static files cause we will be adding two files for OpenAI into the folder '.well-known'

    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), ".well-known")),
        RequestPath = "/.well-known"
    });

    Do that right after 'if (app.Environment.IsDevelopment())'

  8. Next, we will be adding our first and last endpoint in this application

    // Add weather-forecast endpoint.
    app.MapGet("/weather-forecast", async (double latitude, double longitude) =>
    {
        using (var httpClient = new HttpClient())
        {
            var queryParams = $"latitude={latitude}&longitude={longitude}&current_weather=true";
            var url = WEATHER_API_URL + queryParams;
    
            var result = await httpClient.GetStringAsync(url);
            var jsonDocument = JsonDocument.Parse(result);
            var currentWeather = jsonDocument.RootElement.GetProperty("current_weather");
            return JsonSerializer.Deserialize<GetWeatherResponse>(currentWeather);
    
        }
    })
    .WithName("getWeather");
  9. Finally, your 'Program.cs' file should look like this

    using Microsoft.Extensions.FileProviders;
    using System.Text.Json;
    using WeatherPluginV1;
    
    const string WEATHER_API_URL = "https://api.open-meteo.com/v1/forecast?";
    var builder = WebApplication.CreateBuilder(args);
    
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", policy =>
        {
            policy.WithOrigins(
                "https://chat.openai.com",
                "http://localhost:5139")
                .AllowAnyHeader()
                .AllowAnyMethod();
        });
    });
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), ".well-known")),
        RequestPath = "/.well-known"
    });
    
    // Add weather-forecast endpoint.
    app.MapGet("/weather-forecast", async (double latitude, double longitude) =>
    {
        using (var httpClient = new HttpClient())
        {
            var queryParams = $"latitude={latitude}&longitude={longitude}&current_weather=true";
            var url = WEATHER_API_URL + queryParams;
    
            var result = await httpClient.GetStringAsync(url);
            var jsonDocument = JsonDocument.Parse(result);
            var currentWeather = jsonDocument.RootElement.GetProperty("current_weather");
            return JsonSerializer.Deserialize<GetWeatherResponse>(currentWeather);
    
        }
    })
    .WithName("getWeather");
    
    app.Run();
  10. To let OpenAI work with your plugin you have to create the folder '.well-known'

  11. Create file 'ai-plugin.json' in that folder with the following content

    {
     "schema_version": "v1",
     "name_for_human": "Weather forecast",
     "name_for_model": "weather_forecast",
     "description_for_human": "Plugin for forecasting the weather conditions by latitude and longitude.",
     "description_for_model": "Plugin for forecasting the weather conditions by latitude and longitude.",
     "auth": {
       "type": "none"
     },
     "api": {
       "type": "openapi",
       "url": "http://localhost:5139/swagger/v1/swagger.yaml",
       "is_user_authenticated": false
     },
     "logo_url": "http://localhost:5139/.well-known/logo.png",
     "contact_email": "[email protected]",
     "legal_info_url": "https://medium.com/@dmytrosazonov"
    }
  12. And also copy file 'logo.png' into this folder. Both files will be discovered by OpenAI infrastructure during its installation process.

  13. Now you have something like this

    image

  14. Just click Run F5 in your Visual Studio and observe the Swagger as shown on the picture below

    image

  15. As you may see on the picture above, the port for your web API is different from that which we declared in our 'Program.cs'. Adjust it to 'http://localhost:5139' editing the file 'launchSettings.json' as shown below

    "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:5139",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
  16. And now you are ready to test your plugin out in the Chat GPT UI.

  17. Open the Chat GPT (https://chat.openai.com/). If you are the Chat GPT Plus user you have the options GPT.3.5 or GPT 4.0. You have to choose GPT 4.0

    image

    and also then choose 'Plugins' as shown on the picture

    image

    in the 'Plugin store' click the button 'Develop your own plugin',

    image

    and put the URL to your local Swagger-service into the textbox 'Domain' as shown on the picture above. Then click 'Find manifest file'

    if everything is ok and your Swagger-service is discoverable, - you will see next window.

    image

    Just click 'Install localhost plugin' to let Chat GPT use it in its Chatbot UI.

    image

  18. Now you can speak with your plugin as shown on the picture below

    image

Enjoy your initial encounter with broadening the capabilities of Chat GPT to include weather forecasting. What else would you add to Chat GPT?

If you have any questions, feel free to reach me out on Twitter: https://twitter.com/dmytro_sazonov

About

Weather forecasting Chat GPT Plugin via C#

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages