Упражнение. Использование пользователей в запросах

Завершено

Назначение пользователей запросам может повысить качество ответов, созданных крупной языковой моделью (LLM). Personas предоставляет контекст LLM, позволяя ему последовательно создавать ответы, которые лучше соответствуют намерению пользователя. Давайте попробуем!

  1. Откройте проект Visual Studio Code, созданный в предыдущем упражнении.

  2. Обновите запрос из предыдущего упражнения следующим текстом:

    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();
    
    string language = "French";
    string history = @"I'm traveling with my kids and one of them has a peanut allergy.";
    
    // Assign a persona to the prompt
    string prompt = @$"
        You are a travel assistant. You are helpful, creative, and very friendly. 
        Consider the traveler's background:
        ${history}
    
        Create a list of helpful phrases and words in ${language} a traveler would find useful.
    
        Group phrases by category. Include common direction words. 
        Display the phrases in the following format: 
        Hello - Ciao [chow]
    
        Begin with: 'Here are some phrases in ${language} you may find helpful:' 
        and end with: 'I hope this helps you on your trip!'";
    
    var result = await kernel.InvokePromptAsync(prompt);
    Console.WriteLine(result);
    
  3. Запустите код, введя dotnet run в терминал.

    Если вы запускаете код, вы можете заметить, что ответы являются более согласованными, чем предыдущие результаты. LLM, скорее всего, создаст ответ, соответствующий назначенному пользователю и контексту задачи.

    Ответ может выглядеть примерно так:

    Here are some phrases in French you may find helpful:
    
    Greetings:
    - Hello - Bonjour [bon-zhur]
    - Goodbye - Au revoir [oh ruh-vwar]
    - Thank you - Merci [mehr-see]
    
    Directions:
    - Go straight ahead - Allez tout droit [ah-lay too dwa]
    - Turn left/right - Tournez à gauche/droite [toor-nay ah gohsh/dwaht]
    - It's on the left/right - C'est à gauche/droite [say ah gohsh/dwaht]
    
    Food:
    - Does this contain peanuts? - Est-ce que cela contient des cacahuètes? [ess-kuh suh suh-la kohn-tee-eh day kah-kah-weht?]
    - My child has a peanut allergy - Mon enfant est allergique aux cacahuètes [mohn ahn-fahn ay ah-lair-gee-k oh kah-kah-weht]
    
    ...
    
    I hope this helps you on your trip!
    

Вы также можете предоставить инструкции llM, чтобы взять на себя роль при создании ответа, а также предоставить примеры запросов и ответов. В семантическом ядре для определения ролей сообщений используется специальный синтаксис. Чтобы определить роль сообщения, можно упаковать сообщение в <message> тег с именем роли в качестве атрибута. Поддерживаемые роли: user, system, assistant и bot. Давайте попробуем!

  1. Обновите запрос следующим текстом:

    string prompt = @$"
        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>";
    

    Затем обновим входные данные, чтобы предоставить ИИ с некоторыми сведениями о поездке.

  2. input Обновите строку до следующего текста:

    string input = @"I'm planning an anniversary trip with my spouse. We like hiking, mountains, 
        and beaches. Our travel budget is $15000";
    

    Затем запустите код и просмотрите способ реагирования LLM.

  3. Введите в терминале dotnet run.

    That sounds like a great trip ahead! Here are a few suggestions:
    
    1. New Zealand - With stunning mountain ranges, iconic hiking trails, and beautiful beaches, New Zealand is a popular destination for outdoor enthusiasts. Some must-visit spots include the Milford Track, Fox Glacier, and Abel Tasman National Park.
    
    2. Hawaii - Known for its picturesque beaches, Hawaii is also home to several stunning hiking trails. The Kalalau Trail on Kauai is a popular trail that offers breathtaking views of the Na Pali Coast.
    
    3. Costa Rica - Costa Rica boasts beautiful beaches and breathtaking mountains. Hike through the Monteverde Cloud Forest Reserve and catch a glimpse of exotic wildlife like the resplendent quetzal, or take a dip in the turquoise waters of Playa Manuel Antonio.
    
    4. Banff National Park, Canada - Located in the Canadian Rockies, Banff National Park offers some of the most stunning mountain scenery in the world. Explore the park's many hiking trails, relax in hot springs, and take in the beauty of the Canadian wilderness.
    
    5. Amalfi Coast, Italy - The Amalfi Coast is a picturesque stretch of coastline in Southern Italy that offers stunning views of the Mediterranean Sea. Take a hike along the famous Path of the Gods or enjoy a romantic stroll through one of the Amalfi Coast's charming towns like Positano or Ravello.
    
    These are just a few of many options, but with a budget of $15000, you should be able to have a fantastic trip to any of these destinations!
    

    Обратите внимание, что назначение персоны LLM позволяет создавать более естественный и персонализированный разговор.

Кроме того, можно настроить запросы на менее подробные и только выходные данные. Например, предположим, что пользователь хочет получить список рейсов из одного назначения в другое. Вы можете попросить LLM проанализировать входные данные и вернуть только соответствующие сведения в формате, который можно использовать в коде. Давайте попробуем!

  1. Обновите запрос на следующий текст:

    string prompt = @$"
    <message role=""system"">Instructions: Identify the from and to destinations 
    and dates from the user's request</message>
    
    <message role=""user"">Can you give me a list of flights from Seattle to Tokyo? 
    I want to travel from March 11 to March 18.</message>
    
    <message role=""assistant"">Seattle|Tokyo|03/11/2024|03/18/2024</message>
    
    <message role=""user"">${input}</message>";
    

    В этом запросе мы используем <message> и введите пример для LLM. Мы хотим отформатировать выходные данные таким образом, чтобы мы могли анализировать этот формат в примере. Затем обновим input ИИ с некоторыми сведениями о поездке.

  2. Измените следующий input текст:

    string input = @"I have a vacation from June 1 to July 22. I want to go to Greece. 
        I live in Chicago.";
    
  3. Запустите код, введя dotnet run в терминал.

    Chicago|Greece|06/01/2024|07/22/2024
    

    Обратите внимание, что LLM смог проанализировать входные данные и вернуть только соответствующую информацию. Запрос LLM для анализа данных — отличный способ быстро получить необходимую информацию от пользователя.

Внимание

Не забудьте удалить любой код, который вы написали до сих пор, вам потребуется для следующего упражнения.