Udalosti
Vytváranie inteligentných aplikácií
17. 3., 23 - 21. 3., 23
Pripojte sa k sérii meetup a vytvorte škálovateľné riešenia AI na základe prípadov reálneho používania so spolupracovníkmi a odborníkmi.
Zaregistrovať saTento prehliadač už nie je podporovaný.
Inovujte na Microsoft Edge a využívajte najnovšie funkcie, aktualizácie zabezpečenia a technickú podporu.
In this quickstart, you learn how to create a conversational .NET console chat app using an OpenAI or Azure OpenAI model. The app uses the Microsoft.Extensions.AI library so you can write code using AI abstractions rather than a specific SDK. AI abstractions enable you to change the underlying AI model with minimal code changes.
Poznámka
The Microsoft.Extensions.AI
library is currently in Preview.
Poznámka
You can also use Semantic Kernel to accomplish the tasks in this article. Semantic Kernel is a lightweight, open-source SDK that lets you build AI agents and integrate the latest AI models into your .NET apps.
You can create your own app using the steps in the sections ahead, or you can clone the GitHub repository that contains the completed sample apps for all of the quickstarts. If you plan to use Azure OpenAI, the sample repo is also structured as an Azure Developer CLI template that can provision an Azure OpenAI resource for you.
git clone https://github.com/dotnet/ai-samples.git
Complete the following steps to create a .NET console app to connect to an AI model.
In an empty directory on your computer, use the dotnet new
command to create a new console app:
dotnet new console -o ChatAppAI
Change directory into the app folder:
cd ChatAppAI
Install the required packages:
dotnet add package Azure.Identity
dotnet add package Azure.AI.OpenAI
dotnet add package Microsoft.Extensions.AI.OpenAI
dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.UserSecrets
dotnet add package OpenAI
dotnet add package Microsoft.Extensions.AI.OpenAI
dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.UserSecrets
Open the app in Visual Studio Code (or your editor of choice).
code .
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.
From a terminal or command prompt, navigate to the src\quickstarts\azure-openai
directory of the sample repo.
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 Azure OpenAI endpoint and model name.
Navigate to the root of your .NET project from a terminal or command prompt.
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>
dotnet user-secrets set ModelName <your-openai-model-name>
The app uses the Microsoft.Extensions.AI
package to send and receive requests to the AI model and is designed to provide users with information about hiking trails.
In the Program.cs file, add the following code to connect and authenticate to the AI model.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.AI;
using Azure.AI.OpenAI;
using Azure.Identity;
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string endpoint = config["AZURE_OPENAI_ENDPOINT"];
string deployment = config["AZURE_OPENAI_GPT_NAME"];
IChatClient chatClient =
new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
.AsChatClient(deployment);
Poznámka
DefaultAzureCredential searches for authentication credentials from your local tooling. If you aren't using the azd
template to provision the Azure OpenAI resource, you'll need to assign the Azure AI Developer
role to the account you used to sign in to Visual Studio or the Azure CLI. For more information, see Authenticate to Azure AI services with .NET.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.AI;
using OpenAI;
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string model = config["ModelName"];
string key = config["OpenAIKey"];
// Create the IChatClient
IChatClient chatClient =
new OpenAIClient(key).AsChatClient(model);
Create a system prompt to provide the AI model with initial role context and instructions about hiking recommendations:
// Start the conversation with context for the AI model
List<ChatMessage> chatHistory = new()
{
new ChatMessage(ChatRole.System, """
You are a friendly hiking enthusiast who helps people discover fun hikes in their area.
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. The location where they would like to hike
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. At the end of your
response, ask if there is anything else you can help with.
""")
};
Create a conversational loop that accepts an input prompt from the user, sends the prompt to the model, and prints the response completion:
while (true)
{
// Get user prompt and add to chat history
Console.WriteLine("Your prompt:");
var userPrompt = Console.ReadLine();
chatHistory.Add(new ChatMessage(ChatRole.User, userPrompt));
// Stream the AI response and add to chat history
Console.WriteLine("AI Response:");
var response = "";
await foreach (var item in
chatClient.CompleteStreamingAsync(chatHistory))
{
Console.Write(item.Text);
response += item.Text;
}
chatHistory.Add(new ChatMessage(ChatRole.Assistant, response));
Console.WriteLine();
}
Use the dotnet run
command to run the app:
dotnet run
The app prints out the completion response from the AI model. Send additional follow up prompts and ask other questions to experiment with the AI chat functionality.
When you no longer need the sample application or resources, remove the corresponding deployment and all resources.
azd down
Pripomienky k produktu .NET
.NET je open-source projekt. Ak chcete poskytnúť pripomienky, vyberte prepojenie:
Udalosti
Vytváranie inteligentných aplikácií
17. 3., 23 - 21. 3., 23
Pripojte sa k sérii meetup a vytvorte škálovateľné riešenia AI na základe prípadov reálneho používania so spolupracovníkmi a odborníkmi.
Zaregistrovať saŠkolenie
Modul
Generate text and conversations with .NET and Azure OpenAI Completions - Training
Learn how to use the .NET SDK with the Azure OpenAI service to have your applications carry on conversations with users in natural language.
Certifikácia
Microsoft Certified: Azure AI Fundamentals - Certifications
Demonstrate fundamental AI concepts related to the development of software and services of Microsoft Azure to create AI solutions.
Dokumentácia
Quickstart - Generate images using AI with .NET - .NET
Create a simple app using to generate images using .NET and the OpenAI or Azure OpenAI models.
Quickstart - Build a minimal .NET AI RAG app - .NET
Create an AI powered app to search and integrate with vector stores using embeddings and the Microsoft.Extensions.VectorData package for .NET
Quickstart - Summarize text using an AI chat app with .NET - .NET
Create a simple chat app using Microsoft.Extensions.AI to summarize a text.