Files
semantic-kernel/python/samples/kernel-syntax-examples/google_search_plugin.py
T
Evan Mattson 7170f0d6a1 Python: Remove sync function invoke. Update other code to use async invoke. (#4796)
### Motivation and Context

Completes #4794. 

Most of SK Python is written with async code; however, there were some
code paths that masked the underlying async code and made it look like a
sync function invoke. In reality, asyncio spun up event loops and
attempted to manage them properly. This becomes tricky when running a
Jupyter notebook as they have their own event loop.

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

### Description

This PR removes the ability to call a kernel function synchronously.
Since the majority of the code base is written with async methods, and
to match dotnet, which is async, we're removing the sync function invoke
and its dependent code. Some Planners were also run synchronously --
these were updated to run asynchronously. Kernel examples, notebooks,
docs, and tests were updated accordingly.

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

### Contribution Checklist

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

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

89 lines
3.1 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.search_engine import GoogleConnector
from semantic_kernel.core_plugins import WebSearchEnginePlugin
load_dotenv()
async def main():
kernel = sk.Kernel()
api_key, org_id = sk.openai_settings_from_dot_env()
kernel.add_chat_service("chat-gpt", OpenAIChatCompletion("gpt-3.5-turbo", api_key, 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.import_plugin(WebSearchEnginePlugin(connector), "WebSearch")
# The search query
prompt = "Who is Leonardo DiCaprio's current girlfriend?"
search = web_plugin["searchAsync"]
# By default, only one search result is provided
result = await search.invoke(prompt)
print(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.create_semantic_function(prompt, temperature=0.2)
context = kernel.create_new_context()
"""
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.
"""
context["num_results"] = "10"
context["offset"] = "0"
result = await qna.invoke(context=context)
print(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())