使用 .NET 建置 AI 聊天應用程式

建立簡單的 .NET 8 主控台聊天應用程式,以便開始使用 OpenAI 和 Semantic Kernel。 應用程式會在本機執行,並使用 OpenAI gpt-3.5-turbo 模型。 請遵循下列步驟來取得 OpenAI 的存取權,並了解如何使用 Semantic Kernel。

必要條件

  • .NET 8.0 SDK - 安裝 .NET 8.0 SDK
  • OpenAI 中的 API 金鑰,因此您可以執行此範例。
  • 在 Windows 上,需要 PowerShell v7+。 若要驗證您的版本,請在終端機中執行 pwsh。 其應該會傳回目前的版本。 如果傳回錯誤,請執行下列命令:dotnet tool update --global PowerShell

建立簡單的 .NET 8 主控台聊天應用程式,以便開始使用 OpenAI 和 Semantic Kernel。 應用程式會在本機執行,並連線至已部署到 Azure OpenAI 的 OpenAI gpt-35-turbo 模型。 請遵循下列步驟來佈建 Azure OpenAI,並了解如何使用 Semantic Kernel。

必要條件

取得範例專案

複製 GitHub 存放庫,其中包含所有快速入門的範例應用程式:

git clone https://github.com/dotnet/ai-samples.git

建立 Azure OpenAI 服務

範例 GitHub 存放庫的結構是 Azure 開發人員 CLI (azd) 範本, azd 可用來為您布建 Azure OpenAI 服務和模型。

  1. 從終端機或命令提示字元中,流覽至 範例存放庫的 src\quickstarts\azure-openai 目錄。

  2. azd up執行 命令來布建 Azure OpenAI 資源。 建立 Azure OpenAI 服務並部署模型可能需要幾分鐘的時間。

    azd up
    

    azd 也會為範例應用程式設定必要的用戶密碼,例如 OpenAI 存取金鑰。

    注意

    如果您在部署 azd up 期間遇到錯誤,請造訪疑難排解一節。

嘗試 HikerAI 範例

  1. 從終端機或命令提示字元中,瀏覽至 openai\02-HikerAI 目錄。

  2. 執行下列命令,將 OpenAI API 金鑰設定為範例應用程式的祕密:

    dotnet user-secrets init
    dotnet user-secrets set OpenAIKey <your-openai-key>
    
  3. 使用 dotnet run 命令來執行應用程式:

    dotnet run
    
  1. 從終端機或命令提示字元中,瀏覽至 azure-openai\02-HikerAI 目錄。

  2. 使用 dotnet run 命令來執行應用程式:

    dotnet run
    

    提示

    如果您收到錯誤訊息,Azure OpenAI 資源可能尚未完成部署。 請稍候幾分鐘再試一次。

探索程式碼

應用程式會使用 Microsoft.SemanticKernel 套件來傳送及接收 OpenAI 服務的要求。

應用程式程式碼包含在 Program.cs 檔案中。 前幾行程式碼會設定組態值,並取得先前使用 dotnet user-secrets 命令設定的 OpenAI 金鑰。

var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string model = "gpt-3.5-turbo";
string key = config["OpenAIKey"];

OpenAIChatCompletionService 服務促進要求和回應。

// Create the OpenAI Chat Completion Service
OpenAIChatCompletionService service = new(model, key);

探索程式碼

應用程式使用 Microsoft.SemanticKernel 套件來傳送及接收在 Azure 中部署的 Azure OpenAI 服務之要求。

整個應用程式都包含在 Program.cs 檔案中。 前幾行程式碼會擷取應用程式佈建期間在 dotnet user-secrets 中設定的秘密和組態值。

// Retrieve the local secrets saved during the Azure deployment
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string endpoint = config["AZURE_OPENAI_ENDPOINT"];
string deployment = config["AZURE_OPENAI_GPT_NAME"];
string key = config["AZURE_OPENAI_KEY"];

AzureOpenAIChatCompletionService 服務促進要求和回應。

// Create the Azure OpenAI Chat Completion Service
AzureOpenAIChatCompletionService service = new(deployment, endpoint, key);

新增系統提示,為模型提供更多內容,這會影響模型行為以及在交談期間產生的完成。

// Start the conversation with context for the AI model
ChatHistory chatHistory = new("""
    You are a hiking enthusiast who helps people discover fun hikes in their area. 
    You are upbeat and friendly. You introduce yourself when first saying hello.
    When helping people out, you always ask them for this information
    to inform the hiking recommendation you provide:

    1. Where they are located
    2. What hiking intensity they are looking for

    You will then provide three suggestions for nearby hikes that vary in length
    after you get that information. You will also share an interesting fact about
    the local nature on the hikes when making a recommendation.
    """);

使用 AddUserMessage 函式將使用者訊息新增至聊天記錄。 使用 GetChatMessageContentAsync 函式,指示模型根據系統提示和使用者要求產生回應。


// Add user message to chat history
chatHistory.AddUserMessage("Hi! Apparently you can help me find a hike that I will like?");

// Print User Message to console
Console.WriteLine($"{chatHistory.Last().Role} >>> {chatHistory.Last().Content}");

// Get response
var response = await service.GetChatMessageContentAsync(
    chatHistory, new OpenAIPromptExecutionSettings() { MaxTokens = 400 });

從模型新增回應以維護聊天記錄。

// Add response to chat history
chatHistory.Add(response);

// Print Response to console
Console.WriteLine($"{chatHistory.Last().Role} >>> {chatHistory.Last().Content}");

自訂系統提示和使用者訊息來查看模型如何回應,協助您找到喜歡的登山路線。

清除資源

當您不再需要範例應用程式或資源時,請移除對應的部署和所有資源。

azd down

疑難排解

在 Windows 上,執行 azd up 之後,您可能會收到下列錯誤訊息:

postprovision.ps1 未以數位方式簽署。 指令碼不會在系統上執行

執行指令碼 postprovision.ps1 以設定應用程式中使用的 .NET 使用者密碼。 若要避免此錯誤,請執行下列 PowerShell 命令:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

然後重新執行 azd up 命令。

另一個可能的錯誤:

'pwsh' 並未經辨識為內部或外部命令、可執行程式或批次檔案。 警告:'postprovision' 攔截失敗,結束代碼為:'1',路徑:'.\infra\post-script\postprovision.ps1'。 :結束代碼:1 會繼續執行,因為 ContinueOnError 已設定為 true。

執行指令碼 postprovision.ps1 以設定應用程式中使用的 .NET 使用者密碼。 若要避免此錯誤,請使用下列 PowerShell 命令手動執行指令碼:

.\infra\post-script\postprovision.ps1

.NET AI 應用程式現在已設定使用者祕密,且可以進行測試。

下一步