mirror of
https://github.com/microsoft/semantic-kernel.git
synced 2026-10-12 02:19:06 +00:00
### Motivation and Context Solves #4864 The KernelFunction was configured as a Python class without regards to using Pydantic fields and its validations. As an aside, while running a kernel example related to function/tool calling, it didn't succeed. <!-- 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 cleans up the KernelFunction by creating Pydantic fields. We're also able to remove the KernelFunctionBase as it didn't contain a lot of logic after removing the properties. While testing other code, I found that the tool call kernel example wasn't succeeding. The tool_call payload needed a small reformat, and we needed to handle the tool_call_id and correctly handle the ToolCall object. As further work towards v1, we should look at removing support for FunctionCall as it is deprecated in Azure OpenAI. We now see: ``` User:> What is 3+3? Mosscap:> Ah, the timeless question of arithmetic! The sum of 3 and 3 is undoubtedly a splendid number. By utilizing my mathematical prowess, I can confidently declare that 3 plus 3 equals 6. It is a harmonious union of two threes, joining forces to create a new entity, greater in magnitude. The addition of these two numbers results in a perfect balance, a symphony of numerical harmony. ``` <!-- 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 😄 --------- Co-authored-by: Evan Mattson <[email protected]>
122 lines
3.9 KiB
Python
122 lines
3.9 KiB
Python
# Copyright (c) Microsoft. All rights reserved.
|
|
|
|
import asyncio
|
|
from typing import Tuple
|
|
|
|
import semantic_kernel as sk
|
|
import semantic_kernel.connectors.ai.open_ai as sk_oai
|
|
|
|
|
|
async def populate_memory(kernel: sk.Kernel) -> None:
|
|
# Add some documents to the semantic memory
|
|
await kernel.memory.save_information("aboutMe", id="info1", text="My name is Andrea")
|
|
await kernel.memory.save_information("aboutMe", id="info2", text="I currently work as a tour guide")
|
|
await kernel.memory.save_information("aboutMe", id="info3", text="I've been living in Seattle since 2005")
|
|
await kernel.memory.save_information("aboutMe", id="info4", text="I visited France and Italy five times since 2015")
|
|
await kernel.memory.save_information("aboutMe", id="info5", text="My family is from New York")
|
|
|
|
|
|
async def search_memory_examples(kernel: sk.Kernel) -> None:
|
|
questions = [
|
|
"what's my name",
|
|
"where do I live?",
|
|
"where's my family from?",
|
|
"where have I traveled?",
|
|
"what do I do for work",
|
|
]
|
|
|
|
for question in questions:
|
|
print(f"Question: {question}")
|
|
result = await kernel.memory.search("aboutMe", question)
|
|
print(f"Answer: {result[0].text}\n")
|
|
|
|
|
|
async def setup_chat_with_memory(
|
|
kernel: sk.Kernel,
|
|
) -> Tuple[sk.KernelFunction, sk.KernelContext]:
|
|
sk_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:
|
|
- {{$fact1}} {{recall $fact1}}
|
|
- {{$fact2}} {{recall $fact2}}
|
|
- {{$fact3}} {{recall $fact3}}
|
|
- {{$fact4}} {{recall $fact4}}
|
|
- {{$fact5}} {{recall $fact5}}
|
|
|
|
Chat:
|
|
{{$chat_history}}
|
|
User: {{$user_input}}
|
|
ChatBot: """.strip()
|
|
|
|
chat_func = kernel.create_semantic_function(sk_prompt, max_tokens=200, temperature=0.8)
|
|
|
|
context = kernel.create_new_context()
|
|
context["fact1"] = "what is my name?"
|
|
context["fact2"] = "where do I live?"
|
|
context["fact3"] = "where's my family from?"
|
|
context["fact4"] = "where have I traveled?"
|
|
context["fact5"] = "what do I do for work?"
|
|
|
|
context[sk.core_plugins.TextMemoryPlugin.COLLECTION_PARAM] = "aboutMe"
|
|
context[sk.core_plugins.TextMemoryPlugin.RELEVANCE_PARAM] = "0.8"
|
|
|
|
context["chat_history"] = ""
|
|
|
|
return chat_func, context
|
|
|
|
|
|
async def chat(kernel: sk.Kernel, chat_func: sk.KernelFunction, context: sk.KernelContext) -> bool:
|
|
try:
|
|
user_input = input("User:> ")
|
|
context["user_input"] = user_input
|
|
except KeyboardInterrupt:
|
|
print("\n\nExiting chat...")
|
|
return False
|
|
except EOFError:
|
|
print("\n\nExiting chat...")
|
|
return False
|
|
|
|
if user_input == "exit":
|
|
print("\n\nExiting chat...")
|
|
return False
|
|
|
|
answer = await kernel.run(chat_func, input_vars=context.variables)
|
|
context["chat_history"] += f"\nUser:> {user_input}\nChatBot:> {answer}\n"
|
|
|
|
print(f"ChatBot:> {answer}")
|
|
return True
|
|
|
|
|
|
async def main() -> None:
|
|
kernel = sk.Kernel()
|
|
|
|
api_key, org_id = sk.openai_settings_from_dot_env()
|
|
kernel.add_chat_service("chat-gpt", sk_oai.OpenAIChatCompletion("gpt-3.5-turbo", api_key, org_id))
|
|
kernel.add_text_embedding_generation_service(
|
|
"ada", sk_oai.OpenAITextEmbedding("text-embedding-ada-002", api_key, org_id)
|
|
)
|
|
|
|
kernel.register_memory_store(memory_store=sk.memory.VolatileMemoryStore())
|
|
kernel.import_plugin(sk.core_plugins.TextMemoryPlugin(), "TextMemoryPlugin")
|
|
|
|
print("Populating memory...")
|
|
await populate_memory(kernel)
|
|
|
|
print("Asking questions... (manually)")
|
|
await search_memory_examples(kernel)
|
|
|
|
print("Setting up a chat (with memory!)")
|
|
chat_func, context = await setup_chat_with_memory(kernel)
|
|
|
|
print("Begin chatting (type 'exit' to exit):\n")
|
|
chatting = True
|
|
while chatting:
|
|
chatting = await chat(kernel, chat_func, context)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|