SIGN IN SIGN UP

Integrate cutting-edge LLM technology quickly and easily into your apps

0 0 11 C#
2023-03-16 19:54:34 -07:00
# Copyright (c) Microsoft. All rights reserved.
import logging
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
from copy import copy
from typing import TYPE_CHECKING, Any, ClassVar
2023-03-16 19:54:34 -07:00
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
from pydantic import Field, field_validator, model_validator
Python: rebuilt exceptions structure; pythonic version (#5231) ### 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 existing Exceptions structure was very much inspired by dotnet, this is now replaced with a pythonic implementations. This means all Exceptions derive from KernelException and then specialise for different purposes. Closes #2194 ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Added folder for all exception types, all can be imported through `from semantic_kernel.exceptions import ...` no need for a user to know which file the relevant one is in, but keeps things tidy for developers. Removed old KernelException, added back subtypes for the errorcodes. Went through everything to make sure the `raise ... from exc` pattern is used as much as possible as that returns a better stacktrace. ### 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 :smile:
2024-02-28 19:53:53 +01:00
from semantic_kernel.exceptions import CodeBlockRenderException, CodeBlockTokenError
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 :smile:
2024-04-15 15:51:59 +02:00
from semantic_kernel.exceptions.kernel_exceptions import KernelFunctionNotFoundError, KernelPluginNotFoundError
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
from semantic_kernel.functions.kernel_function_metadata import KernelFunctionMetadata
2023-03-16 19:54:34 -07:00
from semantic_kernel.template_engine.blocks.block import Block
from semantic_kernel.template_engine.blocks.block_types import BlockTypes
from semantic_kernel.template_engine.blocks.function_id_block import FunctionIdBlock
from semantic_kernel.template_engine.blocks.named_arg_block import NamedArgBlock
from semantic_kernel.template_engine.code_tokenizer import CodeTokenizer
2023-03-16 19:54:34 -07:00
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
if TYPE_CHECKING:
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.kernel import Kernel
2023-03-16 19:54:34 -07:00
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
logger: logging.Logger = logging.getLogger(__name__)
2023-03-16 19:54:34 -07:00
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
VALID_ARG_TYPES = [BlockTypes.VALUE, BlockTypes.VARIABLE, BlockTypes.NAMED_ARG]
2023-03-16 19:54:34 -07:00
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
class CodeBlock(Block):
"""Create a code block.
A code block is a block that usually contains functions to be executed by the kernel.
It consists of a list of tokens that can be either a function_id, value, a variable or a named argument.
If the first token is not a function_id but a variable or value, the rest of the tokens will be ignored.
Only the first argument for the function can be a variable or value, the rest of the tokens have be named arguments.
Args:
content: The content of the code block.
tokens: The list of tokens that compose the code block, if empty, will be created by the CodeTokenizer.
Raises:
CodeBlockTokenError: If the content does not contain at least one token.
CodeBlockTokenError: If the first token is a named argument.
CodeBlockTokenError: If the second token is not a value or variable.
CodeBlockTokenError: If a token is not a named argument after the second token.
CodeBlockRenderError: If the plugin collection is not set in the kernel.
CodeBlockRenderError: If the function is not found in the plugin collection.
CodeBlockRenderError: If the function does not take any arguments, but it is being
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
called in the template with arguments.
"""
type: ClassVar[BlockTypes] = BlockTypes.CODE
tokens: list[Block] = Field(default_factory=list)
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
@model_validator(mode="before")
@classmethod
def parse_content(cls, fields: Any) -> Any:
"""Parse the content of the code block and tokenize it.
If tokens are already present, skip the tokenizing.
"""
if isinstance(fields, Block) or "tokens" in fields:
return fields
content = fields.get("content", "").strip()
fields["tokens"] = CodeTokenizer.tokenize(content)
return fields
@field_validator("tokens", mode="after")
def check_tokens(cls, tokens: list[Block]) -> list[Block]:
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
"""Check the tokens in the list.
If the first token is a value or variable, the rest of the tokens will be ignored.
If the first token is a function_id, then the next token can be a value,
variable or named_arg, the rest have to be named_args.
Raises:
CodeBlockTokenError: If the content does not contain at least one token.
CodeBlockTokenError: If the first token is a named argument.
CodeBlockTokenError: If the second token is not a value or variable.
CodeBlockTokenError: If a token is not a named argument after the second token.
"""
if not tokens:
raise CodeBlockTokenError("The content should contain at least one token.")
for index, token in enumerate(tokens):
if index == 0 and token.type == BlockTypes.NAMED_ARG:
raise CodeBlockTokenError(
f"The first token needs to be a function_id, value or variable, got: {token.type}"
)
if index == 0 and token.type in [BlockTypes.VALUE, BlockTypes.VARIABLE]:
if len(tokens) > 1:
logger.warning(
"The first token is a value or variable, but there are more tokens in the content, \
these will be ignored."
)
return [token]
if index == 1 and token.type not in VALID_ARG_TYPES:
raise CodeBlockTokenError(
f"Unexpected type for the second token type, should be variable, value or named_arg: {token.type}"
)
if index > 1 and token.type != BlockTypes.NAMED_ARG:
raise CodeBlockTokenError(
f"Every argument for the function after the first has to be a named arg, instead: {token.type}"
)
return tokens
async def render_code(self, kernel: "Kernel", arguments: "KernelArguments") -> str:
"""Render the code block.
If the first token is a function_id, it will call the function from the plugin collection.
Otherwise, it is a value or variable and those are then rendered directly.
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
"""
logger.debug(f"Rendering code: `{self.content}`")
if isinstance(self.tokens[0], FunctionIdBlock):
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
return await self._render_function_call(kernel, arguments)
# validated that if the first token is not a function_id, it is a value or variable
return self.tokens[0].render(kernel, arguments) # type: ignore
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
async def _render_function_call(self, kernel: "Kernel", arguments: "KernelArguments"):
if not isinstance(self.tokens[0], FunctionIdBlock):
raise CodeBlockRenderException("The first token should be a function_id")
function_block: FunctionIdBlock = self.tokens[0]
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 :smile:
2024-04-15 15:51:59 +02:00
try:
function = kernel.get_function(function_block.plugin_name, function_block.function_name)
except (KernelFunctionNotFoundError, KernelPluginNotFoundError) as exc:
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
error_msg = f"Function `{function_block.content}` not found"
logger.error(error_msg)
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 :smile:
2024-04-15 15:51:59 +02:00
raise CodeBlockRenderException(error_msg) from exc
2023-03-16 19:54:34 -07:00
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
arguments_clone = copy(arguments)
if len(self.tokens) > 1:
arguments_clone = self._enrich_function_arguments(kernel, arguments_clone, function.metadata)
try:
result = await function.invoke(kernel, arguments_clone)
except Exception as exc:
error_msg = f"Error invoking function `{function_block.content}`"
logger.error(error_msg)
raise CodeBlockRenderException(error_msg) from exc
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
return str(result) if result else ""
2023-03-16 19:54:34 -07:00
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
def _enrich_function_arguments(
self,
kernel: "Kernel",
arguments: "KernelArguments",
function_metadata: KernelFunctionMetadata,
) -> "KernelArguments":
if not function_metadata.parameters:
Python: rebuilt exceptions structure; pythonic version (#5231) ### 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 existing Exceptions structure was very much inspired by dotnet, this is now replaced with a pythonic implementations. This means all Exceptions derive from KernelException and then specialise for different purposes. Closes #2194 ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Added folder for all exception types, all can be imported through `from semantic_kernel.exceptions import ...` no need for a user to know which file the relevant one is in, but keeps things tidy for developers. Removed old KernelException, added back subtypes for the errorcodes. Went through everything to make sure the `raise ... from exc` pattern is used as much as possible as that returns a better stacktrace. ### 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 :smile:
2024-02-28 19:53:53 +01:00
raise CodeBlockRenderException(
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
f"Function {function_metadata.plugin_name}.{function_metadata.name} does not take any arguments "
f"but it is being called in the template with {len(self.tokens) - 1} arguments."
2023-03-16 19:54:34 -07:00
)
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
for index, token in enumerate(self.tokens[1:], start=1):
logger.debug(f"Parsing variable/value: `{self.tokens[1].content}`")
# For VarBlock, get the raw value to preserve the original type
# For other blocks (ValBlock, NamedArgBlock), render to string as usual
from semantic_kernel.template_engine.blocks.var_block import VarBlock
if isinstance(token, VarBlock):
rendered_value = token.get_value(arguments)
elif isinstance(token, NamedArgBlock):
# NamedArgBlock may contain a VarBlock, so check for that
if token.variable:
rendered_value = token.variable.get_value(arguments)
else:
rendered_value = token.render(kernel, arguments)
else:
rendered_value = token.render(kernel, arguments) # type: ignore
if not isinstance(token, NamedArgBlock) and index == 1:
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
arguments[function_metadata.parameters[0].name] = rendered_value
continue
arguments[token.name] = rendered_value # type: ignore
2023-03-16 19:54:34 -07:00
Python: major features for the Kernel Arguments, Function Result and new Prompt Templating (#5077) ### 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. --> Major work to replace the context with Kernel Arguments on the front-end and Function Results on the back. Updated the function decorator to a new approach, in line with dotnet. Revamps the way function are called, allowing native functions to be completely ignorant of SK, other then the decorator. This also moves things into the new folder structure in sync with dotnet. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> Adds: - KernelArguments, a dict-like class that replaces the variables in KernelContext. Closes #4565 - FunctionResult, a class to hold the results of function executions, includes the function, the value and metadata, as well as two convenient function to get the value out of it (str and get_inner_content) the first is generic, the second specifically for KernelContent responses (from AI services). - AI Service Selector class, has a default, which is based on the order in the arguments followed by the order in the functions, can be overridden to implement your own strategy. Closes #4631 - Introduces ChatHistory and refactors the PromptTemplateConfig. Closes #4856, #4630 - Improves parsing of templates, will now all validate during creation and throw an error then, instead of some that do not check for validaty until used. - Introduces named_args block and thereby the ability to have multiple arguments for a function call in a template. Closes #5003 Updates: - kernel_function decorators, the parameter decorator was removed and instead we now use Annotated to add a description of a field and we get the type and required from the function definition. - core plugins, use the new approach to kernel_function decorators. - planners, template engines have all been updated to use the kernel and kernelarguments instead of Context. - Events have been updated, now use kernelarguments and function_result - Tokenizers support for named_args and improvements on parsing and checking. - Kernel examples and notebooks to use the latest code. - All unit and integration tests. There is more code coverage now than before. Removed: - kernelContext - kernel_function_parameter_decorator - delegate handling code for native functions - file_io_plugin and tests - SemanticFunctionConfig - ChatPromptTemplate ### 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 :smile: --------- Co-authored-by: Evan Mattson <evmattso@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Evan Mattson <evan.mattson@microsoft.com>
2024-02-24 21:05:40 +01:00
return arguments