Skip to content

Commit 37b001d

Browse files
authored
Update chat example 302 (#514)
1 parent df49802 commit 37b001d

File tree

1 file changed

+104
-7
lines changed

1 file changed

+104
-7
lines changed

examples/302-dotnet-sk-km-chat/Program.cs

Lines changed: 104 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,9 @@ private static async Task ChatLoop(IChatCompletionService chatService, IKernelMe
7373
// Chat setup
7474
var systemPrompt = """
7575
You are a helpful assistant replying to user questions using information from your memory.
76-
The topic of the conversation is Kernel Memory (KM) and Semantic Kernel (SK).
76+
Reply very briefly and concisely, get to the point immediately. Don't provide long explanations unless necessary.
7777
Sometimes you don't have relevant memories so you reply saying you don't know, don't have the information.
78+
The topic of the conversation is Kernel Memory (KM) and Semantic Kernel (SK).
7879
""";
7980

8081
var chatHistory = new ChatHistory(systemPrompt);
@@ -86,6 +87,7 @@ The topic of the conversation is Kernel Memory (KM) and Semantic Kernel (SK).
8687

8788
// Infinite chat loop
8889
var reply = new StringBuilder();
90+
8991
while (true)
9092
{
9193
// Get user message (retry if the user enters an empty string)
@@ -95,13 +97,11 @@ The topic of the conversation is Kernel Memory (KM) and Semantic Kernel (SK).
9597
else { chatHistory.AddUserMessage(userMessage); }
9698

9799
// Recall relevant information from memory
98-
MemoryAnswer recall = await memory.AskAsync(userMessage);
99-
Console.WriteLine("--- recall from memory ---");
100-
Console.WriteLine(recall.Result.Trim());
101-
Console.WriteLine("--------------------------");
100+
var longTermMemory = await GetLongTermMemory(memory, userMessage);
101+
// Console.WriteLine("-------------------------- recall from memory\n{longTermMemory}\n--------------------------");
102102

103103
// Inject the memory recall in the initial system message
104-
chatHistory[0].Content = $"{systemPrompt}\n\nLong term memory:\n{recall.Result}";
104+
chatHistory[0].Content = $"{systemPrompt}\n\nLong term memory:\n{longTermMemory}";
105105

106106
// Generate the next chat message, stream the response
107107
Console.Write("\nCopilot> ");
@@ -117,6 +117,20 @@ The topic of the conversation is Kernel Memory (KM) and Semantic Kernel (SK).
117117
}
118118
}
119119

120+
private static async Task<string> GetLongTermMemory(IKernelMemory memory, string query, bool asChunks = true)
121+
{
122+
if (asChunks)
123+
{
124+
// Fetch raw chunks, using KM indexes. More tokens to process with the chat history, but only one LLM request.
125+
SearchResult memories = await memory.SearchAsync(query, limit: 10);
126+
return memories.Results.SelectMany(m => m.Partitions).Aggregate("", (sum, chunk) => sum + chunk.Text + "\n").Trim();
127+
}
128+
129+
// Use KM to generate an answer. Fewer tokens, but one extra LLM request.
130+
MemoryAnswer answer = await memory.AskAsync(query);
131+
return answer.Result.Trim();
132+
}
133+
120134
private static async Task MemorizeDocuments(IKernelMemory memory, List<string> pages)
121135
{
122136
await memory.ImportTextAsync("We can talk about Semantic Kernel and Kernel Memory, you can ask any questions, I will try to reply using information from public documentation in Github", documentId: "help");
@@ -126,7 +140,7 @@ private static async Task MemorizeDocuments(IKernelMemory memory, List<string> p
126140
// Check if the page is already in memory, to avoid importing twice
127141
if (!await memory.IsDocumentReadyAsync(id))
128142
{
129-
await memory.ImportWebPageAsync(url, documentId: GetUrlId(url));
143+
await memory.ImportWebPageAsync(url, documentId: id);
130144
}
131145
}
132146
}
@@ -136,3 +150,86 @@ private static string GetUrlId(string url)
136150
return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(url))).ToUpperInvariant();
137151
}
138152
}
153+
154+
/* Example output:
155+
156+
# Saving documentation into kernel memory...
157+
# Starting chat...
158+
Copilot> Hello, how can I help?
159+
160+
You> what can I ask?
161+
162+
Copilot> You can ask queries related to Semantic Kernel and Kernel Memory based on Github public documentation.
163+
Examples of questions could be about importing web page content, targeting specific documents with questions,
164+
how to use Kernel Memory from the command line, or about KM's security filters.
165+
166+
You> ok tell me more
167+
168+
Copilot> Kernel Memory (KM) is a Long Term Memory solution for your applications, designed to function similarly to
169+
human memory, storing and retrieving information. It works by uploading data in a packaged Document form.
170+
Whether it's a web page URL, files, or strings, these are stored as Documents with unique IDs to avoid duplications.
171+
KM leverages Large Language Models (LLM), such as GPT-4 and Ada-2 from AI providers, to extract meaning from documents
172+
and generate sentences when asking questions.
173+
174+
Semantic Kernel (SK) constitutes the core components that orchestrate your code with AI. It consists of Plugins,
175+
which are used to manipulate the real world, and Prompts that help generate correct responses. Planners,
176+
another key component, are Prompts that help generate plans to complete tasks.
177+
178+
You can interact with KM using command line tools, make specific queries to documents, and ensure
179+
secure operations using KM's Security Filters.
180+
181+
You> could you provide some examples?
182+
183+
Copilot> Sure, here are some examples of interacting with Kernel Memory via command line:
184+
185+
1. To upload a document:
186+
```bash
187+
cd tools
188+
./upload-file.sh -f README.md -i doc01 -s http://127.0.0.1:9001
189+
```
190+
Or using Curl:
191+
```bash
192+
curl -F 'file1=@"README.md"' -F 'documentId="doc01"' http://127.0.0.1:9001/upload
193+
```
194+
195+
2. To ask a question:
196+
```bash
197+
cd tools
198+
./ask.sh -q "Can I use KM from command line?" -s http://127.0.0.1:9001
199+
```
200+
Or using Curl:
201+
```bash
202+
curl -d'{"question":"Can I use KM from command line?"}' -H 'Content-Type: application/json' http://127.0.0.1:9001/ask
203+
```
204+
205+
These examples demonstrate how to upload a document to KM and how to ask a question using KM's API.
206+
Remember to replace `README.md`, `doc01` and `Can I use KM from command line?` with your file name, document id, and your question.
207+
208+
209+
You> and sk?
210+
211+
Copilot> When working with Semantic Kernel (SK), one of the core concepts is "prompts". These are used to
212+
generate responses from AI models. Here's an example of how you might create a prompt function:
213+
214+
```python
215+
from semantic_kernel import Kernel
216+
217+
# Define your prompt function
218+
def greeting_prompt(name):
219+
return f"Hello, {name}. How can I assist you today?"
220+
221+
# Initialize the kernel
222+
kernel = Kernel.get_instance()
223+
224+
# Register your prompt function
225+
kernel.register_prompt_fn(greeting_prompt)
226+
```
227+
228+
In this Python example, a function `greeting_prompt` is defined which takes one argument `name`. This
229+
function is then registered in the SK system using the `register_prompt_fn` method. Now, when sending
230+
inputs to the model, it will generate responses as if it was saying "Hello, [name]. How can I assist you today?".
231+
This helps guide the message generated by AI in a specific direction.
232+
233+
Remember, this is a basic example. SK's powerful features let you run complex prompts, use different
234+
AI services, manage plug-ins for real-world interaction, and more.
235+
*/

0 commit comments

Comments
 (0)