Files
semantic-kernel/python/samples/documentation_examples/prompts.py
T
Eduard van Valkenburg 6751f9d819 Python: Updated plugins (#5827)
### 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 😄
2024-04-15 13:51:59 +00:00

150 lines
5.6 KiB
Python

# Copyright (c) Microsoft. All rights reserved.
import asyncio
from service_configurator import add_service
import semantic_kernel as sk
async def main():
# Initialize the kernel
kernel = sk.Kernel()
# Add the service to the kernel
# use_chat: True to use chat completion, False to use text completion
kernel = add_service(kernel=kernel, use_chat=True)
request = input("Your request: ")
# 0.0 Initial prompt
prompt = f"What is the intent of this request? {request}"
print("0.0 Initial prompt")
print("-------------------------")
prompt_function = kernel.add_function(function_name="sample_zero", plugin_name="sample_plugin", prompt=prompt)
result = await kernel.invoke(prompt_function, request=request)
print(result)
print("-------------------------")
# 1.0 Make the prompt more specific
prompt = f"""What is the intent of this request? {request}
You can choose between SendEmail, SendMessage, CompleteTask, CreateDocument."""
print("1.0 Make the prompt more specific")
print("-------------------------")
prompt_function = kernel.add_function(function_name="sample_one", plugin_name="sample_plugin", prompt=prompt)
result = await kernel.invoke(prompt_function, request=request)
print(result)
print("-------------------------")
# 2.0 Add structure to the output with formatting
prompt = f"""Instructions: What is the intent of this request?
Choices: SendEmail, SendMessage, CompleteTask, CreateDocument.
User Input: {request}
Intent: """
print("2.0 Add structure to the output with formatting")
print("-------------------------")
prompt_function = kernel.add_function(function_name="sample_two", plugin_name="sample_plugin", prompt=prompt)
result = await kernel.invoke(prompt_function, request=request)
print(result)
print("-------------------------")
# 2.1 Add structure to the output with formatting (using Markdown and JSON)
prompt = f"""## Instructions
Provide the intent of the request using the following format:
```json
{{
"intent": {{intent}}
}}
```
## Choices
You can choose between the following intents:
```json
["SendEmail", "SendMessage", "CompleteTask", "CreateDocument"]
```
## User Input
The user input is:
```json
{{
"request": "{request}"\n'
}}
```
## Intent"""
print("2.1 Add structure to the output with formatting (using Markdown and JSON)")
print("-------------------------")
prompt_function = kernel.add_function(function_name="sample_two_one", plugin_name="sample_plugin", prompt=prompt)
result = await kernel.invoke(prompt_function, request=request)
print(result)
print("-------------------------")
# 3.0 Provide examples with few-shot prompting
prompt = f"""Instructions: What is the intent of this request?
Choices: SendEmail, SendMessage, CompleteTask, CreateDocument.
User Input: Can you send a very quick approval to the marketing team?
Intent: SendMessage
User Input: Can you send the full update to the marketing team?
Intent: SendEmail
User Input: {request}
Intent: """
print("3.0 Provide examples with few-shot prompting")
print("-------------------------")
prompt_function = kernel.add_function(function_name="sample_three", plugin_name="sample_plugin", prompt=prompt)
result = await kernel.invoke(prompt_function, request=request)
print(result)
print("-------------------------")
# 4.0 Tell the AI what to do to avoid doing something wrong
prompt = f"""Instructions: What is the intent of this request?
If you don't know the intent, don't guess; instead respond with "Unknown".
Choices: SendEmail, SendMessage, CompleteTask, CreateDocument, Unknown.
User Input: Can you send a very quick approval to the marketing team?
Intent: SendMessage
User Input: Can you send the full update to the marketing team?
Intent: SendEmail
User Input: {request}
Intent: """
print("4.0 Tell the AI what to do to avoid doing something wrong")
print("-------------------------")
prompt_function = kernel.add_function(function_name="sample_four", plugin_name="sample_plugin", prompt=prompt)
result = await kernel.invoke(prompt_function, request=request)
print(result)
print("-------------------------")
# 5.0 Provide context to the AI through a chat history of this user
history = (
"User input: I hate sending emails, no one ever reads them.\n"
"AI response: I'm sorry to hear that. Messages may be a better way to communicate."
)
prompt = f"""Instructions: What is the intent of this request?\n"
If you don't know the intent, don't guess; instead respond with "Unknown".
Choices: SendEmail, SendMessage, CompleteTask, CreateDocument, Unknown.
User Input: Can you send a very quick approval to the marketing team?
Intent: SendMessage
User Input: Can you send the full update to the marketing team?
Intent: SendEmail
{history}
User Input: {request}
Intent: """
print("5.0 Provide context to the AI")
print("-------------------------")
prompt_function = kernel.add_function(function_name="sample_five", plugin_name="sample_plugin", prompt=prompt)
result = await kernel.invoke(prompt_function, request=request, history=history)
print(result)
print("-------------------------")
# Run the main function
if __name__ == "__main__":
asyncio.run(main())