In this example, we show how you can build a simple chat bot by sending and updating the kernel arguments with your requests.
We introduce the Kernel Arguments object which in this demo functions similarly as a key-value store that you can use when running the kernel.
The chat history is local (i.e. in your computer's RAM) and not persisted anywhere beyond the life of this Jupyter session.
In future examples, we will show how to persist the chat history on disk so that you can bring it into your applications.
In this chat scenario, as the user talks back and forth with the bot, the chat context gets populated with the history of the conversation. During each new run of the kernel, the kernel arguments and chat history can provide the AI with its variables' content.
# Note: if using a virtual environment, do not run this cell
%pip install -U semantic-kernel
from semantic_kernel import __version__
__version__
Initial configuration for the notebook to run properly.
# 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)
Let's get started with the necessary configuration to run Semantic Kernel. For Notebooks, we require a .env
file with the proper settings for the model you use. Create a new file named .env
and place it in this directory. Copy the contents of the .env.example
file from this directory and paste it into the .env
file that you just created.
NOTE: Please make sure to include GLOBAL_LLM_SERVICE
set to either OpenAI, AzureOpenAI, or HuggingFace in your .env file. If this setting is not included, the Service will default to AzureOpenAI.
Add your OpenAI Key key to your .env
file (org Id only if you have multiple orgs):
GLOBAL_LLM_SERVICE="OpenAI"
OPENAI_API_KEY="sk-..."
OPENAI_ORG_ID=""
OPENAI_CHAT_MODEL_ID=""
OPENAI_TEXT_MODEL_ID=""
OPENAI_EMBEDDING_MODEL_ID=""
The names should match the names used in the .env
file, as shown above.
Add your Azure Open AI Service key settings to the .env
file in the same folder:
GLOBAL_LLM_SERVICE="AzureOpenAI"
AZURE_OPENAI_API_KEY="..."
AZURE_OPENAI_ENDPOINT="https://..."
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="..."
AZURE_OPENAI_TEXT_DEPLOYMENT_NAME="..."
AZURE_OPENAI_EMBEDDING_DEPLOYMENT_NAME="..."
AZURE_OPENAI_API_VERSION="..."
The names should match the names used in the .env
file, as shown above.
For more advanced configuration, please follow the steps outlined in the setup guide.
We will load our settings and get the LLM service to use for the notebook.
from services import Service
from samples.service_settings import ServiceSettings
service_settings = ServiceSettings.create()
# 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}")
from semantic_kernel import Kernel
kernel = Kernel()
service_id = None
if selectedService == Service.OpenAI:
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
service_id = "default"
kernel.add_service(
OpenAIChatCompletion(
service_id=service_id,
),
)
elif selectedService == Service.AzureOpenAI:
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
service_id = "default"
kernel.add_service(
AzureChatCompletion(
service_id=service_id,
),
)
Let's define a prompt outlining a dialogue chat bot.
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.
{{$history}}
User: {{$user_input}}
ChatBot: """
Register your semantic function
from semantic_kernel.connectors.ai.open_ai import AzureChatPromptExecutionSettings, OpenAIChatPromptExecutionSettings
from semantic_kernel.prompt_template import PromptTemplateConfig
from semantic_kernel.prompt_template.input_variable import InputVariable
if selectedService == Service.OpenAI:
execution_settings = OpenAIChatPromptExecutionSettings(
service_id=service_id,
ai_model_id="gpt-3.5-turbo",
max_tokens=2000,
temperature=0.7,
)
elif selectedService == Service.AzureOpenAI:
execution_settings = AzureChatPromptExecutionSettings(
service_id=service_id,
ai_model_id="gpt-35-turbo",
max_tokens=2000,
temperature=0.7,
)
prompt_template_config = PromptTemplateConfig(
template=prompt,
name="chat",
template_format="semantic-kernel",
input_variables=[
InputVariable(name="user_input", description="The user input", is_required=True),
InputVariable(name="history", description="The conversation history", is_required=True),
],
execution_settings=execution_settings,
)
chat_function = kernel.add_function(
function_name="chat",
plugin_name="chatPlugin",
prompt_template_config=prompt_template_config,
)
from semantic_kernel.contents import ChatHistory
chat_history = ChatHistory()
chat_history.add_system_message("You are a helpful chatbot who is good about giving book recommendations.")
Initialize the Kernel Arguments
from semantic_kernel.functions import KernelArguments
arguments = KernelArguments(user_input="Hi, I'm looking for book suggestions", history=chat_history)
Chat with the Bot
response = await kernel.invoke(chat_function, arguments)
print(response)
Update the history with the output
chat_history.add_assistant_message(str(response))
Keep Chatting!
async def chat(input_text: str) -> None:
# Save new message in the context variables
print(f"User: {input_text}")
# Process the user message and get an answer
answer = await kernel.invoke(chat_function, KernelArguments(user_input=input_text, history=chat_history))
# Show the response
print(f"ChatBot: {answer}")
chat_history.add_user_message(input_text)
chat_history.add_assistant_message(str(answer))
await chat("I love history and philosophy, I'd like to learn something new about Greece, any suggestion?")
await chat("that sounds interesting, what is it about?")
await chat("if I read that book, what exactly will I learn about Greek history?")
await chat("could you list some more books I could read about this topic?")
After chatting for a while, we have built a growing history, which we are attaching to each prompt and which contains the full conversation. Let's take a look!
print(chat_history)