将.Net AI插件集成到自己的程序中

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

Prompty 简介

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

Prompty 由 Microsoft 开发,可在 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 创建一个名为 的新 WebAPI 项目:PromptyWebAPI

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

我们将看到标准的天气预报 API 端点。

在浏览器中运行的 WebAPI 项目

注意: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 步:为预测创建更具描述性摘要的提示

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

让我们将一个新的提示文件添加到文件夹的根目录。这就像 和 一样简单。将创建的文件重命名为 。PromptyWebAPIright-clickNew Promptyweatherforecastdesc.prompty

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

解决方案资源管理器视图,显示添加到解决方案的提示文件

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

在以下示例中,提示定义了一个系统消息,在 Context 中,我们提供了天气的参数。

将提示文件的内容替换为以下内容。

---
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}}

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

直接在输出窗口中使用结果进行快速测试

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

提示:右键单击提示文件,也允许使用语义内核生成 C# 代码以使用当前文件。

从提示文件生成语义内核代码

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

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

现在我们可以直接在我们的项目中使用语义内核来使用这个提示符。让我们编辑该文件并应用以下更改:program.cs

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

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

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);
}

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

注意:这些是随机生成的温度。我不确定一天内温度从 -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 和其他大型语言模型合并到他们的工作流程中。

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

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

posted @ 2024-08-19 20:14  Flamesky  阅读(17)  评论(0编辑  收藏  举报