Упражнение. Сохранение запросов на файлы
Предположим, вы хотите предложить места для путешествий и рекомендовать действия для пользователя. В этом упражнении вы практикуете создавать запросы и сохранять их в файлах. Приступим.
Откройте проект Visual Studio Code, созданный в предыдущем упражнении.
В файле Program.cs удалите
prompt
созданные в предыдущем упражнении переменные,input
чтобы вы оставили следующий код:using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.Core; var builder = Kernel.CreateBuilder(); builder.AddAzureOpenAIChatCompletion( "your-deployment-name", "your-endpoint", "your-api-key", "deployment-model"); var kernel = builder.Build();
Убедитесь, что в проекте существуют следующие папки:
- "Запросы"
- "Запросы/TravelPlugins"
- "Запросы/TravelPlugins/SuggestDestinations"
- "Запросы/TravelPlugins/GetDestination"
- "Запросы/TravelPlugins/SuggestActivities"
Эти каталоги помогут упорядочить запросы. Сначала вы создадите запрос, определяющий назначение, к которому пользователь хочет отправиться. Чтобы создать запрос, необходимо создать config.json и файлы skprompt.txt. Приступим.
В папке GetDestination откройте файл config.json и введите следующий код:
{ "schema": 1, "type": "completion", "description": "Identify the destination of the user's travel plans", "execution_settings": { "default": { "max_tokens": 1200, "temperature": 0 } }, "input_variables": [ { "name": "input", "description": "Text from the user that contains their travel destination", "required": true } ] }
Эта конфигурация сообщает ядру, что делает запрос и какие входные переменные следует принимать. Затем вы укажите текст запроса в файле skprompt.txt.
В папке GetDestination откройте файл skprompt.txt и введите следующий текст:
<message role="system"> Instructions: Identify the destination the user wants to travel to. </message> <message role="user"> I am so excited to take time off work! My partner and I are thinking about going to Santorini in Greece! I absolutely LOVE Greek food, I can't wait to be some place warm. </message> <message role="assistant">Santorini, Greece</message> <message role="user">{{$input}}</message>
Этот запрос помогает большой языковой модели отфильтровать входные данные пользователя и получить только место назначения из текста.
В папке SuggestDestinations откройте файл config.json и введите следующий текст:
{ "schema": 1, "type": "completion", "description": "Recommend travel destinations to the user", "execution_settings": { "default": { "max_tokens": 1200, "temperature": 0.3 } }, "input_variables": [ { "name": "input", "description": "Details about the user's travel plans", "required": true } ] }
В этой конфигурации можно немного увеличить температуру, чтобы сделать выходные данные более творческими.
В папке SuggestDestinations откройте файл skprompt.txt и введите следующий текст:
The following is a conversation with an AI travel assistant. The assistant is helpful, creative, and very friendly. <message role="user">Can you give me some travel destination suggestions?</message> <message role="assistant">Of course! Do you have a budget or any specific activities in mind?</message> <message role="user">${input}</message>
В этом запросе предполагается, что назначения для поездки пользователю основаны на входных данных. Теперь создадим подключаемый модуль, чтобы рекомендовать действия в их назначении.
В папке SuggestActivities откройте файл config.json и введите следующий текст:
{ "schema": 1, "type": "completion", "description": "Recommend activities at a travel destination to the user", "execution_settings": { "default": { "max_tokens": 4000, "temperature": 0.3 } }, "input_variables": [ { "name": "history", "description": "Background information about the user", "required": true }, { "name": "destination", "description": "The user's travel destination", "required": true } ] }
В этой конфигурации вы увеличиваете
max_tokens
объем текста для журнала и созданного текста.В папке SuggestActivities откройте файл skprompt.txt и введите следующий текст:
You are a travel assistant. You are helpful, creative, and very friendly. Consider your previous conversation with the traveler: {{$history}} The traveler would like some activity recommendations, things to do, and points of interest for their trip. They want to go to {{$destination}}. Please provide them with a list of things they might like to do at their chosen destination.
Теперь давайте импортируем и протестируем новые запросы!
Обновите файл Program.cs следующим кодом:
using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.Core; using Microsoft.SemanticKernel.ChatCompletion; var builder = Kernel.CreateBuilder(); builder.AddAzureOpenAIChatCompletion( "your-deployment-name", "your-endpoint", "your-api-key", "deployment-model"); var kernel = builder.Build(); kernel.ImportPluginFromType<ConversationSummaryPlugin>(); var prompts = kernel.ImportPluginFromPromptDirectory("Prompts/TravelPlugins"); ChatHistory history = []; string input = @"I'm planning an anniversary trip with my spouse. We like hiking, mountains, and beaches. Our travel budget is $15000"; var result = await kernel.InvokeAsync<string>(prompts["SuggestDestinations"], new() {{ "input", input }}); Console.WriteLine(result); history.AddUserMessage(input); history.AddAssistantMessage(result);
В этом коде вы импортируете созданные подключаемые модули. Вы также используете
ChatHistory
объект для хранения беседы пользователя. Наконец, вы передаете некоторые сведенияSuggestDestinations
в запрос и записываете результаты. Далее давайте попросим пользователя, где они хотят пойти, чтобы мы могли рекомендовать некоторые действия для них.Добавьте следующий код в файл Program.cs :
Console.WriteLine("Where would you like to go?"); input = Console.ReadLine(); result = await kernel.InvokeAsync<string>(prompts["SuggestActivities"], new() { { "history", history }, { "destination", input }, } ); Console.WriteLine(result);
В этом коде вы получите некоторые входные данные от пользователя, чтобы узнать, куда они хотят пойти. Затем вызовите
SuggestActivities
запрос с назначением и журналом бесед.Чтобы проверить код, введите
dotnet run
в терминале.Окончательные выходные данные могут выглядеть примерно так:
Absolutely! Japan is a wonderful destination with so much to see and do. Here are some recommendations for activities and points of interest: 1. Visit Tokyo Tower: This iconic tower offers stunning views of the city and is a must-visit attraction. 2. Explore the temples of Kyoto: Kyoto is home to many beautiful temples, including the famous Kiyomizu-dera and Fushimi Inari-taisha. 3. Experience traditional Japanese culture: Attend a tea ceremony, try on a kimono, or take a calligraphy class to immerse yourself in Japanese culture.
Теперь вы создали начало помощника по путешествиям ИИ! Попробуйте изменить входные данные, чтобы узнать, как llM отвечает.