संपादित करें

इसके माध्यम से साझा किया गया


Build an AI chat app with .NET

Get started with OpenAI and Semantic Kernel by creating a simple .NET 8 console chat application. The application will run locally and use the OpenAI gpt-3.5-turbo model. Follow these steps to get access to OpenAI and learn how to use Semantic Kernel.

Prerequisites

  • .NET 8.0 SDK - Install the .NET 8.0 SDK.
  • An API key from OpenAI so you can run this sample.
  • On Windows, PowerShell v7+ is required. To validate your version, run pwsh in a terminal. It should return the current version. If it returns an error, execute the following command: dotnet tool update --global PowerShell.

Get started with OpenAI and Semantic Kernel by creating a simple .NET 8 console chat application. The application will run locally and connect to the OpenAI gpt-35-turbo model deployed into Azure OpenAI. Follow these steps to provision Azure OpenAI and learn how to use Semantic Kernel.

Prerequisites

Get the sample project

Clone the GitHub repository that contains the sample apps for all of the quickstarts:

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

Create the Azure OpenAI service

The sample GitHub repository is structured as an Azure Developer CLI (azd) template, which azd can use to provision the Azure OpenAI service and model for you.

  1. From a terminal or command prompt, navigate to the src\quickstarts\azure-openai directory of the sample repo.

  2. Run the azd up command to provision the Azure OpenAI resources. It might take several minutes to create the Azure OpenAI service and deploy the model.

    azd up
    

    azd also configures the required user secrets for the sample app, such as the OpenAI access key.

    Note

    If you encounter an error during the azd up deployment, visit the troubleshooting section.

Try the HikerAI sample

  1. From a terminal or command prompt, navigate to the openai\02-HikerAI directory.

  2. Run the following commands to configure your OpenAI API key as a secret for the sample app:

    dotnet user-secrets init
    dotnet user-secrets set OpenAIKey <your-openai-key>
    
  3. Use the dotnet run command to run the app:

    dotnet run
    
  1. From a terminal or command prompt, navigate to the azure-openai\02-HikerAI directory.

  2. Use the dotnet run command to run the app:

    dotnet run
    

    Tip

    If you get an error message, the Azure OpenAI resources might not have finished deploying. Wait a couple of minutes and try again.

Explore the code

The app uses the Microsoft.SemanticKernel package to send and receive requests to the OpenAI service.

The app code is contained within the Program.cs file. The first several lines of code set configuration values and get the OpenAI Key that was previously set using the dotnet user-secrets command.

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

The OpenAIChatCompletionService service facilitates the requests and responses.

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

Explore the code

The application uses the Microsoft.SemanticKernel package to send and receive requests to an Azure OpenAI service deployed in Azure.

The entire application is contained within the Program.cs file. The first several lines of code retrieve the secrets and configuration values that were set in the dotnet user-secrets for you during the application provisioning.

// 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"];

The AzureOpenAIChatCompletionService service facilitates the requests and responses.

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

Add a system prompt to provide more context to the model, which influences model behavior and the generated completions during the conversation.

// 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.
    """);

Add a user message to the chat history using the AddUserMessage function. Use the GetChatMessageContentAsync function to instruct the model to generate a response based off the system prompt and the user request.


// 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 the response from the mode to maintain the chat history.

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

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

Customize the system prompt and user message to see how the model responds to help you find a hike that you'll like.

Clean up resources

Remove the corresponding deployment and all resources when you no longer need the sample application or resources.

azd down

Troubleshoot

On Windows, you might get the following error messages after running azd up:

postprovision.ps1 is not digitally signed. The script will not execute on the system

The script postprovision.ps1 is executed to set the .NET user secrets used in the application. To avoid this error, run the following PowerShell command:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

Then re-run the azd up command.

Another possible error:

'pwsh' is not recognized as an internal or external command, operable program or batch file. WARNING: 'postprovision' hook failed with exit code: '1', Path: '.\infra\post-script\postprovision.ps1'. : exit code: 1 Execution will continue since ContinueOnError has been set to true.

The script postprovision.ps1 is executed to set the .NET user secrets used in the application. To avoid this error, manually run the script using the following PowerShell command:

.\infra\post-script\postprovision.ps1

The .NET AI apps now have the user secrets configured and they can be tested.

Next steps