SWOT-Analysis

with Semantic Kernel

Jan Kirenz

Create a SWOT with the Semantic Kernel

Setup

Python

from semantic_kernel.skill_definition import (
    sk_function,
    sk_function_context_parameter,
)
import semantic_kernel as sk

from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, OpenAIChatCompletion
from IPython.display import display, Markdown

Kernel

kernel = sk.Kernel()

api_key, org_id = sk.openai_settings_from_dot_env()

kernel.add_text_completion_service(
    "openai", OpenAIChatCompletion("gpt-3.5-turbo", api_key, org_id))

print("A kernel is now ready.")

Semantic Function

Prompt template

sk_prompt = """
{{$input}}

Summarize the content above in less than 140 characters.
"""

Define semantic function

summary_function = kernel.create_semantic_function(prompt_template=sk_prompt,
                                                   description="Summarizes the input to length of an old tweet.",
                                                   max_tokens=200,
                                                   temperature=0.1,
                                                   top_p=0.5)
# as a reminder
print("A semantic function for summarization has been registered.")

Prompt input

sk_input = """
Let me illustrate an example. Many weekends, I drive a few minutes from my house to a local pizza store to buy 
a slice of Hawaiian pizza from the gentleman that owns this pizza store. And his pizza is great, but he always 
has a lot of cold pizzas sitting around, and every weekend some different flavor of pizza is out of stock. 
But when I watch him operate his store, I get excited, because by selling pizza, he is generating data. 
And this is data that he can take advantage of if he had access to AI.

AI systems are good at spotting patterns when given access to the right data, and perhaps an AI system could spot 
if Mediterranean pizzas sell really well on a Friday night, maybe it could suggest to him to make more of it on a 
Friday afternoon. Now you might say to me, "Hey, Andrew, this is a small pizza store. What's the big deal?" And I 
say, to the gentleman that owns this pizza store, something that could help him improve his revenues by a few 
thousand dollars a year, that will be a huge deal to him.
"""
# Text source: https://www.ted.com/talks/andrew_ng_how_ai_could_empower_any_business/transcript

Run kernel

summary_result = await kernel.run_async(summary_function,
                                        input_str=sk_input)

Output

display(Markdown("### ✨ " + str(summary_result)))
  • ✨ AI can help a small pizza store owner improve revenues by analyzing data and suggesting changes, like making more popular pizzas on certain days.

Output

Alternative to run kernel: summary_function

  • Shorter version to call semantic function (same result)
summary_result = summary_function(sk_input)
display(Markdown("### ✨ " + str(summary_result)))
  • ✨ AI can help a small pizza store owner increase revenue by analyzing data to identify patterns and make informed decisions.

Alternative to run kernel: summary_function

Register Native functions

Define a function

  • Write some function
class ExoticLanguagePlugin:
    def word_to_pig_latin(self, word):
        vowels = "AEIOUaeiou"
        if word[0] in vowels:
            return word + "way"
        for idx, letter in enumerate(word):
            if letter in vowels:
                break
        else:
            return word + "ay"
        return word[idx:] + word[:idx] + "ay"

    @sk_function(
        description="Takes text and converts it to pig latin",
        name="pig_latin",
        input_description="The text to convert to pig latin",
    )
    def pig_latin(self, sentence: str) -> str:
        words = sentence.split()
        pig_latin_words = []
        for word in words:
            pig_latin_words.append(self.word_to_pig_latin(word))
        return ' '.join(pig_latin_words)

Register function

  • Register custom function in the kernel
exotic_language_plugin = kernel.import_skill(
    ExoticLanguagePlugin(), skill_name="exotic_language_plugin")

pig_latin_function = exotic_language_plugin["pig_latin"]

Run kernel with semantic function and native function

final_result = await kernel.run_async(summary_function,
                                      pig_latin_function,
                                      input_str=sk_input)

Output

display(Markdown("### ✨ " + str(final_result)))
  • ✨ AIway ancay elphay away allsmay izzapay orestay ownerway increaseway evenueray byay analyzingway ataday andway uggestingsay opularpay izzapay avorsflay onway ecificspay ays.day

Output

SWOT Basics

Strengths

  1. Strengths
    • What unique recipes or ingredients does the pizza shop use?
    • What are the skills and experience of the staff?
    • Does the pizza shop have a strong reputation in the local area?
    • Are there any unique features of the shop or its location that attract customers?

Weaknesses

  1. Weaknesses
    • What are the operational challenges of the pizza shop? (e.g., slow service, high staff turnover)
    • Are there financial constraints that limit growth or improvements?
    • Are there any gaps in the product offering?
    • Are there customer complaints or negative reviews that need to be addressed?

Opportunities

  1. Opportunities
    • Is there potential for new products or services (e.g., catering, delivery)?
    • Are there under-served customer segments or market areas?
    • Can new technologies or systems enhance the business operations?
    • Are there partnerships or local events that can be leveraged for marketing?

Threats

  1. Threats
    • Who are the major competitors and what are they offering?
    • Are there potential negative impacts due to changes in the local area (e.g., construction, closure of nearby businesses)?
    • Are there economic or industry trends that could impact the business negatively (e.g., increased ingredient costs)?
    • Is there any risk due to changes in regulations or legislation (e.g., health and safety, employment)?

SW Overview

Strengths Weaknesses
Unique garlic pizza recipe that wins top awards High staff turnover
Owner trained in Sicily at some of the best pizzerias Floods in the area damaged the seating areas that are in need of repair
Strong local reputation Absence of popular calzones from menu
Prime location on university campus Negative reviews from younger demographic for lack of hip ingredients

Meanwhile there’s money being left on the table (their opportunities) with calamities (their threats) waiting in the wings to possibly happen and may knock their pizza shop out cold.

OT overview

Opportunities Threats
Untapped catering potential Rising competition from cheaper pizza businesses nearby
Growing local tech startup community There’s nearby street construction that will impact foot traffic
Unexplored online presence and order capabilities Rising cost of cheese
Upcoming annual food fair No immediate local regulatory changes but it’s election season

SWOT Workflow

Input

swot_interview = """
1. **Strengths**
    - What unique recipes or ingredients does the pizza shop use?
    - What are the skills and experience of the staff?
    - Does the pizza shop have a strong reputation in the local area?
    - Are there any unique features of the shop or its location that attract customers?
2. **Weaknesses**
    - What are the operational challenges of the pizza shop? (e.g., slow service, high staff turnover)
    - Are there financial constraints that limit growth or improvements?
    - Are there any gaps in the product offering?
    - Are there customer complaints or negative reviews that need to be addressed?
3. **Opportunities**
    - Is there potential for new products or services (e.g., catering, delivery)?
    - Are there under-served customer segments or market areas?
    - Can new technologies or systems enhance the business operations?
    - Are there partnerships or local events that can be leveraged for marketing?
4. **Threats**
    - Who are the major competitors and what are they offering?
    - Are there potential negative impacts due to changes in the local area (e.g., construction, closure of nearby businesses)?
    - Are there economic or industry trends that could impact the business negatively (e.g., increased ingredient costs)?
    - Is there any risk due to changes in regulations or legislation (e.g., health and safety, employment)?"""

Prompt template

sk_prompt = """
{{$input}}

Convert the analysis provided above to the business domain of {{$domain}}.
"""

Define semantic function

shift_domain_function = kernel.create_semantic_function(prompt_template=sk_prompt,
                                                        description="Translate an idea to another domain.",
                                                        max_tokens=1000,
                                                        temperature=0.1,
                                                        top_p=0.5)

Context

my_context = kernel.create_new_context()
my_context['input'] = swot_interview
my_context['domain'] = "construction management"

Run kernel

result = await kernel.run_async(shift_domain_function,
                                input_context=my_context)

Output

display(Markdown(
    f"### ✨ Shift the SWOT interview questions to the world of {my_context['domain']}\n" + str(result)))
✨ Shift the SWOT interview questions to the world of construction management
1. **Strengths**
What unique construction methods or techniques does the construction company use?
What are the skills and experience of the construction team?
Does the construction company have a strong reputation in the local area?
Are there any unique features of the company or its projects that attract clients?
2. **Weaknesses**
What are the operational challenges of the construction company? (e.g., delays in project completion, high employee turnover)
Are there financial constraints that limit growth or improvements?
Are there any gaps in the services offered by the company?
Are there client complaints or negative reviews that need to be addressed?
3. **Opportunities**
Is there potential for new construction projects or services (e.g., renovation, green building)?
Are there under-served client segments or market areas?
Can new technologies or systems enhance the construction processes?
Are there partnerships or local events that can be leveraged for marketing?
4. **Threats**
Who are the major competitors in the construction industry and what services do they offer?
Are there potential negative impacts due to changes in the local area (e.g., zoning regulations, environmental restrictions)?
Are there economic or industry trends that could impact the construction business negatively (e.g., increased material costs)?
Is there any risk due to changes in regulations or legislation (e.g., safety regulations, building codes)?

Output

Change Output Style

Prompt template

sk_prompt = """
{{$input}}

Rewrite the text above to be understood by a {{$level}}.
"""

Define semantic function

shift_reading_level_function = kernel.create_semantic_function(prompt_template=sk_prompt,
                                                               description="Change the reading level of a given text.",
                                                               max_tokens=1000,
                                                               temperature=0.1,
                                                               top_p=0.5)

Context

my_context['input'] = swot_interview
my_context['domain'] = "construction management"
my_context["level"] = "child"

Run kernel

result = await kernel.run_async(shift_domain_function, shift_reading_level_function, input_context=my_context)

Output

display(Markdown(
    f"### ✨ Shift the SWOT interview questions to the world of {my_context['domain']} at the level of {my_context['level']}\n" + str(result)))
✨ Shift the SWOT interview questions to the world of construction management at the level of child
1. **Strengths**
What cool ways does the construction company build things?
Are the people who work for the construction company really good at building?
Do a lot of people like the construction company and think they do a great job?
Does the construction company do anything special that makes people want to hire them?
2. **Weaknesses**
Are there things that make it hard for the construction company to do their work? (like taking a long time to finish projects or people quitting their jobs)
Do they not have a lot of money to make things better or grow?
Are there things that the construction company doesn't do that people want them to do?
Do some people say bad things about the construction company or not like their work?
3. **Opportunities**
Can the construction company do new and different projects or offer new services?
Are there people who need construction work but don't have anyone to do it for them?
Can the construction company use new tools or ways of doing things to make their work even better?
Can the construction company work with other people or go to events to tell more people about what they do?
4. **Threats**
Are there other companies that do construction and might be better than them?
Are there things happening in the area that could make it harder for the construction company to do their work? (like rules about where they can build or not having enough materials)
Are there things happening in the world that could make it harder for the construction company to do their job? (like things costing more money)
Are there new rules or laws that could make it harder for the construction company to do their work? (like rules about safety or how buildings are made)

Output

Acknowledgments

This tutorial is mainly based on the excellent course “How Business Thinkers Can Start Building AI Plugins With Semantic Kernel” provided by John Maeda and Andrew Ng

What’s next?

Congratulations! You have completed this tutorial 👍

Next, you may want to go back to the lab’s website