mirror of
https://github.com/microsoft/semantic-kernel.git
synced 2026-10-12 02:19:06 +00:00
### Motivation and Context
<!-- Thank you for your contribution to the semantic-kernel repo!
Please help reviewers and future users, providing the following
information:
1. Why is this change required?
2. What problem does it solve?
3. What scenario does it contribute to?
4. If it fixes an open issue, please link to the issue here.
-->
The loading of plugins and functions into Kernel was not fully
consistent and clear, this is now simplified.
Adding a plugin can now be done in two ways:
- multiple: `kernel.add_plugins[plugin1, plugin2]`
- single plugin: `kernel.add_plugin(plugin)`
- if the plugin here is a class, with methods that have the
kernel_function decorator then that is parsed into a plugin
Adding a function can now be done in three ways:
- multiple: `kernel.add_functions([func1, func2]` or
`kernel.add_function({'func1': func1})`
- single: `kernel.add_function('plugin_name', func1)`
- from a prompt: `kernel.add_function(function_name='func1',
prompt='test prompt', ...)`
In other words, all the different methods that were available have been
simplified, these methods also return the created plugin (or updated
plugin for the `add_functions` method. The `add_function` (singular)
method has a parameter `return_plugin` to control whether you get the
created or updated plugin, instead of the created function.
**An important callout:**
One big internal change that this introduces is that a function that
gets added to a plugin (new or existing) is automatically copied, the
metadata is deep-copied and the plugin_name in the metadata is updated,
so this sequence is valid now:
```python
@kernel_function(name='test')
def f(...):
etc
func = KernelFunctionFromMethod(method=f)
func2 = kernel.add_function('plugin', func)
assert func != func2
```
Also closes: #5855
### Description
<!-- Describe your changes, the overall approach, the underlying design.
These notes will help understanding how your code works. Thanks! -->
Removed KernelPluginCollection
Updated KernelPlugin
added from_... method to load from different sources
Updated KernelFunctionFromPrompt
added from_yaml and from_directory methods.
Added and updated tests to 99% coverage of KernelPlugin and
KernelFunctionFromPrompt
### Contribution Checklist
<!-- Before submitting this PR, please make sure: -->
- [x] The code builds clean without any errors or warnings
- [x] The PR follows the [SK Contribution
Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md)
and the [pre-submission formatting
script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts)
raises no violations
- [x] All unit tests pass, and I have added new tests where possible
- [ ] I didn't break anyone 😄
96 lines
3.4 KiB
Python
96 lines
3.4 KiB
Python
# Copyright (c) Microsoft. All rights reserved.
|
|
|
|
import os
|
|
|
|
from dotenv import load_dotenv
|
|
|
|
import semantic_kernel as sk
|
|
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
|
|
from semantic_kernel.connectors.ai.prompt_execution_settings import PromptExecutionSettings
|
|
from semantic_kernel.connectors.search_engine import GoogleConnector
|
|
from semantic_kernel.core_plugins import WebSearchEnginePlugin
|
|
from semantic_kernel.functions.kernel_arguments import KernelArguments
|
|
|
|
load_dotenv()
|
|
|
|
|
|
async def main():
|
|
kernel = sk.Kernel()
|
|
api_key, org_id = sk.openai_settings_from_dot_env()
|
|
kernel.add_service(
|
|
OpenAIChatCompletion(service_id="chat-gpt", ai_model_id="gpt-3.5-turbo", api_key=api_key, org_id=org_id)
|
|
)
|
|
|
|
"""
|
|
Instantiate a Google Connector
|
|
Make sure to have the following keys in a .env file or set as environment variables
|
|
- GOOGLE_API_KEY
|
|
- GOOGLE_SEARCH_ENGINE_ID
|
|
|
|
A Google Custom Search API has to be created in order to have an API key and a search engine ID.
|
|
To create a Google Custom Search API, follow the guide - https://developers.google.com/custom-search/v1/overview.
|
|
If you have already created the service, the credentials can be found in the Credentials tab on the page
|
|
https://console.cloud.google.com/apis/api/customsearch.googleapis.com
|
|
"""
|
|
connector = GoogleConnector(
|
|
api_key=os.getenv("GOOGLE_API_KEY"),
|
|
search_engine_id=os.getenv("GOOGLE_SEARCH_ENGINE_ID"),
|
|
)
|
|
|
|
# Import the WebSearchEnginePlugin and pass the Google Connector to it.
|
|
web_plugin = kernel.add_plugin(WebSearchEnginePlugin(connector), "WebSearch")
|
|
|
|
# The search query
|
|
search = web_plugin["searchAsync"]
|
|
prompt = "Who is Leonardo DiCaprio's current girlfriend?"
|
|
|
|
# By default, only one search result is provided
|
|
result = await search.invoke(kernel, query=prompt)
|
|
print(str(result))
|
|
|
|
"""
|
|
Output:
|
|
["Celebrity Celebrity News Everything You Need to Know About Leonardo DiCaprio and Camila Morrone's
|
|
Relationship From the beginning of their romance to today, we track their relationship here. By..."]
|
|
"""
|
|
|
|
# Following example demonstrates the use of the plugin within a semantic function
|
|
prompt = """
|
|
Answer the question using only the data that is provided in the data section.
|
|
Do not use any prior knowledge to answer the question.
|
|
Data: {{WebSearch.SearchAsync "What is semantic kernel?"}}
|
|
Question: What is semantic kernel?
|
|
Answer:
|
|
"""
|
|
|
|
qna = kernel.add_function(
|
|
plugin_name="qa",
|
|
function_name="qna",
|
|
prompt=prompt,
|
|
prompt_execution_settings=PromptExecutionSettings(temperature=0.2),
|
|
)
|
|
|
|
"""
|
|
Two context parameters can be passed to the search engine plugin.
|
|
- num_results controls the number of results returned by the web search.
|
|
- offset controls the number of results to omit.
|
|
"""
|
|
arguments = KernelArguments(num_results="10", offset="0")
|
|
|
|
result = await qna.invoke(kernel, arguments)
|
|
print(str(result))
|
|
|
|
"""
|
|
Output:
|
|
Semantic Kernel is an open-source SDK that lets you easily combine AI services like OpenAI,
|
|
Azure OpenAI, and Hugging Face with conventional programming languages like C# and Python.
|
|
By doing so, you can create AI apps that combine the best of both worlds.
|
|
Semantic Kernel is at the center of the copilot stack.
|
|
"""
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import asyncio
|
|
|
|
asyncio.run(main())
|