mirror of
https://github.com/microsoft/semantic-kernel.git
synced 2026-10-12 02:19:06 +00:00
### Motivation and Context Bump Python project version to 1.2.0 for a release. <!-- 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 Bump Python project version to 1.2.0 for a release. <!-- 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 - [X] I didn't break anyone 😄
21 KiB
21 KiB
In [ ]:
# Note: if using a Poetry virtual environment, do not run this cell
%pip install semantic-kernel==1.2.0
%pip install azure-core==1.30.1
%pip install azure-search-documents==11.6.0b4In [ ]:
# Make sure paths are correct for the imports
import os
import sys
notebook_dir = os.path.abspath("")
parent_dir = os.path.dirname(notebook_dir)
grandparent_dir = os.path.dirname(parent_dir)
sys.path.append(grandparent_dir)In [ ]:
from services import Service
from samples.service_settings import ServiceSettings
service_settings = ServiceSettings()
# Select a service to use for this notebook (available services: OpenAI, AzureOpenAI, HuggingFace)
selectedService = (
Service.AzureOpenAI
if service_settings.global_llm_service is None
else Service(service_settings.global_llm_service.lower())
)
print(f"Using service type: {selectedService}")In [ ]:
from semantic_kernel.connectors.ai.open_ai.services.azure_chat_completion import AzureChatCompletion
from semantic_kernel.connectors.ai.open_ai.services.azure_text_embedding import AzureTextEmbedding
from semantic_kernel.connectors.ai.open_ai.services.open_ai_chat_completion import OpenAIChatCompletion
from semantic_kernel.connectors.ai.open_ai.services.open_ai_text_embedding import OpenAITextEmbedding
from semantic_kernel.core_plugins.text_memory_plugin import TextMemoryPlugin
from semantic_kernel.kernel import Kernel
from semantic_kernel.memory.semantic_text_memory import SemanticTextMemory
from semantic_kernel.memory.volatile_memory_store import VolatileMemoryStore
kernel = Kernel()
chat_service_id = "chat"
# Configure AI service used by the kernel
if selectedService == Service.AzureOpenAI:
azure_chat_service = AzureChatCompletion(
service_id=chat_service_id,
)
# next line assumes embeddings deployment name is "text-embedding", adjust the deployment name to the value of your chat model if needed
embedding_gen = AzureTextEmbedding(
service_id="embedding",
)
kernel.add_service(azure_chat_service)
kernel.add_service(embedding_gen)
elif selectedService == Service.OpenAI:
oai_chat_service = OpenAIChatCompletion(
service_id=chat_service_id,
)
embedding_gen = OpenAITextEmbedding(
ai_model_id="embedding",
)
kernel.add_service(oai_chat_service)
kernel.add_service(embedding_gen)
memory = SemanticTextMemory(storage=VolatileMemoryStore(), embeddings_generator=embedding_gen)
kernel.add_plugin(TextMemoryPlugin(memory), "TextMemoryPlugin")In [ ]:
collection_id = "generic"
async def populate_memory(memory: SemanticTextMemory) -> None:
# Add some documents to the semantic memory
await memory.save_information(collection=collection_id, id="info1", text="Your budget for 2024 is $100,000")
await memory.save_information(collection=collection_id, id="info2", text="Your savings from 2023 are $50,000")
await memory.save_information(collection=collection_id, id="info3", text="Your investments are $80,000")In [ ]:
await populate_memory(memory)In [ ]:
async def search_memory_examples(memory: SemanticTextMemory) -> None:
questions = [
"What is my budget for 2024?",
"What are my savings from 2023?",
"What are my investments?",
]
for question in questions:
print(f"Question: {question}")
result = await memory.search(collection_id, question)
print(f"Answer: {result[0].text}\n")In [ ]:
await search_memory_examples(memory)In [ ]:
from semantic_kernel.functions import KernelFunction
from semantic_kernel.prompt_template import PromptTemplateConfig
async def setup_chat_with_memory(
kernel: Kernel,
service_id: str,
) -> KernelFunction:
prompt = """
ChatBot can have a conversation with you about any topic.
It can give explicit instructions or say 'I don't know' if
it does not have an answer.
Information about me, from previous conversations:
- {{recall 'budget by year'}} What is my budget for 2024?
- {{recall 'savings from previous year'}} What are my savings from 2023?
- {{recall 'investments'}} What are my investments?
{{$request}}
""".strip()
prompt_template_config = PromptTemplateConfig(
template=prompt,
execution_settings={
service_id: kernel.get_service(service_id).get_prompt_execution_settings_class()(service_id=service_id)
},
)
return kernel.add_function(
function_name="chat_with_memory",
plugin_name="chat",
prompt_template_config=prompt_template_config,
)In [ ]:
print("Populating memory...")
await populate_memory(memory)
print("Asking questions... (manually)")
await search_memory_examples(memory)
print("Setting up a chat (with memory!)")
chat_func = await setup_chat_with_memory(kernel, chat_service_id)
print("Begin chatting (type 'exit' to exit):\n")
print(
"Welcome to the chat bot!\
\n Type 'exit' to exit.\
\n Try asking a question about your finances (i.e. \"talk to me about my finances\")."
)
async def chat(user_input: str):
print(f"User: {user_input}")
answer = await kernel.invoke(chat_func, request=user_input)
print(f"ChatBot:> {answer}")In [ ]:
await chat("What is my budget for 2024?")In [ ]:
await chat("talk to me about my finances")In [ ]:
github_files = {}
github_files["https://github.com/microsoft/semantic-kernel/blob/main/README.md"] = (
"README: Installation, getting started, and how to contribute"
)
github_files[
"https://github.com/microsoft/semantic-kernel/blob/main/dotnet/notebooks/02-running-prompts-from-file.ipynb"
] = "Jupyter notebook describing how to pass prompts from a file to a semantic plugin or function"
github_files["https://github.com/microsoft/semantic-kernel/blob/main/dotnet/notebooks/00-getting-started.ipynb"] = (
"Jupyter notebook describing how to get started with the Semantic Kernel"
)
github_files["https://github.com/microsoft/semantic-kernel/tree/main/samples/plugins/ChatPlugin/ChatGPT"] = (
"Sample demonstrating how to create a chat plugin interfacing with ChatGPT"
)
github_files[
"https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel/Memory/Volatile/VolatileMemoryStore.cs"
] = "C# class that defines a volatile embedding store"In [ ]:
memory_collection_name = "SKGitHub"
print("Adding some GitHub file URLs and their descriptions to a volatile Semantic Memory.")
for index, (entry, value) in enumerate(github_files.items()):
await memory.save_reference(
collection=memory_collection_name,
description=value,
text=value,
external_id=entry,
external_source_name="GitHub",
)
print(" URL {} saved".format(index))In [ ]:
ask = "I love Jupyter notebooks, how should I get started?"
print("===========================\n" + "Query: " + ask + "\n")
memories = await memory.search(memory_collection_name, ask, limit=5, min_relevance_score=0.77)
for index, memory in enumerate(memories):
print(f"Result {index}:")
print(" URL: : " + memory.id)
print(" Title : " + memory.description)
print(" Relevance: " + str(memory.relevance))
print()In [ ]:
api_key = os.getenv("AZURE_AI_SEARCH_API_KEY")
endpoint = os.getenv("AZURE_AI_SEARCH_ENDPOINT")In [ ]:
from semantic_kernel.connectors.memory.azure_cognitive_search import AzureCognitiveSearchMemoryStore
acs_memory_store = AzureCognitiveSearchMemoryStore(vector_size=1536, admin_key=api_key, search_endpoint=endpoint)
memory = SemanticTextMemory(storage=acs_memory_store, embeddings_generator=embedding_gen)
kernel.add_plugin(TextMemoryPlugin(memory), "TextMemoryPluginACS")In [ ]:
await populate_memory(memory)In [ ]:
await search_memory_examples(memory)