mirror of
https://github.com/microsoft/semantic-kernel.git
synced 2026-10-12 02:19:06 +00:00
### Motivation and Context
<!-- 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.
-->
The loading of plugins and functions into Kernel was not fully
consistent and clear, this is now simplified.
Adding a plugin can now be done in two ways:
- multiple: `kernel.add_plugins[plugin1, plugin2]`
- single plugin: `kernel.add_plugin(plugin)`
- if the plugin here is a class, with methods that have the
kernel_function decorator then that is parsed into a plugin
Adding a function can now be done in three ways:
- multiple: `kernel.add_functions([func1, func2]` or
`kernel.add_function({'func1': func1})`
- single: `kernel.add_function('plugin_name', func1)`
- from a prompt: `kernel.add_function(function_name='func1',
prompt='test prompt', ...)`
In other words, all the different methods that were available have been
simplified, these methods also return the created plugin (or updated
plugin for the `add_functions` method. The `add_function` (singular)
method has a parameter `return_plugin` to control whether you get the
created or updated plugin, instead of the created function.
**An important callout:**
One big internal change that this introduces is that a function that
gets added to a plugin (new or existing) is automatically copied, the
metadata is deep-copied and the plugin_name in the metadata is updated,
so this sequence is valid now:
```python
@kernel_function(name='test')
def f(...):
etc
func = KernelFunctionFromMethod(method=f)
func2 = kernel.add_function('plugin', func)
assert func != func2
```
Also closes: #5855
### Description
<!-- Describe your changes, the overall approach, the underlying design.
These notes will help understanding how your code works. Thanks! -->
Removed KernelPluginCollection
Updated KernelPlugin
added from_... method to load from different sources
Updated KernelFunctionFromPrompt
added from_yaml and from_directory methods.
Added and updated tests to 99% coverage of KernelPlugin and
KernelFunctionFromPrompt
### 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
- [ ] I didn't break anyone 😄
29 KiB
29 KiB
In [ ]:
!python -m pip install semantic-kernel==0.9.5b1In [ ]:
from services import Service
# Select a service to use for this notebook (available services: OpenAI, AzureOpenAI, HuggingFace)
selectedService = Service.OpenAIIn [ ]:
import semantic_kernel as sk
kernel = sk.Kernel()
if selectedService == Service.AzureOpenAI:
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
deployment, api_key, endpoint = sk.azure_openai_settings_from_dot_env()
service_id = "aoai_chat" # used later in the notebook
azure_chat_service = AzureChatCompletion(
service_id=service_id, deployment_name="gpt-35-turbo", endpoint=endpoint, api_key=api_key
) # set the deployment name to the value of your chat model
kernel.add_service(azure_chat_service)
# Configure OpenAI service
if selectedService == Service.OpenAI:
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
api_key, org_id = sk.openai_settings_from_dot_env()
service_id = "oai_chat" # used later in the notebook
oai_chat_service = OpenAIChatCompletion(
service_id=service_id, ai_model_id="gpt-4-turbo-1106", api_key=api_key, org_id=org_id
)
kernel.add_service(oai_chat_service)In [ ]:
import random
from semantic_kernel.functions import kernel_function
class GenerateNumberPlugin:
"""
Description: Generate a number between 3-x.
"""
@kernel_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 eIn [ ]:
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. It must be this length.
"""
if selectedService == Service.OpenAI:
execution_settings = sk_oai.OpenAIChatPromptExecutionSettings(
service_id=service_id,
ai_model_id="gpt-3.5-turbo-1106",
max_tokens=2000,
temperature=0.7,
)
elif selectedService == Service.AzureOpenAI:
execution_settings = sk_oai.OpenAIChatPromptExecutionSettings(
service_id=service_id,
ai_model_id=deployment,
max_tokens=2000,
temperature=0.7,
)
prompt_template_config = sk.PromptTemplateConfig(
template=prompt,
name="story",
template_format="semantic-kernel",
input_variables=[
InputVariable(name="input", description="The user input", is_required=True),
],
execution_settings=execution_settings,
)
corgi_story = kernel.add_function(
function_name="CorgiStory",
plugin_name="CorgiPlugin",
prompt_template_config=prompt_template_config,
)
generate_number_plugin = kernel.add_plugin(GenerateNumberPlugin(), "GenerateNumberPlugin")In [ ]:
# Run the number generator
generate_number_three_or_higher = generate_number_plugin["GenerateNumberThreeOrHigher"]
number_result = await generate_number_three_or_higher(kernel, input=6)
print(number_result)In [ ]:
story = await corgi_story.invoke(kernel, input=number_result.value)In [ ]:
print(f"Generating a corgi story exactly {number_result.value} paragraphs long.")
print("=====================================================")
print(story)In [ ]:
import sys
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, OpenAIChatCompletion
if sys.version_info >= (3, 9):
pass
else:
pass
kernel = sk.Kernel()
if selectedService == Service.AzureOpenAI:
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
deployment, api_key, endpoint = sk.azure_openai_settings_from_dot_env()
service_id = "aoai_chat" # used later in the notebook
azure_chat_service = AzureChatCompletion(
service_id=service_id, deployment_name=deployment, endpoint=endpoint, api_key=api_key
) # set the deployment name to the value of your chat model
kernel.add_service(azure_chat_service)
# Configure OpenAI service
if selectedService == Service.OpenAI:
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
api_key, org_id = sk.openai_settings_from_dot_env()
service_id = "oai_chat" # used later in the notebook
oai_chat_service = OpenAIChatCompletion(
service_id=service_id, ai_model_id="gpt-4-turbo-1106", api_key=api_key, org_id=org_id
)
kernel.add_service(oai_chat_service)In [ ]:
import random
from semantic_kernel.functions import kernel_function
class GenerateNumberPlugin:
"""
Description: Generate a number between a min and a max.
"""
@kernel_function(
name="GenerateNumber",
description="Generate a random number between min and max",
)
def generate_number(
self,
min: Annotated[int, "the minimum number of paragraphs"],
max: Annotated[int, "the maximum number of paragraphs"] = 10,
) -> Annotated[int, "the output is a number"]:
"""
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(min, max))
except ValueError as e:
print(f"Invalid input {min} and {max}")
raise eIn [ ]:
generate_number_plugin = kernel.add_plugin(GenerateNumberPlugin(), "GenerateNumberPlugin")
generate_number = generate_number_plugin["GenerateNumber"]In [ ]:
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}}
"""
if selectedService == Service.OpenAI:
execution_settings = sk_oai.OpenAIChatPromptExecutionSettings(
service_id=service_id,
ai_model_id="gpt-3.5-turbo-1106",
max_tokens=2000,
temperature=0.7,
)
elif selectedService == Service.AzureOpenAI:
execution_settings = sk_oai.OpenAIChatPromptExecutionSettings(
service_id=service_id,
ai_model_id=deployment,
max_tokens=2000,
temperature=0.7,
)
prompt_template_config = sk.PromptTemplateConfig(
template=prompt,
name="summarize",
template_format="semantic-kernel",
input_variables=[
InputVariable(name="paragraph_count", description="The number of paragraphs", is_required=True),
InputVariable(name="language", description="The language of the story", is_required=True),
],
execution_settings=execution_settings,
)
corgi_story = kernel.add_function(
function_name="CorgiStory",
plugin_name="CorgiPlugin",
prompt_template_config=prompt_template_config,
)In [ ]:
result = await generate_number.invoke(kernel, min=1, max=5)
num_paragraphs = result.value
print(f"Generating a corgi story {num_paragraphs} paragraphs long.")In [ ]:
# Pass the output to the semantic story function
desired_language = "Spanish"
story = await corgi_story.invoke(kernel, paragraph_count=num_paragraphs, language=desired_language)In [ ]:
print(f"Generating a corgi story {num_paragraphs} paragraphs long in {desired_language}.")
print("=====================================================")
print(story)In [ ]:
import random
from semantic_kernel.functions import kernel_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 @kernel_function decorator. In this case, we're using
# the same name as the function name for simplicity.
@kernel_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.add_plugin(GenerateNamesPlugin(), plugin_name="GenerateNames")
generate_names = generate_names_plugin["generate_names"]In [ ]:
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 [ ]:
if selectedService == Service.OpenAI:
execution_settings = sk_oai.OpenAIChatPromptExecutionSettings(
service_id=service_id,
ai_model_id="gpt-3.5-turbo-1106",
max_tokens=2000,
temperature=0.7,
)
elif selectedService == Service.AzureOpenAI:
execution_settings = sk_oai.OpenAIChatPromptExecutionSettings(
service_id=service_id,
ai_model_id=deployment,
max_tokens=2000,
temperature=0.7,
)
prompt_template_config = sk.PromptTemplateConfig(
template=prompt,
name="corgi-new",
template_format="semantic-kernel",
input_variables=[
InputVariable(name="paragraph_count", description="The number of paragraphs", is_required=True),
InputVariable(name="language", description="The language of the story", is_required=True),
],
execution_settings=execution_settings,
)
corgi_story = kernel.add_function(
function_name="CorgiStoryUpdated",
plugin_name="CorgiPluginUpdated",
prompt_template_config=prompt_template_config,
)In [ ]:
result = await generate_number.invoke(kernel, min=1, max=5)
num_paragraphs = result.valueIn [ ]:
desired_language = "French"
story = await corgi_story.invoke(kernel, paragraph_count=num_paragraphs, language=desired_language)In [ ]:
print(f"Generating a corgi story {num_paragraphs} paragraphs long in {desired_language}.")
print("=====================================================")
print(story)