Files
semantic-kernel/python/notebooks/08-native-function-inline.ipynb
T
Evan MattsonandEvan Mattson 674af5468d Python: Rename skills to plugins. Update prompt template config to use execution settings to align with dotnet. (#4595)
### Motivation and Context

To better align with SK dotnet v1, Python skills have been renamed to
plugins. This removes the root samples skills directory as dotnet
supports the plugins and their configs. This the beginning of more work
to consolidate other files/names, per the backlog. I've run several
greps for files or file names containing "skill" (case insensitive), and
no results appear. Do alert if you find anything else that includes
"skill."

Fixes #3319 

<!-- Thank you for your contribution to the semantic-kernel repo!
Please help reviewers and future users, providing the following
information:
  1. Why is this change required?
  2. What problem does it solve?
  3. What scenario does it contribute to?
  4. If it fixes an open issue, please link to the issue here.
-->

### Description

This is a large, breaking change PR as the replacement of "skills" to
"plugins" affects many files. It was difficult to break this up into
smaller chunks without leaving the SK Python repo in a bad state for
some time. Other updates include:

- Prompt template has been updated to use `execution_settings`, which
aligns with dotnet, from the previous `completion` that Python used.
- AzureOpenAI/OpenAI function calling has been updated to match the
current versions of tools/tool_choice. Parsing messages in the open_ai
utils respects this as it now looks for tool_calls and it configures the
function_call with the id (new), name, and argument).
- File renames, where the filename used to contain "skill" will look
like new code, but it's the same code, just with "plugin" in the name.
- Kernel examples and notebooks have been tested and are working. Unit
tests and integration tests are passing.

<!-- Describe your changes, the overall approach, the underlying design.
These notes will help understanding how your code works. Thanks! -->

### Contribution Checklist

<!-- Before submitting this PR, please make sure: -->

- [X] The code builds clean without any errors or warnings
- [X] The PR follows the [SK Contribution
Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md)
and the [pre-submission formatting
script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts)
raises no violations
- [X] All unit tests pass, and I have added new tests where possible
- [X] I didn't break anyone 😄

---------

Co-authored-by: Evan Mattson <[email protected]>
2024-01-19 16:47:30 +00:00

19 KiB

Running Native Functions

Two of the previous notebooks showed how to execute semantic functions inline and how to run prompts from a file.

In this notebook, we'll show how to use native functions from a file. We will also show how to call semantic functions from native functions.

This can be useful in a few scenarios:

  • Writing logic around how to run a prompt that changes the prompt's outcome.
  • Using external data sources to gather data to concatenate into your prompt.
  • Validating user input data prior to sending it to the LLM prompt.

Native functions are defined using standard Python code. The structure is simple, but not well documented at this point.

The following examples are intended to help guide new users towards successful native & semantic function use with the SK Python framework.

Prepare a semantic kernel instance first, loading also the AI service settings defined in the Setup notebook:

In [ ]:
!python -m pip install semantic-kernel==0.4.5.dev0
In [ ]:
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import (
    AzureChatCompletion,
    OpenAIChatCompletion,
)

kernel = sk.Kernel()

useAzureOpenAI = False

# Configure AI service used by the kernel
if useAzureOpenAI:
    deployment, api_key, endpoint = sk.azure_openai_settings_from_dot_env()
    azure_chat_service = AzureChatCompletion(
        deployment_name="turbo", endpoint=endpoint, api_key=api_key
    )  # set the deployment name to the value of your chat model
    kernel.add_chat_service("chat_completion", azure_chat_service)
else:
    api_key, org_id = sk.openai_settings_from_dot_env()
    oai_chat_service = OpenAIChatCompletion(ai_model_id="gpt-3.5-turbo", api_key=api_key, org_id=org_id)
    kernel.add_chat_service("chat-gpt", oai_chat_service)

Let's create a native function that gives us a random number between 3 and a user input as the upper limit. We'll use this number to create 3-x paragraphs of text when passed to a semantic function.

First, let's create our native function.

In [ ]:
import random
from semantic_kernel.plugin_definition import sk_function


class GenerateNumberPlugin:
    """
    Description: Generate a number between 3-x.
    """

    @sk_function(
        description="Generate a random number between 3-x",
        name="GenerateNumberThreeOrHigher",
    )
    def generate_number_three_or_higher(self, input: str) -> str:
        """
        Generate a number between 3-<input>
        Example:
            "8" => rand(3,8)
        Args:
            input -- The upper limit for the random number generation
        Returns:
            int value
        """
        try:
            return str(random.randint(3, int(input)))
        except ValueError as e:
            print(f"Invalid input {input}")
            raise e

Next, let's create a semantic function that accepts a number as {{$input}} and generates that number of paragraphs about two Corgis on an adventure. $input is a default variable semantic functions can use.

In [ ]:
sk_prompt = """
Write a short story about two Corgis on an adventure.
The story must be:
- G rated
- Have a positive message
- No sexism, racism or other bias/bigotry
- Be exactly {{$input}} paragraphs long
"""

corgi_story = kernel.create_semantic_function(
    prompt_template=sk_prompt,
    function_name="CorgiStory",
    plugin_name="CorgiPlugin",
    description="Write a short story about two Corgis on an adventure",
    max_tokens=500,
    temperature=0.5,
    top_p=0.5,
)

generate_number_plugin = kernel.import_plugin(GenerateNumberPlugin())
In [ ]:
# Run the number generator
generate_number_three_or_higher = generate_number_plugin["GenerateNumberThreeOrHigher"]
number_result = generate_number_three_or_higher(6)
print(number_result)
In [ ]:
story = await corgi_story.invoke_async(input=number_result.result)
In [ ]:
print("Generating a corgi story exactly {} paragraphs long: ".format(number_result.result))
print("=====================================================")
print(story)

Context Variables

That works! But let's expand on our example to make it more generic.

For the native function, we'll introduce the lower limit variable. This means that a user will input two numbers and the number generator function will pick a number between the first and second input.

We'll make use of the semantic_kernel.ContextVariables class to do hold these variables.

In [ ]:
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import (
    AzureChatCompletion,
    OpenAIChatCompletion,
)

kernel = sk.Kernel()

useAzureOpenAI = False

# Configure AI service used by the kernel
if useAzureOpenAI:
    deployment, api_key, endpoint = sk.azure_openai_settings_from_dot_env()
    azure_chat_service = AzureChatCompletion(
        deployment_name="turbo", endpoint=endpoint, api_key=api_key
    )  # set the deployment name to the value of your chat model
    kernel.add_chat_service("chat_completion", azure_chat_service)
else:
    api_key, org_id = sk.openai_settings_from_dot_env()
    oai_chat_service = OpenAIChatCompletion(ai_model_id="gpt-3.5-turbo", api_key=api_key, org_id=org_id)
    kernel.add_chat_service("chat-gpt", oai_chat_service)

Let's start with the native function. Notice that we're also adding @sk_function_context_parameter decorators to the function here to provide context about what variables need to be provided to the function, and any defaults for those inputs. Using the @sk_function_context_parameter decorator provides the name, description and default values for a function's inputs to the planner.

In [ ]:
import random
from semantic_kernel.plugin_definition import sk_function, sk_function_context_parameter
from semantic_kernel import SKContext


class GenerateNumberPlugin:
    """
    Description: Generate a number between a min and a max.
    """

    @sk_function(
        description="Generate a random number between min and max",
        name="GenerateNumber",
    )
    @sk_function_context_parameter(name="min", description="Minimum number of paragraphs.")
    @sk_function_context_parameter(name="max", description="Maximum number of paragraphs.", default_value="10")
    def generate_number(self, context: SKContext) -> str:
        """
        Generate a number between min-max
        Example:
            min="4" max="10" => rand(4,8)
        Args:
            min -- The lower limit for the random number generation
            max -- The upper limit for the random number generation
        Returns:
            int value
        """
        try:
            return str(random.randint(int(context["min"]), int(context["max"])))
        except ValueError as e:
            print(f"Invalid input {context['min']} {context['max']}")
            raise e
In [ ]:
generate_number_plugin = kernel.import_plugin(GenerateNumberPlugin())
generate_number = generate_number_plugin["GenerateNumber"]

Now let's also allow the semantic function to take in additional arguments. In this case, we're going to allow the our CorgiStory function to be written in a specified language. We'll need to provide a paragraph_count and a language.

In [ ]:
sk_prompt = """
Write a short story about two Corgis on an adventure.
The story must be:
- G rated
- Have a positive message
- No sexism, racism or other bias/bigotry
- Be exactly {{$paragraph_count}} paragraphs long
- Be written in this language: {{$language}}
"""

corgi_story = kernel.create_semantic_function(
    prompt_template=sk_prompt,
    function_name="CorgiStory",
    plugin_name="CorgiPlugin",
    description="Write a short story about two Corgis on an adventure",
    max_tokens=500,
    temperature=0.5,
    top_p=0.5,
)

Now we can call this using our invoke function by passing in our context_variables in the variables parameter.

In [ ]:
context_variables = sk.ContextVariables(variables={"min": "1", "max": "5", "language": "Spanish"})

Let's add a paragraph count to our context variables

In [ ]:
context_variables["paragraph_count"] = generate_number.invoke(variables=context_variables).result
In [ ]:
# Pass the output to the semantic story function
story = await corgi_story.invoke_async(variables=context_variables)
In [ ]:
print(
    "Generating a corgi story exactly {} paragraphs long in {} language: ".format(
        context_variables["paragraph_count"], context_variables["language"]
    )
)
print("=====================================================")
print(story)

Calling Native Functions within a Semantic Function

One neat thing about the Semantic Kernel is that you can also call native functions from within Semantic Functions!

We will make our CorgiStory semantic function call a native function GenerateNames which will return names for our Corgi characters.

We do this using the syntax {{plugin_name.function_name}}. You can read more about our prompte templating syntax here.

In [ ]:
import random
from semantic_kernel.plugin_definition import sk_function


class GenerateNamesPlugin:
    """
    Description: Generate character names.
    """

    # The default function name will be the name of the function itself, however you can override this
    # by setting the name=<name override> in the @sk_function decorator. In this case, we're using
    # the same name as the function name for simplicity.
    @sk_function(description="Generate character names", name="generate_names")
    def generate_names(self) -> str:
        """
        Generate two names.
        Returns:
            str
        """
        names = {"Hoagie", "Hamilton", "Bacon", "Pizza", "Boots", "Shorts", "Tuna"}
        first_name = random.choice(list(names))
        names.remove(first_name)
        second_name = random.choice(list(names))
        return f"{first_name}, {second_name}"
In [ ]:
generate_names_plugin = kernel.import_plugin(GenerateNamesPlugin(), plugin_name="GenerateNames")
generate_names = generate_names_plugin["generate_names"]
In [ ]:
sk_prompt = """
Write a short story about two Corgis on an adventure.
The story must be:
- G rated
- Have a positive message
- No sexism, racism or other bias/bigotry
- Be exactly {{$paragraph_count}} paragraphs long
- Be written in this language: {{$language}}
- The two names of the corgis are {{GenerateNames.generate_names}}
"""
In [ ]:
corgi_story = kernel.create_semantic_function(
    prompt_template=sk_prompt,
    function_name="CorgiStory",
    plugin_name="CorgiPlugin",
    description="Write a short story about two Corgis on an adventure",
    max_tokens=500,
    temperature=0.5,
    top_p=0.5,
)
In [ ]:
context_variables = sk.ContextVariables(variables={"min": "1", "max": "5", "language": "Spanish"})
context_variables["paragraph_count"] = generate_number.invoke(variables=context_variables).result
In [ ]:
# Pass the output to the semantic story function
story = await corgi_story.invoke_async(variables=context_variables)
In [ ]:
print(
    "Generating a corgi story exactly {} paragraphs long in {} language: ".format(
        context_variables["paragraph_count"], context_variables["language"]
    )
)
print("=====================================================")
print(story)

Recap

A quick review of what we've learned here:

  • We've learned how to create native and semantic functions and register them to the kernel
  • We've seen how we can use context variables to pass in more custom variables into our prompt
  • We've seen how we can call native functions within semantic function prompts.