Welcome to the very first post in a series of blogs about my journey building a chatbot with Semantic Kernel. In particular, I will work with the new experimental Python library 🗪
Let's begin this exciting journey together!
What is Semantic Kernel?
According to the official documentation:
, which is still in development phase.
Installation
To begin, install the
semantic-kernelpackage using pip:
CODEpip install semantic-kernel
For C# or Java implementations, you can refer to the official Semantic Kernel . This service type generates responses in conversational contexts, where the model not only use the last user message isolated, but within a context (the conversation history) so the response is coherent and relevant to the conversation.
CODE# Add chat completion service
kernel.add_service(AzureChatCompletion(
base_url='base_url' # For example, an Azure OpenAI instace url
api_key='api_key', # The Api Key associated to the previous instace
deplyoment_name='deployment_name' # A chat model like gpt-4o-mini
))
Alternatively, if the settings are not provided explicitly on the constructor, Semantic Kernel will try to load them from the environment based on predefined names. For example,
Azure OpenAIrelated settings are always prefixed withAZURE_OPEN_AI(e.g:AZURE_OPENAI_BASE_URL,AZURE_OPENAI_API_KEY,AZURE_OPENAI_CHAT_DEPLOYMENT_NAME).
Once a service is added to the
Kernel, it can be retrieved later by its type.
CODEchat_service = kernel.get_service(type=ChatCompletionClientBase)
The agent
For this series of blogs, I will build a book assistant. Feel free to experiment with your preferred theme for your chatbot.
To start with it, we create a
book_assistant.pyfile. In the constructor, we initialize theKerneland the corresponding AI services.
CODEfrom semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
class BookAssistant:
def __init__(self):
# Initalize the kernel and the AI Services
self.kernel = Kernel()
self.chat_service = AzureChatCompletion(
service_id="chat_completion"
)
# Add AI Services to the kernel
self.kernel.add_service(self.chat_service)
For this conversational agent, we'll be using the tracks and maintains the record of messages throughout a chat session, enabling context preservation and continuity of conversation.
For now, we just initialize it on the
__init__assistant method:
CODEfrom semantic_kernel.contents import ChatHistory
class BookAssistant:
def __init__(self):
... # More code
self.history = ChatHistory()
Calling the model
Once we have the
ChatCompletionAgentand theChatHistoryinitialized, we are ready to interact with the agent. We add a new async methodcallin ourBookAssistantclass. The method will:
- Receive the last
user_messageas an argument.
- Add it to the
ChatHistoryas a user message.
- Invoke the agent with the
invokemethod passing theChatHistory.
- The
ChatCompletionAgentuses the model to generate a reply to the lastuser_messageguided by the context provided in theChatHistory.
- Add the response to the
ChatHistoryas an assistant message.
- Return back the response to the caller so it's shown in the chat interface.
CODEfrom semantic_kernel.contents.utils.author_role import AuthorRole
async def call(self, user_message: str) -> str:
self.history.add_message(ChatMessageContent(role=AuthorRole.USER, content=user_message))
async for response in self.agent.invoke(self.history):
self.history.add_message(response)
return str(response)
With this simple piece of code, we already have an easy way of having a conversation with the chatbot. However, the agent does not act as a book assistant yet, it is just a generic one. For example, if we ask what kind of things can do, it replies with a vague and generic response:
to instruct the agent who/what it should be, how it should behave and how it should respond. In previous version of Semantic Kernel, System Prompt was defined using the Persona. However, as we are using the new experimental
Agent Framework, the System Prompt is now provided on the Agent initialization:
CODEself.agent = ChatCompletionAgent(
service_id='chat_completion',
name='BookAssistant',
kernel=self.kernel,
instructions="""
You are a knowledgeable book assistant who helps readers explore and understand literature. You provide thoughtful analysis of themes, characters, and writing styles while avoiding spoilers unless explicitly requested.
Your responses are concise but insightful, and you're careful to ask clarifying questions when needed to better understand readers' preferences and needs. When uncertain about details, you openly acknowledge limitations and present literary interpretations as possibilities rather than absolutes.
"""
)
With these simple instructions, we have adjusted the agent's tone, specifying its purpose, and adding some remarks about how we expect it to act under some circumstances. If we now repeat the previous question, the agent replies with a more concrete and precise answer.
documentation.
Summary
In this chapter, we have accomplished the first steps on the development of a chatbot using Semantic Kernel with the new experimental Agent Framework. We have gone through some basic concepts, and provide some "personality" to the agent.
Remember that all the code is already available on my GitHub repository .
↗ Original-Artikel auf dev.to lesenVollständiger Original-BerichtAusführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
SOCIAL SHARE CARD GENERATOR