AI Summarization Agent🧾 in 7 minutes! 🔥



This content originally appeared on DEV Community and was authored by vamsi dogiparthi

Hi Buddy! Welcome to a quick tutorial on building an AI summarization agent that will allow you to summarize lengthier meeting conversations, long pages of various concepts using Semantic Kernel & Open API (model GPT 4o).

This will be a quick tutorial aimed to be max of 7mins for you to quickly create an AI Agent.

This tutorial uses 2 major tools.

  • Semantic Kernel (Chat completion & Function plugins).
  • Open AI Account (with paid or trail use).

So, without wasting anymore time lets dive into the rest of the steps.

Prerequisites:

  • Create an Open AI Account.
  • Create a project in Open AI Account.
    Open AI Project creation pic

  • Add a token amount if you are choosing the paid version in the billing section.

  • Download Visual Studio and .NET 9 framework through this link.

Step by Step Project setup:

  • Create new Console Application using .NET9.
  • Install below necessary packages.
dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.Extensions.Logging
dotnet add package Microsoft.Extensions.Logging.Console
dotnet add package Microsoft.Extensions.Configuration.FileExtensions
dotnet add package Microsoft.Extensions.Configuration.Json
dotnet add package Microsoft.Extensions.Configuration.UserSecrets
dotnet add package Microsoft.Extensions.Configuration.CommandLine
dotnet add package Microsoft.Extensions.Configuration.EnvironmentVariables
dotnet add package Microsoft.SemanticKernel.PromptTemplates.Handlebars
dotnet add package Microsoft.SemanticKernel.Yaml
  • Add appsettings.json file to the project directory and add below code to the csproj project file.
<ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
</ItemGroup>
  • Add OpenAIConfiguration.cs to Options folder underneath the project.
namespace AIAgentTextSummarization.Options
{
    public class OpenAIConfiguration
    {
        public const string SectionName = "OpenAIConfiguration";
        public string Endpoint { get; set; } = string.Empty;
        public string ApiKey { get; set; } = string.Empty;
        public string ModelId { get; set; } = string.Empty;
        public int MaxTokens { get; set; }
        public double Temperature { get; set; }
        public double TopP { get; set; }
    }
}
  • Add TextSummarizationPlugin.cs to Plugins folder
using System.ComponentModel;
using AIAgentTextSummarization.Services;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.PromptTemplates.Handlebars;

namespace AIAgentTextSummarization.Plugins.PromptPlugins.TextSummarizationPromptPlugin;

public class TextSummarizationPromptPlugin(ILogger<TextSummarizationPromptPlugin> logger)
{
    [KernelFunction("summarize_text")]
    [Description("Summarize the given text.")]
    public async Task<FunctionResult?> GetSummarizedText(
        [Description("input text to be summarize")] string input,
        Kernel kernel
    )
    {
        var handlebarsPromptYaml = EmbeddedResource.Read("TextSummarizationYamlTemplate.yaml");
        var templateFactory = new HandlebarsPromptTemplateFactory();
        var function = kernel.CreateFunctionFromPromptYaml(handlebarsPromptYaml, templateFactory);

        var arguments = new KernelArguments() { { "input", input } };

        var response = await kernel.InvokeAsync(function, arguments);
        logger.LogInformation("Response: {Response}", response);
        return response;
    }
}
  • Add TextSummarizationPromptTemplate.yaml to Plugins -> PromptPlugins -> TextSummarizationPromptPlugin folder.
name: SummarizeInformation
template: |
  <message role="system">
      # System Instructions
      You are a expert text summarizer. Your task is to summarize the information provided in the conversation history into key points.
      You should focus on the most important details and present them in a clear and concise manner.
      The summary should categorize the 7 main sections: 
      Acronyms, Glossary, Problem Statement, Description, Key Points, Entities (Location, people, places, Books), Next Steps.
      Each section should be clearly labeled and the information should be presented in a bullet point format.

      Each section should have atmost 5 bullet points.
      The summary should be no more than 200 words in total.

      You should also correct any grammar and spelling errors in the history.
      The summary should be in English.
      The summary should be in a professional tone and should not include any personal opinions or subjective statements.

      # Safety
      - Don't use any bad words, hateful tone, angy tone, sad tone.
      - Don't use any sensitive information, or confidential information.         

      # Example Input starts here:
      - Bruce: These days people are so busy with their work that they don't have time to read books and know about the history
      - Wayne: Yes, I agree. I think it's important to take time to read and learn about our history. We are what we are because of our past.
      - Bruce: I think we should make it a point to read at least one book a month. It can be about anything, but it should be something that teaches us something new.
      - Wayne: That's a great idea! I will try to do that. I think it will help us grow as individuals and as a society.
      - Bruce: I read about different cultures and their history, expecially native indian culture. I think it's important to understand and appreciate the diversity of our world.
      - Wayne: Yes, I agree. Understanding different cultures can help us become more empathetic and open-minded. It can also help us appreciate the beauty of our world.
      - Marry: I think we should also make an effort to learn about the history of our own culture and heritage. It's important to know where we come from and what has shaped us as a people.
      - Bruce: Yes, I agree. I think it's important to have a strong sense of identity and to understand our roots. It can help us navigate the world and make informed decisions about our future.
      - Wayne: We should also learn about historical places like the pyramids and the great wall of china. They are not only important landmarks, but they also tell us a lot about the cultures and civilizations that built them.
      # Example Input ends here.
      # Example Output Starts Here:
      -Acronyms:
          - N/A
      -Glossary:
          - Empathy: The ability to understand and share the feelings of another.
          - Heritage: Property that is or may be inherited; an inheritance.
          - Culture: The ideas, customs, and social behavior of a particular people or society.
          - Diversity: The state of being diverse; variety.
      - Problem Statement:
          - People are busy with work and don't have time to read books.
          - Importance of reading and learning about history.
          - Suggestion to read at least one book a month.
          - Learn about historical places and cultures.
          - Understanding different cultures can help us become more empathetic.
      - Key Points:
          - People are busy with work and don't have time to read books.
          - Importance of reading and learning about history.
          - Suggestion to read at least one book a month.
          - Understanding different cultures can help us become more empathetic.
          - Importance of learning about our own culture and heritage.
      - Description:
          - People are busy with work and don't have time to read books.
          - Importance of reading and learning about history.
          - Suggestion to read at least one book a month.
          - Understanding different cultures can help us become more empathetic.
          - Importance of learning about our own culture and heritage.
      - Entities:
            - Locations: China
            - People: Bruce, Wayne, Marry
            - Places: Pyramids, Great Wall of China
            - Books: Great wall of china, george washignton, native indian culture
      - Next Steps: 
            - Make it a point to read at least one book a month.
            - Learn about different cultures and their history.
            - Understand and appreciate the diversity of our world.
            - Learn about the history of our own culture and heritage.
            - Learn about historical places like the pyramids and the great wall of china.
        #Example Output ends Here
  </message>
  <message role="user">
        {{input}}
  </message>
template_format: handlebars
description: Contoso chat prompt template.
input_variables:
  - name: input
    description: user message to be summarized.
    is_required: true
    allow_dangerously_set_content : false
output_variable:
  description: The summarized information.
execution_settings:
  service1:
    model_id: gpt-4o
    temperature: 0.6
  default:
    temperature: 0.5
  • Add conversation.txt as our conversation sample to be used for this text summarization project under Assets folder
**Conversation:**

**Emma:** *Alright everyone, today’s family picnic turned into a history class. But that’s okay, isn’t it?* Look at this—Statue of Liberty! It’s stunning, isn’t it?

**Ryan:** *Yeah, it’s alright,* but don’t you think some monuments are... um... boring? Like, why do we even care about something from, like, the 1800s?

**Maya:** *Oh, Ryan!* You youngsters have so much to learn. The Statue of Liberty, gifted by France in 1886, represents freedom and democracy. Imagine the stories it witnessed over time. You can't call that boring!

**Ethan:** Maya has a point. But Ryan does, too, in a way. How do we make kids care about these landmarks? Shouldn’t we use tech, like VR, to let them experience the history?

**Emma:** I think Ethan’s onto something. Virtual reality tours of places like the Colosseum in Rome or the Pyramids in Egypt could be fascinating. But Ryan, why do you find history boring?

**Ryan:** *I mean,* it just feels... distant, you know? Like, I know George Washington led battles, but, like, how does that matter to me?

**Maya:** It matters because it’s part of your identity, Ryan. History tells us where we came from. Without it, culture fades. Have you been to the Alamo in Texas? It's a reminder of resilience and sacrifice. Without those stories, how will we learn courage?

**Ethan:** True, but here's a problem—many monuments, like the Taj Mahal, are decaying because of pollution and neglect. Shouldn't we focus on fixing that first?

**Emma:** *Absolutely!* I read last week about how smog is damaging India’s Taj Mahal. It’s heart-wrenching. Preserving monuments must go hand-in-hand with teaching their value. Any ideas, Ryan?

**Ryan:** Maybe we could, like, organize cleanups or raise funds for conservation? Schools could include those activities so we, um, actually feel involved.

**Maya:** That’s a wonderful idea, Ryan! Did you know during the 1940s, the Mount Rushmore National Memorial was improved as part of a community-driven effort? It’s proof that every little action helps.

**Ethan:** And not just local action. Global awareness is key. Social media could spotlight these issues. Imagine a campaign encouraging people worldwide to protect the Great Wall of China.

**Emma:** Let’s not forget to highlight the cultural aspect too. I once took a trip to Kyoto, Japan, and visited the Fushimi Inari Shrine. Learning about its spiritual significance deeply moved me. We must keep those cultural stories alive.

**Maya:** So, the problem is clear. Awareness, preservation, education—*all* need attention. The solution? A mix of passion, action, and modern tools, just like you all suggested.

**Ryan:** I guess you’re right. I mean, the Golden Gate Bridge wouldn’t be the same if it crumbled away, huh? Alright, I’m in. Let’s save some history!

**Ethan:** That’s the spirit, Ryan! History doesn’t have to stay in dusty textbooks. We can make it alive for everyone!

**Emma:** And that’s the beauty of culture—it connects us across time. Let’s plan something. Maybe we can start with a local landmark?

**Maya:** Perfect idea! How about a visit to Fort Ticonderoga? It’s close by, rich in history, and we can brainstorm ways to help.

---

**End of Conversation**
  • We are using EmbeddedResource approach to attach these assets & resources to cs.proj and read them when needed using below EmbeddedResource Service Class.
using System.Reflection;

namespace AIAgentTextSummarization.Services;

public static class EmbeddedResource
{
    public static string Read(string resourceName)
    {
        var assembly = Assembly.GetExecutingAssembly();
        var resourcePath =
            assembly
                .GetManifestResourceNames()
                .FirstOrDefault(name =>
                    name.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase)
                ) ?? throw new FileNotFoundException($"Resource '{resourceName}' not found.");
        using var stream =
            assembly.GetManifestResourceStream(resourcePath)
            ?? throw new FileNotFoundException($"Resource stream for '{resourceName}' is null.");
        using var reader = new StreamReader(stream);
        return reader.ReadToEnd();
    }
}
  • Attach the yaml template & example conversation .txt to the .csproj
  <ItemGroup>
    <EmbeddedResource Include="Plugins\PromptPlugins\TextSummarizationPromptPlugin\TextSummarizationYamlTemplate.yaml" />
    <EmbeddedResource Include="Assets\Conversation.txt" />
    <None Update="appsettings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>
  • We will be using a separate class called Brain.cs to perform our text summarization. So, please create it under Brain folder with below content
using AIAgentTextSummarization.Services;

namespace AIAgentTextSummarization.Brain;

public interface IBrain
{
    Task Run(Kernel kernel);
}

public class Brain(ILogger<Brain> logger) : IBrain
{
    public async Task Run(Kernel kernel)
    {
        logger.LogInformation("Starting AI Agent Text Summarization...");
        var conversation = EmbeddedResource.Read("Conversation.txt");

        var result = await kernel.InvokeAsync(
            "TextSummarizationPromptPlugin",
            "summarize_text",
            new KernelArguments() { { "input", conversation } }
        );

        logger.LogInformation("Result: {Result}", result.ToString());
    }
}
  • I like to use globalusings for common namespaces to keep the class files lean. Please create GlobalUsings.cs under you root project folder with namespaces.
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Logging;
global using Microsoft.SemanticKernel;
global using Microsoft.SemanticKernel.ChatCompletion;
  • Finally, lets setup our program.cs file with below code to run our project.
// See https://aka.ms/new-console-template for more information
using AIAgentTextSummarization.Brain;
using AIAgentTextSummarization.Options;
using AIAgentTextSummarization.Plugins.FunctionPlugins.TimePlugin;
using AIAgentTextSummarization.Plugins.PromptPlugins.TextSummarizationPromptPlugin;

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddUserSecrets<Program>(optional: true)
    .AddEnvironmentVariables()
    .Build();

var kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.Services.AddLogging(loggingBuilder =>
    loggingBuilder.AddConsole().AddConfiguration(configuration.GetSection("Logging"))
);

kernelBuilder.Services.AddOptions();
kernelBuilder.Services.Configure<OpenAIConfiguration>(
    configuration.GetSection(OpenAIConfiguration.SectionName)
);

kernelBuilder.Services.AddTransient<IBrain, Brain>();

var openAIConfiguration =
    configuration.GetSection(OpenAIConfiguration.SectionName).Get<OpenAIConfiguration>()
    ?? throw new Exception("OpenAI configuration is missing");

kernelBuilder.Services.AddOpenAIChatCompletion(
    openAIConfiguration.ModelId,
    openAIConfiguration.ApiKey
);

var kernel = kernelBuilder.Build();
kernel.Plugins.AddFromType<TimePlugin>();
kernel.ImportPluginFromType<TextSummarizationPromptPlugin>(); 

var logger = kernel.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Starting the AI Calendar Agent");
await kernel.GetRequiredService<IBrain>().Run(kernel);
  • Before running your project, please make sure appsettings.json file which was added to our project directory has values to below settings.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Information",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "Console": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    }
  },
  "OpenAIConfiguration": {
    "ModelId": "gpt-4o",
    "ApiKey": "api-key",
    "Endpoint": "api-endpoint"
  },
}
  • Run the program.cs using dotnet run command. You will see the below output
Result: 
- Acronyms:
  - VR: Virtual Reality

- Glossary:
  - Monuments: Structures created to commemorate a person or event.
  - Preservation: The act of maintaining something in its original or existing state.
  - Conservation: The protection and care of natural resources and cultural heritage.
  - Resilience: The capacity to recover quickly from difficulties; toughness.

- Problem Statement:
  - Many people, especially younger generations, find historical monuments boring or irrelevant.
  - Monuments like the Taj Mahal are decaying due to pollution and neglect.
  - There is a lack of awareness and modern engagement with historical sites.

- Description:
  - Discussion on making history engaging for younger generations using modern tools like VR.
  - Importance of preserving monuments and integrating cultural education.
  - Suggestions for organizing community-driven efforts for conservation.
  - Emphasis on global awareness and social media campaigns for monument preservation.

- Key Points:
  - The Statue of Liberty symbolizes freedom and democracy.
  - Integrating tech, such as VR, to make history engaging.
  - Need for preservation and conservation of historical sites.
  - Importance of cultural education and community involvement.
  - Potential for social media to raise global awareness.

- Entities:
  - Locations: Statue of Liberty, Colosseum, Pyramids, Alamo, Taj Mahal, Great Wall of China, Kyoto, Fushimi Inari Shrine, Golden Gate Bridge, Fort Ticonderoga
  - People: Emma, Ryan, Maya, Ethan
  - Places: France, Rome, Egypt, Texas, India, Japan, China

- Next Steps:
  - Organize cleanups or fundraisers for monument conservation.
  - Plan visits to local landmarks, like Fort Ticonderoga, to brainstorm preservation efforts.
  - Utilize social media for global awareness campaigns.
  - Incorporate VR tours into educational curricula.
  - Foster community involvement in cultural and historical education.

Concepts Showcased:

  • Function Invocation through kernel.
  • Handlebars prompt template using YAML schema for prompt plugins.
  • Injecting KernelArguments into Prompt templates.
  • Seperation of Concerns
  • .NET Dependency Injection.
  • .NET Options Pattern.
  • Natural Language Processing & Natural Language Understanding.
  • Text Summarization, grammar correction.

Conclusion:

Using powerful sematic kernel, we can easily create NLP, NLU based AI Agents on fly with few simple steps and configurations for very common use cases such as the one showed in this article. With minimal effort we can reduce our workload, processing times and improve efficiency. Hope this tutorial can help you get started to build your own AI Agent.

To get access to my source code. Please visit this GitHub link.

To get more tutorials🧾 like this! Follow me! see ya 👋!


This content originally appeared on DEV Community and was authored by vamsi dogiparthi