使用Prompty轻松将AI添加到您的.NET应用程序

目录

Prompty简介

开发人员在Visual Studio Code中使用Prompty的典型流程描述

使用WebAPI应用程序的真实示例

第1步:设置WebAPI项目

第2步:为Forecast创建更具描述性的摘要

第3步:使用prompty更新终端节点以获取预测摘要

总结


.NET开发中添加AI功能是一种令人兴奋的新体验。在这篇博文中,我们将探讨Prompty以及如何使用它来将大型语言模型(如GPT-4o)集成到您的开发流程和.NET应用程序中。

Prompty简介

作为AI爱好者和.NET开发人员,我们一直在寻找能够简化工作流程并提高工作效率的工具。Prompty就是这样一个强大的工具,它是一个Visual Studio Code扩展,旨在促进将GPT-4o等大型语言模型(LLM)集成到您的应用程序中。Prompty提供了一个直观的界面,可以直接从您的开发环境与LLM进行交互,从而比以往任何时候都更容易将AI功能添加到您的项目中。

PromptyMicrosoft开发,可在Visual Studio Code市场上免费获得。无论您是构建聊天机器人、创建内容生成器,还是试验其他AI驱动的应用程序,Prompty都可以显着简化您的开发过程。

开发人员在Visual Studio Code中使用Prompty的典型流程描述

 

  

让我们看一下如何使用Prompty的示例流程。此过程通常涉及几个关键步骤:

1、安装: 首先从Visual Studio Code Marketplace安装Prompty扩展。

2、设置:安装后,通过提供您的API密钥并设置必要的参数来配置扩展以连接到您选择的LLM,例如GPT-4o

3、集成: Prompty与您的开发工作流程无缝集成。首先创建一个新文件或打开一个要使用LLM的现有文件。Prompty提供命令和代码段,以便轻松插入提示和处理响应。

4、开发:直接在代码库中编写提示以与LLM交互。Prompty支持各种提示格式,并提供语法高亮显示,使您的提示可读和可维护。

您可以使用该扩展生成代码片段、创建文档,甚至通过向LLM询问特定问题来调试您的应用程序。准备好提示后,您可以使用该扩展生成代码片段、创建文档,甚至通过向LLM询问特定问题来调试您的应用程序。

5、测试:测试您的提示并根据需要进行调整,以便从LLM获得所需的响应。Prompty允许您快速迭代,优化您的提示以提高AI响应的准确性和相关性。

使用WebAPI应用程序的真实示例

让我们来看看在.NET WebAPI应用程序中使用Prompty的实际示例。

1步:设置WebAPI项目

首先,使用.NET CLI创建一个名为PromptyWebAPI的新WebAPI项目:

dotnet new webapi -n PromptyWebAPI
cd PromptyWebAPI

添加以下依赖项:

dotnet add package Microsoft.SemanticKernel --version 1.15.1
dotnet add package Microsoft.SemanticKernel.Prompty --version 1.15.1-alpha
dotnet add package Microsoft.Extensions.Configuration.UserSecrets --version 8.0.0

直接从Visual Studio Code或使用命令运行项目:

dotnet run

我们将看到标准的Weather Forecast API端点。

  

注意:WebAPI项目使用用户密钥访问GPT-4o Azure OpenAI模型。使用以下命令设置用户密钥:

dotnet user-secrets init
dotnet user-secrets set "AZURE_OPENAI_MODEL" "< model >"
dotnet user-secrets set "AZURE_OPENAI_ENDPOINT" "< endpoint >"
dotnet user-secrets set "AZURE_OPENAI_APIKEY" "< api key >"

2步:为Forecast创建更具描述性的摘要

天气预报返回一个虚构的预报,包括日期、温度(CF)和摘要。我们的目标是创建一个可以生成更详细总结的Prompt

让我们将一个新的prompty文件添加到PromptyWebAPI文件夹的根目录下。这就像right-clickNew Prompty一样简单。将创建的文件重命名为weatherforecastdesc.prompty

我们的解决方案应如下所示:

 

  

现在是时候完成prompty文件的各个部分了。每个部分都包含与使用LLM相关的特定信息。例如,model部分将定义要使用的模型,sample部分将为预期输出提供示例,最后我们可以使用提示。

在以下示例中,提示定义System消息,在Context中,我们提供天气参数。

prompty文件的内容替换为以下内容。

---
name: generate_weather_detailed_description
description: A prompt that generated a detaled description for a weather forecast
authors:
  - Bruno Capuano
model:
  api: chat
  configuration:
    type: azure_openai
    azure_endpoint: ${env:AZURE_OPENAI_ENDPOINT}
    azure_deployment: ${env:AZURE_OPENAI_MODEL}
  parameters:
    max_tokens: 3000
sample:
  today: > 
    2024-07-16

  date: > 
    2024-07-17

  forecastTemperatureC: >
    25°C
---

# System:
You are an AI assistant who generated detailed weather forecast descriptions. The detailed description is a paragraph long.
You use the full description of the date, including the weekday.
You also give a reference to the forecast compared to the current date today.
As the assistant, you generate descriptions using a funny style and even add some personal flair with appropriate emojis.

# Context
Use the following context to generated a detailed weather forecast descriptions 
- Today: {{today}}
- Date: {{date}}
- TemperatureC: {{forecastTemperatureC}}

一旦我们的prompty准备好了,我们就可以按 F5 测试提示符了。运行prompty后,我们应该在输出窗口中看到结果:

 

  

现在是开始完善我们的提示的时候了!

奖金:右键单击prompty文件,也允许使用Semantic Kernel生成C#代码以使用当前文件。

 

  

注意:在此之前,我们需要为prompty提供必要的信息以供LLM使用。按照扩展配置来执行此操作。最简单的方法是创建一个包含LLM信息的.env文件。

3步:使用prompty更新终端节点以获取预测摘要

现在我们可以直接在项目中使用Semantic Kernel来使用这个prompty。让我们编辑program.cs文件并应用以下更改:

  • 将必要的usings添加到文件顶部。
  • 创建Semantic Kernel以生成预测摘要。
  • 在预测结果中添加新的预测摘要。

为了生成详细的摘要,Semantic Kernel将使用prompty文件和天气信息。

using Microsoft.SemanticKernel;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// Azure OpenAI keys
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
var deploymentName = config["AZURE_OPENAI_MODEL"];
var endpoint = config["AZURE_OPENAI_ENDPOINT"];
var apiKey = config["AZURE_OPENAI_APIKEY"];

// Create a chat completion service
builder.Services.AddKernel();
builder.Services.AddAzureOpenAIChatCompletion(deploymentName, endpoint, apiKey);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapGet("/weatherforecast", async (HttpContext context, Kernel kernel) =>
{
    var forecast = new List<WeatherForecast>();
    for (int i = 0; i < 3; i++)
    {
        var forecastDate = DateOnly.FromDateTime(DateTime.Now.AddDays(i));
        var forecastTemperature = Random.Shared.Next(-20, 55);

        var weatherFunc = kernel.CreateFunctionFromPromptyFile("weatherforecastdesc.prompty");
        var forecastSummary = await weatherFunc.InvokeAsync<string>(kernel, new()
        {
            { "today", $"{DateOnly.FromDateTime(DateTime.Now)}" },
            { "date", $"{forecastDate}" },
            { "forecastTemperatureC", $"{forecastTemperature}" }
        });

        forecast.Add(new WeatherForecast(forecastDate, forecastTemperature, forecastSummary));
    }
    return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

当我们再次测试/weatherforecast终端节点时,输出应包含更详细的摘要。以下示例包括当前日期(Jul-16)和另外2天:

注意:这些是随机生成的温度。我不确定一天内温度是否会从-4C/25F 变为45C/112F

[
  {
    "date": "2024-07-16",
    "temperatureC": -4,
    "summary": " Happy Tuesday, July 16th, 2024, folks! Guess what? Today’s weather forecast is brought to you by the Frozen Frappuccino Club, because it’s a chilly one! With a temperature of -4°C, it’s colder than a snowman’s nose out there!  So, get ready to channel your inner penguin and waddle through the frosty air. Remember to layer up with your snuggiest sweaters and warmest scarves, or you might just turn into an icicle! Compared to good old yesterday, well... there’s not much change, because yesterday was just as brrrrr-tastic. Stay warm, my friends, and maybe keep a hot chocolate handy for emergencies! ",
    "temperatureF": 25
  },
  {
    "date": "2024-07-17",
    "temperatureC": 45,
    "summary": " Well, buckle up, buttercup, because *Wednesday, July 17, 2024*, is coming in hot! If you thought today was toasty, wait until you get a load of tomorrow. With a sizzling temperature of 45°C, it's like Mother Nature cranked the thermostat up to \"sauna mode.\"  Don't even think about wearing dark colors or stepping outside without some serious SPF and hydration on standby! Maybe it's a good day to try frying an egg on the sidewalk for breakfast—just kidding, or am I?  Anyway, stay cool, find a shady spot, and keep your ice cream close; you're gonna need it! ",
    "temperatureF": 112
  },
  {
    "date": "2024-07-18",
    "temperatureC": 35,
    "summary": "Ladies and gentlemen, fasten your seatbelts and hold onto your hats—it’s going to be a sizzling ride!  On Thursday, July 18, 2024, just two days from today, Mother Nature cranks up the heat like she’s trying to turn the entire planet into a giant summer barbecue.  With the temperature shooting up to a toasty 35°C, it’s the perfect day to channel your inner popsicle in front of the A/C. Water fights, ice cream sundaes, and epic pool floats are all highly recommended survival strategies. And remember, folks, sunscreen is your best friend—don't be caught out there lookin’ like a lobster in a sauna!  So get ready to sweat but with style, as we dive headfirst into the fantastic scorching adventure that Thursday promises to be! ",
    "temperatureF": 94
  }
]

总结

Prompty.NET开发人员提供了一种将AI功能集成到其应用程序中的有效方法。通过使用此Visual Studio Code扩展,开发人员可以毫不费力地将GPT-4o和其他大型语言模型整合到他们的工作流程中。

PromptySemantic Kernel简化了生成代码片段、创建文档和调试应用程序的过程,以AI驱动为重点。

要了解有关Prompty的更多信息并探索其功能,请访问Prompty主页,查看Prompty Visual Studio Code扩展,深入研究 GitHub上的Prompty源代码或观看构建会议使用Prompty和AI Studio进行实用的端到端AI开发|BRK114 的。

https://devblogs.microsoft.com/dotnet/add-ai-to-your-dotnet-apps-easily-with-prompty/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值