GitHub Models provides free access to AI models directly through GitHub, making it easy to integrate AI capabilities into your applications without requiring separate API keys or cloud accounts. In this module, we'll integrate GitHub Models with our Weather Hub application to enhance the weather forecast experience with AI-powered background selection.
GitHub Models offers free access to popular AI models including:
- GPT-4o and GPT-4o mini for chat completions
- Phi-3 models for lightweight AI tasks
- Other foundation models for various AI scenarios
The integration uses your GitHub authentication, making it seamless for developers already using GitHub.
Before we begin, here are some useful links to learn more about GitHub's AI offerings:
- GitHub Models Documentation - Official documentation for GitHub Models
- GitHub Models Marketplace - Browse available AI models
- GitHub Copilot - AI-powered code completion and chat
- Getting Started with GitHub Models - Blog post introducing GitHub Models
- GitHub Models API Reference - API documentation for integrating with GitHub Models
- A GitHub account
- Access to GitHub Models (currently in preview)
- Your GitHub personal access token with appropriate permissions
First, we need to add the GitHub Models integration package to the AppHost project using the Aspire CLI:
-
Navigate to your project directory
-
Use the Aspire CLI to add the GitHub Models hosting integration:
aspire add github-modelsThis command will automatically add the Aspire.Hosting.GitHub.Models package reference to your AppHost project and restore packages.
Now let's add the GitHub Models integration to our AppHost project:
- Open your
AppHost/AppHost.csfile - Add the GitHub Models integration:
var builder = DistributedApplication.CreateBuilder(args);
...
// Add GitHub Models integration
var githubModel = builder.AddGitHubModel("chat-model", GitHubModel.OpenAI.OpenAIGPT4oMini);
...
var web = builder.AddProject<Projects.MyWeatherHub>("myweatherhub")
.WithReference(api)
.WithReference(weatherDb)
.WithReference(githubModel) // Reference the GitHub model
.WaitFor(postgres)
.WithExternalHttpEndpoints();Add the necessary NuGet packages to your MyWeatherHub project:
- Open your
MyWeatherHub/MyWeatherHub.csprojfile - Add the following package references:
<PackageReference Include="Aspire.Azure.AI.Inference" Version="13.1.2-preview.1.26125.13" />
<PackageReference Include="Microsoft.Extensions.AI" Version="10.4.0" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.4.0" />Update your MyWeatherHub/Program.cs to configure the AI services:
using MyWeatherHub;
using MyWeatherHub.Components;
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
builder.Services.AddHttpClient<NwsManager>(client =>
{
client.BaseAddress = new("https+http://api");
});
// Add GitHub Models chat client
builder.AddAzureChatCompletionsClient("chat-model")
.AddChatClient();
// Register the ForecastSummarizer service
builder.Services.AddScoped<ForecastSummarizer>();
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddMemoryCache();
builder.AddNpgsqlDbContext<MyWeatherContext>(connectionName: "weatherdb");
var app = builder.Build();
// Rest of your application configuration...Create a new file MyWeatherHub/ForecastSummarizer.cs:
using Microsoft.Extensions.AI;
namespace MyWeatherHub;
public class ForecastSummarizer(IChatClient chatClient)
{
public async Task<string> SummarizeForecastAsync(string forecasts)
{
var prompt = $"""
You are a weather assistant. Summarize the following forecast
as one of the following conditions: Sunny, Cloudy, Rainy, Snowy.
Only those four values are allowed. Be as concise as possible.
I want a 1-word response with one of these options: Sunny, Cloudy, Rainy, Snowy.
The forecast is: {forecasts}
""";
var response = await chatClient.GetResponseAsync(prompt);
// Look for one of the four values in the response
if (string.IsNullOrEmpty(response.Text))
{
return "Cloudy"; // Default fallback
}
var condition = response.Text switch
{
string s when s.Contains("Snowy", StringComparison.OrdinalIgnoreCase) => "Snowy",
string s when s.Contains("Rainy", StringComparison.OrdinalIgnoreCase) => "Rainy",
string s when s.Contains("Cloudy", StringComparison.OrdinalIgnoreCase) => "Cloudy",
string s when s.Contains("Sunny", StringComparison.OrdinalIgnoreCase) => "Sunny",
string s when s.Contains("Clear", StringComparison.OrdinalIgnoreCase) => "Sunny",
_ => "Cloudy" // Default fallback
};
return condition;
}
}Update your Components/Pages/Home.razor to use the AI-powered forecast summarization:
- Add the ForecastSummarizer injection at the top:
@inject ForecastSummarizer Summarizer- Add a property to store the AI summary:
@code {
// ... existing properties ...
string Summary { get; set; } = string.Empty;
int randomBackground = new Random().Next(1, 4);
// ... rest of existing code ...
}- Update the
SelectZonemethod to use AI summarization:
private async Task SelectZone(Zone zone)
{
SelectedZone = zone;
IsLoading = true;
StateHasChanged();
await Task.Delay(50);
try
{
IsLoading = false;
Forecast = await NwsManager.GetForecastByZoneAsync(zone.Key);
Error = string.Empty;
}
catch (Exception ex)
{
IsLoading = false;
Logger.LogError(ex, "Error getting forecast for {0}({1})", zone.Name, zone.Key);
Forecast = null!;
Error = $"Unable to locate weather for {SelectedZone.Name}({SelectedZone.Key})";
}
if (string.IsNullOrEmpty(Error))
{
Summary = await Summarizer.SummarizeForecastAsync(Forecast.FirstOrDefault().DetailedForecast);
}
}- Update the forecast display to use the AI summary for background selection:
@if (SelectedZone != null && Forecast != null)
{
<div class="forecast-background-container"
style="background-image: url('img/@(Summary.ToLowerInvariant())/@(randomBackground).jpg');">
<h3 class="weather-headline">
Weather for @SelectedZone.Name<text>, </text> @SelectedZone.State (@SelectedZone.Key)
</h3>
<div class="row row-cols-1 row-cols-md-4 g-4">
@foreach (var forecast in Forecast.Take(8))
{
<div class="col">
<div class="card forecast-card">
<div class="card-header">@forecast.Name</div>
<div class="card-body">@forecast.DetailedForecast</div>
</div>
</div>
}
</div>
</div>
}We've already prepared weather-themed background images for you! The project includes an img folder in MyWeatherHub/wwwroot/img/ with the following structure:
sunny/- containing sunny weather background imagescloudy/- containing cloudy weather background imagesrainy/- containing rainy weather background imagessnowy/- containing snowy weather background images
Each folder contains multiple background images that the AI will randomly select from based on its weather analysis, creating a dynamic and visually appealing experience.
- Set up GitHub Models access: Ensure your GitHub token has access to GitHub Models
- Run the application: Use
dotnet runor the Aspire dashboard - Test AI integration: Select different weather zones and observe:
- The AI analyzing weather forecasts
- Dynamic background selection based on AI analysis
- The display showing which background the AI selected
You can customize the AI behavior by modifying the prompt in ForecastSummarizer.cs:
var prompt = $"""
You are a weather expert analyzing forecasts for background image selection.
Based on the forecast, determine the most appropriate background theme.
Available options: Sunny, Cloudy, Rainy, Snowy
Consider dominant weather patterns and time of day.
Forecast: {forecasts}
Respond with only one word from the available options.
""";The implementation includes robust error handling:
- Default to "Cloudy" background if AI fails
- Graceful degradation when GitHub Models is unavailable
- Logging for debugging AI responses
- AI calls are made only when selecting new zones
- Results could be cached for repeated zone selections
- Background image loading is optimized with CSS
The GitHub Models integration will appear in your Aspire dashboard:
- Monitor AI model usage and response times
- View connection status and health
- Debug configuration issues
Now that you have GitHub Models integrated:
- Experiment with different models - Try other available models for different use cases
- Add more AI features - Consider adding weather recommendations or alerts
- Implement caching - Cache AI responses to improve performance
- Add user preferences - Let users choose between manual and AI background selection
In this module, you added AI as a feature of your app. But Aspire 13.1 also makes AI your development partner. While GitHub Models powers your weather backgrounds, the Aspire agentic development workflow lets AI assistants operate on your entire running system.
Traditional AI coding assistants suggest code. Aspire-connected agents go further:
| Capability | Traditional AI | Aspire-Connected Agent |
|---|---|---|
| Code suggestions | ✅ | ✅ |
| Read source files | ✅ | ✅ |
| Query live resource states | ❌ | ✅ |
| Read real-time logs & traces | ❌ | ✅ |
| Run dashboard commands | ❌ | ✅ |
| Discover integrations & endpoints | ❌ | ✅ |
When you run aspire mcp init (covered in Module #6), your AI assistant connects to the Aspire MCP server. From there, it can reason about your running application — not just your source code.
Here are practical examples using your Weather Hub application:
You ask your AI agent: "The Philadelphia forecast is failing — why?"
The agent:
- Queries the Aspire dashboard for the
apiresource status - Reads recent structured logs filtered by "Philadelphia"
- Finds the
NwsManagerDiagnostics.failedRequestCounterspike - Checks the distributed trace and sees a timeout on the external weather API call
- Reports back: "The NWS API is timing out for zone PAZ071. The retry policy is firing but the upstream service is slow. Consider increasing the timeout or adding a circuit breaker."
You ask: "How is my Redis cache performing?"
The agent:
- Checks the
cache_hits_totalandcache_misses_totalmetrics - Queries Redis Insight via the dashboard endpoint
- Reports: "Cache hit rate is 73%. The zones endpoint has a 100% hit rate after the first request, but forecast requests show frequent misses because the 15-minute TTL is expiring."
You ask: "Is everything healthy?"
The agent:
- Lists all resources and their health status from the dashboard
- Checks the
/healthendpoints for bothapiandmyweatherhub - Verifies the PostgreSQL and Redis containers are running
- Reports: "All 4 resources are healthy. PostgreSQL has been up for 2 hours. Redis has 847 keys. The API has served 234 requests with a 4.2% error rate (intentional test errors)."
If you haven't already set up MCP in Module 6:
# Initialize MCP for your AI tools
aspire mcp init
# Start your application
aspire runThen open your AI assistant and start asking questions about your running system!
The combination of:
- GitHub Models (this module) — AI as an application feature
- Aspire MCP (Module #6) — AI as a development tool
- Custom Commands (Module #12) — Scriptable dashboard operations the agent can invoke
...creates a powerful feedback loop where your AI assistant understands both your code and your running infrastructure.
- Aspire Agentic Development Blog Post
- MCP for AI Coding Agents Deep Dive
- Aspire Roadmap — Agent Features
You've successfully integrated GitHub Models with your Aspire application! You now have AI-powered weather background selection that enhances the user experience with intelligent, dynamic visuals.
Throughout this workshop, you've learned how to build, configure, and enhance cloud-native applications using Aspire. You now have the skills to create resilient, observable, and scalable distributed applications with AI capabilities.
Previous: Module #13 - Healthchecks | Next: Module #15 - Docker Integration